Merge pull request #435 from chriswritescode-dev/feat/agent-built-change-walkthrough

feat(walkthrough): build the change walkthrough in a spawned agent session
This commit is contained in:
Chris Scott authored and GitHub committed 2026-10-16 00:56:06 -04:00
commit 4bca305167
42 files changed
+3648 -4998

No files matched your search

+195 -25
View File
@@ -1,16 +1,56 @@
import type { Database } from 'bun:sqlite'
import {
ChangeWalkthroughSchema,
WalkthroughGenerationErrorSchema,
WALKTHROUGH_GENERATION_TIMEOUT_MS,
parseWalkthroughSourceKey,
walkthroughSourceKey,
type ChangeWalkthrough,
type WalkthroughGenerationError,
type WalkthroughSource,
type WalkthroughStatus,
} from '@opencode-manager/shared/schemas'
interface ChangeWalkthroughRow {
session_id: string
source_key: string
diff_hash: string
payload: string
generation_id: string
walkthrough_session_id: string | null
status: string
artifact_path: string | null
published_at: number | null
error: string | null
model: string | null
created_at: number
updated_at: number
execution_started_at: number | null
}
const ROW_COLUMNS = 'session_id, source_key, diff_hash, generation_id, walkthrough_session_id, status, artifact_path, published_at, error, model, created_at, updated_at, execution_started_at'
export interface ChangeWalkthroughPatch {
walkthroughSessionId?: string | null
status?: WalkthroughStatus
publishedAt?: number | null
executionStartedAt?: number | null
error?: WalkthroughGenerationError | null
updatedAt?: number
}
export interface ChangeWalkthroughUpdateOptions {
walkthroughSessionId?: string
running?: boolean
}
export interface ClaimChangeWalkthroughGenerationInput {
sessionId: string
source: WalkthroughSource
diffHash: string
generationId: string
artifactPath: string
model: string | null
now: number
}
export function ensureChangeWalkthroughTable(db: Database): void {
@@ -24,44 +64,174 @@ export function ensureChangeWalkthroughTable(db: Database): void {
`)
}
function parseStoredError(raw: string | null): WalkthroughGenerationError | null {
if (raw === null) {
return null
}
try {
const parsed = WalkthroughGenerationErrorSchema.safeParse(JSON.parse(raw))
return parsed.success ? parsed.data : null
} catch {
return null
}
}
function mapRow(row: ChangeWalkthroughRow): ChangeWalkthrough | null {
const source = parseWalkthroughSourceKey(row.source_key)
if (!source) {
return null
}
const parsed = ChangeWalkthroughSchema.safeParse({
sessionId: row.session_id,
source,
diffHash: row.diff_hash,
walkthroughSessionId: row.walkthrough_session_id,
status: row.status,
artifactPath: row.artifact_path,
publishedAt: row.published_at,
executionStartedAt: row.execution_started_at,
error: parseStoredError(row.error),
model: row.model,
createdAt: row.created_at,
updatedAt: row.updated_at,
})
return parsed.success ? parsed.data : null
}
export function getChangeWalkthrough(
db: Database,
sessionId: string,
sourceKey: string,
): ChangeWalkthrough | null {
const row = db
.prepare(
'SELECT session_id, source_key, diff_hash, payload, created_at FROM change_walkthroughs WHERE session_id = ? AND source_key = ?',
)
.prepare(`SELECT ${ROW_COLUMNS} FROM change_walkthroughs WHERE session_id = ? AND source_key = ?`)
.get(sessionId, sourceKey) as ChangeWalkthroughRow | undefined
return row ? mapRow(row) : null
}
export function getChangeWalkthroughByWalkthroughSession(
db: Database,
walkthroughSessionId: string,
): { walkthrough: ChangeWalkthrough; generationId: string } | null {
const row = db
.prepare(`SELECT ${ROW_COLUMNS} FROM change_walkthroughs WHERE walkthrough_session_id = ?`)
.get(walkthroughSessionId) as ChangeWalkthroughRow | undefined
if (!row) {
return null
}
try {
return ChangeWalkthroughSchema.parse(JSON.parse(row.payload))
} catch {
const walkthrough = mapRow(row)
if (!walkthrough) {
return null
}
return { walkthrough, generationId: row.generation_id }
}
export function claimChangeWalkthroughGeneration(
db: Database,
input: ClaimChangeWalkthroughGenerationInput,
): boolean {
const result = db.prepare(`
INSERT INTO change_walkthroughs(
session_id, source_key, diff_hash, generation_id, walkthrough_session_id, status,
artifact_path, published_at, error, model, created_at, updated_at, execution_started_at
) VALUES(?,?,?,?,NULL,'generating',?,NULL,NULL,?,?,?,NULL)
ON CONFLICT(session_id, source_key) DO UPDATE SET
diff_hash = excluded.diff_hash,
generation_id = excluded.generation_id,
walkthrough_session_id = NULL,
status = 'generating',
artifact_path = excluded.artifact_path,
published_at = NULL,
error = NULL,
model = excluded.model,
updated_at = excluded.updated_at,
execution_started_at = NULL
WHERE change_walkthroughs.status != 'generating' OR change_walkthroughs.updated_at < ?
`).run(
input.sessionId,
walkthroughSourceKey(input.source),
input.diffHash,
input.generationId,
input.artifactPath,
input.model,
input.now,
input.now,
input.now - WALKTHROUGH_GENERATION_TIMEOUT_MS,
)
return result.changes > 0
}
export function updateChangeWalkthrough(
db: Database,
sessionId: string,
sourceKey: string,
expectedStatuses: WalkthroughStatus[],
patch: ChangeWalkthroughPatch,
options: ChangeWalkthroughUpdateOptions = {},
): ChangeWalkthrough | null {
const assignments: string[] = []
const params: (string | number | null)[] = []
if (patch.walkthroughSessionId !== undefined) {
assignments.push('walkthrough_session_id = ?')
params.push(patch.walkthroughSessionId)
}
if (patch.status !== undefined) {
assignments.push('status = ?')
params.push(patch.status)
}
if (patch.publishedAt !== undefined) {
assignments.push('published_at = ?')
params.push(patch.publishedAt)
}
if (patch.executionStartedAt !== undefined) {
assignments.push('execution_started_at = ?')
params.push(patch.executionStartedAt)
}
if (patch.error !== undefined) {
assignments.push('error = ?')
params.push(patch.error === null ? null : JSON.stringify(patch.error))
}
if (patch.updatedAt !== undefined) {
assignments.push('updated_at = ?')
params.push(patch.updatedAt)
}
if (assignments.length === 0 || expectedStatuses.length === 0) {
return null
}
const placeholders = expectedStatuses.map(() => '?').join(', ')
const conditions = ['session_id = ?', 'source_key = ?', `status IN (${placeholders})`]
const conditionParams: (string | number | null)[] = [sessionId, sourceKey, ...expectedStatuses]
if (options.walkthroughSessionId !== undefined) {
conditions.push('walkthrough_session_id = ?')
conditionParams.push(options.walkthroughSessionId)
}
if (options.running !== undefined) {
conditions.push(options.running ? 'execution_started_at IS NOT NULL' : 'execution_started_at IS NULL')
}
const result = db
.prepare(`UPDATE change_walkthroughs SET ${assignments.join(', ')} WHERE ${conditions.join(' AND ')}`)
.run(...params, ...conditionParams)
if (result.changes === 0) {
return null
}
return getChangeWalkthrough(db, sessionId, sourceKey)
}
export function listChangeWalkthroughs(db: Database, sessionId: string): ChangeWalkthrough[] {
const rows = db
.prepare(`SELECT ${ROW_COLUMNS} FROM change_walkthroughs WHERE session_id = ?`)
.all(sessionId) as ChangeWalkthroughRow[]
return rows.flatMap((row) => {
const mapped = mapRow(row)
return mapped ? [mapped] : []
})
}
export function deleteChangeWalkthroughs(db: Database, sessionId: string): void {
db.prepare('DELETE FROM change_walkthroughs WHERE session_id = ?').run(sessionId)
}
export function saveChangeWalkthrough(db: Database, walkthrough: ChangeWalkthrough): void {
const sourceKey = walkthroughSourceKey(walkthrough.source)
db.prepare(`
INSERT INTO change_walkthroughs(session_id, source_key, diff_hash, payload, created_at)
VALUES(?,?,?,?,?)
ON CONFLICT(session_id, source_key) DO UPDATE SET
diff_hash = excluded.diff_hash,
payload = excluded.payload,
created_at = excluded.created_at
`).run(
walkthrough.sessionId,
sourceKey,
walkthrough.diffHash,
JSON.stringify(walkthrough),
walkthrough.createdAt,
)
}
@@ -0,0 +1,36 @@
import type { Migration } from '../migration-runner'
const migration: Migration = {
id: '202610151200-change-walkthrough-sessions',
up(db) {
const columns = db.prepare('PRAGMA table_info(change_walkthroughs)').all() as Array<{ name: string }>
if (columns.some((column) => column.name === 'generation_id')) {
return
}
db.run('DROP TABLE IF EXISTS change_walkthroughs')
db.run(`
CREATE TABLE change_walkthroughs (
session_id TEXT NOT NULL,
source_key TEXT NOT NULL,
diff_hash TEXT NOT NULL,
generation_id TEXT NOT NULL,
walkthrough_session_id TEXT,
status TEXT NOT NULL,
artifact_path TEXT,
published_at INTEGER,
error TEXT,
model TEXT,
created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL,
PRIMARY KEY (session_id, source_key)
)
`)
db.run('CREATE INDEX change_walkthroughs_walkthrough_session ON change_walkthroughs(walkthrough_session_id)')
},
down(db) {
db.run('DROP TABLE IF EXISTS change_walkthroughs')
},
}
export default migration
@@ -0,0 +1,22 @@
import type { Migration } from '../migration-runner'
interface ColumnInfo {
name: string
}
const migration: Migration = {
id: '202610161200-change-walkthrough-execution',
up(db) {
const columns = db.prepare('PRAGMA table_info(change_walkthroughs)').all() as ColumnInfo[]
if (!columns.some((column) => column.name === 'execution_started_at')) {
db.run('ALTER TABLE change_walkthroughs ADD COLUMN execution_started_at INTEGER')
}
},
down(db) {
void db
},
}
export default migration
+4
View File
@@ -31,6 +31,8 @@ import migration202610061700 from './202610061700-multi-run-fusions'
import migration202610061701 from './202610061701-change-walkthroughs'
import migration202610081200 from './202610081200-change-walkthrough-sources'
import migration202610141200 from './202610141200-session-sandbox-modes'
import migration202610151200 from './202610151200-change-walkthrough-sessions'
import migration202610161200 from './202610161200-change-walkthrough-execution'
export const allMigrations: Migration[] = [
migration001,
@@ -65,4 +67,6 @@ export const allMigrations: Migration[] = [
migration202610061701,
migration202610081200,
migration202610141200,
migration202610151200,
migration202610161200,
]
+8
View File
@@ -43,6 +43,7 @@ import { createSessionSandboxRoutes } from './routes/session-sandbox'
import { createSessionGoalRoutes } from './routes/session-goals'
import { createMultiRunRoutes } from './routes/multi-runs'
import { createChangeWalkthroughRoutes } from './routes/change-walkthroughs'
import { getChangeWalkthroughByWalkthroughSession } from './db/change-walkthroughs'
import { createLogRoutes } from './routes/logs'
import { createPreviewRoutes, createPreviewAvailability } from './routes/preview'
import { createPreviewGatewayApp, PreviewSessionStore } from './services/preview/gateway'
@@ -88,6 +89,7 @@ import {
getTrustedOrigins,
ENV
} from '@opencode-manager/shared/config/env'
import { NotificationEventType } from '@opencode-manager/shared/schemas'
const { PORT, HOST } = ENV.SERVER
@@ -304,6 +306,12 @@ notificationService.addEventSuppressor(async (event, sessionId) => {
return (await sessionPermissionModeService.getEffectiveMode(sessionId)).mode === 'auto'
})
notificationService.addEventSuppressor(async (event, sessionId) => {
if (!sessionId) return false
if (event.type !== NotificationEventType.SESSION_IDLE && event.type !== NotificationEventType.SESSION_FAILED) return false
return getChangeWalkthroughByWalkthroughSession(db, sessionId) !== null
})
if (ENV.VAPID.PUBLIC_KEY && ENV.VAPID.PRIVATE_KEY) {
if (!ENV.VAPID.SUBJECT) {
logger.warn('VAPID_SUBJECT is not set — push notifications require a mailto: subject (e.g. mailto:you@example.com)')
+18 -4
View File
@@ -2,6 +2,7 @@ import { Hono } from 'hono'
import {
DEFAULT_WALKTHROUGH_SOURCE,
GenerateChangeWalkthroughRequestSchema,
RefineChangeWalkthroughRequestSchema,
parseWalkthroughSourceKey,
} from '@opencode-manager/shared/schemas'
import type { ChangeWalkthroughService } from '../services/change-walkthroughs'
@@ -19,8 +20,7 @@ export function createChangeWalkthroughRoutes(service: ChangeWalkthroughService)
}
try {
const hunksFor = c.req.query('hunksFor')
const state = await service.getState(c.req.param('sessionId'), source, hunksFor)
const state = await service.getState(c.req.param('sessionId'), source)
return c.json(state)
} catch (error) {
return handleServiceError(c, error, 'Failed to read change walkthrough', ServiceError)
@@ -41,14 +41,28 @@ export function createChangeWalkthroughRoutes(service: ChangeWalkthroughService)
}
})
app.delete('/:sessionId', (c) => {
app.post('/:sessionId/refine', async (c) => {
const parsed = await parseJsonBody(c, RefineChangeWalkthroughRequestSchema)
if (!parsed.ok) {
return parsed.response
}
try {
const state = await service.refine(c.req.param('sessionId'), parsed.data)
return c.json(state, 202)
} catch (error) {
return handleServiceError(c, error, 'Failed to refine the change walkthrough', ServiceError)
}
})
app.delete('/:sessionId', async (c) => {
const sourceParam = c.req.query('source')
const source = sourceParam === undefined ? DEFAULT_WALKTHROUGH_SOURCE : parseWalkthroughSourceKey(sourceParam)
if (!source) {
return c.json({ error: 'Invalid walkthrough source' }, 400)
}
service.cancelGeneration(c.req.param('sessionId'), source)
await service.cancelGeneration(c.req.param('sessionId'), source)
return c.body(null, 204)
})
+2
View File
@@ -21,6 +21,7 @@ import { createInternalSessionArtifactRoutes } from './session-artifacts'
import { createSessionGoalRoutes } from '../session-goals'
import { createMultiRunRoutes } from '../multi-runs'
import { createChangeWalkthroughRoutes } from '../change-walkthroughs'
import { createInternalWalkthroughSessionRoutes } from './walkthrough-sessions'
import type { SessionPermissionModeService } from '../../services/session-permission-modes'
import type { SessionSandboxService } from '../../services/session-sandbox'
import type { RepoWorkspaceService } from '../../services/repo-workspace'
@@ -61,6 +62,7 @@ export function createInternalRoutes(
app.route('/sessions', createInternalSessionRoutes(db, openCodeClient, permissionModes, repoWorkspaces))
app.route('/assistant', createInternalAssistantRoutes(openCodeClient))
app.route('/change-walkthroughs', createChangeWalkthroughRoutes(changeWalkthroughService))
app.route('/walkthrough-sessions', createInternalWalkthroughSessionRoutes(changeWalkthroughService))
app.route('/session-artifacts', createInternalSessionArtifactRoutes(openCodeClient))
app.route('/git-credentials', createInternalGitCredentialsRoutes(db))
app.route('/sandbox', createInternalSandboxRoutes(db, sessionSandbox))
@@ -0,0 +1,34 @@
import { Hono } from 'hono'
import { WalkthroughChangesParamsSchema } from '@opencode-manager/shared/schemas'
import type { ChangeWalkthroughService } from '../../services/change-walkthroughs'
import { handleServiceError, parseJsonBody } from '../../utils/route-helpers'
import { ServiceError } from '../../utils/service-error'
export function createInternalWalkthroughSessionRoutes(service: ChangeWalkthroughService) {
const app = new Hono()
app.post('/:sessionId/changes', async (c) => {
const parsed = await parseJsonBody(c, WalkthroughChangesParamsSchema, { allowEmpty: true })
if (!parsed.ok) {
return parsed.response
}
try {
const text = await service.readChangesForWalkthroughSession(c.req.param('sessionId'), parsed.data.file)
return c.json({ text })
} catch (error) {
return handleServiceError(c, error, 'Failed to read walkthrough changes', ServiceError)
}
})
app.post('/:sessionId/publish', async (c) => {
try {
const result = await service.publishFromWalkthroughSession(c.req.param('sessionId'))
return c.json(result)
} catch (error) {
return handleServiceError(c, error, 'Failed to publish the walkthrough', ServiceError)
}
})
return app
}
File diff suppressed because it is too large. Load diff
@@ -5,7 +5,9 @@ import {
MANAGER_PROMPT_CLIENTS,
MANAGER_TOOL_ACTIONS,
MANAGER_TOOL_NAME,
PublishWalkthroughParamsSchema,
ShowArtifactParamsSchema,
WalkthroughChangesParamsSchema,
WalkthroughSourceSchema,
} from '@opencode-manager/shared/schemas'
@@ -78,13 +80,15 @@ const ManagerToolWalkthroughParamsSchema = z
source: WalkthroughSourceSchema.optional().describe('The change source to walk through. Defaults to the changes in this session.'),
})
.strict()
.describe("Request the change Walkthrough for this session, generating it if needed. It opens in the user's Manager window when this session is open on desktop; otherwise the user can open it from this tool call.")
.describe("Start a separate walkthrough session that builds an interactive walkthrough UI for this session's changes, generating it if needed. It opens in the user's Manager walkthrough panel when this session is open on desktop; otherwise the user can open it from this tool call.")
const MANAGER_TOOL_ACTION_PARAMS_SCHEMAS: Record<(typeof MANAGER_TOOL_ACTIONS)[number], z.ZodType> = {
send_notification: ManagerToolNotificationParamsSchema,
request: ManagerToolRequestParamsSchema,
open_walkthrough: ManagerToolWalkthroughParamsSchema,
show_artifact: ShowArtifactParamsSchema.describe('Show a self-contained HTML file the agent wrote to the user, rendered inline in the Manager chat in a sandboxed frame.'),
walkthrough_changes: WalkthroughChangesParamsSchema.describe('Read the changed files of the walkthrough. Omit params.file for an outline of every changed file; pass params.file to get one file\'s full hunks.'),
publish_walkthrough: PublishWalkthroughParamsSchema.describe('Publish the walkthrough HTML file you wrote so the Manager walkthrough panel renders it.'),
}
export function parseAllowedRoute(route: string): { method: string; path: string } {
@@ -119,6 +123,8 @@ function buildManagerToolInputJsonSchema(): Record<string, unknown> {
MANAGER_TOOL_ACTION_PARAMS_SCHEMAS.request,
MANAGER_TOOL_ACTION_PARAMS_SCHEMAS.open_walkthrough,
MANAGER_TOOL_ACTION_PARAMS_SCHEMAS.show_artifact,
MANAGER_TOOL_ACTION_PARAMS_SCHEMAS.walkthrough_changes,
MANAGER_TOOL_ACTION_PARAMS_SCHEMAS.publish_walkthrough,
])
.describe('The parameters for the chosen action.'),
})
@@ -139,7 +145,9 @@ function buildManagerToolDescription(): string {
'Actions:',
'- send_notification: send a push notification to every device the user has registered.',
'- request: call an allow-listed internal API route to read and manage settings, the OpenCode configuration file, repos (list, inspect, clone from a git URL with POST /repos and body { repoUrl, branch?, directoryName? }), OpenCode workspaces, sessions (list, create, follow up, read the latest reply, fork), and schedules.',
"- open_walkthrough: request the change Walkthrough for the current session, generating it if needed. It opens in the user's Manager window when this session is open on desktop; otherwise the user opens it from this tool call. Use when the user asks to walk through, review or explain the changes.",
"- open_walkthrough: start a separate walkthrough session that builds an interactive walkthrough UI for the current session's changes, opened in the Manager walkthrough panel. It opens in the user's Manager window when this session is open on desktop; otherwise the user opens it from this tool call. Use when the user asks to walk through, review or explain the changes.",
"- walkthrough_changes: only valid inside a walkthrough session. Call it with no arguments for an outline of the changed files, or with { file } for one file's full hunks.",
'- publish_walkthrough: only valid inside a walkthrough session. Call it after writing the walkthrough HTML to publish it to the Manager walkthrough panel.',
'- show_artifact: write a self-contained .html file with your file tools, then call show_artifact with its path to show it to the user, rendered inline in this session\'s Manager chat inside a sandboxed frame. Edit the file to fix or change it (no need to resend content). Inline your own CSS and JavaScript; libraries may load from public CDNs. Forms, popups, cookies and local storage are blocked. Single file only: sibling .js and .css files will not load.',
'Allowed request routes:',
]
@@ -282,13 +290,9 @@ var ACTIONS = {
var state = await postInternalApi('/change-walkthroughs/' + encodeURIComponent(context.sessionID), body, context.signal)
var hint = ' It opens in the Manager window when this session is open on desktop; otherwise the user can open it from this tool call.'
if (state.generating === true) {
return 'Requested the walkthrough; it is generating.' + hint
return 'Started a walkthrough session that builds an interactive walkthrough.' + hint
}
var stops = state.walkthrough && Array.isArray(state.walkthrough.stops) ? state.walkthrough.stops.length : 0
if (state.walkthrough) {
return 'Requested the walkthrough (' + stops + ' stops).' + hint
}
return 'Requested the walkthrough.' + hint
return 'The walkthrough is ready.' + hint
},
},
show_artifact: {
@@ -304,6 +308,22 @@ var ACTIONS = {
}
},
},
walkthrough_changes: {
run: async function (params, context) {
var body = params.file === undefined ? undefined : { file: params.file }
var result = await postInternalApi('/walkthrough-sessions/' + encodeURIComponent(context.sessionID) + '/changes', body, context.signal)
return result.text
},
},
publish_walkthrough: {
run: async function (params, context) {
var result = await postInternalApi('/walkthrough-sessions/' + encodeURIComponent(context.sessionID) + '/publish', undefined, context.signal)
return {
content: 'Published the walkthrough from ' + result.path + '. The Manager walkthrough panel renders the current file; edit it and call publish_walkthrough again after significant changes.',
metadata: { path: result.path },
}
},
},
}
function assertParams(actionName, params) {
+3 -13
View File
@@ -12,20 +12,11 @@ export class GenerateTextTimeoutError extends Error {
export async function generateTextWithTimeout(
client: OpenCodeClient,
input: { prompt: string; model?: ModelRef },
input: { prompt: string },
timeoutMs: number,
signal?: AbortSignal,
): Promise<string> {
const controller = new AbortController()
let timer: ReturnType<typeof setTimeout> | undefined
const abortFromSignal = () => controller.abort(signal?.reason)
if (signal) {
if (signal.aborted) {
controller.abort(signal.reason)
} else {
signal.addEventListener('abort', abortFromSignal, { once: true })
}
}
const timeout = new Promise<never>((_resolve, reject) => {
timer = setTimeout(() => {
controller.abort()
@@ -38,16 +29,15 @@ export async function generateTextWithTimeout(
return text
} finally {
if (timer) clearTimeout(timer)
signal?.removeEventListener('abort', abortFromSignal)
}
}
async function generateText(
client: OpenCodeClient,
input: { prompt: string; model?: ModelRef },
input: { prompt: string },
signal: AbortSignal,
): Promise<{ text: string }> {
const model = input.model ?? await resolveGenerateModel(client, signal)
const model = await resolveGenerateModel(client, signal)
return client.api.generate.text({ prompt: input.prompt, model }, { signal })
}
+23 -14
View File
@@ -14,6 +14,28 @@ export class SessionArtifactError extends ServiceError {
}
}
/**
* Validates that a resolved path is a regular `.html`/`.htm` file within the artifact size limit.
* This is the single owner of the HTML artifact file rules; callers that already know the path is
* contained pass the lexical display path for error messages.
*/
export async function assertHtmlArtifactFile(filePath: string, displayPath: string): Promise<void> {
const stats = await fs.stat(filePath).catch(() => {
throw new SessionArtifactError(`Artifact file not found: ${displayPath}`, 404)
})
if (!stats.isFile()) {
throw new SessionArtifactError(`Artifact file not found: ${displayPath}`, 404)
}
if (!ARTIFACT_EXTENSIONS.has(path.extname(filePath).toLowerCase())) {
throw new SessionArtifactError('Artifact must be an .html file', 400)
}
if (stats.size > ARTIFACT_LIMITS.FILE_MAX_BYTES) {
throw new SessionArtifactError('Artifact file exceeds 5 MB', 413)
}
}
/**
* Resolves an `ocm` `show_artifact` path to the absolute path of a self-contained HTML file inside the session
* directory, rejecting paths that escape it (including through symlinks), non-HTML files and oversized files.
@@ -48,20 +70,7 @@ export async function resolveSessionArtifactFile(
throw new SessionArtifactError(`Artifact path must be inside the session directory ${sessionDirectory}`, 400)
}
const stats = await fs.stat(realFile).catch(() => {
throw new SessionArtifactError(`Artifact file not found: ${artifactPath}`, 404)
})
if (!stats.isFile()) {
throw new SessionArtifactError(`Artifact file not found: ${artifactPath}`, 404)
}
if (!ARTIFACT_EXTENSIONS.has(path.extname(realFile).toLowerCase())) {
throw new SessionArtifactError('Artifact must be an .html file', 400)
}
if (stats.size > ARTIFACT_LIMITS.FILE_MAX_BYTES) {
throw new SessionArtifactError('Artifact file exceeds 5 MB', 413)
}
await assertHtmlArtifactFile(realFile, artifactPath)
return resolved
}
+307
View File
@@ -0,0 +1,307 @@
import { createHash } from 'node:crypto'
import {
MECHANICAL_TEXT_BUDGET,
WALKTHROUGH_DIFF_MAX_CHARS,
WALKTHROUGH_HUNK_MAX_CHARS,
WALKTHROUGH_OUTLINE_LINE_MAX_CHARS,
WALKTHROUGH_OUTLINE_PREVIEW_LINES,
type WalkthroughHunk,
type WalkthroughOmittedFile,
} from '@opencode-manager/shared/schemas'
import type { FileDiffInfo } from '@opencode-manager/shared/opencode'
import { countDiffLineChanges, parseDiffLines, splitDiffHunks, type DiffHunk } from '@opencode-manager/shared/utils'
import { truncateText } from '../utils/text-truncate'
const HUNK_TRUNCATION_MARKER = '\n[hunk truncated]'
const OUTPUT_TRUNCATION_MARKER = '\n[output truncated]'
const TEXT_TRUNCATION_MARKER = ''
const OUTLINE_RETRY_DEPTHS = [3, 1, 0]
const MECHANICAL_LOCKFILE_NAMES = new Set([
'pnpm-lock.yaml',
'package-lock.json',
'npm-shrinkwrap.json',
'yarn.lock',
'bun.lock',
'bun.lockb',
'Cargo.lock',
'Gemfile.lock',
'composer.lock',
'poetry.lock',
'uv.lock',
'Pipfile.lock',
'go.sum',
'flake.lock',
])
const MECHANICAL_SUFFIXES = ['.snap', '.min.js', '.min.css', '.map']
export interface WalkthroughInput {
hunks: WalkthroughHunk[]
mechanicalHunks: WalkthroughHunk[]
omittedFiles: WalkthroughOmittedFile[]
}
export interface WalkthroughOutline {
hunks: WalkthroughHunk[]
omittedFiles: WalkthroughOmittedFile[]
outline: string
}
export interface FormatWalkthroughOutlineOptions {
title: string
sourceDescription: string
changes: FileDiffInfo[]
}
export function isMechanicalChangePath(file: string): boolean {
const segments = file.split('/')
const basename = segments.at(-1) ?? file
if (MECHANICAL_LOCKFILE_NAMES.has(basename)) {
return true
}
if (MECHANICAL_SUFFIXES.some((suffix) => file.endsWith(suffix))) {
return true
}
return segments.includes('__snapshots__')
}
export function computeChangesHash(changes: FileDiffInfo[]): string {
const hash = createHash('sha256')
for (const change of changes) {
hash.update(`${change.file}\0${change.status}\0${change.patch}\n`)
}
return hash.digest('hex')
}
export function computeHunkId(file: string, status: FileDiffInfo['status'], hunkText: string): string {
const body = hunkText.split('\n').slice(1).join('\n')
const digest = createHash('sha256').update(`${file}\0${status}\0${body}`).digest('hex')
return `h_${digest.slice(0, 12)}`
}
export function buildWalkthroughInput(changes: FileDiffInfo[]): WalkthroughInput {
const hunks: WalkthroughHunk[] = []
const mechanicalHunks: WalkthroughHunk[] = []
const omittedFiles: WalkthroughOmittedFile[] = []
const hunkIdCounts = new Map<string, number>()
let mechanicalTextLength = 0
const nextHunkId = (file: string, status: FileDiffInfo['status'], text: string): string => {
const baseId = computeHunkId(file, status, text)
const count = (hunkIdCounts.get(baseId) ?? 0) + 1
hunkIdCounts.set(baseId, count)
return count === 1 ? baseId : `${baseId}_${count}`
}
const prepareHunks = (change: FileDiffInfo, fileHunks: DiffHunk[]): WalkthroughHunk[] =>
fileHunks.map((hunk) => {
const truncated = truncateText(hunk.text, WALKTHROUGH_HUNK_MAX_CHARS, HUNK_TRUNCATION_MARKER)
return {
id: nextHunkId(change.file, change.status, hunk.text),
file: change.file,
status: change.status,
header: hunk.header,
text: truncated.text,
truncated: truncated.truncated,
} satisfies WalkthroughHunk
})
const buildMechanicalHunk = (change: FileDiffInfo, fileHunks: DiffHunk[]): WalkthroughHunk => {
const text = fileHunks.map((hunk) => hunk.text).join('\n')
return {
id: nextHunkId(change.file, change.status, text),
file: change.file,
status: change.status,
header: fileHunks[0]!.header,
text,
truncated: false,
additions: change.additions,
deletions: change.deletions,
} satisfies WalkthroughHunk
}
const buildMechanicalSummaryHunk = (change: FileDiffInfo): WalkthroughHunk => ({
id: nextHunkId(change.file, change.status, ''),
file: change.file,
status: change.status,
header: '',
text: '',
truncated: true,
additions: change.additions,
deletions: change.deletions,
})
changes.forEach((change) => {
const mechanical = isMechanicalChangePath(change.file)
const fileHunks = splitDiffHunks(change.patch)
if (fileHunks.length === 0) {
omittedFiles.push({ file: change.file, reason: classifyOmittedFileReason(change.patch) })
return
}
if (mechanical) {
const text = fileHunks.map((hunk) => hunk.text).join('\n')
if (mechanicalTextLength + text.length <= MECHANICAL_TEXT_BUDGET) {
mechanicalHunks.push(buildMechanicalHunk(change, fileHunks))
mechanicalTextLength += text.length
} else {
mechanicalHunks.push(buildMechanicalSummaryHunk(change))
}
return
}
hunks.push(...prepareHunks(change, fileHunks))
})
return { hunks, mechanicalHunks, omittedFiles }
}
export function formatHunkOutline(
hunk: WalkthroughHunk,
previewLines = WALKTHROUGH_OUTLINE_PREVIEW_LINES,
): string {
const { added, removed } = countDiffLineChanges(hunk.text)
const head = `### ${hunk.id} ${hunk.file} (${hunk.status}) ${hunk.header} +${added} -${removed}`
const preview = parseDiffLines(hunk.text)
.filter((line) => line.type === 'add' || line.type === 'remove')
.slice(0, previewLines)
.map((line) =>
truncateText(
`${line.type === 'add' ? '+' : '-'}${line.content}`,
WALKTHROUGH_OUTLINE_LINE_MAX_CHARS,
TEXT_TRUNCATION_MARKER,
).text,
)
return [head, ...preview].join('\n')
}
export function formatHunkBlock(hunk: WalkthroughHunk): string {
return `### ${hunk.id} ${hunk.file} (${hunk.status})\n\n\`\`\`diff\n${hunk.text}\n\`\`\``
}
function classifyOmittedFileReason(patch: string): WalkthroughOmittedFile['reason'] {
const binary = patch.includes('Binary files') || patch.includes('GIT binary patch')
if (!binary && patch.includes('rename to ')) {
return 'renamed'
}
if (!binary && (patch.includes('old mode ') || patch.includes('new mode '))) {
return 'modeChange'
}
return 'binary'
}
function groupHunksByFile(hunks: WalkthroughHunk[]): WalkthroughHunk[][] {
const groups: WalkthroughHunk[][] = []
for (const hunk of hunks) {
const last = groups.at(-1)
if (last && last[0]!.file === hunk.file) {
last.push(hunk)
} else {
groups.push([hunk])
}
}
return groups
}
export function buildWalkthroughOutline(input: WalkthroughInput, prefixLength: number): WalkthroughOutline {
const groups = groupHunksByFile(input.hunks)
const pack = (previewLines: number) => {
let outline = ''
const hunks: WalkthroughHunk[] = []
const omittedFiles: WalkthroughOmittedFile[] = []
let exhausted = false
for (const fileHunks of groups) {
if (exhausted) {
omittedFiles.push({ file: fileHunks[0]!.file, reason: 'budget' })
continue
}
const block = fileHunks.map((hunk) => formatHunkOutline(hunk, previewLines)).join('\n')
const next = outline.length === 0 ? block : `${outline}\n\n${block}`
if (prefixLength + next.length > WALKTHROUGH_DIFF_MAX_CHARS) {
exhausted = true
omittedFiles.push({ file: fileHunks[0]!.file, reason: 'budget' })
continue
}
outline = next
hunks.push(...fileHunks)
}
return { hunks, omittedFiles, outline }
}
let packed = pack(WALKTHROUGH_OUTLINE_PREVIEW_LINES)
if (packed.omittedFiles.length > 0) {
for (const previewLines of OUTLINE_RETRY_DEPTHS) {
const candidate = pack(previewLines)
packed = candidate
if (candidate.omittedFiles.length === 0) {
break
}
}
}
return {
hunks: packed.hunks,
omittedFiles: [...input.omittedFiles, ...packed.omittedFiles],
outline: packed.outline,
}
}
function formatMechanicalFiles(hunks: WalkthroughHunk[]): string {
if (hunks.length === 0) {
return ''
}
return [
'## Mechanical files',
...hunks.map((hunk) => `- ${hunk.file} (${hunk.status}, +${hunk.additions ?? 0}/-${hunk.deletions ?? 0})`),
].join('\n')
}
function formatOmittedFiles(files: WalkthroughOmittedFile[]): string {
if (files.length === 0) {
return ''
}
return ['## Omitted files', ...files.map((file) => `- ${file.file} (${file.reason})`)].join('\n')
}
export function formatWalkthroughOutline({ title, sourceDescription, changes }: FormatWalkthroughOutlineOptions): string {
const input = buildWalkthroughInput(changes)
const header = [
`# ${title}`,
sourceDescription,
`${changes.length} files, ${input.hunks.length} text hunks. Call walkthrough_changes with { file } for a file's full hunks.`,
].join('\n\n')
const mechanical = formatMechanicalFiles(input.mechanicalHunks)
const prefixLength =
[header, mechanical, formatOmittedFiles(input.omittedFiles)].filter((section) => section.length > 0).join('\n\n')
.length + '\n\n## Outline\n'.length
const outline = buildWalkthroughOutline(input, prefixLength)
const sections = [header]
if (mechanical.length > 0) {
sections.push(mechanical)
}
const omitted = formatOmittedFiles(outline.omittedFiles)
if (omitted.length > 0) {
sections.push(omitted)
}
sections.push(`## Outline\n${outline.outline}`)
return truncateText(sections.join('\n\n'), WALKTHROUGH_DIFF_MAX_CHARS, OUTPUT_TRUNCATION_MARKER).text
}
export function formatWalkthroughFileChanges(changes: FileDiffInfo[], file: string): string | null {
const change = changes.find((candidate) => candidate.file === file)
if (!change) {
return null
}
const input = buildWalkthroughInput([change])
const blocks = [...input.hunks, ...input.mechanicalHunks].map((hunk) =>
hunk.text.length === 0
? `${hunk.file} (${hunk.status}, +${hunk.additions ?? 0}/-${hunk.deletions ?? 0})`
: formatHunkBlock(hunk),
)
const text = blocks.length > 0 ? blocks.join('\n\n') : `${change.file} (${change.status}) has no textual changes`
return truncateText(text, WALKTHROUGH_DIFF_MAX_CHARS, OUTPUT_TRUNCATION_MARKER).text
}
-67
View File
@@ -1,67 +0,0 @@
export async function mapWithConcurrency<T, R>(
items: T[],
limit: number,
fn: (item: T, index: number) => Promise<R>,
): Promise<R[]> {
const results = new Array<R>(items.length)
const workerCount = Math.max(1, Math.min(limit, items.length))
let nextIndex = 0
const worker = async (): Promise<void> => {
while (true) {
const index = nextIndex
nextIndex += 1
if (index >= items.length) {
return
}
results[index] = await fn(items[index]!, index)
}
}
await Promise.all(Array.from({ length: workerCount }, () => worker()))
return results
}
export interface Limiter {
readonly activeCount: number
run<T>(task: () => Promise<T>): Promise<T>
}
export function createLimiter(limit: number): Limiter {
const max = Math.max(1, limit)
let active = 0
const waiters: Array<() => void> = []
const acquire = (): Promise<void> => {
if (active < max) {
active += 1
return Promise.resolve()
}
return new Promise<void>((resolve) => {
waiters.push(resolve)
})
}
const release = (): void => {
const next = waiters.shift()
if (next) {
next()
return
}
active -= 1
}
return {
get activeCount(): number {
return active
},
async run<T>(task: () => Promise<T>): Promise<T> {
await acquire()
try {
return await task()
} finally {
release()
}
},
}
}
+265 -119
View File
@@ -1,56 +1,48 @@
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
import { Database } from 'bun:sqlite'
import type { ChangeWalkthrough } from '@opencode-manager/shared/schemas'
import { WALKTHROUGH_GENERATION_TIMEOUT_MS } from '@opencode-manager/shared/schemas'
import {
claimChangeWalkthroughGeneration,
deleteChangeWalkthroughs,
ensureChangeWalkthroughTable,
getChangeWalkthrough,
saveChangeWalkthrough,
getChangeWalkthroughByWalkthroughSession,
listChangeWalkthroughs,
updateChangeWalkthrough,
type ClaimChangeWalkthroughGenerationInput,
} from '../../src/db/change-walkthroughs'
import { migrate } from '../../src/db/migration-runner'
import { allMigrations } from '../../src/db/migrations'
import migration202610081200 from '../../src/db/migrations/202610081200-change-walkthrough-sources'
import migration202610151200 from '../../src/db/migrations/202610151200-change-walkthrough-sessions'
import migration202610161200 from '../../src/db/migrations/202610161200-change-walkthrough-execution'
const SESSION_ID = 'ses_walkthrough'
const SESSION_SOURCE = 'session'
const STAGED_SOURCE = 'staged'
const NOW = 10_000_000
function walkthrough(overrides: Partial<ChangeWalkthrough> = {}): ChangeWalkthrough {
function claim(
overrides: Partial<ClaimChangeWalkthroughGenerationInput> = {},
): ClaimChangeWalkthroughGenerationInput {
return {
sessionId: SESSION_ID,
source: { kind: 'session' },
diffHash: 'hash-1',
model: null,
summary: 'A short summary',
stops: [
{ id: 's_1', title: 'First stop', explanation: 'Why it matters', hunkIds: ['h_1'], status: 'ready', explanationKey: null },
],
hunks: [
{
id: 'h_1',
file: 'src/app.ts',
status: 'modified',
header: '@@ -1,2 +1,2 @@',
text: '@@ -1,2 +1,2 @@\n-const a = 1;\n+const a = 2;',
truncated: false,
},
],
omittedFiles: [{ file: 'assets/logo.png', reason: 'binary' }],
createdAt: 1_000,
generationId: 'gen-1',
artifactPath: '/workspace/walkthroughs/ses_walkthrough/gen-1/index.html',
model: 'anthropic/claude',
now: NOW,
...overrides,
}
}
function walkthroughTableExists(db: Database): boolean {
return Boolean(
db.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'change_walkthroughs'").get(),
)
}
function tableColumns(db: Database): string[] {
return (db.prepare('PRAGMA table_info(change_walkthroughs)').all() as Array<{ name: string }>).map(
(column) => column.name,
)
function insertRow(db: Database, sourceKey: string): void {
db.prepare(`
INSERT INTO change_walkthroughs(
session_id, source_key, diff_hash, generation_id, walkthrough_session_id, status,
artifact_path, published_at, error, model, created_at, updated_at
) VALUES(?,?,?,?,?,?,?,?,?,?,?,?)
`).run(SESSION_ID, sourceKey, 'hash-1', 'gen-1', null, 'generating', null, null, null, null, NOW, NOW)
}
describe('change walkthroughs', () => {
@@ -65,98 +57,267 @@ describe('change walkthroughs', () => {
db.close()
})
it('creates the change_walkthroughs table with per-source storage', () => {
expect(walkthroughTableExists(db)).toBe(true)
expect(tableColumns(db)).toContain('source_key')
it('creates the sessions table with the expected columns, primary key, and index', () => {
const columns = db.prepare('PRAGMA table_info(change_walkthroughs)').all() as Array<{
name: string
pk: number
}>
const names = columns.map((column) => column.name)
expect(names).toEqual(
expect.arrayContaining([
'generation_id',
'walkthrough_session_id',
'status',
'artifact_path',
'published_at',
'error',
'model',
'updated_at',
'execution_started_at',
]),
)
const primaryKey = columns
.filter((column) => column.pk > 0)
.sort((a, b) => a.pk - b.pk)
.map((column) => column.name)
expect(primaryKey).toEqual(['session_id', 'source_key'])
const indexes = db.prepare('PRAGMA index_list(change_walkthroughs)').all() as Array<{ name: string }>
expect(indexes.map((index) => index.name)).toContain('change_walkthroughs_walkthrough_session')
})
it('upgrades an existing single-source table and stays idempotent', () => {
const legacy = new Database(':memory:')
try {
ensureChangeWalkthroughTable(legacy)
migrate(legacy, allMigrations)
expect(tableColumns(legacy)).toContain('source_key')
expect(() => migrate(legacy, allMigrations)).not.toThrow()
expect(() => migration202610081200.up(legacy)).not.toThrow()
expect(tableColumns(legacy)).toContain('source_key')
} finally {
legacy.close()
}
it('applies the migration up idempotently', () => {
expect(() => migration202610151200.up(db)).not.toThrow()
})
it('creates the old table idempotently', () => {
expect(() => ensureChangeWalkthroughTable(db)).not.toThrow()
expect(walkthroughTableExists(db)).toBe(true)
it('adds the execution_started_at column idempotently', () => {
const columns = db.prepare('PRAGMA table_info(change_walkthroughs)').all() as Array<{ name: string }>
expect(columns.map((column) => column.name)).toContain('execution_started_at')
expect(() => migration202610161200.up(db)).not.toThrow()
})
it('returns null for a session without a stored walkthrough', () => {
it('claims a generation on a fresh row', () => {
expect(claimChangeWalkthroughGeneration(db, claim())).toBe(true)
const stored = getChangeWalkthrough(db, SESSION_ID, SESSION_SOURCE)
expect(stored).toMatchObject({
sessionId: SESSION_ID,
source: { kind: 'session' },
diffHash: 'hash-1',
status: 'generating',
walkthroughSessionId: null,
publishedAt: null,
executionStartedAt: null,
error: null,
model: 'anthropic/claude',
artifactPath: '/workspace/walkthroughs/ses_walkthrough/gen-1/index.html',
createdAt: NOW,
updatedAt: NOW,
})
})
it('rejects a second claim while a fresh generation is in progress', () => {
expect(claimChangeWalkthroughGeneration(db, claim())).toBe(true)
expect(claimChangeWalkthroughGeneration(db, claim({ generationId: 'gen-2', now: NOW + 1 }))).toBe(false)
})
it.each(['ready', 'failed', 'cancelled'] as const)('reclaims a row whose status is %s', (status) => {
expect(claimChangeWalkthroughGeneration(db, claim())).toBe(true)
updateChangeWalkthrough(db, SESSION_ID, SESSION_SOURCE, ['generating'], {
status,
walkthroughSessionId: 'ses_generated',
publishedAt: NOW + 5,
error: status === 'failed' ? { message: 'boom' } : null,
updatedAt: NOW + 10,
})
expect(
claimChangeWalkthroughGeneration(
db,
claim({
generationId: 'gen-2',
diffHash: 'hash-2',
artifactPath: '/workspace/walkthroughs/ses_walkthrough/gen-2/index.html',
now: NOW + 20,
}),
),
).toBe(true)
const stored = getChangeWalkthrough(db, SESSION_ID, SESSION_SOURCE)
expect(stored).toMatchObject({
status: 'generating',
diffHash: 'hash-2',
artifactPath: '/workspace/walkthroughs/ses_walkthrough/gen-2/index.html',
walkthroughSessionId: null,
publishedAt: null,
executionStartedAt: null,
error: null,
createdAt: NOW,
updatedAt: NOW + 20,
})
})
it('rejects a stale claim within the timeout but allows one after it', () => {
expect(claimChangeWalkthroughGeneration(db, claim())).toBe(true)
expect(
claimChangeWalkthroughGeneration(
db,
claim({ generationId: 'gen-2', now: NOW + WALKTHROUGH_GENERATION_TIMEOUT_MS }),
),
).toBe(false)
expect(
claimChangeWalkthroughGeneration(
db,
claim({ generationId: 'gen-3', now: NOW + WALKTHROUGH_GENERATION_TIMEOUT_MS + 1 }),
),
).toBe(true)
})
it('stores both sources of one session as separate rows', () => {
expect(claimChangeWalkthroughGeneration(db, claim())).toBe(true)
expect(
claimChangeWalkthroughGeneration(db, claim({ source: { kind: 'staged' }, diffHash: 'hash-2' })),
).toBe(true)
const list = listChangeWalkthroughs(db, SESSION_ID)
expect(list).toHaveLength(2)
expect(list.map((walkthrough) => walkthrough.source.kind).sort()).toEqual(['session', 'staged'])
})
it('returns null for an unknown session or source', () => {
expect(getChangeWalkthrough(db, 'ses_missing', SESSION_SOURCE)).toBeNull()
})
it('round-trips a stored walkthrough', () => {
const stored = walkthrough()
saveChangeWalkthrough(db, stored)
expect(getChangeWalkthrough(db, SESSION_ID, SESSION_SOURCE)).toEqual(stored)
it('returns null when the stored source key is unparseable', () => {
insertRow(db, 'bogus')
expect(getChangeWalkthrough(db, SESSION_ID, 'bogus')).toBeNull()
})
it('reads a walkthrough whose mechanical hunks predate hunk counts', () => {
const legacy = walkthrough({
stops: [
{
id: 's_mech',
title: 'Mechanical changes',
explanation: 'Lock files',
hunkIds: ['h_lock'],
status: 'ready',
explanationKey: null,
},
],
hunks: [
{
id: 'h_lock',
file: 'pnpm-lock.yaml',
status: 'modified',
header: '@@ -1 +1 @@',
text: '@@ -1 +1 @@\n-old-lock\n+new-lock',
truncated: false,
},
],
it('finds a walkthrough by its generation session id', () => {
expect(claimChangeWalkthroughGeneration(db, claim())).toBe(true)
updateChangeWalkthrough(db, SESSION_ID, SESSION_SOURCE, ['generating'], {
walkthroughSessionId: 'ses_generated',
updatedAt: NOW + 1,
})
saveChangeWalkthrough(db, legacy)
const stored = getChangeWalkthrough(db, SESSION_ID, SESSION_SOURCE)
expect(stored).toEqual(legacy)
expect(stored!.hunks[0]!.additions).toBeUndefined()
const found = getChangeWalkthroughByWalkthroughSession(db, 'ses_generated')
expect(found?.generationId).toBe('gen-1')
expect(found?.walkthrough.source.kind).toBe('session')
expect(getChangeWalkthroughByWalkthroughSession(db, 'ses_unknown')).toBeNull()
})
it('stores walkthroughs for two sources of one session side by side', () => {
saveChangeWalkthrough(db, walkthrough({ diffHash: 'hash-session' }))
saveChangeWalkthrough(db, walkthrough({ source: { kind: 'staged' }, diffHash: 'hash-staged', summary: 'Staged' }))
it('does not update a row whose status is not expected', () => {
expect(claimChangeWalkthroughGeneration(db, claim())).toBe(true)
expect(getChangeWalkthrough(db, SESSION_ID, SESSION_SOURCE)?.diffHash).toBe('hash-session')
expect(getChangeWalkthrough(db, SESSION_ID, STAGED_SOURCE)?.diffHash).toBe('hash-staged')
expect(
updateChangeWalkthrough(db, SESSION_ID, SESSION_SOURCE, ['ready'], {
status: 'ready',
updatedAt: NOW + 1,
}),
).toBeNull()
expect(getChangeWalkthrough(db, SESSION_ID, SESSION_SOURCE)?.status).toBe('generating')
})
it('keeps a single row holding the latest payload on repeated saves of one source', () => {
saveChangeWalkthrough(db, walkthrough())
saveChangeWalkthrough(db, walkthrough({ diffHash: 'hash-2', summary: 'Updated', createdAt: 2_000 }))
it('updates only while the walkthrough session id matches the guard', () => {
expect(claimChangeWalkthroughGeneration(db, claim())).toBe(true)
updateChangeWalkthrough(db, SESSION_ID, SESSION_SOURCE, ['generating'], {
walkthroughSessionId: 'ses_a',
updatedAt: NOW + 1,
})
const count = db
.prepare('SELECT COUNT(*) AS count FROM change_walkthroughs WHERE session_id = ?')
.get(SESSION_ID) as { count: number }
expect(count.count).toBe(1)
expect(
updateChangeWalkthrough(
db,
SESSION_ID,
SESSION_SOURCE,
['generating'],
{ status: 'ready', updatedAt: NOW + 2 },
{ walkthroughSessionId: 'ses_b' },
),
).toBeNull()
expect(getChangeWalkthrough(db, SESSION_ID, SESSION_SOURCE)).toMatchObject({
status: 'generating',
walkthroughSessionId: 'ses_a',
})
const stored = getChangeWalkthrough(db, SESSION_ID, SESSION_SOURCE)
expect(stored).toMatchObject({ diffHash: 'hash-2', summary: 'Updated', createdAt: 2_000 })
expect(
updateChangeWalkthrough(
db,
SESSION_ID,
SESSION_SOURCE,
['generating'],
{ status: 'ready', updatedAt: NOW + 3 },
{ walkthroughSessionId: 'ses_a' },
)?.status,
).toBe('ready')
})
it('deletes every source of the given session', () => {
saveChangeWalkthrough(db, walkthrough())
saveChangeWalkthrough(db, walkthrough({ source: { kind: 'staged' } }))
saveChangeWalkthrough(db, walkthrough({ sessionId: 'ses_other' }))
it('guards updates by whether an execution is running', () => {
expect(claimChangeWalkthroughGeneration(db, claim())).toBe(true)
updateChangeWalkthrough(db, SESSION_ID, SESSION_SOURCE, ['generating'], {
walkthroughSessionId: 'ses_a',
executionStartedAt: NOW + 1,
updatedAt: NOW + 1,
})
expect(
updateChangeWalkthrough(
db,
SESSION_ID,
SESSION_SOURCE,
['generating'],
{ status: 'ready', updatedAt: NOW + 2 },
{ running: false },
),
).toBeNull()
expect(
updateChangeWalkthrough(
db,
SESSION_ID,
SESSION_SOURCE,
['generating'],
{ status: 'ready', executionStartedAt: null, updatedAt: NOW + 3 },
{ running: true },
),
).toMatchObject({ status: 'ready', executionStartedAt: null })
})
it('updates a row whose status matches and persists the patch', () => { expect(claimChangeWalkthroughGeneration(db, claim())).toBe(true)
const failed = updateChangeWalkthrough(db, SESSION_ID, SESSION_SOURCE, ['generating'], {
status: 'failed',
error: { message: 'boom', code: 'E_FAIL' },
updatedAt: NOW + 1,
})
expect(failed?.status).toBe('failed')
expect(failed?.error).toEqual({ message: 'boom', code: 'E_FAIL' })
expect(getChangeWalkthrough(db, SESSION_ID, SESSION_SOURCE)?.error).toEqual({
message: 'boom',
code: 'E_FAIL',
})
const cleared = updateChangeWalkthrough(db, SESSION_ID, SESSION_SOURCE, ['failed'], {
error: null,
updatedAt: NOW + 2,
})
expect(cleared?.error).toBeNull()
expect(getChangeWalkthrough(db, SESSION_ID, SESSION_SOURCE)?.error).toBeNull()
})
it('returns null when there is nothing to update', () => {
expect(claimChangeWalkthroughGeneration(db, claim())).toBe(true)
expect(updateChangeWalkthrough(db, SESSION_ID, SESSION_SOURCE, ['generating'], {})).toBeNull()
expect(updateChangeWalkthrough(db, SESSION_ID, SESSION_SOURCE, [], { status: 'ready' })).toBeNull()
})
it('deletes every source of one session but not another', () => {
claimChangeWalkthroughGeneration(db, claim())
claimChangeWalkthroughGeneration(db, claim({ source: { kind: 'staged' } }))
claimChangeWalkthroughGeneration(db, claim({ sessionId: 'ses_other' }))
deleteChangeWalkthroughs(db, SESSION_ID)
@@ -165,23 +326,8 @@ describe('change walkthroughs', () => {
expect(getChangeWalkthrough(db, 'ses_other', SESSION_SOURCE)).not.toBeNull()
})
it('ignores deleting a session without a stored walkthrough', () => {
expect(() => deleteChangeWalkthroughs(db, 'ses_missing')).not.toThrow()
})
it('treats a corrupt payload as missing', () => {
db.prepare(
'INSERT INTO change_walkthroughs(session_id, source_key, diff_hash, payload, created_at) VALUES(?,?,?,?,?)',
).run(SESSION_ID, SESSION_SOURCE, 'hash-1', '{not json', 1_000)
expect(getChangeWalkthrough(db, SESSION_ID, SESSION_SOURCE)).toBeNull()
})
it('treats a payload that fails schema validation as missing', () => {
db.prepare(
'INSERT INTO change_walkthroughs(session_id, source_key, diff_hash, payload, created_at) VALUES(?,?,?,?,?)',
).run(SESSION_ID, SESSION_SOURCE, 'hash-1', JSON.stringify({ sessionId: SESSION_ID }), 1_000)
expect(getChangeWalkthrough(db, SESSION_ID, SESSION_SOURCE)).toBeNull()
it('creates the table idempotently', () => {
expect(() => ensureChangeWalkthroughTable(db)).not.toThrow()
expect(() => ensureChangeWalkthroughTable(db)).not.toThrow()
})
})
+135 -361
View File
@@ -1,189 +1,56 @@
import { afterAll, afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { Hono } from 'hono'
import { Database } from 'bun:sqlite'
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import path from 'node:path'
import type { FileDiffInfo, SessionInfo } from '@opencode-manager/shared/opencode'
import { walkthroughHunksIdentity } from '@opencode-manager/shared/schemas'
import type { ChangeWalkthrough } from '@opencode-manager/shared/schemas'
import { migrate } from '../../src/db/migration-runner'
import { allMigrations } from '../../src/db/migrations'
import { saveChangeWalkthrough } from '../../src/db/change-walkthroughs'
import { ChangeWalkthroughService, computeChangesHash, computeHunkId } from '../../src/services/change-walkthroughs'
import { SettingsService } from '../../src/services/settings'
import type { ChangeWalkthroughState } from '@opencode-manager/shared/schemas'
import { createChangeWalkthroughRoutes } from '../../src/routes/change-walkthroughs'
import type { OpenCodeClient } from '../../src/services/opencode/client'
import type { GitService } from '../../src/services/git/GitService'
import { stubLoadedModelCatalog } from '../helpers/stub-opencode-client'
import { createCommittedRepo, createGitAuthService, git, uniqueName } from '../helpers/git-fixtures'
import { ChangeWalkthroughError } from '../../src/services/change-walkthrough-error'
import type { ChangeWalkthroughService } from '../../src/services/change-walkthroughs'
const SESSION_ID = 'ses_walkthrough'
function change(file: string, patch: string, status: FileDiffInfo['status'] = 'modified'): FileDiffInfo {
return { file, patch, additions: 1, deletions: 1, status }
}
const CHANGES: FileDiffInfo[] = [change('src/a.ts', '@@ -1,2 +1,2 @@\n-const a = 1;\n+const a = 2;')]
const HUNK_ID = computeHunkId(CHANGES[0]!.file, CHANGES[0]!.status, CHANGES[0]!.patch)
const MODEL_REPLY = JSON.stringify({
summary: 'A summary',
stops: [{ title: 'First', explanation: 'Why', hunkIds: [HUNK_ID] }],
})
interface FakeSession {
info?: SessionInfo | Error
changes?: FileDiffInfo[] | Error
}
function createFakeClient(sessions: Record<string, FakeSession>) {
const generateCalls: string[] = []
let generateImpl: (prompt: string) => Promise<string> = async () => MODEL_REPLY
const client = {
api: {
...stubLoadedModelCatalog(),
session: {
get: vi.fn(async ({ sessionID }: { sessionID: string }) => {
const config = sessions[sessionID]
if (!config) {
throw Object.assign(new Error('Session not found'), { _tag: 'SessionNotFoundError' })
}
if (config.info instanceof Error) {
throw config.info
}
return config.info ?? ({ id: sessionID, title: `Title ${sessionID}` } as SessionInfo)
}),
diff: vi.fn(async ({ sessionID }: { sessionID: string }) => {
const config = sessions[sessionID]
if (config?.changes instanceof Error) {
throw config.changes
}
return config?.changes ?? []
}),
},
message: {
list: vi.fn(async ({ sessionID }: { sessionID: string }) => {
if (!sessions[sessionID]) {
return { data: [], cursor: {} }
}
return { data: [{ id: 'msg-1', type: 'user', time: { created: 0 }, text: 'x' }], cursor: {} }
}),
},
generate: {
text: vi.fn(async (input: { prompt: string }) => {
generateCalls.push(input.prompt)
return { text: await generateImpl(input.prompt) }
}),
},
},
forwardRaw: vi.fn(),
} as unknown as OpenCodeClient
function state(overrides: Partial<ChangeWalkthroughState> = {}): ChangeWalkthroughState {
return {
client,
generateCalls,
setGenerateImpl: (impl: (prompt: string) => Promise<string>) => {
generateImpl = impl
},
walkthrough: null,
currentDiffHash: 'hash',
stale: false,
generating: false,
running: false,
error: null,
...overrides,
}
}
const routeRepoRoot = mkdtempSync(path.join(tmpdir(), 'walkthrough-routes-'))
afterAll(() => {
rmSync(routeRepoRoot, { recursive: true, force: true })
})
function createRepoWithStagedChange(): string {
const repo = path.join(routeRepoRoot, uniqueName('repo'))
createCommittedRepo(repo)
writeFileSync(path.join(repo, 'a.txt'), 'one\n')
git(['add', 'a.txt'], repo)
git(['commit', '-m', 'add a'], repo)
writeFileSync(path.join(repo, 'a.txt'), 'two\n')
git(['add', 'a.txt'], repo)
return repo
}
function replyForPrompt(prompt: string, summary = 'A summary'): string {
const ids = [...prompt.matchAll(/^### (h_\S+) /gm)].map((match) => match[1]!)
return JSON.stringify({ summary, stops: [{ title: 'A', explanation: 'Why', hunkIds: ids }] })
}
function createDeferred<T>(): { promise: Promise<T>; resolve: (value: T) => void } {
let resolve!: (value: T) => void
const promise = new Promise<T>((res) => {
resolve = res
})
return { promise, resolve }
}
describe('change walkthrough routes', () => {
let db: Database
let sessions: Record<string, FakeSession>
let fake: ReturnType<typeof createFakeClient>
let getState: ReturnType<typeof vi.fn>
let startGeneration: ReturnType<typeof vi.fn>
let cancelGeneration: ReturnType<typeof vi.fn>
let refine: ReturnType<typeof vi.fn>
let app: Hono
beforeEach(() => {
db = new Database(':memory:')
migrate(db, allMigrations)
sessions = { [SESSION_ID]: { changes: CHANGES } }
fake = createFakeClient(sessions)
const service = new ChangeWalkthroughService(
db,
fake.client,
new SettingsService(db),
createGitAuthService(),
{ fetchRemoteRef: vi.fn(async () => {}) } as unknown as GitService,
)
getState = vi.fn(async () => state())
startGeneration = vi.fn(async () => state({ generating: true }))
cancelGeneration = vi.fn(async () => true)
refine = vi.fn(async () => state({ generating: true }))
app = new Hono()
app.route('/change-walkthroughs', createChangeWalkthroughRoutes(service))
app.route(
'/change-walkthroughs',
createChangeWalkthroughRoutes({ getState, startGeneration, cancelGeneration, refine } as unknown as ChangeWalkthroughService),
)
})
afterEach(() => {
db.close()
})
it('GET returns the state for a session', async () => {
it('GET returns the state for the default source', async () => {
const res = await app.request(`/change-walkthroughs/${SESSION_ID}`)
expect(res.status).toBe(200)
const body = (await res.json()) as {
walkthrough: unknown
currentDiffHash: string | null
stale: boolean
generating: boolean
error: unknown
}
expect(body.walkthrough).toBeNull()
expect(body.stale).toBe(false)
expect(body.currentDiffHash).toEqual(expect.any(String))
expect(body.generating).toBe(false)
expect(body.error).toBeNull()
await expect(res.json()).resolves.toEqual(state())
expect(getState).toHaveBeenCalledWith(SESSION_ID, { kind: 'session' })
})
it('GET returns 404 for a missing session', async () => {
const res = await app.request('/change-walkthroughs/ses_missing')
it('GET reads the requested source', async () => {
const res = await app.request(`/change-walkthroughs/${SESSION_ID}?source=staged`)
expect(res.status).toBe(404)
await expect(res.json()).resolves.toMatchObject({ error: 'Session not found' })
})
it('GET reads the diff of the requested source', async () => {
const repo = createRepoWithStagedChange()
sessions[SESSION_ID]!.info = { id: SESSION_ID, title: 'Title', location: { directory: repo } } as SessionInfo
const sessionRes = await app.request(`/change-walkthroughs/${SESSION_ID}`)
const sessionBody = (await sessionRes.json()) as { currentDiffHash: string | null }
const stagedRes = await app.request(`/change-walkthroughs/${SESSION_ID}?source=staged`)
const stagedBody = (await stagedRes.json()) as { currentDiffHash: string | null }
expect(stagedRes.status).toBe(200)
expect(typeof stagedBody.currentDiffHash).toBe('string')
expect(stagedBody.currentDiffHash).not.toBe(sessionBody.currentDiffHash)
expect(res.status).toBe(200)
expect(getState).toHaveBeenCalledWith(SESSION_ID, { kind: 'staged' })
})
it('GET rejects an invalid source with 400', async () => {
@@ -191,54 +58,19 @@ describe('change walkthrough routes', () => {
expect(res.status).toBe(400)
await expect(res.json()).resolves.toMatchObject({ error: 'Invalid walkthrough source' })
expect(getState).not.toHaveBeenCalled()
})
it('GET omits hunks when hunksFor matches the stored identity and returns them otherwise', async () => {
const stored: ChangeWalkthrough = {
sessionId: SESSION_ID,
source: { kind: 'session' },
diffHash: computeChangesHash(CHANGES),
model: null,
summary: 'A summary',
stops: [
{ id: 's_1', title: 'First', explanation: 'Why', hunkIds: [HUNK_ID], status: 'ready', explanationKey: null },
],
hunks: [
{
id: HUNK_ID,
file: CHANGES[0]!.file,
status: CHANGES[0]!.status,
header: '@@ -1,2 +1,2 @@',
text: CHANGES[0]!.patch,
truncated: false,
},
],
omittedFiles: [],
createdAt: 42,
}
saveChangeWalkthrough(db, stored)
const identity = walkthroughHunksIdentity(stored)
it('GET maps a service error', async () => {
getState.mockRejectedValueOnce(new ChangeWalkthroughError('Session not found', 404))
const fullRes = await app.request(`/change-walkthroughs/${SESSION_ID}`)
const compactRes = await app.request(
`/change-walkthroughs/${SESSION_ID}?hunksFor=${encodeURIComponent(identity)}`,
)
const mismatchRes = await app.request(`/change-walkthroughs/${SESSION_ID}?hunksFor=other`)
const res = await app.request('/change-walkthroughs/ses_missing')
const full = (await fullRes.json()) as { walkthrough: { hunks?: unknown[] } }
const compact = (await compactRes.json()) as { walkthrough: { hunks?: unknown[] } }
const mismatch = (await mismatchRes.json()) as { walkthrough: { hunks?: unknown[] } }
expect(full.walkthrough.hunks).toHaveLength(1)
expect(compact.walkthrough.hunks).toBeUndefined()
expect(mismatch.walkthrough.hunks).toHaveLength(1)
expect(res.status).toBe(404)
await expect(res.json()).resolves.toMatchObject({ error: 'Session not found' })
})
it('POST stores the walkthrough under the requested source', async () => {
const repo = createRepoWithStagedChange()
sessions[SESSION_ID]!.info = { id: SESSION_ID, title: 'Title', location: { directory: repo } } as SessionInfo
fake.setGenerateImpl(async (prompt) => replyForPrompt(prompt, 'Staged summary'))
it('POST returns 202 while generating and forwards the body', async () => {
const res = await app.request(`/change-walkthroughs/${SESSION_ID}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
@@ -246,113 +78,33 @@ describe('change walkthrough routes', () => {
})
expect(res.status).toBe(202)
await vi.waitFor(async () => {
const getRes = await app.request(`/change-walkthroughs/${SESSION_ID}?source=staged`)
const state = (await getRes.json()) as { walkthrough: { summary: string } | null }
expect(state.walkthrough?.summary).toBe('Staged summary')
})
})
it('POST returns 202 while generating, then GET reads the walkthrough back', async () => {
let resolveGenerate: (text: string) => void = () => {}
fake.setGenerateImpl(() => new Promise<string>((resolve) => {
resolveGenerate = resolve
}))
const postRes = await app.request(`/change-walkthroughs/${SESSION_ID}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({}),
})
expect(postRes.status).toBe(202)
const body = (await postRes.json()) as { generating: boolean; walkthrough: unknown }
expect(body.generating).toBe(true)
expect(body.walkthrough).toBeNull()
resolveGenerate(MODEL_REPLY)
await vi.waitFor(async () => {
const getRes = await app.request(`/change-walkthroughs/${SESSION_ID}`)
const state = (await getRes.json()) as { walkthrough: { summary: string } | null; generating: boolean }
expect(state.generating).toBe(false)
expect(state.walkthrough?.summary).toBe('A summary')
})
expect(startGeneration).toHaveBeenCalledWith(SESSION_ID, { source: { kind: 'staged' } })
})
it('POST accepts an empty body', async () => {
let resolveGenerate: (text: string) => void = () => {}
fake.setGenerateImpl(() => new Promise<string>((resolve) => {
resolveGenerate = resolve
}))
const res = await app.request(`/change-walkthroughs/${SESSION_ID}`, { method: 'POST' })
expect(res.status).toBe(202)
resolveGenerate(MODEL_REPLY)
await vi.waitFor(async () => {
const getRes = await app.request(`/change-walkthroughs/${SESSION_ID}`)
const state = (await getRes.json()) as { walkthrough: unknown }
expect(state.walkthrough).not.toBeNull()
})
expect(startGeneration).toHaveBeenCalledWith(SESSION_ID, {})
})
it('POST returns 200 with the stored walkthrough without a second model call', async () => {
await app.request(`/change-walkthroughs/${SESSION_ID}`, { method: 'POST' })
await vi.waitFor(async () => {
const getRes = await app.request(`/change-walkthroughs/${SESSION_ID}`)
const state = (await getRes.json()) as { walkthrough: unknown }
expect(state.walkthrough).not.toBeNull()
})
it('POST returns 200 when the walkthrough is ready', async () => {
startGeneration.mockResolvedValueOnce(state({ generating: false }))
const second = await app.request(`/change-walkthroughs/${SESSION_ID}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({}),
})
const res = await app.request(`/change-walkthroughs/${SESSION_ID}`, { method: 'POST' })
expect(second.status).toBe(200)
const body = (await second.json()) as { walkthrough: { summary: string }; generating: boolean }
expect(body.walkthrough.summary).toBe('A summary')
expect(body.generating).toBe(false)
expect(fake.generateCalls).toHaveLength(1)
expect(res.status).toBe(200)
})
it('POST regenerates when asked', async () => {
await app.request(`/change-walkthroughs/${SESSION_ID}`, { method: 'POST' })
await vi.waitFor(async () => {
const getRes = await app.request(`/change-walkthroughs/${SESSION_ID}`)
const state = (await getRes.json()) as { walkthrough: unknown }
expect(state.walkthrough).not.toBeNull()
})
it('POST returns 409 with the service code', async () => {
startGeneration.mockRejectedValueOnce(
new ChangeWalkthroughError('No changes', 409, { code: 'WALKTHROUGH_NO_TEXT_CHANGES' }),
)
let resolveGenerate: (text: string) => void = () => {}
fake.setGenerateImpl(() => new Promise<string>((resolve) => {
resolveGenerate = resolve
}))
const res = await app.request(`/change-walkthroughs/${SESSION_ID}`, { method: 'POST' })
const res = await app.request(`/change-walkthroughs/${SESSION_ID}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ regenerate: true }),
})
expect(res.status).toBe(202)
resolveGenerate(MODEL_REPLY)
await vi.waitFor(() => expect(fake.generateCalls).toHaveLength(2))
})
it('POST rejects an invalid body with 400', async () => {
const res = await app.request(`/change-walkthroughs/${SESSION_ID}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ regenerate: 'yes' }),
})
expect(res.status).toBe(400)
expect(res.status).toBe(409)
await expect(res.json()).resolves.toMatchObject({ code: 'WALKTHROUGH_NO_TEXT_CHANGES' })
})
it('POST rejects malformed JSON with 400', async () => {
@@ -363,83 +115,49 @@ describe('change walkthrough routes', () => {
})
expect(res.status).toBe(400)
expect(startGeneration).not.toHaveBeenCalled()
})
it('POST returns 409 with a code when there are no text changes', async () => {
sessions[SESSION_ID]!.changes = [
change('assets/logo.png', 'diff --git a/assets/logo.png b/assets/logo.png\nBinary files differ'),
]
const res = await app.request(`/change-walkthroughs/${SESSION_ID}`, { method: 'POST' })
expect(res.status).toBe(409)
await expect(res.json()).resolves.toMatchObject({ code: 'WALKTHROUGH_NO_TEXT_CHANGES' })
})
it('POST records an unparseable model reply that GET surfaces', async () => {
fake.setGenerateImpl(async () => 'not json')
const res = await app.request(`/change-walkthroughs/${SESSION_ID}`, { method: 'POST' })
expect(res.status).toBe(202)
await vi.waitFor(async () => {
const getRes = await app.request(`/change-walkthroughs/${SESSION_ID}`)
const state = (await getRes.json()) as { generating: boolean; error: { code?: string } | null }
expect(state.generating).toBe(false)
expect(state.error?.code).toBe('WALKTHROUGH_UNPARSEABLE')
it('POST rejects an invalid body with 400', async () => {
const res = await app.request(`/change-walkthroughs/${SESSION_ID}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ regenerate: 'yes' }),
})
expect(res.status).toBe(400)
expect(startGeneration).not.toHaveBeenCalled()
})
it('POST returns 404 for a missing session', async () => {
startGeneration.mockRejectedValueOnce(new ChangeWalkthroughError('Session not found', 404))
const res = await app.request('/change-walkthroughs/ses_missing', { method: 'POST' })
expect(res.status).toBe(404)
})
it('DELETE stops an in-flight generation', async () => {
fake.setGenerateImpl(() => new Promise<string>(() => {}))
it('DELETE awaits the cancel and returns 204', async () => {
let resolveCancel: (value: boolean) => void = () => {}
cancelGeneration.mockImplementationOnce(
() =>
new Promise<boolean>((resolve) => {
resolveCancel = resolve
}),
)
const postRes = await app.request(`/change-walkthroughs/${SESSION_ID}`, { method: 'POST' })
expect(postRes.status).toBe(202)
const res = await app.request(`/change-walkthroughs/${SESSION_ID}`, { method: 'DELETE' })
expect(res.status).toBe(204)
const getRes = await app.request(`/change-walkthroughs/${SESSION_ID}`)
const state = (await getRes.json()) as { generating: boolean; error: unknown }
expect(state.generating).toBe(false)
expect(state.error).toBeNull()
})
it('resolves a pending POST with the stopped state after DELETE cancels it', async () => {
const diff = createDeferred<FileDiffInfo[]>()
const diffMock = vi.mocked(fake.client.api.session.diff)
diffMock.mockImplementationOnce(() => diff.promise)
const postPromise = app.request(`/change-walkthroughs/${SESSION_ID}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({}),
let settled = false
const pending = Promise.resolve(app.request(`/change-walkthroughs/${SESSION_ID}`, { method: 'DELETE' })).then((res) => {
settled = true
return res
})
await vi.waitFor(() => expect(diffMock).toHaveBeenCalledTimes(1))
const deleteRes = await app.request(`/change-walkthroughs/${SESSION_ID}`, { method: 'DELETE' })
expect(deleteRes.status).toBe(204)
diff.resolve(CHANGES)
const postRes = await postPromise
expect(postRes.status).toBe(200)
const body = (await postRes.json()) as { generating: boolean; walkthrough: unknown; error: unknown }
expect(body.generating).toBe(false)
expect(body.walkthrough).toBeNull()
expect(body.error).toBeNull()
})
it('DELETE is a no-op when nothing is generating', async () => {
const res = await app.request(`/change-walkthroughs/${SESSION_ID}`, { method: 'DELETE' })
await vi.waitFor(() => expect(cancelGeneration).toHaveBeenCalledWith(SESSION_ID, { kind: 'session' }))
await Promise.resolve()
expect(settled).toBe(false)
resolveCancel(true)
const res = await pending
expect(res.status).toBe(204)
})
@@ -447,5 +165,61 @@ describe('change walkthrough routes', () => {
const res = await app.request(`/change-walkthroughs/${SESSION_ID}?source=branch:-x`, { method: 'DELETE' })
expect(res.status).toBe(400)
expect(cancelGeneration).not.toHaveBeenCalled()
})
it('POST refine returns 202 and forwards the text', async () => {
const res = await app.request(`/change-walkthroughs/${SESSION_ID}/refine`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ text: 'Explain the risk section' }),
})
expect(res.status).toBe(202)
await expect(res.json()).resolves.toMatchObject({ generating: true })
expect(refine).toHaveBeenCalledWith(SESSION_ID, { text: 'Explain the risk section' })
})
it('POST refine forwards the requested source', async () => {
await app.request(`/change-walkthroughs/${SESSION_ID}/refine`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ source: { kind: 'staged' }, text: 'more' }),
})
expect(refine).toHaveBeenCalledWith(SESSION_ID, { source: { kind: 'staged' }, text: 'more' })
})
it('POST refine rejects empty text with 400', async () => {
const res = await app.request(`/change-walkthroughs/${SESSION_ID}/refine`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ text: ' ' }),
})
expect(res.status).toBe(400)
expect(refine).not.toHaveBeenCalled()
})
it('POST refine rejects an empty body with 400', async () => {
const res = await app.request(`/change-walkthroughs/${SESSION_ID}/refine`, { method: 'POST' })
expect(res.status).toBe(400)
expect(refine).not.toHaveBeenCalled()
})
it('POST refine maps a service error', async () => {
refine.mockRejectedValueOnce(
new ChangeWalkthroughError('The walkthrough is still being built', 409, { code: 'WALKTHROUGH_BUSY' }),
)
const res = await app.request(`/change-walkthroughs/${SESSION_ID}/refine`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ text: 'more' }),
})
expect(res.status).toBe(409)
await expect(res.json()).resolves.toMatchObject({ code: 'WALKTHROUGH_BUSY' })
})
})
@@ -79,6 +79,6 @@ describe('internal/change-walkthroughs routes', () => {
})
expect(res.status).toBe(200)
expect(getState).toHaveBeenCalledWith(SESSION_ID, { kind: 'staged' }, undefined)
expect(getState).toHaveBeenCalledWith(SESSION_ID, { kind: 'staged' })
})
})
@@ -0,0 +1,113 @@
import { describe, it, expect, beforeEach, vi } from 'vitest'
import { Hono } from 'hono'
import { Database } from 'bun:sqlite'
import { allMigrations } from '../../src/db/migrations'
import { getOrCreateInternalToken } from '../../src/services/internal-token'
import { migrate } from '../../src/db/migration-runner'
import type { ChangeWalkthroughService } from '../../src/services/change-walkthroughs'
import { ChangeWalkthroughError } from '../../src/services/change-walkthrough-error'
import { createInternalTestApp } from '../helpers/internal-test-app'
const SESSION_ID = 'ses_walk'
describe('internal/walkthrough-sessions routes', () => {
let db: Database
let app: Hono
let token: string
let readChangesForWalkthroughSession: ReturnType<typeof vi.fn>
let publishFromWalkthroughSession: ReturnType<typeof vi.fn>
beforeEach(() => {
db = new Database(':memory:')
migrate(db, allMigrations)
readChangesForWalkthroughSession = vi.fn(async () => '## Outline')
publishFromWalkthroughSession = vi.fn(async () => ({ path: '/workspace/walkthroughs/ses_walk/gen/index.html' }))
app = new Hono()
app.route(
'/api/internal',
createInternalTestApp(db, {
changeWalkthroughService: {
readChangesForWalkthroughSession,
publishFromWalkthroughSession,
} as unknown as ChangeWalkthroughService,
}),
)
token = getOrCreateInternalToken(db)
})
it('POST /api/internal/walkthrough-sessions/:id/changes returns 401 without a bearer token', async () => {
const res = await app.request(`/api/internal/walkthrough-sessions/${SESSION_ID}/changes`, { method: 'POST' })
expect(res.status).toBe(401)
expect(readChangesForWalkthroughSession).not.toHaveBeenCalled()
})
it('POST /changes returns the outline with an empty body', async () => {
const res = await app.request(`/api/internal/walkthrough-sessions/${SESSION_ID}/changes`, {
method: 'POST',
headers: { authorization: `Bearer ${token}` },
})
expect(res.status).toBe(200)
await expect(res.json()).resolves.toEqual({ text: '## Outline' })
expect(readChangesForWalkthroughSession).toHaveBeenCalledWith(SESSION_ID, undefined)
})
it('POST /changes forwards the requested file', async () => {
readChangesForWalkthroughSession.mockResolvedValueOnce('diff')
const res = await app.request(`/api/internal/walkthrough-sessions/${SESSION_ID}/changes`, {
method: 'POST',
headers: { authorization: `Bearer ${token}`, 'content-type': 'application/json' },
body: JSON.stringify({ file: 'src/a.ts' }),
})
expect(res.status).toBe(200)
await expect(res.json()).resolves.toEqual({ text: 'diff' })
expect(readChangesForWalkthroughSession).toHaveBeenCalledWith(SESSION_ID, 'src/a.ts')
})
it('POST /changes maps a service error', async () => {
readChangesForWalkthroughSession.mockRejectedValueOnce(
new ChangeWalkthroughError('This session is not a walkthrough session', 404, { code: 'WALKTHROUGH_NOT_A_WALKTHROUGH_SESSION' }),
)
const res = await app.request(`/api/internal/walkthrough-sessions/${SESSION_ID}/changes`, {
method: 'POST',
headers: { authorization: `Bearer ${token}` },
})
expect(res.status).toBe(404)
await expect(res.json()).resolves.toMatchObject({
error: 'This session is not a walkthrough session',
code: 'WALKTHROUGH_NOT_A_WALKTHROUGH_SESSION',
})
})
it('POST /publish returns the artifact path', async () => {
const res = await app.request(`/api/internal/walkthrough-sessions/${SESSION_ID}/publish`, {
method: 'POST',
headers: { authorization: `Bearer ${token}` },
})
expect(res.status).toBe(200)
await expect(res.json()).resolves.toEqual({ path: '/workspace/walkthroughs/ses_walk/gen/index.html' })
expect(publishFromWalkthroughSession).toHaveBeenCalledWith(SESSION_ID)
})
it('POST /publish maps a service error', async () => {
publishFromWalkthroughSession.mockRejectedValueOnce(
new ChangeWalkthroughError('This session is not a walkthrough session', 404, { code: 'WALKTHROUGH_NOT_A_WALKTHROUGH_SESSION' }),
)
const res = await app.request(`/api/internal/walkthrough-sessions/${SESSION_ID}/publish`, {
method: 'POST',
headers: { authorization: `Bearer ${token}` },
})
expect(res.status).toBe(404)
await expect(res.json()).resolves.toMatchObject({ error: 'This session is not a walkthrough session' })
})
})
File diff suppressed because it is too large. Load diff
@@ -65,6 +65,14 @@ function artifactParamsSchema(tool: GeneratedTool): JsonSchema {
return toolInputSchema(tool).properties?.params?.anyOf?.[3] ?? {}
}
function changesParamsSchema(tool: GeneratedTool): JsonSchema {
return toolInputSchema(tool).properties?.params?.anyOf?.[4] ?? {}
}
function publishParamsSchema(tool: GeneratedTool): JsonSchema {
return toolInputSchema(tool).properties?.params?.anyOf?.[5] ?? {}
}
async function runToolResult(
tool: GeneratedTool,
input: unknown,
@@ -170,8 +178,8 @@ describe('ocm-manager plugin', () => {
expect(schema.type).toBe('object')
expect(schema.required).toEqual(['action', 'params'])
expect(schema.additionalProperties).toBe(false)
expect(schema.properties?.action?.enum).toEqual(['send_notification', 'request', 'open_walkthrough', 'show_artifact'])
expect(schema.properties?.params?.anyOf).toHaveLength(4)
expect(schema.properties?.action?.enum).toEqual(['send_notification', 'request', 'open_walkthrough', 'show_artifact', 'walkthrough_changes', 'publish_walkthrough'])
expect(schema.properties?.params?.anyOf).toHaveLength(6)
expect(notificationParamsSchema(tool).required).toEqual(['title', 'body'])
expect(requestParamsSchema(tool).required).toEqual(['method', 'path'])
expect(walkthroughParamsSchema(tool).required).toBeUndefined()
@@ -190,16 +198,30 @@ describe('ocm-manager plugin', () => {
'branch',
'pullRequest',
])
expect(changesParamsSchema(tool).required).toBeUndefined()
expect(changesParamsSchema(tool).additionalProperties).toBe(false)
expect(changesParamsSchema(tool).properties?.file?.maxLength).toBe(1000)
expect(changesParamsSchema(tool).properties?.file?.minLength).toBe(1)
expect(publishParamsSchema(tool).required).toBeUndefined()
expect(publishParamsSchema(tool).additionalProperties).toBe(false)
})
it('lists the open_walkthrough action in the description', async () => {
const tool = await loadTool(configHome)
expect(tool.description).toContain('open_walkthrough')
expect(tool.description).toContain('request the change Walkthrough for the current session')
expect(tool.description).toContain('start a separate walkthrough session')
expect(tool.description).toContain('when this session is open on desktop')
})
it('lists the walkthrough data actions in the description', async () => {
const tool = await loadTool(configHome)
expect(tool.description).toContain('walkthrough_changes')
expect(tool.description).toContain('publish_walkthrough')
expect(tool.description).toContain('only valid inside a walkthrough session')
})
it('lists the show_artifact action in the description', async () => {
const tool = await loadTool(configHome)
@@ -316,7 +338,7 @@ describe('ocm-manager plugin', () => {
expect(init.headers['content-type']).toBe('application/json')
expect(JSON.parse(init.body)).toEqual({ source: { kind: 'staged' } })
expect(result.content).toBe(
'Requested the walkthrough (2 stops). It opens in the Manager window when this session is open on desktop; otherwise the user can open it from this tool call.',
'The walkthrough is ready. It opens in the Manager window when this session is open on desktop; otherwise the user can open it from this tool call.',
)
expect(result.metadata).toBeUndefined()
})
@@ -328,7 +350,7 @@ describe('ocm-manager plugin', () => {
const result = await runToolResult(tool, { action: 'open_walkthrough', params: {} }, { sessionID: 'ses_abc' })
expect(result.content).toBe(
'Requested the walkthrough; it is generating. It opens in the Manager window when this session is open on desktop; otherwise the user can open it from this tool call.',
'Started a walkthrough session that builds an interactive walkthrough. It opens in the Manager window when this session is open on desktop; otherwise the user can open it from this tool call.',
)
expect(result.metadata).toBeUndefined()
})
@@ -347,6 +369,53 @@ describe('ocm-manager plugin', () => {
expect(init.body).toBeUndefined()
})
it('requests the outline through walkthrough_changes with no body', async () => {
const fetchMock = jsonResponse({ text: '## Outline' })
vi.stubGlobal('fetch', fetchMock)
const tool = await loadTool(configHome)
await expect(runTool(tool, { action: 'walkthrough_changes', params: {} }, { sessionID: 'ses_abc' })).resolves.toBe('## Outline')
expect(fetchMock).toHaveBeenCalledTimes(1)
const [url, init] = fetchMock.mock.calls[0] ?? []
expect(url).toBe('http://localhost:5003/api/internal/walkthrough-sessions/ses_abc/changes')
expect(init.method).toBe('POST')
expect(init.headers.Authorization).toBe('Bearer secret-token')
expect(init.headers['content-type']).toBeUndefined()
expect(init.body).toBeUndefined()
})
it('requests one file through walkthrough_changes', async () => {
const fetchMock = jsonResponse({ text: 'diff' })
vi.stubGlobal('fetch', fetchMock)
const tool = await loadTool(configHome)
await runTool(tool, { action: 'walkthrough_changes', params: { file: 'src/a.ts' } }, { sessionID: 'ses_abc' })
expect(fetchMock).toHaveBeenCalledTimes(1)
const [url, init] = fetchMock.mock.calls[0] ?? []
expect(url).toBe('http://localhost:5003/api/internal/walkthrough-sessions/ses_abc/changes')
expect(init.headers['content-type']).toBe('application/json')
expect(JSON.parse(init.body)).toEqual({ file: 'src/a.ts' })
})
it('publishes the walkthrough through the internal API and reports the path', async () => {
const fetchMock = jsonResponse({ path: '/workspace/walkthroughs/ses_abc/gen/index.html' })
vi.stubGlobal('fetch', fetchMock)
const tool = await loadTool(configHome)
const result = await runToolResult(tool, { action: 'publish_walkthrough', params: {} }, { sessionID: 'ses_abc' })
expect(fetchMock).toHaveBeenCalledTimes(1)
const [url, init] = fetchMock.mock.calls[0] ?? []
expect(url).toBe('http://localhost:5003/api/internal/walkthrough-sessions/ses_abc/publish')
expect(init.method).toBe('POST')
expect(result.content).toBe(
'Published the walkthrough from /workspace/walkthroughs/ses_abc/gen/index.html. The Manager walkthrough panel renders the current file; edit it and call publish_walkthrough again after significant changes.',
)
expect(result.metadata).toEqual({ path: '/workspace/walkthroughs/ses_abc/gen/index.html' })
})
it('resolves the artifact file through the internal API and reports the resolved path', async () => {
const fetchMock = jsonResponse({ path: '/workspace/repos/app/report.html' })
vi.stubGlobal('fetch', fetchMock)
@@ -442,6 +511,8 @@ describe('ocm-manager plugin', () => {
it('allows every route in the exported allow list', async () => {
const tool = await loadTool(configHome)
expect(MANAGER_TOOL_ALLOWED_ROUTES.some((route) => route.includes('/walkthrough-sessions'))).toBe(false)
for (const route of MANAGER_TOOL_ALLOWED_ROUTES) {
const { method, path: pattern } = parseAllowedRoute(route)
const path = pattern.split('/').map((segment) => (segment === '*' ? 'x' : segment)).join('/')
@@ -498,6 +569,8 @@ describe('ocm-manager plugin', () => {
['POST', '/multi-runs/1/entries/2/discard'],
['GET', '/change-walkthroughs/x'],
['POST', '/change-walkthroughs/x'],
['POST', '/walkthrough-sessions/x/changes'],
['POST', '/walkthrough-sessions/x/publish'],
] as const
for (const [method, path] of deniedRoutes) {
@@ -723,7 +796,7 @@ describe.skipIf(SHIPPED_OPENCODE_BIN === null)('ocm-manager plugin against the s
expect(managerTool?.function?.parameters).toMatchObject({
type: 'object',
properties: {
action: { type: 'string', enum: ['send_notification', 'request', 'open_walkthrough', 'show_artifact'] },
action: { type: 'string', enum: ['send_notification', 'request', 'open_walkthrough', 'show_artifact', 'walkthrough_changes', 'publish_walkthrough'] },
params: {
anyOf: [
{
@@ -761,6 +834,17 @@ describe.skipIf(SHIPPED_OPENCODE_BIN === null)('ocm-manager plugin against the s
path: { type: 'string', minLength: 1, maxLength: 1000 },
},
},
{
type: 'object',
additionalProperties: false,
properties: {
file: { type: 'string', minLength: 1, maxLength: 1000 },
},
},
{
type: 'object',
additionalProperties: false,
},
],
},
},
@@ -77,16 +77,6 @@ describe('generateTextWithTimeout', () => {
expect(calls[0]?.input.model).toEqual({ providerID: 'openai', id: 'gpt-5-mini' })
})
it('forwards the model when provided without reading the catalog', async () => {
const { client, calls, modelList } = makeClient(async () => ({ text: 'hello' }))
const model: ModelRef = { providerID: 'anthropic', id: 'claude-sonnet-4' }
await generateTextWithTimeout(client, { prompt: 'write', model }, 1000)
expect(calls[0]?.input).toEqual({ prompt: 'write', model })
expect(modelList).not.toHaveBeenCalled()
})
it('rejects with GenerateTextTimeoutError and aborts the request after the timeout', async () => {
vi.useFakeTimers()
const { client, calls } = makeClient(() => new Promise<never>(() => {}))
@@ -0,0 +1,532 @@
import { describe, expect, it } from 'vitest'
import type { FileDiffInfo } from '@opencode-manager/shared/opencode'
import {
MECHANICAL_TEXT_BUDGET,
WALKTHROUGH_DIFF_MAX_CHARS,
WALKTHROUGH_HUNK_MAX_CHARS,
WALKTHROUGH_OUTLINE_LINE_MAX_CHARS,
WALKTHROUGH_OUTLINE_PREVIEW_LINES,
type WalkthroughHunk,
} from '@opencode-manager/shared/schemas'
import {
buildWalkthroughInput,
buildWalkthroughOutline,
computeChangesHash,
computeHunkId,
formatHunkBlock,
formatHunkOutline,
formatWalkthroughFileChanges,
formatWalkthroughOutline,
isMechanicalChangePath,
} from '../../src/services/walkthrough-outline'
function change(file: string, patch: string, status: FileDiffInfo['status'] = 'modified'): FileDiffInfo {
return { file, patch, additions: 1, deletions: 1, status }
}
function hunkPatch(line: number): string {
return `@@ -${line},2 +${line},2 @@\n-const a${line} = 1;\n+const a${line} = 2;`
}
function bigHunk(index: number, size = WALKTHROUGH_HUNK_MAX_CHARS): string {
return `@@ -${index},1 +${index},1 @@\n+${'x'.repeat(size)}_${index}`
}
function longHunk(index: number): string {
const lines = Array.from(
{ length: 6 },
(_, line) => `+${'x'.repeat(200)}_${index}_${line}`,
)
return `@@ -${index + 1},6 +${index + 1},6 @@\n${lines.join('\n')}`
}
function longPatch(count: number, offset = 0): string {
return Array.from({ length: count }, (_, index) => longHunk(offset + index)).join('\n')
}
function hunkFixture(file: string, text: string, status: FileDiffInfo['status'] = 'modified'): WalkthroughHunk {
return {
id: computeHunkId(file, status, text),
file,
status,
header: text.split('\n')[0] ?? '',
text,
truncated: false,
}
}
describe('computeChangesHash', () => {
it('is stable for identical changes', () => {
const changes = [change('src/a.ts', hunkPatch(1))]
expect(computeChangesHash(changes)).toBe(computeChangesHash(changes))
})
it('changes when any field changes', () => {
const base = change('src/a.ts', hunkPatch(1))
expect(computeChangesHash([base])).not.toBe(computeChangesHash([change('src/a.ts', hunkPatch(2))]))
expect(computeChangesHash([base])).not.toBe(computeChangesHash([change('src/b.ts', hunkPatch(1))]))
expect(computeChangesHash([base])).not.toBe(
computeChangesHash([change('src/a.ts', hunkPatch(1), 'added')]),
)
})
it('is order sensitive', () => {
const a = change('src/a.ts', hunkPatch(1))
const b = change('src/b.ts', hunkPatch(1))
expect(computeChangesHash([a, b])).not.toBe(computeChangesHash([b, a]))
})
})
describe('isMechanicalChangePath', () => {
it('matches lockfiles by basename', () => {
const lockfiles = [
'pnpm-lock.yaml',
'package-lock.json',
'npm-shrinkwrap.json',
'yarn.lock',
'bun.lock',
'bun.lockb',
'Cargo.lock',
'Gemfile.lock',
'composer.lock',
'poetry.lock',
'uv.lock',
'Pipfile.lock',
'go.sum',
'flake.lock',
'deep/nested/pnpm-lock.yaml',
]
expect(lockfiles.every(isMechanicalChangePath)).toBe(true)
})
it('matches generated suffixes and snapshot directories', () => {
expect(isMechanicalChangePath('src/__snapshots__/a.ts.snap')).toBe(true)
expect(isMechanicalChangePath('src/__snapshots__/a.ts')).toBe(true)
expect(isMechanicalChangePath('dist/bundle.min.js')).toBe(true)
expect(isMechanicalChangePath('dist/app.min.css')).toBe(true)
expect(isMechanicalChangePath('dist/bundle.js.map')).toBe(true)
})
it('does not match ordinary source and config files', () => {
expect(isMechanicalChangePath('src/lock.ts')).toBe(false)
expect(isMechanicalChangePath('package.json')).toBe(false)
expect(isMechanicalChangePath('src/snapshots/a.ts')).toBe(false)
expect(isMechanicalChangePath('src/map.ts')).toBe(false)
})
})
describe('buildWalkthroughInput', () => {
it('assigns a distinct content id and the file to each hunk', () => {
const { hunks, omittedFiles } = buildWalkthroughInput([
change('src/a.ts', `${hunkPatch(1)}\n${hunkPatch(10)}`),
change('src/b.ts', hunkPatch(1)),
])
expect(omittedFiles).toEqual([])
expect(hunks.map((hunk) => hunk.file)).toEqual(['src/a.ts', 'src/a.ts', 'src/b.ts'])
const ids = hunks.map((hunk) => hunk.id)
expect(ids.every((id) => id.startsWith('h_'))).toBe(true)
expect(new Set(ids).size).toBe(3)
})
it('keeps a hunk id when an earlier hunk in the file changes', () => {
const before = buildWalkthroughInput([
change(
'src/a.ts',
'@@ -1,2 +1,2 @@\n-const a = 1;\n+const a = 2;\n@@ -10,2 +10,2 @@\n-const b = 1;\n+const b = 2;',
),
])
const after = buildWalkthroughInput([
change(
'src/a.ts',
'@@ -1,3 +1,3 @@\n-const a = 1;\n+const a = 2;\n+const extra = 3;\n@@ -11,2 +11,2 @@\n-const b = 1;\n+const b = 2;',
),
])
expect(before.hunks).toHaveLength(2)
expect(after.hunks).toHaveLength(2)
expect(after.hunks[0]!.id).not.toBe(before.hunks[0]!.id)
expect(after.hunks[1]!.id).toBe(before.hunks[1]!.id)
})
it('suffixes duplicate hunk content', () => {
const { hunks } = buildWalkthroughInput([change('src/a.ts', `${hunkPatch(1)}\n${hunkPatch(1)}`)])
expect(hunks).toHaveLength(2)
expect(hunks[0]!.id).not.toBe(hunks[1]!.id)
expect(hunks[1]!.id).toBe(`${hunks[0]!.id}_2`)
})
it('omits files with no hunks as binary', () => {
const { hunks, omittedFiles } = buildWalkthroughInput([
change('assets/logo.png', 'diff --git a/assets/logo.png b/assets/logo.png\nBinary files differ'),
change('src/a.ts', hunkPatch(1)),
])
expect(hunks).toHaveLength(1)
expect(omittedFiles).toEqual([{ file: 'assets/logo.png', reason: 'binary' }])
})
it('truncates an oversized hunk and marks it', () => {
const longLine = `+${'x'.repeat(WALKTHROUGH_HUNK_MAX_CHARS + 100)}`
const { hunks } = buildWalkthroughInput([change('src/a.ts', `@@ -1 +1 @@\n${longLine}`)])
expect(hunks[0]!.truncated).toBe(true)
expect(hunks[0]!.text).toContain('[hunk truncated]')
})
it('separates mechanical hunks from the prompt hunks', () => {
const { hunks, mechanicalHunks, omittedFiles } = buildWalkthroughInput([
change('src/a.ts', hunkPatch(1)),
change('pnpm-lock.yaml', hunkPatch(2)),
])
expect(hunks.map((hunk) => hunk.file)).toEqual(['src/a.ts'])
expect(mechanicalHunks.map((hunk) => hunk.file)).toEqual(['pnpm-lock.yaml'])
expect(omittedFiles).toEqual([])
})
it('keeps mechanical hunk text within the budget and summarizes every file with counts', () => {
const oversizedPatch = Array.from({ length: 40 }, (_, index) => bigHunk(index)).join('\n')
const { mechanicalHunks, omittedFiles } = buildWalkthroughInput([
{ file: 'pnpm-lock.yaml', patch: oversizedPatch, additions: 1200, deletions: 800, status: 'modified' },
{ file: 'src/__snapshots__/a.ts.snap', patch: hunkPatch(1), additions: 2, deletions: 3, status: 'modified' },
])
expect(mechanicalHunks.map((hunk) => hunk.file)).toEqual([
'pnpm-lock.yaml',
'src/__snapshots__/a.ts.snap',
])
expect(mechanicalHunks.reduce((total, hunk) => total + hunk.text.length, 0)).toBeLessThanOrEqual(
MECHANICAL_TEXT_BUDGET,
)
expect(mechanicalHunks[0]).toMatchObject({ text: '', truncated: true, additions: 1200, deletions: 800 })
expect(mechanicalHunks[1]).toMatchObject({ additions: 2, deletions: 3 })
expect(mechanicalHunks[1]!.text).toContain('@@')
expect(omittedFiles).toEqual([])
})
it('stores mechanical hunk text and counts while within the budget', () => {
const { mechanicalHunks } = buildWalkthroughInput([
{
file: 'pnpm-lock.yaml',
patch: `${hunkPatch(1)}\n${hunkPatch(2)}`,
additions: 2,
deletions: 2,
status: 'modified',
},
])
expect(mechanicalHunks).toHaveLength(1)
expect(mechanicalHunks[0]!.text).toContain('@@ -1,2 +1,2 @@')
expect(mechanicalHunks[0]!.text).toContain('@@ -2,2 +2,2 @@')
expect(mechanicalHunks[0]!.additions).toBe(2)
expect(mechanicalHunks[0]!.deletions).toBe(2)
})
it('omits a binary mechanical file as binary', () => {
const { mechanicalHunks, omittedFiles } = buildWalkthroughInput([
change('pnpm-lock.yaml', 'diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml\nBinary files differ'),
])
expect(mechanicalHunks).toEqual([])
expect(omittedFiles).toEqual([{ file: 'pnpm-lock.yaml', reason: 'binary' }])
})
it('labels a pure rename as renamed', () => {
const { omittedFiles } = buildWalkthroughInput([
change(
'src/new.ts',
'diff --git a/src/old.ts b/src/new.ts\nsimilarity index 100%\nrename from src/old.ts\nrename to src/new.ts',
),
])
expect(omittedFiles).toEqual([{ file: 'src/new.ts', reason: 'renamed' }])
})
it('labels a mode-only change as modeChange', () => {
const { omittedFiles } = buildWalkthroughInput([
change('script.sh', 'diff --git a/script.sh b/script.sh\nold mode 100644\nnew mode 100755'),
])
expect(omittedFiles).toEqual([{ file: 'script.sh', reason: 'modeChange' }])
})
})
describe('formatHunkOutline', () => {
it('renders the id, file, status, header and change counts', () => {
const hunk = hunkFixture('src/a.ts', '@@ -1,2 +1,2 @@\n-const a = 1;\n+const a = 2;')
const [first] = formatHunkOutline(hunk).split('\n')
expect(first).toBe(`### ${hunk.id} src/a.ts (modified) @@ -1,2 +1,2 @@ +1 -1`)
})
it('previews changed lines and counts content lines that start with -- or ++', () => {
const hunk = hunkFixture(
'src/a.ts',
'@@ -1,4 +1,4 @@\n--- a/x\n+++ b/x\n-const a = 1;\n+const a = 2;\n-const b = 1;\n+const b = 2;',
)
const single = formatHunkOutline(hunk, 1).split('\n')
expect(single).toHaveLength(2)
expect(single[1]).toBe('--- a/x')
const full = formatHunkOutline(hunk).split('\n')
expect(full).toContain('--- a/x')
expect(full).toContain('+++ b/x')
expect(full).toContain('-const a = 1;')
expect(full).toContain('+const a = 2;')
expect(full).toContain('-const b = 1;')
expect(full).toContain('+const b = 2;')
expect(full[0]).toContain('+3 -3')
})
it('defaults to the shared preview line count', () => {
const text = `@@ -1,8 +1,8 @@\n${Array.from({ length: 8 }, (_, index) => `+line${index}`).join('\n')}`
const hunk = hunkFixture('src/a.ts', text)
expect(formatHunkOutline(hunk).split('\n')).toHaveLength(1 + WALKTHROUGH_OUTLINE_PREVIEW_LINES)
})
it('truncates a long changed line to the line max', () => {
const hunk = hunkFixture('src/a.ts', `@@ -1 +1 @@\n+${'x'.repeat(200)}`)
const line = formatHunkOutline(hunk).split('\n')[1]!
expect(line).toHaveLength(WALKTHROUGH_OUTLINE_LINE_MAX_CHARS)
})
})
describe('buildWalkthroughOutline', () => {
it('packs every text hunk when the prefix is empty', () => {
const input = buildWalkthroughInput(
Array.from({ length: 300 }, (_, index) => change(`src/f${index}.ts`, hunkPatch(index))),
)
const { hunks, omittedFiles, outline } = buildWalkthroughOutline(input, 0)
expect(omittedFiles).toEqual([])
expect(hunks).toHaveLength(300)
for (const hunk of input.hunks) {
expect(outline).toContain(hunk.id)
}
})
it('omits trailing files as budget and never half-includes a file', () => {
const input = buildWalkthroughInput(
Array.from({ length: 400 }, (_, index) => change(`src/f${index}.ts`, longPatch(3, index * 3))),
)
const { omittedFiles, outline } = buildWalkthroughOutline(input, 0)
expect(omittedFiles.some((file) => file.reason === 'budget')).toBe(true)
const idsByFile = new Map<string, string[]>()
for (const hunk of input.hunks) {
const ids = idsByFile.get(hunk.file) ?? []
ids.push(hunk.id)
idsByFile.set(hunk.file, ids)
}
const includedFiles = new Set<string>()
for (const [file, ids] of idsByFile) {
const present = ids.filter((id) => outline.includes(id)).length
expect(present === 0 || present === ids.length).toBe(true)
if (present > 0) {
includedFiles.add(file)
}
}
expect(omittedFiles.map((file) => file.file)).toEqual(
[...idsByFile.keys()].filter((file) => !includedFiles.has(file)),
)
})
it('falls back to header-only outlines when a single file does not fit at the default preview depth', () => {
const input = buildWalkthroughInput([change('src/huge.ts', longPatch(100))])
const { hunks, omittedFiles, outline } = buildWalkthroughOutline(input, 0)
expect(hunks).toHaveLength(100)
expect(omittedFiles).toEqual([])
for (const hunk of input.hunks) {
expect(outline).toContain(hunk.id)
}
})
it('keeps mechanical hunks out of the outline', () => {
const input = buildWalkthroughInput([
change('src/a.ts', hunkPatch(1)),
change('pnpm-lock.yaml', hunkPatch(2)),
])
const { omittedFiles, outline } = buildWalkthroughOutline(input, 0)
expect(input.mechanicalHunks).toHaveLength(1)
expect(outline).not.toContain(input.mechanicalHunks[0]!.id)
expect(outline).not.toContain('pnpm-lock.yaml')
expect(omittedFiles).toEqual([])
})
it('admits less content behind a larger prefix', () => {
const input = buildWalkthroughInput(
Array.from({ length: 800 }, (_, index) => change(`src/f${index}.ts`, hunkPatch(index))),
)
const withoutPrefix = buildWalkthroughOutline(input, 0)
const withPrefix = buildWalkthroughOutline(input, 20_000)
expect(withPrefix.hunks.length).toBeLessThan(withoutPrefix.hunks.length)
expect(withPrefix.omittedFiles.some((file) => file.reason === 'budget')).toBe(true)
expect(buildWalkthroughOutline(input, 0).outline.length).toBeLessThanOrEqual(WALKTHROUGH_DIFF_MAX_CHARS)
})
it('bounds the included hunks and omits the remaining files as budget', () => {
const input = buildWalkthroughInput(
Array.from({ length: 200 }, (_, index) => change(`src/f${index}.ts`, longPatch(6, index * 6))),
)
const { hunks, omittedFiles, outline } = buildWalkthroughOutline(input, 0)
expect(hunks.length).toBeLessThan(input.hunks.length)
expect(omittedFiles.filter((file) => file.reason === 'budget').length).toBeGreaterThan(0)
expect(omittedFiles.every((file) => file.reason === 'budget')).toBe(true)
expect(outline.length).toBeLessThanOrEqual(WALKTHROUGH_DIFF_MAX_CHARS)
})
it('never half-includes a file', () => {
const input = buildWalkthroughInput([
change('src/small.ts', hunkPatch(1)),
change('src/huge.ts', longPatch(2000)),
])
const { outline } = buildWalkthroughOutline(input, 0)
const hugeIds = input.hunks.filter((hunk) => hunk.file === 'src/huge.ts').map((hunk) => hunk.id)
expect(hugeIds.length).toBeGreaterThan(0)
expect(hugeIds.every((id) => !outline.includes(id))).toBe(true)
})
it('keeps the outline within budget for many small hunks behind a very long path', () => {
const longPath = `src/${'p'.repeat(996)}.ts`
const manyHunks = Array.from(
{ length: 300 },
(_, index) => `@@ -${index + 1} +${index + 1} @@\n+line${index}`,
).join('\n')
const input = buildWalkthroughInput([
change('src/small.ts', hunkPatch(1)),
change(longPath, manyHunks),
])
const { hunks, omittedFiles, outline } = buildWalkthroughOutline(input, 0)
expect(hunks.length).toBeGreaterThan(0)
expect(omittedFiles).toEqual([{ file: longPath, reason: 'budget' }])
expect(outline.length).toBeLessThanOrEqual(WALKTHROUGH_DIFF_MAX_CHARS)
})
it('retries at a shallower preview depth so every file fits', () => {
const input = buildWalkthroughInput(
Array.from({ length: 70 }, (_, index) => change(`src/f${index}.ts`, longPatch(1, index))),
)
const { hunks, omittedFiles } = buildWalkthroughOutline(input, 0)
expect(omittedFiles).toEqual([])
expect(hunks).toHaveLength(70)
})
})
describe('formatWalkthroughOutline', () => {
it('renders the header, the mechanical listing and the outline', () => {
const changes = [change('src/a.ts', hunkPatch(1)), change('pnpm-lock.yaml', hunkPatch(2))]
const text = formatWalkthroughOutline({
title: 'My session',
sourceDescription: 'the changes in this session',
changes,
})
expect(text).toContain('# My session')
expect(text).toContain('the changes in this session')
expect(text).toContain('2 files, 1 text hunks.')
expect(text).toContain("Call walkthrough_changes with { file } for a file's full hunks.")
expect(text).toContain('## Mechanical files')
expect(text).toContain('- pnpm-lock.yaml (modified, +1/-1)')
expect(text).toContain('## Outline')
expect(text).toContain(computeHunkId('src/a.ts', 'modified', hunkPatch(1)))
expect(text).not.toContain(hunkPatch(2))
})
it('lists omitted files with their reasons', () => {
const changes = [
change('assets/logo.png', 'diff --git a/assets/logo.png b/assets/logo.png\nBinary files differ'),
change(
'src/new.ts',
'diff --git a/src/old.ts b/src/new.ts\nsimilarity index 100%\nrename from src/old.ts\nrename to src/new.ts',
),
]
const text = formatWalkthroughOutline({
title: 'My session',
sourceDescription: 'the changes in this session',
changes,
})
expect(text).toContain('## Omitted files')
expect(text).toContain('- assets/logo.png (binary)')
expect(text).toContain('- src/new.ts (renamed)')
})
it('never exceeds the budget plus the truncation marker', () => {
const changes = Array.from(
{ length: 4000 },
(_, index) => change(`src/f${index}.ts`, longPatch(3, index * 3)),
)
const text = formatWalkthroughOutline({
title: 'My session',
sourceDescription: 'the changes in this session',
changes,
})
expect(text.length).toBeLessThanOrEqual(WALKTHROUGH_DIFF_MAX_CHARS + '\n[output truncated]'.length)
})
})
describe('formatWalkthroughFileChanges', () => {
it('returns the full hunks for a known file', () => {
const changes = [
change('src/a.ts', `${hunkPatch(1)}\n${hunkPatch(10)}`),
change('src/b.ts', hunkPatch(20)),
]
const text = formatWalkthroughFileChanges(changes, 'src/a.ts')!
expect(text).toContain(hunkPatch(1))
expect(text).toContain(hunkPatch(10))
expect(text).not.toContain(hunkPatch(20))
expect(text).toContain('```diff')
expect(text).toContain(formatHunkBlock(hunkFixture('src/a.ts', hunkPatch(1))))
})
it('returns null for an unknown file', () => {
const changes = [change('src/a.ts', hunkPatch(1))]
expect(formatWalkthroughFileChanges(changes, 'src/nope.ts')).toBeNull()
})
it('returns the text of a mechanical file within the budget', () => {
const changes = [change('pnpm-lock.yaml', hunkPatch(1))]
const text = formatWalkthroughFileChanges(changes, 'pnpm-lock.yaml')!
expect(text).toContain(hunkPatch(1))
expect(text).toContain('```diff')
})
it('returns a counts-only line for an oversized mechanical file', () => {
const oversized = Array.from({ length: 40 }, (_, index) => bigHunk(index)).join('\n')
const changes = [
{ file: 'pnpm-lock.yaml', patch: oversized, additions: 1200, deletions: 800, status: 'modified' },
] as FileDiffInfo[]
const text = formatWalkthroughFileChanges(changes, 'pnpm-lock.yaml')!
expect(text).toBe('pnpm-lock.yaml (modified, +1200/-800)')
expect(text).not.toContain('@@')
})
it('truncates to the budget plus the truncation marker', () => {
const changes = [change('src/a.ts', longPatch(2000))]
const text = formatWalkthroughFileChanges(changes, 'src/a.ts')!
expect(text.length).toBe(WALKTHROUGH_DIFF_MAX_CHARS + '\n[output truncated]'.length)
expect(text.endsWith('\n[output truncated]')).toBe(true)
})
})
-95
View File
@@ -1,95 +0,0 @@
import { describe, expect, it } from 'vitest'
import { createLimiter, mapWithConcurrency } from '../../src/utils/concurrency'
describe('mapWithConcurrency', () => {
it('keeps result order', async () => {
const result = await mapWithConcurrency([1, 2, 3, 4, 5], 2, async (item) => item * 2)
expect(result).toEqual([2, 4, 6, 8, 10])
})
it('runs at most limit calls at once', async () => {
let inFlight = 0
let maxInFlight = 0
await mapWithConcurrency([1, 2, 3, 4, 5, 6], 2, async (item) => {
inFlight += 1
maxInFlight = Math.max(maxInFlight, inFlight)
await new Promise((resolve) => setTimeout(resolve, 1))
inFlight -= 1
return item
})
expect(maxInFlight).toBe(2)
})
it('propagates a rejection', async () => {
await expect(
mapWithConcurrency([1, 2, 3], 2, async (item) => {
if (item === 2) {
throw new Error('boom')
}
return item
}),
).rejects.toThrow('boom')
})
it('passes the index to the callback', async () => {
const result = await mapWithConcurrency(['a', 'b'], 2, async (item, index) => `${item}${index}`)
expect(result).toEqual(['a0', 'b1'])
})
})
describe('createLimiter', () => {
it('runs at most limit tasks at once', async () => {
const limiter = createLimiter(2)
let inFlight = 0
let maxInFlight = 0
const task = async (value: number): Promise<number> => {
inFlight += 1
maxInFlight = Math.max(maxInFlight, inFlight)
await new Promise((resolve) => setTimeout(resolve, 1))
inFlight -= 1
return value
}
const results = await Promise.all([1, 2, 3, 4, 5].map((value) => limiter.run(() => task(value))))
expect(results).toEqual([1, 2, 3, 4, 5])
expect(maxInFlight).toBe(2)
expect(limiter.activeCount).toBe(0)
})
it('queues tasks beyond the limit until a slot frees', async () => {
const limiter = createLimiter(1)
const order: string[] = []
let releaseFirst: () => void = () => {}
const first = limiter.run(async () => {
order.push('first')
await new Promise<void>((resolve) => {
releaseFirst = resolve
})
})
const second = limiter.run(async () => {
order.push('second')
})
await new Promise((resolve) => setTimeout(resolve, 0))
expect(order).toEqual(['first'])
releaseFirst()
await Promise.all([first, second])
expect(order).toEqual(['first', 'second'])
})
it('releases the slot when a task rejects', async () => {
const limiter = createLimiter(1)
await expect(limiter.run(async () => {
throw new Error('boom')
})).rejects.toThrow('boom')
await expect(limiter.run(async () => 'ok')).resolves.toBe('ok')
expect(limiter.activeCount).toBe(0)
})
})
+15 -8
View File
@@ -3,8 +3,8 @@ import { API_BASE_URL } from '@/config'
import { walkthroughSourceKey } from '@opencode-manager/shared/schemas'
import type {
ChangeWalkthroughState,
ChangeWalkthroughStateWire,
GenerateChangeWalkthroughRequest,
RefineChangeWalkthroughRequest,
WalkthroughSource,
} from '@opencode-manager/shared/schemas'
@@ -15,13 +15,9 @@ function walkthroughUrl(sessionId: string): string {
export async function getChangeWalkthrough(
sessionId: string,
source: WalkthroughSource,
hunksFor?: string,
): Promise<ChangeWalkthroughStateWire> {
return fetchWrapper<ChangeWalkthroughStateWire>(walkthroughUrl(sessionId), {
params: {
source: walkthroughSourceKey(source),
...(hunksFor === undefined ? {} : { hunksFor }),
},
): Promise<ChangeWalkthroughState> {
return fetchWrapper<ChangeWalkthroughState>(walkthroughUrl(sessionId), {
params: { source: walkthroughSourceKey(source) },
})
}
@@ -36,6 +32,17 @@ export async function generateChangeWalkthrough(
})
}
export async function refineChangeWalkthrough(
sessionId: string,
request: RefineChangeWalkthroughRequest,
): Promise<ChangeWalkthroughState> {
return fetchWrapper<ChangeWalkthroughState>(`${walkthroughUrl(sessionId)}/refine`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(request),
})
}
export async function cancelChangeWalkthrough(
sessionId: string,
source: WalkthroughSource,
@@ -5,6 +5,7 @@ import type { FileInfo } from '@/types/files'
import { getFileApiUrl } from '@/api/files'
import { saveFileFromUrl } from '@/lib/download'
import { VirtualizedTextView, type VirtualizedTextViewHandle } from '@/components/ui/virtualized-text-view'
import { SandboxedHtmlFrame } from '@/components/ui/sandboxed-html-frame'
import { MarkdownRenderer } from './MarkdownRenderer'
@@ -234,14 +235,7 @@ export const FilePreview = memo(function FilePreview({ file, hideHeader = false,
}
if (showHtmlPreview) {
return (
<iframe
src={rawFileUrl}
title={file.name}
sandbox="allow-scripts"
className="w-full h-full border-0 bg-white"
/>
)
return <SandboxedHtmlFrame src={rawFileUrl} title={file.name} className="h-full" />
}
if (shouldVirtualize && isTextFile) {
@@ -1,6 +1,7 @@
import { memo, useState } from 'react'
import { AppWindow, ExternalLink, RotateCw } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { SandboxedHtmlFrame } from '@/components/ui/sandboxed-html-frame'
interface ArtifactPartProps {
title: string
@@ -46,15 +47,7 @@ export const ArtifactPart = memo(function ArtifactPart({ title, src, path }: Art
</a>
</Button>
</div>
<iframe
key={reloadKey}
src={src}
title={title}
sandbox="allow-scripts"
loading="lazy"
referrerPolicy="no-referrer"
className="block w-full h-[480px] border-0 bg-white"
/>
<SandboxedHtmlFrame src={src} title={title} reloadKey={reloadKey} className="h-[480px]" />
</div>
)
})
@@ -25,10 +25,9 @@ vi.mock('@/components/repo/RepoActionsDialog', () => ({ RepoActionsContent: () =
vi.mock('@/components/repo/RepoSkillsDialog', () => ({ RepoSkillsContent: () => <div>skills-tool</div> }))
vi.mock('@/components/session/ChangesWalkthroughSheet', () => ({
ChangesWalkthroughProvider: ({ children }: { children: ReactNode }) => <>{children}</>,
ChangesWalkthroughNav: () => null,
ChangesWalkthroughRegenerate: () => null,
ChangesWalkthroughSourcePicker: () => null,
ChangesWalkthroughStop: () => null,
ChangesWalkthroughCancel: () => null,
ChangesWalkthroughView: () => <div>walkthrough-tool</div>,
}))
@@ -5,11 +5,10 @@ import { FileBrowser } from '@/components/file-browser/FileBrowser'
import { SourceControlContent } from '@/components/source-control'
import { TerminalWorkspace } from '@/components/terminal/TerminalPanel'
import {
ChangesWalkthroughNav,
ChangesWalkthroughCancel,
ChangesWalkthroughProvider,
ChangesWalkthroughRegenerate,
ChangesWalkthroughSourcePicker,
ChangesWalkthroughStop,
ChangesWalkthroughView,
type WalkthroughSourceRequest,
} from '@/components/session/ChangesWalkthroughSheet'
@@ -41,6 +40,7 @@ interface ToolSidePanelProps {
onSkillLoaded?: (skill: SkillFileInfo) => void
walkthroughSourceRequest?: WalkthroughSourceRequest
walkthroughModel?: ModelRef | null
walkthroughOnOpenSession?: (id: string) => void
}
interface RailButtonProps {
@@ -96,6 +96,7 @@ export function ToolSidePanel({
onSkillLoaded,
walkthroughSourceRequest,
walkthroughModel,
walkthroughOnOpenSession,
}: ToolSidePanelProps) {
const { activeTool, toggleTool, closePanel } = panel
const location = useLocation()
@@ -176,9 +177,8 @@ export function ToolSidePanel({
{activeTool === 'walkthrough' ? (
<>
<ChangesWalkthroughSourcePicker />
<ChangesWalkthroughStop />
<ChangesWalkthroughCancel />
<ChangesWalkthroughRegenerate />
<ChangesWalkthroughNav />
</>
) : null}
<button
@@ -204,6 +204,7 @@ export function ToolSidePanel({
active
sourceRequest={walkthroughSourceRequest}
model={walkthroughModel}
onOpenSession={walkthroughOnOpenSession}
>
{panelContent}
</ChangesWalkthroughProvider>
@@ -258,6 +258,7 @@ export function MultiRunSheet({ repoId, directory, defaultBaseRef, open, onOpenC
onOpenChange={(next) => {
if (!next) setWalkthroughSessionId(null)
}}
onOpenSession={(id) => navigate(buildSessionPath(repoId, id))}
/>
) : null}
</>
@@ -10,110 +10,43 @@ import type { ChangeWalkthrough, ChangeWalkthroughState } from '@opencode-manage
const mocks = vi.hoisted(() => ({
getChangeWalkthrough: vi.fn(),
generateChangeWalkthrough: vi.fn(),
refineChangeWalkthrough: vi.fn(),
cancelChangeWalkthrough: vi.fn(),
}))
vi.mock('@/api/changeWalkthroughs', () => ({
getChangeWalkthrough: mocks.getChangeWalkthrough,
generateChangeWalkthrough: mocks.generateChangeWalkthrough,
refineChangeWalkthrough: mocks.refineChangeWalkthrough,
cancelChangeWalkthrough: mocks.cancelChangeWalkthrough,
}))
const artifactPath = '/workspace/walkthroughs/ses_1/gen/index.html'
const walkthrough: ChangeWalkthrough = {
sessionId: 'ses_1',
source: { kind: 'session' },
diffHash: 'hash-1',
walkthroughSessionId: 'ses_walk',
status: 'ready',
artifactPath,
publishedAt: 1000,
executionStartedAt: null,
error: null,
model: null,
summary: 'This change adds a greeting.',
stops: [
{
id: 's_greet',
title: 'Add the greeting',
explanation: 'Introduces the greeting helper.',
hunkIds: ['f0h0'],
status: 'ready',
explanationKey: null,
},
{
id: 's_wire',
title: 'Wire it up',
explanation: 'Calls the helper from the entry point.',
hunkIds: ['f1h0'],
status: 'ready',
explanationKey: null,
},
],
hunks: [
{
id: 'f0h0',
file: 'src/greet.ts',
status: 'modified',
header: '@@ -1 +1 @@',
text: '@@ -1 +1 @@\n-const a = 1\n+const a = 2',
truncated: false,
},
{
id: 'f1h0',
file: 'src/main.ts',
status: 'added',
header: '@@ -0,0 +1 @@',
text: '@@ -0,0 +1 @@\n+const b = 3',
truncated: true,
},
],
omittedFiles: [{ file: 'assets/logo.png', reason: 'binary' }],
createdAt: 1,
updatedAt: 2,
}
const mechanicalWalkthrough: ChangeWalkthrough = {
const generatingWalkthrough: ChangeWalkthrough = {
...walkthrough,
stops: [
{
id: 's_mech',
title: 'Mechanical changes',
explanation: 'Lock files, snapshots and generated files.',
hunkIds: ['m_lock', 'm_snap', 'm_map'],
status: 'ready',
explanationKey: null,
},
],
hunks: [
{
id: 'm_lock',
file: 'pnpm-lock.yaml',
status: 'modified',
header: '@@ -1 +1 @@',
text: '@@ -1 +1 @@\n-old-lock\n+new-lock',
truncated: false,
additions: 120,
deletions: 80,
},
{
id: 'm_snap',
file: 'src/__snapshots__/a.ts.snap',
status: 'added',
header: '',
text: '',
truncated: true,
additions: 5,
deletions: 0,
},
{
id: 'm_map',
file: 'dist/app.js.map',
status: 'deleted',
header: '',
text: '',
truncated: true,
additions: 0,
deletions: 7,
},
],
omittedFiles: [],
status: 'generating',
artifactPath: null,
publishedAt: null,
}
function state(overrides: Partial<ChangeWalkthroughState> = {}): ChangeWalkthroughState {
return { walkthrough, currentDiffHash: 'hash-1', stale: false, generating: false, error: null, ...overrides }
return { walkthrough, currentDiffHash: 'hash-1', stale: false, generating: false, running: false, error: null, ...overrides }
}
function createWrapper() {
@@ -145,7 +78,7 @@ describe('ChangesWalkthroughSheet', () => {
vi.clearAllMocks()
})
it('generates a walkthrough and opens on the overview page', async () => {
it('offers to generate a walkthrough and starts a walkthrough session', async () => {
const user = userEvent.setup()
let generated = false
mocks.getChangeWalkthrough.mockImplementation(async () =>
@@ -157,18 +90,12 @@ describe('ChangesWalkthroughSheet', () => {
})
renderSheet()
const generate = await screen.findByRole('button', { name: 'Generate walkthrough' })
await user.click(generate)
await user.click(await screen.findByRole('button', { name: 'Generate walkthrough' }))
await waitFor(() => {
expect(mocks.generateChangeWalkthrough).toHaveBeenCalledWith('ses_1', { source: { kind: 'session' } })
})
expect(await screen.findByText('This change adds a greeting.')).toBeInTheDocument()
expect(screen.getByText('Overview')).toBeInTheDocument()
expect(screen.getByRole('button', { name: '1. Add the greeting' })).toBeInTheDocument()
expect(screen.getByRole('button', { name: '2. Wire it up' })).toBeInTheDocument()
expect(screen.queryByText('src/greet.ts')).not.toBeInTheDocument()
expect(screen.getByText('assets/logo.png — binary file')).toBeInTheDocument()
expect(await screen.findByTitle('Change walkthrough')).toHaveAttribute('sandbox', 'allow-scripts')
})
it('generates with the selected model', async () => {
@@ -187,69 +114,102 @@ describe('ChangesWalkthroughSheet', () => {
})
})
it('opens a stop from the overview list without the summary or list', async () => {
it('shows the building status and opens the walkthrough session while generating', async () => {
const user = userEvent.setup()
const onOpenSession = vi.fn()
mocks.getChangeWalkthrough.mockResolvedValue(state({ generating: true, walkthrough: generatingWalkthrough }))
mocks.cancelChangeWalkthrough.mockResolvedValue(undefined)
renderSheet({ onOpenSession })
expect(await screen.findByText('Building the walkthrough in a separate session…')).toBeInTheDocument()
await user.click(screen.getByRole('button', { name: 'Open walkthrough session' }))
expect(onOpenSession).toHaveBeenCalledWith('ses_walk')
await user.click(screen.getByRole('button', { name: 'Stop generating walkthrough' }))
await waitFor(() => {
expect(mocks.cancelChangeWalkthrough).toHaveBeenCalledWith('ses_1', { kind: 'session' })
})
})
it('does not show a stop button when idle', async () => {
mocks.getChangeWalkthrough.mockResolvedValue(state())
renderSheet()
await user.click(await screen.findByRole('button', { name: '2. Wire it up' }))
expect(await screen.findByText('2 of 2')).toBeInTheDocument()
expect(screen.getByText('src/main.ts')).toBeInTheDocument()
expect(screen.queryByText('This change adds a greeting.')).not.toBeInTheDocument()
expect(screen.queryByRole('button', { name: '1. Add the greeting' })).not.toBeInTheDocument()
await screen.findByRole('button', { name: 'Regenerate walkthrough' })
expect(screen.queryByRole('button', { name: 'Stop generating walkthrough' })).not.toBeInTheDocument()
})
it('jumps between pages from the header dropdown', async () => {
it('keeps the stop control and hides the refine form while a published walkthrough is still running', async () => {
const user = userEvent.setup()
mocks.getChangeWalkthrough.mockResolvedValue(state({ running: true }))
mocks.cancelChangeWalkthrough.mockResolvedValue(undefined)
renderSheet()
expect(await screen.findByTitle('Change walkthrough')).toBeInTheDocument()
expect(screen.getByText('Refining…')).toBeInTheDocument()
expect(screen.queryByLabelText('Refine walkthrough')).not.toBeInTheDocument()
await user.click(screen.getByRole('button', { name: 'Stop generating walkthrough' }))
await waitFor(() => {
expect(mocks.cancelChangeWalkthrough).toHaveBeenCalledWith('ses_1', { kind: 'session' })
})
})
it('shows the refine form and no stop control once the execution ends', async () => {
mocks.getChangeWalkthrough.mockResolvedValue(state())
renderSheet()
await user.click(await screen.findByRole('button', { name: '1. Add the greeting' }))
expect(await screen.findByText('1 of 2')).toBeInTheDocument()
await user.click(screen.getByRole('button', { name: 'Jump to page' }))
await user.click(await screen.findByRole('menuitemradio', { name: '2. Wire it up' }))
expect(await screen.findByText('2 of 2')).toBeInTheDocument()
expect(screen.getByText('src/main.ts')).toBeInTheDocument()
await user.click(screen.getByRole('button', { name: 'Jump to page' }))
await user.click(await screen.findByRole('menuitemradio', { name: 'Overview' }))
expect(await screen.findByText('This change adds a greeting.')).toBeInTheDocument()
expect(await screen.findByLabelText('Refine walkthrough')).toBeInTheDocument()
expect(screen.queryByRole('button', { name: 'Stop generating walkthrough' })).not.toBeInTheDocument()
expect(screen.queryByText('Refining…')).not.toBeInTheDocument()
})
it('moves through the overview and stops with the navigator in order', async () => {
const user = userEvent.setup()
it('renders the published artifact in a sandboxed iframe with the raw file source', async () => {
mocks.getChangeWalkthrough.mockResolvedValue(state())
renderSheet()
expect(await screen.findByText('Overview')).toBeInTheDocument()
expect(screen.getByRole('button', { name: /previous/i })).toBeDisabled()
const frame = await screen.findByTitle('Change walkthrough')
expect(frame.tagName).toBe('IFRAME')
expect(frame).toHaveAttribute('sandbox', 'allow-scripts')
expect(frame.getAttribute('sandbox')).not.toContain('allow-same-origin')
await user.click(screen.getByRole('button', { name: /next/i }))
expect(await screen.findByText('1 of 2')).toBeInTheDocument()
expect(screen.getByText('src/greet.ts')).toBeInTheDocument()
expect(screen.getByText('const a = 2')).toBeInTheDocument()
expect(screen.queryByText('This change adds a greeting.')).not.toBeInTheDocument()
await user.click(screen.getByRole('button', { name: /next/i }))
expect(await screen.findByText('2 of 2')).toBeInTheDocument()
expect(screen.getByText('src/main.ts')).toBeInTheDocument()
expect(screen.queryByText('src/greet.ts')).not.toBeInTheDocument()
expect(screen.getByText('truncated')).toBeInTheDocument()
expect(screen.getByRole('button', { name: /next/i })).toBeDisabled()
await user.click(screen.getByRole('button', { name: /previous/i }))
expect(await screen.findByText('1 of 2')).toBeInTheDocument()
await user.click(screen.getByRole('button', { name: /previous/i }))
expect(await screen.findByText('Overview')).toBeInTheDocument()
expect(screen.getByText('This change adds a greeting.')).toBeInTheDocument()
const src = frame.getAttribute('src') ?? ''
expect(src).toContain('/api/files?')
expect(src).toContain('raw=true')
expect(src).toContain(encodeURIComponent(artifactPath))
})
it('updates a stale walkthrough incrementally', async () => {
it('renders no stop list or page navigation', async () => {
mocks.getChangeWalkthrough.mockResolvedValue(state())
renderSheet()
await screen.findByTitle('Change walkthrough')
expect(screen.queryByRole('button', { name: 'Jump to page' })).not.toBeInTheDocument()
expect(screen.queryByRole('button', { name: /previous/i })).not.toBeInTheDocument()
expect(screen.queryByRole('button', { name: /next/i })).not.toBeInTheDocument()
expect(screen.queryByRole('list')).not.toBeInTheDocument()
})
it('refines a published walkthrough through the walkthrough session', async () => {
const user = userEvent.setup()
mocks.getChangeWalkthrough.mockResolvedValue(state())
mocks.refineChangeWalkthrough.mockResolvedValue(state({ generating: true }))
renderSheet()
const textarea = await screen.findByLabelText('Refine walkthrough')
await user.type(textarea, 'tighten the introduction')
await user.click(screen.getByRole('button', { name: 'Send' }))
await waitFor(() => {
expect(mocks.refineChangeWalkthrough).toHaveBeenCalledWith('ses_1', {
source: { kind: 'session' },
text: 'tighten the introduction',
})
})
})
it('updates a stale walkthrough', async () => {
const user = userEvent.setup()
mocks.getChangeWalkthrough.mockResolvedValue(state({ stale: true, currentDiffHash: 'hash-2' }))
mocks.generateChangeWalkthrough.mockResolvedValue(state({ generating: true }))
@@ -272,7 +232,7 @@ describe('ChangesWalkthroughSheet', () => {
mocks.generateChangeWalkthrough.mockResolvedValue(state())
renderSheet()
await screen.findByText('Overview')
await screen.findByTitle('Change walkthrough')
await user.click(screen.getByRole('button', { name: 'Regenerate walkthrough' }))
await waitFor(() => {
@@ -283,28 +243,6 @@ describe('ChangesWalkthroughSheet', () => {
})
})
it('stops an in-flight generation from the header', async () => {
const user = userEvent.setup()
mocks.getChangeWalkthrough.mockResolvedValue(state({ generating: true }))
mocks.cancelChangeWalkthrough.mockResolvedValue(undefined)
renderSheet()
const stop = await screen.findByRole('button', { name: 'Stop generating walkthrough' })
await user.click(stop)
await waitFor(() => {
expect(mocks.cancelChangeWalkthrough).toHaveBeenCalledWith('ses_1', { kind: 'session' })
})
})
it('does not show a stop button when idle', async () => {
mocks.getChangeWalkthrough.mockResolvedValue(state())
renderSheet()
await screen.findByText('Overview')
expect(screen.queryByRole('button', { name: 'Stop generating walkthrough' })).not.toBeInTheDocument()
})
it('switches to staged changes', async () => {
const user = userEvent.setup()
mocks.getChangeWalkthrough.mockResolvedValue(state({ walkthrough: null }))
@@ -530,126 +468,25 @@ describe('ChangesWalkthroughSheet', () => {
expect(await screen.findByRole('button', { name: 'Generate walkthrough' })).toBeVisible()
})
it('scrolls back to the top of the overview when a walkthrough is regenerated', async () => {
const user = userEvent.setup()
const scrollTo = vi.spyOn(Element.prototype, 'scrollTo')
let createdAt = 1
mocks.getChangeWalkthrough.mockImplementation(async () => state({ walkthrough: { ...walkthrough, createdAt } }))
mocks.generateChangeWalkthrough.mockImplementation(async () => {
createdAt = 2
return state({ walkthrough: { ...walkthrough, createdAt } })
})
renderSheet()
await user.click(await screen.findByRole('button', { name: '1. Add the greeting' }))
expect(await screen.findByText('1 of 2')).toBeInTheDocument()
scrollTo.mockClear()
await user.click(screen.getByRole('button', { name: 'Regenerate walkthrough' }))
await waitFor(() => expect(scrollTo).toHaveBeenCalledWith({ top: 0 }))
expect(await screen.findByText('Overview')).toBeInTheDocument()
})
it('shows a skeleton and planning status while the server is generating without stops', async () => {
mocks.getChangeWalkthrough.mockResolvedValue(state({ walkthrough: null, generating: true }))
renderSheet()
expect(await screen.findByText('Planning the walkthrough…')).toBeInTheDocument()
expect(screen.getByTestId('walkthrough-skeleton')).toHaveAttribute('aria-hidden', 'true')
expect(screen.queryByRole('button', { name: 'Generate walkthrough' })).not.toBeInTheDocument()
expect(screen.queryByText(/Generating walkthrough/)).not.toBeInTheDocument()
})
it('shows a skeleton while the walkthrough state is loading', async () => {
it('shows a loading status while the walkthrough state is loading', async () => {
mocks.getChangeWalkthrough.mockImplementation(() => new Promise(() => {}))
renderSheet()
expect(await screen.findByText('Loading the walkthrough…')).toBeInTheDocument()
expect(screen.getByTestId('walkthrough-skeleton')).toBeInTheDocument()
})
it('shows a stop body skeleton while its explanation is pending', async () => {
const user = userEvent.setup()
mocks.getChangeWalkthrough.mockResolvedValue(
state({
generating: true,
walkthrough: {
...walkthrough,
stops: [
{ ...walkthrough.stops[0], status: 'ready' },
{ ...walkthrough.stops[1], status: 'pending', explanation: '' },
],
},
}),
)
renderSheet()
await user.click(await screen.findByRole('button', { name: /2\. Wire it up/ }))
expect(await screen.findByText('Explaining this stop…')).toBeInTheDocument()
expect(screen.getByTestId('walkthrough-skeleton')).toBeInTheDocument()
})
it('renders ready and pending stops while generating', async () => {
const user = userEvent.setup()
mocks.getChangeWalkthrough.mockResolvedValue(
state({
generating: true,
walkthrough: {
...walkthrough,
stops: [
{ ...walkthrough.stops[0], status: 'ready' },
{ ...walkthrough.stops[1], status: 'pending', explanation: '' },
],
},
}),
)
renderSheet()
expect(await screen.findByText(/1 of 2 stops explained/)).toBeInTheDocument()
expect(screen.getByRole('button', { name: '1. Add the greeting' })).toBeInTheDocument()
expect(screen.getByLabelText('Explaining')).toBeInTheDocument()
await user.click(screen.getByRole('button', { name: '1. Add the greeting' }))
expect(await screen.findByText('Introduces the greeting helper.')).toBeInTheDocument()
})
it('retries unexplained stops', async () => {
const user = userEvent.setup()
mocks.getChangeWalkthrough.mockResolvedValue(
state({
walkthrough: {
...walkthrough,
stops: [
{ ...walkthrough.stops[0], status: 'failed', explanation: '' },
{ ...walkthrough.stops[1], status: 'ready' },
],
},
}),
)
mocks.generateChangeWalkthrough.mockResolvedValue(state({ generating: true }))
renderSheet()
await user.click(await screen.findByRole('button', { name: /1\. Add the greeting/ }))
expect(await screen.findByText('This stop could not be explained.')).toBeInTheDocument()
await user.click(screen.getByRole('button', { name: 'Retry unexplained stops' }))
await waitFor(() => {
expect(mocks.generateChangeWalkthrough).toHaveBeenCalledWith('ses_1', { source: { kind: 'session' } })
})
})
it('renders a generation failure recorded by the server', async () => {
mocks.getChangeWalkthrough.mockResolvedValue(
state({
walkthrough: null,
error: { message: 'The model did not return a usable change walkthrough', code: 'WALKTHROUGH_UNPARSEABLE' },
error: { message: 'The walkthrough session did not publish within 15 minutes', code: 'WALKTHROUGH_TIMEOUT' },
}),
)
renderSheet()
expect(await screen.findByText('The model did not return a usable change walkthrough')).toBeInTheDocument()
expect(
await screen.findByText('The walkthrough session did not publish within 15 minutes'),
).toBeInTheDocument()
expect(screen.getByRole('button', { name: 'Generate walkthrough' })).toBeEnabled()
})
@@ -679,129 +516,6 @@ describe('ChangesWalkthroughSheet', () => {
expect(await screen.findByText('model exploded')).toBeInTheDocument()
})
it('lists the omitted files when the diff is too large to walk through', async () => {
const user = userEvent.setup()
mocks.getChangeWalkthrough.mockResolvedValue(state({ walkthrough: null, currentDiffHash: null }))
mocks.generateChangeWalkthrough.mockRejectedValue(
new FetchError('These changes are too large to walk through', 413, 'WALKTHROUGH_CONTEXT_LIMIT', undefined, {
details: {
omittedFiles: [
{ file: 'src/big.ts', reason: 'budget' },
{ file: 'assets/logo.png', reason: 'binary' },
],
},
}),
)
renderSheet()
await user.click(await screen.findByRole('button', { name: 'Generate walkthrough' }))
expect(await screen.findByText('These changes are too large to walk through')).toBeInTheDocument()
expect(screen.getByText('src/big.ts — over the diff budget')).toBeInTheDocument()
expect(screen.getByText('assets/logo.png — binary file')).toBeInTheDocument()
})
it('labels renamed and mode-change omitted files', async () => {
mocks.getChangeWalkthrough.mockResolvedValue(
state({
walkthrough: {
...walkthrough,
omittedFiles: [
{ file: 'src/old.ts', reason: 'renamed' },
{ file: 'script.sh', reason: 'modeChange' },
],
},
}),
)
renderSheet()
expect(await screen.findByText('src/old.ts — renamed')).toBeInTheDocument()
expect(screen.getByText('script.sh — mode change')).toBeInTheDocument()
})
it('renders mechanical files as a compact summary list with counts and diff text for budgeted hunks', async () => {
const user = userEvent.setup()
mocks.getChangeWalkthrough.mockResolvedValue(state({ walkthrough: mechanicalWalkthrough }))
renderSheet()
await user.click(await screen.findByRole('button', { name: '1. Mechanical changes' }))
expect(
await screen.findByRole('list', { name: 'Mechanical file summaries' }),
).toBeInTheDocument()
expect(screen.getByText('pnpm-lock.yaml')).toBeInTheDocument()
expect(screen.getByText('src/__snapshots__/a.ts.snap')).toBeInTheDocument()
expect(screen.getByText('dist/app.js.map')).toBeInTheDocument()
expect(screen.getByText('+120')).toBeInTheDocument()
expect(screen.getByText('-80')).toBeInTheDocument()
expect(screen.getByText('+5')).toBeInTheDocument()
expect(screen.getByText('-7')).toBeInTheDocument()
expect(screen.getByText('new-lock')).toBeInTheDocument()
})
it('renders a stored mechanical stop whose hunks predate hunk counts', async () => {
const user = userEvent.setup()
mocks.getChangeWalkthrough.mockResolvedValue(
state({
walkthrough: {
...walkthrough,
stops: [
{
id: 's_mech',
title: 'Mechanical changes',
explanation: 'Lock files',
hunkIds: ['m_lock'],
status: 'ready',
explanationKey: null,
},
],
hunks: [
{
id: 'm_lock',
file: 'pnpm-lock.yaml',
status: 'modified',
header: '@@ -1 +1 @@',
text: '@@ -1 +1 @@\n-old-lock\n+new-lock',
truncated: false,
},
],
omittedFiles: [],
},
}),
)
renderSheet()
await user.click(await screen.findByRole('button', { name: '1. Mechanical changes' }))
expect(await screen.findByText('pnpm-lock.yaml')).toBeInTheDocument()
expect(screen.getByText('new-lock')).toBeInTheDocument()
expect(screen.queryByRole('list', { name: 'Mechanical file summaries' })).not.toBeInTheDocument()
})
it('renders raw HTML in the summary and stop explanation as inert text', async () => {
const payload =
'<iframe srcdoc="&lt;script&gt;parent.document.documentElement.dataset.walkthroughProbe = 1&lt;/script&gt;"></iframe>'
mocks.getChangeWalkthrough.mockResolvedValue(
state({
walkthrough: {
...walkthrough,
summary: `Summary ${payload}`,
stops: [
{ id: 's_x', title: 'Stop', explanation: `Explanation ${payload}`, hunkIds: ['f0h0'], status: 'ready', explanationKey: null },
],
},
}),
)
const user = userEvent.setup()
const { container } = renderSheet()
expect(await screen.findByText(/Summary/)).toBeInTheDocument()
expect(container.querySelector('iframe')).toBeNull()
await user.click(screen.getByRole('button', { name: /next/i }))
expect(await screen.findByText(/Explanation/)).toBeInTheDocument()
expect(container.querySelector('iframe')).toBeNull()
expect(container.querySelector('script')).toBeNull()
expect(document.documentElement.dataset.walkthroughProbe).toBeUndefined()
})
it.each([
['WALKTHROUGH_NO_CHANGES', 'This session has no changes to walk through'],
['WALKTHROUGH_NO_TEXT_CHANGES', 'This session has no text changes to walk through'],
@@ -832,7 +546,7 @@ describe('ChangesWalkthroughSheet', () => {
await user.click(generate)
expect(await screen.findByText('This change adds a greeting.')).toBeInTheDocument()
expect(await screen.findByTitle('Change walkthrough')).toHaveAttribute('sandbox', 'allow-scripts')
expect(screen.queryByText(serverMessage)).not.toBeInTheDocument()
})
})
@@ -1,48 +1,32 @@
import { createContext, memo, useCallback, useContext, useEffect, useRef, useState } from 'react'
import type { ReactNode, RefObject } from 'react'
import { ChevronDown, ChevronLeft, ChevronRight, Loader2, RefreshCw, Square } from 'lucide-react'
import { createContext, memo, useCallback, useContext, useEffect, useState } from 'react'
import type { ReactNode } from 'react'
import { Loader2, RefreshCw, Square } from 'lucide-react'
import { SideDrawer, SideDrawerHeader } from '@/components/ui/side-drawer'
import { Button } from '@/components/ui/button'
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuRadioGroup,
DropdownMenuRadioItem,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu'
import { Badge } from '@/components/ui/badge'
import { Input } from '@/components/ui/input'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { DiffLines } from '@/components/file-browser/DiffLines'
import { ScheduleRunMarkdown } from '@/components/schedules/ScheduleRunMarkdown'
import { Textarea } from '@/components/ui/textarea'
import { SandboxedHtmlFrame } from '@/components/ui/sandboxed-html-frame'
import { getFileApiUrl } from '@/api/files'
import {
useCancelChangeWalkthrough,
useChangeWalkthrough,
useGenerateChangeWalkthrough,
useRefineChangeWalkthrough,
} from '@/hooks/useChangeWalkthrough'
import { GIT_STATUS_COLORS, GIT_STATUS_LABELS } from '@/lib/git-status-styles'
import { cn } from '@/lib/utils'
import {
DEFAULT_WALKTHROUGH_SOURCE,
describeWalkthroughSource,
toWalkthroughSource,
walkthroughSourceKey,
WalkthroughOmittedFileSchema,
} from '@opencode-manager/shared/schemas'
import type {
ChangeWalkthrough,
WalkthroughHunk,
WalkthroughOmittedFile,
WalkthroughSource,
WalkthroughStop,
WALKTHROUGH_REFINE_MAX_CHARS,
} from '@opencode-manager/shared/schemas'
import type { ChangeWalkthrough, WalkthroughSource } from '@opencode-manager/shared/schemas'
import { formatOpenCodeModelRef, type ModelRef } from '@opencode-manager/shared/opencode'
interface WalkthroughErrorLike {
message?: string
code?: string
details?: unknown
}
function errorCode(error: unknown): string | undefined {
@@ -54,20 +38,7 @@ function isNoChangesError(error: unknown): boolean {
return code === 'WALKTHROUGH_NO_CHANGES' || code === 'WALKTHROUGH_NO_TEXT_CHANGES'
}
function isContextLimitError(error: unknown): boolean {
return errorCode(error) === 'WALKTHROUGH_CONTEXT_LIMIT'
}
function omittedFilesFromError(error: unknown): WalkthroughOmittedFile[] {
const details = (error as { details?: { omittedFiles?: unknown } } | null)?.details
const parsed = WalkthroughOmittedFileSchema.array().safeParse(details?.omittedFiles)
return parsed.success ? parsed.data : []
}
function walkthroughErrorMessage(error: unknown): string {
if (isContextLimitError(error)) {
return 'These changes are too large to walk through'
}
const message = (error as WalkthroughErrorLike | null)?.message
if (isNoChangesError(error)) {
return message || 'This session has no text changes to walk through'
@@ -75,74 +46,20 @@ function walkthroughErrorMessage(error: unknown): string {
return message || 'Failed to load the walkthrough'
}
const OMITTED_REASON_LABELS: Record<WalkthroughOmittedFile['reason'], string> = {
binary: 'binary file',
budget: 'over the diff budget',
renamed: 'renamed',
modeChange: 'mode change',
}
function OmittedFiles({ files }: { files: WalkthroughOmittedFile[] }) {
return (
<div className="space-y-1 rounded-md border border-border bg-muted/20 p-3">
<p className="text-xs font-medium text-muted-foreground">Omitted files</p>
{files.map((omitted) => (
<p key={omitted.file} className="break-all text-xs text-muted-foreground">
{omitted.file} — {OMITTED_REASON_LABELS[omitted.reason]}
</p>
))}
</div>
)
}
function isMechanicalHunk(hunk: WalkthroughHunk): boolean {
return hunk.additions !== undefined || hunk.deletions !== undefined
}
function MechanicalHunks({ hunks }: { hunks: WalkthroughHunk[] }) {
return (
<ul aria-label="Mechanical file summaries" className="space-y-3">
{hunks.map((hunk) => (
<li key={hunk.id} className="overflow-hidden rounded-md border border-border">
<div className="flex items-center gap-2 px-3 py-1.5">
<span className="min-w-0 flex-1 truncate text-xs font-medium text-foreground" title={hunk.file}>
{hunk.file}
</span>
<span className={`text-xs ${GIT_STATUS_COLORS[hunk.status]}`}>
{GIT_STATUS_LABELS[hunk.status]}
</span>
<span className="text-xs text-diff-add">+{hunk.additions ?? 0}</span>
<span className="text-xs text-diff-delete">-{hunk.deletions ?? 0}</span>
</div>
{hunk.text.length > 0 ? (
<div className="overflow-x-auto border-t border-border">
<DiffLines diff={hunk.text} />
</div>
) : null}
</li>
))}
</ul>
)
}
interface ChangesWalkthroughContextValue {
isLoading: boolean
walkthrough: ChangeWalkthrough | null
stale: boolean
generating: boolean
running: boolean
error: unknown
contextLimitFiles: WalkthroughOmittedFile[]
generate: () => void
regenerate: () => void
stop: () => void
stopping: boolean
stops: WalkthroughStop[]
stopIndex: number | null
selectedStop: WalkthroughStop | null
selectedHunks: WalkthroughHunk[]
selectStop: (index: number | null) => void
scrollRef: RefObject<HTMLDivElement | null>
failedStopCount: number
refine: (text: string) => void
refining: boolean
onOpenSession?: (walkthroughSessionId: string) => void
source: WalkthroughSource
setSource: (source: WalkthroughSource) => void
sourceKind: WalkthroughSource['kind']
@@ -259,6 +176,7 @@ interface ChangesWalkthroughProviderProps {
active: boolean
sourceRequest?: WalkthroughSourceRequest
model?: ModelRef | null
onOpenSession?: (walkthroughSessionId: string) => void
children: ReactNode
}
@@ -268,6 +186,7 @@ export function ChangesWalkthroughProvider({
active,
sourceRequest,
model,
onOpenSession,
children,
}: ChangesWalkthroughProviderProps) {
const [source, setSource] = useState<WalkthroughSource>(DEFAULT_WALKTHROUGH_SOURCE)
@@ -278,17 +197,18 @@ export function ChangesWalkthroughProvider({
const stateQuery = useChangeWalkthrough(sessionId, active, source)
const generate = useGenerateChangeWalkthrough(sessionId, source)
const cancel = useCancelChangeWalkthrough(sessionId, source)
const refineMutation = useRefineChangeWalkthrough(sessionId, source)
const stop = useCallback(() => cancel.mutate(), [cancel])
const resetGenerate = generate.reset
const [stopIndex, setStopIndex] = useState<number | null>(null)
const scrollRef = useRef<HTMLDivElement>(null)
const resetRefine = refineMutation.reset
const state = stateQuery.data
const walkthrough = state?.walkthrough ?? null
const stale = state?.stale ?? false
const generating = generate.isPending || (state?.generating ?? false)
const error = generate.error ?? stateQuery.error ?? (generating ? null : state?.error ?? null)
const contextLimitFiles = isContextLimitError(error) ? omittedFilesFromError(error) : []
const generating = generate.isPending || refineMutation.isPending || (state?.generating ?? false)
const running = refineMutation.isPending || (state?.running ?? false)
const error =
generate.error ?? refineMutation.error ?? stateQuery.error ?? (generating ? null : state?.error ?? null)
const selectedSource = toWalkthroughSource({ kind: sourceKind, base: baseInput, number: Number(numberInput) })
const sourcePending =
@@ -297,12 +217,8 @@ export function ChangesWalkthroughProvider({
useEffect(() => {
resetGenerate()
}, [active, sessionId, sourceKey, resetGenerate])
useEffect(() => {
setStopIndex(null)
scrollRef.current?.scrollTo?.({ top: 0 })
}, [active, sessionId, sourceKey, walkthrough?.createdAt])
resetRefine()
}, [active, sessionId, sourceKey, resetGenerate, resetRefine])
useEffect(() => {
if (!sourceRequest) return
@@ -318,43 +234,22 @@ export function ChangesWalkthroughProvider({
}
}, [sourceRequest])
const hunksById = new Map(walkthrough?.hunks.map((hunk) => [hunk.id, hunk]) ?? [])
const stops = walkthrough?.stops ?? []
const clampedIndex = stopIndex === null || stops.length === 0 ? null : Math.min(stopIndex, stops.length - 1)
const selectedStop = clampedIndex === null ? null : stops[clampedIndex] ?? null
const selectedHunks = (selectedStop?.hunkIds ?? [])
.map((id) => hunksById.get(id))
.filter((hunk): hunk is WalkthroughHunk => hunk !== undefined)
const failedStopCount = stops.filter(
(stop) => stop.status === 'failed' || (stop.status === 'pending' && !generating),
).length
const modelRequest = model ? { model: formatOpenCodeModelRef(model) } : {}
const selectStop = useCallback((index: number | null) => {
setStopIndex(index)
scrollRef.current?.scrollTo?.({ top: 0 })
}, [])
const value: ChangesWalkthroughContextValue = {
isLoading: stateQuery.isLoading,
walkthrough,
stale,
generating,
running,
error,
contextLimitFiles,
generate: () => generate.mutate(modelRequest),
regenerate: () => generate.mutate({ ...modelRequest, regenerate: true }),
stop,
stopping: cancel.isPending,
stops,
stopIndex: clampedIndex,
selectedStop,
selectedHunks,
selectStop,
scrollRef,
failedStopCount,
refine: (text: string) => refineMutation.mutate(text),
refining: refineMutation.isPending,
onOpenSession,
source,
setSource,
sourceKind,
@@ -369,62 +264,11 @@ export function ChangesWalkthroughProvider({
return <ChangesWalkthroughContext.Provider value={value}>{children}</ChangesWalkthroughContext.Provider>
}
/** Previous/next page controls (overview, then each stop) for the walkthrough chrome; renders nothing until a walkthrough has stops. */
export const ChangesWalkthroughNav = memo(function ChangesWalkthroughNav() {
const { stops, stopIndex, selectStop } = useChangesWalkthrough()
/** Stops the in-flight walkthrough session from the chrome; renders nothing when the walkthrough is neither generating nor running. */
export const ChangesWalkthroughCancel = memo(function ChangesWalkthroughCancel() {
const { generating, running, stopping, stop } = useChangesWalkthrough()
if (stops.length === 0) return null
return (
<div className="flex shrink-0 items-center gap-1">
<Button
variant="outline"
size="icon-sm"
aria-label="Previous stop"
onClick={() => selectStop(stopIndex === null || stopIndex === 0 ? null : stopIndex - 1)}
disabled={stopIndex === null}
>
<ChevronLeft />
</Button>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="ghost" size="sm" aria-label="Jump to page" className="h-7 gap-1 px-2 text-xs text-muted-foreground">
{stopIndex === null ? 'Overview' : `${stopIndex + 1} of ${stops.length}`}
<ChevronDown className="h-3 w-3" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="max-h-[60vh] w-72 overflow-y-auto">
<DropdownMenuRadioGroup
value={stopIndex === null ? 'overview' : String(stopIndex)}
onValueChange={(value) => selectStop(value === 'overview' ? null : Number(value))}
>
<DropdownMenuRadioItem value="overview">Overview</DropdownMenuRadioItem>
<DropdownMenuSeparator />
{stops.map((stop, index) => (
<DropdownMenuRadioItem key={index} value={String(index)}>
{index + 1}. {stop.title}
</DropdownMenuRadioItem>
))}
</DropdownMenuRadioGroup>
</DropdownMenuContent>
</DropdownMenu>
<Button
variant="outline"
size="icon-sm"
aria-label="Next stop"
onClick={() => selectStop(stopIndex === null ? 0 : stopIndex + 1)}
disabled={stopIndex !== null && stopIndex >= stops.length - 1}
>
<ChevronRight />
</Button>
</div>
)
})
export const ChangesWalkthroughStop = memo(function ChangesWalkthroughStop() {
const { generating, stopping, stop } = useChangesWalkthrough()
if (!generating) return null
if (!generating && !running) return null
return (
<Button
@@ -460,67 +304,6 @@ export const ChangesWalkthroughRegenerate = memo(function ChangesWalkthroughRege
)
})
const SKELETON_BAR = 'rounded bg-muted animate-pulse motion-reduce:animate-none'
function WalkthroughSkeletonBar({ className }: { className?: string }) {
return <div className={cn(SKELETON_BAR, 'h-3.5', className)} />
}
function WalkthroughHunkSkeleton() {
const diffLineWidths = ['w-3/4', 'w-1/2', 'w-5/6', 'w-2/3', 'w-1/3', 'w-4/5']
return (
<div className="overflow-hidden rounded-md border border-border">
<div className="flex items-center gap-2 border-b border-border bg-muted/30 px-3 py-1.5">
<WalkthroughSkeletonBar className="h-3 w-2/5" />
<div className="ml-auto flex items-center gap-1.5">
<WalkthroughSkeletonBar className="h-3.5 w-10 rounded-full" />
<WalkthroughSkeletonBar className="h-3.5 w-6 rounded-full" />
<WalkthroughSkeletonBar className="h-3.5 w-6 rounded-full" />
</div>
</div>
<div className="space-y-1.5 p-3">
{diffLineWidths.map((width, row) => (
<div key={row} className="flex items-center gap-3">
<WalkthroughSkeletonBar className="h-3 w-6 shrink-0" />
<WalkthroughSkeletonBar className={cn('h-3', width)} />
</div>
))}
</div>
</div>
)
}
/** Placeholder that mirrors the walkthrough layout while it loads or generates; the overview variant adds the title and stop list. */
function WalkthroughSkeleton({ variant = 'overview' }: { variant?: 'overview' | 'body' }) {
return (
<div data-testid="walkthrough-skeleton" aria-hidden="true" className="space-y-4">
{variant === 'overview' ? <WalkthroughSkeletonBar className="h-4 w-1/3" /> : null}
<div className="space-y-2">
<WalkthroughSkeletonBar className="w-full" />
<WalkthroughSkeletonBar className="w-11/12" />
<WalkthroughSkeletonBar className="w-4/5" />
</div>
<div className="space-y-3">
<WalkthroughHunkSkeleton />
{variant === 'overview' ? <WalkthroughHunkSkeleton /> : null}
</div>
{variant === 'overview' ? (
<div className="space-y-1">
{['w-2/3', 'w-1/2', 'w-3/5'].map((width, row) => (
<div key={row} className="flex items-center gap-2 px-2 py-1">
<div className={cn(SKELETON_BAR, 'h-3 w-4 shrink-0 bg-muted/60')} />
<div className={cn(SKELETON_BAR, 'h-3 bg-muted/60', width)} />
</div>
))}
</div>
) : null}
</div>
)
}
/** Renders the walkthrough body; the provider and its chrome supply the surrounding panel. */
export const ChangesWalkthroughView = memo(function ChangesWalkthroughView() {
const {
@@ -528,27 +311,31 @@ export const ChangesWalkthroughView = memo(function ChangesWalkthroughView() {
walkthrough,
stale,
generating,
running,
error,
contextLimitFiles,
generate,
stops,
selectedStop,
selectedHunks,
selectStop,
scrollRef,
failedStopCount,
refine,
refining,
onOpenSession,
source,
sourcePending,
} = useChangesWalkthrough()
const [reload, setReload] = useState(0)
const [refineText, setRefineText] = useState('')
const readyStopCount = stops.filter((stop) => stop.status === 'ready').length
const mechanicalHunks = selectedHunks.filter(isMechanicalHunk)
const diffHunks = selectedHunks.filter((hunk) => !isMechanicalHunk(hunk))
const showInitialSkeleton = isLoading || (generating && (walkthrough === null || stops.length === 0))
const artifactPath = walkthrough?.artifactPath ?? null
const published = walkthrough?.publishedAt != null && artifactPath !== null
const artifactUrl = artifactPath === null ? null : getFileApiUrl(artifactPath, { params: { raw: true } })
const walkthroughSessionId = walkthrough?.walkthroughSessionId ?? null
const openSession =
walkthroughSessionId && onOpenSession
? () => onOpenSession(walkthroughSessionId)
: null
if (sourcePending) {
return (
<div className="min-h-0 flex-1 space-y-4 overflow-y-auto p-4">
<div className="flex min-h-0 flex-1 flex-col gap-4 overflow-y-auto p-4">
<WalkthroughSourceInputs />
<p className="text-sm text-muted-foreground">Enter a pull request number</p>
</div>
@@ -556,133 +343,114 @@ export const ChangesWalkthroughView = memo(function ChangesWalkthroughView() {
}
return (
<div ref={scrollRef} className="min-h-0 flex-1 space-y-4 overflow-y-auto p-4">
<div className="flex min-h-0 flex-1 flex-col gap-4 overflow-y-auto p-4">
<WalkthroughSourceInputs />
{error ? (
<div className="space-y-2">
<p className="text-sm text-destructive">{walkthroughErrorMessage(error)}</p>
{contextLimitFiles.length > 0 ? <OmittedFiles files={contextLimitFiles} /> : null}
{error ? <p className="text-sm text-destructive">{walkthroughErrorMessage(error)}</p> : null}
{stale && !generating ? (
<div className="flex flex-wrap items-center justify-between gap-2 rounded-md border border-warning/40 bg-warning/10 px-3 py-2">
<p className="text-sm text-warning">
Changes have been updated since this walkthrough was generated
</p>
<Button variant="outline" size="sm" onClick={generate}>
<RefreshCw className="mr-2 h-3.5 w-3.5" />
Update walkthrough
</Button>
</div>
) : null}
{showInitialSkeleton ? (
{isLoading && !walkthrough && !generating ? (
<p role="status" aria-live="polite" className="text-sm text-muted-foreground">
Loading the walkthrough…
</p>
) : null}
{!isLoading && !walkthrough && !generating ? (
<div className="space-y-4">
<p role="status" aria-live="polite" className="text-sm text-muted-foreground">
{generating ? 'Planning the walkthrough…' : 'Loading the walkthrough…'}
<p className="text-sm text-muted-foreground">
Build an interactive walkthrough of {describeWalkthroughSource(source)}.
</p>
<WalkthroughSkeleton />
<Button onClick={generate}>Generate walkthrough</Button>
</div>
) : (
<>
{generating ? (
<div className="flex items-center gap-2 rounded-md border border-border bg-muted/20 px-3 py-2 text-sm text-muted-foreground">
<Loader2 className="h-4 w-4 shrink-0 animate-spin motion-reduce:animate-none" />
<span>{`Generating walkthrough… ${readyStopCount} of ${stops.length} stops explained`}</span>
</div>
) : null}
{generating && !published ? (
<div className="flex flex-wrap items-center gap-2 rounded-md border border-border bg-muted/20 px-3 py-2 text-sm text-muted-foreground">
<Loader2 className="h-4 w-4 shrink-0 animate-spin motion-reduce:animate-none" />
<span role="status" aria-live="polite">
Building the walkthrough in a separate session…
</span>
{openSession ? (
<Button variant="outline" size="sm" className="ml-auto" onClick={openSession}>
Open walkthrough session
</Button>
) : null}
</div>
) : null}
{!walkthrough ? (
<div className="space-y-4">
<p className="text-sm text-muted-foreground">
Generate a step-by-step walkthrough of {describeWalkthroughSource(source)}.
</p>
<Button onClick={generate}>Generate walkthrough</Button>
</div>
) : (
<div className="space-y-4">
{stale && !generating ? (
<div className="flex flex-wrap items-center justify-between gap-2 rounded-md border border-warning/40 bg-warning/10 px-3 py-2">
<p className="text-sm text-warning">
Changes have been updated since this walkthrough was generated
</p>
<Button variant="outline" size="sm" onClick={generate}>
<RefreshCw className="mr-2 h-3.5 w-3.5" />
Update walkthrough
</Button>
</div>
) : null}
{published && artifactUrl !== null ? (
<div className="flex min-h-0 flex-1 flex-col gap-2">
<div className="flex flex-wrap items-center gap-2">
<Button
variant="outline"
size="sm"
aria-label="Reload walkthrough"
onClick={() => setReload((value) => value + 1)}
>
<RefreshCw className="h-3.5 w-3.5" />
Reload
</Button>
<Button asChild variant="outline" size="sm">
<a href={artifactUrl} target="_blank" rel="noreferrer">
Open in new tab
</a>
</Button>
{openSession ? (
<Button variant="outline" size="sm" onClick={openSession}>
Open walkthrough session
</Button>
) : null}
{generating || running ? (
<span role="status" aria-live="polite" className="text-sm text-muted-foreground">
Refining…
</span>
) : null}
</div>
<SandboxedHtmlFrame
src={artifactUrl}
title="Change walkthrough"
reloadKey={`${walkthrough?.publishedAt}:${reload}`}
className="min-h-0 flex-1"
/>
</div>
) : null}
{failedStopCount > 0 && !generating ? (
<div className="flex flex-wrap items-center justify-between gap-2 rounded-md border border-border bg-muted/20 px-3 py-2">
<p className="text-sm text-muted-foreground">Some stops could not be explained</p>
<Button variant="outline" size="sm" onClick={generate}>
Retry unexplained stops
</Button>
</div>
) : null}
{selectedStop ? (
<div className="space-y-3">
<h3 className="text-sm font-semibold text-foreground">{selectedStop.title}</h3>
{selectedStop.status === 'ready' ? (
<ScheduleRunMarkdown content={selectedStop.explanation} />
) : generating && selectedStop.status === 'pending' ? (
<div className="space-y-3">
<p role="status" aria-live="polite" className="text-sm text-muted-foreground">
Explaining this stop…
</p>
<WalkthroughSkeleton variant="body" />
</div>
) : (
<p className="text-sm text-muted-foreground">
{generating ? 'Explaining this stop…' : 'This stop could not be explained.'}
</p>
)}
{mechanicalHunks.length > 0 ? <MechanicalHunks hunks={mechanicalHunks} /> : null}
{diffHunks.map((hunk) => (
<div key={hunk.id} className="overflow-hidden rounded-md border border-border">
<div className="flex items-center gap-2 border-b border-border bg-muted/30 px-3 py-1.5">
<span className="min-w-0 flex-1 truncate text-xs font-medium text-foreground" title={hunk.file}>
{hunk.file}
</span>
{hunk.truncated ? <Badge variant="outline">truncated</Badge> : null}
<span className={`text-xs ${GIT_STATUS_COLORS[hunk.status]}`}>
{GIT_STATUS_LABELS[hunk.status]}
</span>
</div>
<div className="overflow-x-auto">
<DiffLines diff={hunk.text} />
</div>
</div>
))}
</div>
) : (
<>
<ScheduleRunMarkdown content={walkthrough.summary} />
{stops.length > 0 ? (
<ol className="space-y-0.5">
{stops.map((stop, index) => (
<li key={stop.id}>
<button
type="button"
onClick={() => selectStop(index)}
className="w-full rounded-md px-2 py-1 text-left text-sm text-muted-foreground hover:bg-accent/20 hover:text-foreground"
>
<span className="flex items-center gap-2">
<span className="min-w-0 flex-1 truncate">
{index + 1}. {stop.title}
</span>
{stop.status === 'pending' && generating ? (
<Loader2 className="h-3.5 w-3.5 shrink-0 animate-spin" aria-label="Explaining" />
) : stop.status === 'failed' || stop.status === 'pending' ? (
<span className="shrink-0 text-xs text-muted-foreground">not explained</span>
) : null}
</span>
</button>
</li>
))}
</ol>
) : null}
{walkthrough.omittedFiles.length > 0 ? <OmittedFiles files={walkthrough.omittedFiles} /> : null}
</>
)}
</div>
)}
</>
)}
{walkthroughSessionId && !generating && !running ? (
<form
className="space-y-2"
onSubmit={(event) => {
event.preventDefault()
const text = refineText.trim()
if (text.length === 0 || refining) return
refine(text)
setRefineText('')
}}
>
<Textarea
aria-label="Refine walkthrough"
placeholder="Ask for a change to the walkthrough"
maxLength={WALKTHROUGH_REFINE_MAX_CHARS}
value={refineText}
onChange={(event) => setRefineText(event.target.value)}
/>
<div className="flex justify-end">
<Button type="submit" size="sm" disabled={refineText.trim().length === 0 || refining}>
{refining ? 'Sending…' : 'Send'}
</Button>
</div>
</form>
) : null}
</div>
)
})
@@ -693,6 +461,7 @@ interface ChangesWalkthroughSheetProps {
onOpenChange: (open: boolean) => void
sourceRequest?: WalkthroughSourceRequest
model?: ModelRef | null
onOpenSession?: (walkthroughSessionId: string) => void
}
/** The walkthrough as a right-side sheet: full screen on mobile, a drawer over the page on desktop. */
@@ -702,21 +471,28 @@ export function ChangesWalkthroughSheet({
onOpenChange,
sourceRequest,
model,
onOpenSession,
}: ChangesWalkthroughSheetProps) {
const close = useCallback(() => onOpenChange(false), [onOpenChange])
return (
<SideDrawer isOpen={open} onClose={close} side="right" widthClass="w-full sm:w-[min(640px,92vw)]" ariaLabel="Change walkthrough">
<ChangesWalkthroughProvider key={sessionId} sessionId={sessionId} active={open} sourceRequest={sourceRequest} model={model}>
<ChangesWalkthroughProvider
key={sessionId}
sessionId={sessionId}
active={open}
sourceRequest={sourceRequest}
model={model}
onOpenSession={onOpenSession}
>
<SideDrawerHeader
title="Change walkthrough"
onClose={close}
actions={
<>
<ChangesWalkthroughSourcePicker />
<ChangesWalkthroughStop />
<ChangesWalkthroughCancel />
<ChangesWalkthroughRegenerate />
<ChangesWalkthroughNav />
</>
}
/>
@@ -23,7 +23,7 @@ export function WalkthroughSettings() {
<div className="min-w-0 space-y-0.5">
<Label htmlFor="walkthroughModel">Walkthrough model</Label>
<p className="text-sm text-muted-foreground">
Model that writes change walkthroughs. A small, fast model works well. Leave empty to use the session's model, or the OpenCode default.
Model of the walkthrough session that builds the walkthrough UI. Leave empty to use the session's model, or the OpenCode default.
</p>
</div>
<ModelCombobox
@@ -0,0 +1,36 @@
import { render, screen } from '@testing-library/react'
import { describe, it, expect } from 'vitest'
import { SandboxedHtmlFrame } from './sandboxed-html-frame'
describe('SandboxedHtmlFrame', () => {
it('restricts the iframe to allow-scripts without same-origin access', () => {
render(<SandboxedHtmlFrame src="/artifact" title="Artifact" />)
const iframe = screen.getByTitle('Artifact')
expect(iframe).toHaveAttribute('sandbox', 'allow-scripts')
expect(iframe.getAttribute('sandbox')).not.toContain('allow-same-origin')
})
it('sets a no-referrer policy', () => {
const { container } = render(<SandboxedHtmlFrame src="/artifact" title="Artifact" />)
const iframe = container.querySelector('iframe')
expect(iframe).toHaveAttribute('referrerpolicy', 'no-referrer')
})
it('remounts the iframe when reloadKey changes', () => {
const { container, rerender } = render(
<SandboxedHtmlFrame src="/artifact" title="Artifact" reloadKey={1} />,
)
const first = container.querySelector('iframe')
rerender(<SandboxedHtmlFrame src="/artifact" title="Artifact" reloadKey={2} />)
const second = container.querySelector('iframe')
expect(second).not.toBe(first)
})
it('merges the className prop with the base classes', () => {
const { container } = render(
<SandboxedHtmlFrame src="/artifact" title="Artifact" className="h-[480px]" />,
)
const iframe = container.querySelector('iframe')
expect(iframe).toHaveClass('block', 'w-full', 'border-0', 'bg-white', 'h-[480px]')
})
})
@@ -0,0 +1,29 @@
import { cn } from '@/lib/utils'
/**
* Renders untrusted HTML in an iframe restricted to `allow-scripts` without same-origin access.
* Owns the artifact sandbox policy so callers cannot widen it; remounts when `reloadKey` changes.
*/
export function SandboxedHtmlFrame({
src,
title,
reloadKey,
className,
}: {
src: string
title: string
reloadKey?: string | number
className?: string
}) {
return (
<iframe
key={reloadKey}
src={src}
title={title}
sandbox="allow-scripts"
referrerPolicy="no-referrer"
loading="lazy"
className={cn('block w-full border-0 bg-white', className)}
/>
)
}
@@ -2,23 +2,27 @@ import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { act, renderHook, waitFor } from '@testing-library/react'
import type { ReactNode } from 'react'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { changeWalkthroughQueryKey, useCancelChangeWalkthrough, useChangeWalkthrough, useGenerateChangeWalkthrough } from './useChangeWalkthrough'
import { DEFAULT_WALKTHROUGH_SOURCE, walkthroughHunksIdentity } from '@opencode-manager/shared/schemas'
import type {
ChangeWalkthrough,
ChangeWalkthroughState,
ChangeWalkthroughStateWire,
} from '@opencode-manager/shared/schemas'
import {
changeWalkthroughQueryKey,
useCancelChangeWalkthrough,
useChangeWalkthrough,
useGenerateChangeWalkthrough,
useRefineChangeWalkthrough,
} from './useChangeWalkthrough'
import { DEFAULT_WALKTHROUGH_SOURCE } from '@opencode-manager/shared/schemas'
import type { ChangeWalkthrough, ChangeWalkthroughState } from '@opencode-manager/shared/schemas'
const mocks = vi.hoisted(() => ({
getChangeWalkthrough: vi.fn(),
generateChangeWalkthrough: vi.fn(),
refineChangeWalkthrough: vi.fn(),
cancelChangeWalkthrough: vi.fn(),
}))
vi.mock('@/api/changeWalkthroughs', () => ({
getChangeWalkthrough: mocks.getChangeWalkthrough,
generateChangeWalkthrough: mocks.generateChangeWalkthrough,
refineChangeWalkthrough: mocks.refineChangeWalkthrough,
cancelChangeWalkthrough: mocks.cancelChangeWalkthrough,
}))
@@ -26,16 +30,19 @@ const walkthroughForA: ChangeWalkthrough = {
sessionId: 'ses_A',
source: { kind: 'session' },
diffHash: 'hash-a',
walkthroughSessionId: 'ses_walk',
status: 'ready',
artifactPath: '/workspace/walkthroughs/ses_A/gen/index.html',
publishedAt: 1,
executionStartedAt: null,
error: null,
model: null,
summary: 'A summary',
stops: [],
hunks: [],
omittedFiles: [],
createdAt: 1,
updatedAt: 2,
}
function state(overrides: Partial<ChangeWalkthroughState> = {}): ChangeWalkthroughState {
return { walkthrough: null, currentDiffHash: 'hash-a', stale: false, generating: false, error: null, ...overrides }
return { walkthrough: null, currentDiffHash: 'hash-a', stale: false, generating: false, running: false, error: null, ...overrides }
}
function deferred<T>() {
@@ -122,53 +129,46 @@ describe('useChangeWalkthrough', () => {
}
})
it('merges cached hunks when the server omits them for a matching identity', async () => {
it('keeps polling while a published walkthrough is still running', async () => {
vi.useFakeTimers({ shouldAdvanceTime: true })
try {
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
const walkthroughWithHunks: ChangeWalkthrough = {
...walkthroughForA,
hunks: [
{
id: 'h_1',
file: 'src/a.ts',
status: 'modified',
header: '@@ -1 +1 @@',
text: '@@ -1 +1 @@\n-a\n+b',
truncated: false,
},
],
}
const compact: ChangeWalkthroughStateWire = {
...state({ generating: true }),
walkthrough: { ...walkthroughWithHunks, hunks: undefined },
}
mocks.getChangeWalkthrough
.mockResolvedValueOnce(state({ walkthrough: walkthroughWithHunks, generating: true }))
.mockResolvedValueOnce(compact)
.mockResolvedValueOnce(state({ walkthrough: walkthroughForA, running: true }))
.mockResolvedValueOnce(state({ walkthrough: walkthroughForA }))
const { result } = renderHook(() => useChangeWalkthrough('ses_A', true, DEFAULT_WALKTHROUGH_SOURCE), {
wrapper: createWrapper(queryClient),
})
await waitFor(() => expect(result.current.data?.walkthrough?.hunks).toHaveLength(1))
await waitFor(() => expect(result.current.data?.running).toBe(true))
await act(async () => {
await vi.advanceTimersByTimeAsync(2_000)
})
await waitFor(() => expect(mocks.getChangeWalkthrough).toHaveBeenCalledTimes(2))
expect(mocks.getChangeWalkthrough).toHaveBeenLastCalledWith(
'ses_A',
DEFAULT_WALKTHROUGH_SOURCE,
walkthroughHunksIdentity(walkthroughWithHunks),
)
expect(result.current.data?.walkthrough).toEqual(walkthroughWithHunks)
await waitFor(() => expect(result.current.data?.running).toBe(false))
await act(async () => {
await vi.advanceTimersByTimeAsync(10_000)
})
expect(mocks.getChangeWalkthrough).toHaveBeenCalledTimes(2)
} finally {
vi.useRealTimers()
}
})
it('requests the walkthrough state for the session and source only', async () => {
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
mocks.getChangeWalkthrough.mockResolvedValue(state())
renderHook(() => useChangeWalkthrough('ses_A', true, { kind: 'staged' }), {
wrapper: createWrapper(queryClient),
})
await waitFor(() => expect(mocks.getChangeWalkthrough).toHaveBeenCalledWith('ses_A', { kind: 'staged' }))
})
it('invalidating the session key refetches every source', async () => {
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
mocks.getChangeWalkthrough.mockResolvedValue(state())
@@ -190,17 +190,46 @@ describe('useChangeWalkthrough', () => {
})
})
describe('useRefineChangeWalkthrough', () => {
beforeEach(() => {
vi.clearAllMocks()
})
it('sends the refine text for the source and caches the returned state', async () => {
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
mocks.refineChangeWalkthrough.mockResolvedValue(state({ generating: true }))
const { result } = renderHook(() => useRefineChangeWalkthrough('ses_A', DEFAULT_WALKTHROUGH_SOURCE), {
wrapper: createWrapper(queryClient),
})
await act(async () => {
result.current.mutate('tighten the introduction')
})
expect(mocks.refineChangeWalkthrough).toHaveBeenCalledWith('ses_A', {
source: { kind: 'session' },
text: 'tighten the introduction',
})
await waitFor(() => {
expect(queryClient.getQueryData(changeWalkthroughQueryKey('ses_A', 'session'))).toEqual(
state({ generating: true }),
)
})
})
})
describe('useCancelChangeWalkthrough', () => {
beforeEach(() => {
vi.clearAllMocks()
})
it('cancels the walkthrough and optimistically clears the generating state', async () => {
it('cancels the walkthrough and optimistically clears the generating and running state', async () => {
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
const queryKey = changeWalkthroughQueryKey('ses_A', 'session')
queryClient.setQueryData(queryKey, state({ generating: true }))
queryClient.setQueryData(queryKey, state({ generating: true, running: true }))
mocks.cancelChangeWalkthrough.mockResolvedValue(undefined)
mocks.getChangeWalkthrough.mockResolvedValue(state({ generating: false }))
mocks.getChangeWalkthrough.mockResolvedValue(state())
const { result } = renderHook(() => useCancelChangeWalkthrough('ses_A', DEFAULT_WALKTHROUGH_SOURCE), {
wrapper: createWrapper(queryClient),
@@ -214,5 +243,6 @@ describe('useCancelChangeWalkthrough', () => {
await waitFor(() => {
expect(queryClient.getQueryData<ChangeWalkthroughState>(queryKey)?.generating).toBe(false)
})
expect(queryClient.getQueryData<ChangeWalkthroughState>(queryKey)?.running).toBe(false)
})
})
+39 -42
View File
@@ -1,68 +1,53 @@
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { cancelChangeWalkthrough, generateChangeWalkthrough, getChangeWalkthrough } from '@/api/changeWalkthroughs'
import { walkthroughHunksIdentity, walkthroughSourceKey } from '@opencode-manager/shared/schemas'
import type { QueryClient } from '@tanstack/react-query'
import {
cancelChangeWalkthrough,
generateChangeWalkthrough,
getChangeWalkthrough,
refineChangeWalkthrough,
} from '@/api/changeWalkthroughs'
import { walkthroughSourceKey } from '@opencode-manager/shared/schemas'
import type {
ChangeWalkthrough,
ChangeWalkthroughState,
ChangeWalkthroughStateWire,
ChangeWalkthroughWire,
GenerateChangeWalkthroughRequest,
WalkthroughSource,
} from '@opencode-manager/shared/schemas'
const GENERATING_POLL_INTERVAL_MS = 2_000
type ChangeWalkthroughMutationResult = {
sessionId: string
sourceKey: string
state: ChangeWalkthroughState
}
function writeChangeWalkthroughToCache(
queryClient: QueryClient,
{ sessionId, sourceKey, state }: ChangeWalkthroughMutationResult,
) {
queryClient.setQueryData(changeWalkthroughQueryKey(sessionId, sourceKey), state)
}
export function changeWalkthroughQueryKey(sessionId: string, sourceKey?: string) {
return sourceKey === undefined
? (['change-walkthrough', sessionId] as const)
: (['change-walkthrough', sessionId, sourceKey] as const)
}
function isCompleteWalkthrough(walkthrough: ChangeWalkthroughWire): walkthrough is ChangeWalkthrough {
return walkthrough.hunks !== undefined
}
function mergeChangeWalkthroughState(
state: ChangeWalkthroughStateWire,
cached: ChangeWalkthrough | null,
): ChangeWalkthroughState {
const incoming = state.walkthrough
if (!incoming) {
return { ...state, walkthrough: null }
}
if (isCompleteWalkthrough(incoming)) {
return { ...state, walkthrough: incoming }
}
const hunks =
cached && walkthroughHunksIdentity(cached) === walkthroughHunksIdentity(incoming)
? cached.hunks
: []
return { ...state, walkthrough: { ...incoming, hunks } }
}
export function useChangeWalkthrough(
sessionId: string | undefined,
enabled: boolean,
source: WalkthroughSource,
) {
const sourceKey = walkthroughSourceKey(source)
const queryClient = useQueryClient()
const queryKey = changeWalkthroughQueryKey(sessionId ?? '', sourceKey)
return useQuery({
queryKey,
queryFn: async () => {
const cached = queryClient.getQueryData<ChangeWalkthroughState>(queryKey)
const cachedWalkthrough = cached?.walkthrough ?? null
const hunksFor = cachedWalkthrough ? walkthroughHunksIdentity(cachedWalkthrough) : undefined
const state =
hunksFor === undefined
? await getChangeWalkthrough(sessionId!, source)
: await getChangeWalkthrough(sessionId!, source, hunksFor)
return mergeChangeWalkthroughState(state, cachedWalkthrough)
},
queryFn: () => getChangeWalkthrough(sessionId!, source),
enabled: enabled && !!sessionId,
staleTime: 30_000,
refetchInterval: (query) => (query.state.data?.generating ? GENERATING_POLL_INTERVAL_MS : false),
refetchInterval: (query) =>
query.state.data?.generating || query.state.data?.running ? GENERATING_POLL_INTERVAL_MS : false,
})
}
@@ -76,9 +61,21 @@ export function useGenerateChangeWalkthrough(sessionId: string | undefined, sour
const state = await generateChangeWalkthrough(targetSessionId, { ...request, source })
return { sessionId: targetSessionId, sourceKey, state }
},
onSuccess: ({ sessionId: targetSessionId, sourceKey: targetSourceKey, state }) => {
queryClient.setQueryData(changeWalkthroughQueryKey(targetSessionId, targetSourceKey), state)
onSuccess: (result) => writeChangeWalkthroughToCache(queryClient, result),
})
}
export function useRefineChangeWalkthrough(sessionId: string | undefined, source: WalkthroughSource) {
const queryClient = useQueryClient()
const sourceKey = walkthroughSourceKey(source)
return useMutation({
mutationFn: async (text: string) => {
const targetSessionId = sessionId!
const state = await refineChangeWalkthrough(targetSessionId, { source, text })
return { sessionId: targetSessionId, sourceKey, state }
},
onSuccess: (result) => writeChangeWalkthroughToCache(queryClient, result),
})
}
@@ -95,7 +92,7 @@ export function useCancelChangeWalkthrough(sessionId: string | undefined, source
onSuccess: ({ sessionId: targetSessionId, sourceKey: targetSourceKey }) => {
const queryKey = changeWalkthroughQueryKey(targetSessionId, targetSourceKey)
queryClient.setQueryData<ChangeWalkthroughState>(queryKey, (cached) =>
cached ? { ...cached, generating: false, error: null } : cached,
cached ? { ...cached, generating: false, running: false, error: null } : cached,
)
queryClient.invalidateQueries({ queryKey })
},
+1 -1
View File
@@ -59,7 +59,7 @@ export const BUILTIN_COMMANDS: readonly BuiltinCommand[] = [
{ name: 'details', description: 'Toggle tool execution details', action: 'toggleDetails' },
{ name: 'mcp', description: 'Manage MCP servers', action: 'showMcp' },
{ name: 'skills', description: 'Load a skill', action: 'showSkills' },
{ name: 'walkthrough', description: 'Walk through the session changes, explained step by step', action: 'showWalkthrough' },
{ name: 'walkthrough', description: 'Build an interactive walkthrough of the session changes', action: 'showWalkthrough' },
{ name: 'settings', description: 'Open settings', action: 'showSettings' },
{ name: 'connect', description: 'Connect a provider', action: 'connectProvider' },
]
+2
View File
@@ -860,6 +860,7 @@ export function SessionDetail() {
onSkillLoaded={handleSkillLoaded}
walkthroughSourceRequest={walkthroughSourceRequest}
walkthroughModel={modelRef}
walkthroughOnOpenSession={handleChildSessionClick}
/>
)}
</div>
@@ -941,6 +942,7 @@ export function SessionDetail() {
onOpenChange={setWalkthroughOpen}
sourceRequest={walkthroughSourceRequest}
model={modelRef}
onOpenSession={handleChildSessionClick}
/>
)}
+1
View File
@@ -30,6 +30,7 @@ export const DEFAULTS = {
BASE_PATH: './workspace',
REPOS_DIR: 'repos',
SCHEDULE_WORKTREES_DIR: 'schedule-worktrees',
WALKTHROUGHS_DIR: 'walkthroughs',
CONFIG_DIR: '.config/opencode',
},
+2
View File
@@ -88,6 +88,7 @@ export const ENV = {
get BROWSE_ROOT() { return resolveBrowseRoot() },
REPOS_DIR: DEFAULTS.WORKSPACE.REPOS_DIR,
SCHEDULE_WORKTREES_DIR: DEFAULTS.WORKSPACE.SCHEDULE_WORKTREES_DIR,
WALKTHROUGHS_DIR: DEFAULTS.WORKSPACE.WALKTHROUGHS_DIR,
CONFIG_DIR: DEFAULTS.WORKSPACE.CONFIG_DIR,
},
@@ -148,6 +149,7 @@ export const getWorkspacePath = () => ENV.WORKSPACE.BASE_PATH
export const getBrowseRootPath = () => ENV.WORKSPACE.BROWSE_ROOT
export const getReposPath = () => path.join(ENV.WORKSPACE.BASE_PATH, ENV.WORKSPACE.REPOS_DIR)
export const getScheduleWorktreesPath = () => path.join(ENV.WORKSPACE.BASE_PATH, ENV.WORKSPACE.SCHEDULE_WORKTREES_DIR)
export const getWalkthroughsPath = () => path.join(ENV.WORKSPACE.BASE_PATH, ENV.WORKSPACE.WALKTHROUGHS_DIR)
export const getAssistantModePath = () => path.join(getReposPath(), ASSISTANT_REPO_PATH)
export const getAssistantOpenCodeDir = () => path.join(getAssistantModePath(), ASSISTANT_OPENCODE_DIR_NAME)
export const getOpenCodeConfigHome = () => path.join(ENV.WORKSPACE.BASE_PATH, '.config')
+31 -45
View File
@@ -4,8 +4,8 @@ import { gitRefSchema } from './git'
export const WALKTHROUGH_DIFF_MAX_CHARS = 60000;
export const WALKTHROUGH_HUNK_MAX_CHARS = 8000;
export const MECHANICAL_TEXT_BUDGET = 20000;
export const WALKTHROUGH_MAX_STOPS = 20;
export const WALKTHROUGH_TEXT_MAX_CHARS = 2000;
export const WALKTHROUGH_GENERATION_TIMEOUT_MS = 15 * 60 * 1000;
export const WALKTHROUGH_REFINE_MAX_CHARS = 4000;
export const WALKTHROUGH_OUTLINE_PREVIEW_LINES = 6;
export const WALKTHROUGH_OUTLINE_LINE_MAX_CHARS = 160;
@@ -116,17 +116,6 @@ export const WalkthroughHunkSchema = z.object({
export type WalkthroughHunk = z.infer<typeof WalkthroughHunkSchema>;
export const WalkthroughStopSchema = z.object({
id: z.string(),
title: z.string(),
explanation: z.string(),
hunkIds: z.array(z.string()),
status: z.enum(["pending", "ready", "failed"]),
explanationKey: z.string().nullable(),
});
export type WalkthroughStop = z.infer<typeof WalkthroughStopSchema>;
export const WalkthroughOmittedFileSchema = z.object({
file: z.string(),
reason: z.enum(["binary", "budget", "renamed", "modeChange"]),
@@ -134,20 +123,6 @@ export const WalkthroughOmittedFileSchema = z.object({
export type WalkthroughOmittedFile = z.infer<typeof WalkthroughOmittedFileSchema>;
export const ChangeWalkthroughSchema = z.object({
sessionId: z.string(),
source: WalkthroughSourceSchema,
diffHash: z.string(),
model: z.string().nullable(),
summary: z.string(),
stops: z.array(WalkthroughStopSchema),
hunks: z.array(WalkthroughHunkSchema),
omittedFiles: z.array(WalkthroughOmittedFileSchema),
createdAt: z.number(),
});
export type ChangeWalkthrough = z.infer<typeof ChangeWalkthroughSchema>;
export const WalkthroughGenerationErrorSchema = z.object({
message: z.string(),
code: z.string().optional(),
@@ -156,34 +131,38 @@ export const WalkthroughGenerationErrorSchema = z.object({
export type WalkthroughGenerationError = z.infer<typeof WalkthroughGenerationErrorSchema>;
export const WalkthroughStatusSchema = z.enum(['generating', 'ready', 'failed', 'cancelled'])
export type WalkthroughStatus = z.infer<typeof WalkthroughStatusSchema>
export const ChangeWalkthroughSchema = z.object({
sessionId: z.string(),
source: WalkthroughSourceSchema,
diffHash: z.string(),
walkthroughSessionId: z.string().nullable(),
status: WalkthroughStatusSchema,
artifactPath: z.string().nullable(),
publishedAt: z.number().nullable(),
executionStartedAt: z.number().nullable(),
error: WalkthroughGenerationErrorSchema.nullable(),
model: z.string().nullable(),
createdAt: z.number(),
updatedAt: z.number(),
})
export type ChangeWalkthrough = z.infer<typeof ChangeWalkthroughSchema>;
export const ChangeWalkthroughStateSchema = z.object({
walkthrough: ChangeWalkthroughSchema.nullable(),
currentDiffHash: z.string().nullable(),
stale: z.boolean(),
generating: z.boolean(),
running: z.boolean(),
error: WalkthroughGenerationErrorSchema.nullable(),
});
export type ChangeWalkthroughState = z.infer<typeof ChangeWalkthroughStateSchema>;
export const ChangeWalkthroughWireSchema = ChangeWalkthroughSchema.extend({
hunks: z.array(WalkthroughHunkSchema).optional(),
});
export type ChangeWalkthroughWire = z.infer<typeof ChangeWalkthroughWireSchema>;
export const ChangeWalkthroughStateWireSchema = ChangeWalkthroughStateSchema.extend({
walkthrough: ChangeWalkthroughWireSchema.nullable(),
});
export type ChangeWalkthroughStateWire = z.infer<typeof ChangeWalkthroughStateWireSchema>;
export function walkthroughHunksIdentity(
walkthrough: Pick<ChangeWalkthrough, 'diffHash' | 'createdAt'>,
): string {
return `${walkthrough.diffHash}:${walkthrough.createdAt}`
}
export const GenerateChangeWalkthroughRequestSchema = z.object({
regenerate: z.boolean().optional(),
source: WalkthroughSourceSchema.optional(),
@@ -191,3 +170,10 @@ export const GenerateChangeWalkthroughRequestSchema = z.object({
});
export type GenerateChangeWalkthroughRequest = z.infer<typeof GenerateChangeWalkthroughRequestSchema>;
export const RefineChangeWalkthroughRequestSchema = z.object({
source: WalkthroughSourceSchema.optional(),
text: z.string().trim().min(1).max(WALKTHROUGH_REFINE_MAX_CHARS),
})
export type RefineChangeWalkthroughRequest = z.infer<typeof RefineChangeWalkthroughRequestSchema>
+18
View File
@@ -13,11 +13,17 @@ export const MANAGER_TOOL_OPEN_WALKTHROUGH_ACTION = 'open_walkthrough'
export const MANAGER_TOOL_SHOW_ARTIFACT_ACTION = 'show_artifact'
export const MANAGER_TOOL_WALKTHROUGH_CHANGES_ACTION = 'walkthrough_changes'
export const MANAGER_TOOL_PUBLISH_WALKTHROUGH_ACTION = 'publish_walkthrough'
export const MANAGER_TOOL_ACTIONS = [
'send_notification',
'request',
MANAGER_TOOL_OPEN_WALKTHROUGH_ACTION,
MANAGER_TOOL_SHOW_ARTIFACT_ACTION,
MANAGER_TOOL_WALKTHROUGH_CHANGES_ACTION,
MANAGER_TOOL_PUBLISH_WALKTHROUGH_ACTION,
] as const
export const ARTIFACT_LIMITS = {
@@ -40,6 +46,18 @@ export const ShowArtifactParamsSchema = z
export type ShowArtifactParams = z.infer<typeof ShowArtifactParamsSchema>
export const WalkthroughChangesParamsSchema = z
.object({
file: z.string().min(1).max(1000).optional().describe('A changed file path from the outline; omit for the outline.'),
})
.strict()
export type WalkthroughChangesParams = z.infer<typeof WalkthroughChangesParamsSchema>
export const PublishWalkthroughParamsSchema = z.object({}).strict()
export type PublishWalkthroughParams = z.infer<typeof PublishWalkthroughParamsSchema>
export const AssistantNotificationPrioritySchema = z.enum(['normal', 'high'])
export const ASSISTANT_NOTIFICATION_LIMITS = {