Merge pull request #437 from chriswritescode-dev/fix/walkthrough-tool-waits-until-ready

fix(walkthrough): wait for the walkthrough to be ready before completing open_walkthrough
This commit is contained in:
Chris Scott authored and GitHub committed 2026-10-16 17:02:56 -04:00
commit 4e8051b75a
2 files changed
+172 -22

No files matched your search

@@ -1,6 +1,7 @@
import { z } from 'zod'
import {
ASSISTANT_NOTIFICATION_LIMITS,
DEFAULT_WALKTHROUGH_SOURCE,
MANAGER_PROMPT_CLIENT_METADATA_KEY,
MANAGER_PROMPT_CLIENTS,
MANAGER_TOOL_ACTIONS,
@@ -9,6 +10,7 @@ import {
ShowArtifactParamsSchema,
WalkthroughChangesParamsSchema,
WalkthroughSourceSchema,
walkthroughSourceKey,
} from '@opencode-manager/shared/schemas'
const MANAGER_TOOL_REQUEST_TIMEOUT_MS = 60000
@@ -80,7 +82,7 @@ const ManagerToolWalkthroughParamsSchema = z
source: WalkthroughSourceSchema.optional().describe('The change source to walk through. Defaults to the changes in this session.'),
})
.strict()
.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.")
.describe("Start a separate walkthrough session that builds an interactive walkthrough UI for this session's changes and waits until it is ready, which can take several minutes. 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,
@@ -145,7 +147,7 @@ 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: 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.",
"- open_walkthrough: start a separate walkthrough session that builds an interactive walkthrough UI for the current session's changes and waits until it is ready (this can take several minutes), then it opens in the Manager walkthrough panel 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.',
@@ -159,6 +161,8 @@ function buildManagerToolDescription(): string {
export function buildManagerToolPluginSource(id: string): string {
return `var REQUEST_TIMEOUT_MS = ${MANAGER_TOOL_REQUEST_TIMEOUT_MS}
var WALKTHROUGH_POLL_INTERVAL_MS = 2000
var ALLOWED_ROUTES = ${JSON.stringify(MANAGER_TOOL_ALLOWED_ROUTES)}
var ALLOWED_MATCHERS = ${JSON.stringify(buildRouteMatchers())}.map(function (matcher) {
@@ -181,6 +185,10 @@ var DESKTOP_CLIENT = ${JSON.stringify(DESKTOP_PROMPT_CLIENT)}
var MOBILE_OUTPUT_INSTRUCTIONS = ${JSON.stringify(MANAGER_MOBILE_OUTPUT_INSTRUCTIONS)}
var DEFAULT_WALKTHROUGH_SOURCE = ${JSON.stringify(DEFAULT_WALKTHROUGH_SOURCE)}
var walkthroughSourceKey = ${walkthroughSourceKey.toString()}
var MOBILE_SESSIONS = new Set()
/** Updates mobile mode from explicit client metadata, preserving it when metadata is absent. */
@@ -258,7 +266,15 @@ async function requestInternalApi(method, path, body, signal) {
}
async function postInternalApi(routePath, body, signal) {
var text = await requestInternalApi('POST', routePath, body, signal)
return await requestInternalJson('POST', routePath, body, signal)
}
async function getInternalApi(routePath, signal) {
return await requestInternalJson('GET', routePath, undefined, signal)
}
async function requestInternalJson(method, routePath, body, signal) {
var text = await requestInternalApi(method, routePath, body, signal)
try {
return JSON.parse(text)
} catch (error) {
@@ -266,6 +282,26 @@ async function postInternalApi(routePath, body, signal) {
}
}
/** Waits one walkthrough poll interval, rejecting promptly when the signal aborts. */
function waitForWalkthroughPoll(signal) {
return new Promise(function (resolve, reject) {
var timer
function onAbort() {
clearTimeout(timer)
reject(new Error('The walkthrough wait was aborted before it was ready.'))
}
if (signal.aborted) {
reject(new Error('The walkthrough wait was aborted before it was ready.'))
return
}
timer = setTimeout(function () {
signal.removeEventListener('abort', onAbort)
resolve()
}, WALKTHROUGH_POLL_INTERVAL_MS)
signal.addEventListener('abort', onAbort)
})
}
var ACTIONS = {
send_notification: {
run: async function (params, context) {
@@ -286,13 +322,24 @@ var ACTIONS = {
},
open_walkthrough: {
run: async function (params, context) {
var source = params.source === undefined ? DEFAULT_WALKTHROUGH_SOURCE : params.source
var body = params.source === undefined ? undefined : { source: params.source }
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 'Started a walkthrough session that builds an interactive walkthrough.' + hint
var statePath = '/change-walkthroughs/' + encodeURIComponent(context.sessionID)
var state = await postInternalApi(statePath, body, context.signal)
var pollPath = statePath + '?source=' + encodeURIComponent(walkthroughSourceKey(source))
while (state.generating === true) {
await waitForWalkthroughPoll(context.signal)
state = await getInternalApi(pollPath, context.signal)
}
return 'The walkthrough is ready.' + hint
var hint = ' It opens in the Manager walkthrough panel when this session is open on desktop; otherwise the user can open it from this tool call.'
if (state.walkthrough && state.walkthrough.status === 'ready') {
return 'The walkthrough is ready.' + hint
}
var failure = state.error || (state.walkthrough && state.walkthrough.error)
if (failure || (state.walkthrough && state.walkthrough.status === 'failed')) {
throw new Error('The walkthrough failed: ' + (failure && failure.message ? failure.message : 'unknown error'))
}
throw new Error('The walkthrough was cancelled before it was ready.')
},
},
show_artifact: {
@@ -76,15 +76,15 @@ function publishParamsSchema(tool: GeneratedTool): JsonSchema {
async function runToolResult(
tool: GeneratedTool,
input: unknown,
context: { sessionID?: string } = {},
context: { sessionID?: string; signal?: AbortSignal } = {},
): Promise<{ content: string; metadata?: Record<string, unknown> }> {
return (await tool.execute!(input, { signal: new AbortController().signal, sessionID: context.sessionID })) as {
return (await tool.execute!(input, { signal: context.signal ?? new AbortController().signal, sessionID: context.sessionID })) as {
content: string
metadata?: Record<string, unknown>
}
}
async function runTool(tool: GeneratedTool, input: unknown, context: { sessionID?: string } = {}): Promise<string> {
async function runTool(tool: GeneratedTool, input: unknown, context: { sessionID?: string; signal?: AbortSignal } = {}): Promise<string> {
return (await runToolResult(tool, input, context)).content
}
@@ -211,6 +211,7 @@ describe('ocm-manager plugin', () => {
expect(tool.description).toContain('open_walkthrough')
expect(tool.description).toContain('start a separate walkthrough session')
expect(tool.description).toContain('waits until it is ready')
expect(tool.description).toContain('when this session is open on desktop')
})
@@ -319,8 +320,8 @@ describe('ocm-manager plugin', () => {
expect(fetchMock).not.toHaveBeenCalled()
})
it('opens the walkthrough for the current session with the requested source', async () => {
const fetchMock = jsonResponse({ walkthrough: { stops: [{}, {}] }, currentDiffHash: 'h', stale: false, generating: false, error: null })
it('opens the walkthrough for the current session with the requested source and returns immediately when it is ready', async () => {
const fetchMock = jsonResponse({ walkthrough: { status: 'ready' }, currentDiffHash: 'h', stale: false, generating: false, error: null })
vi.stubGlobal('fetch', fetchMock)
const tool = await loadTool(configHome)
@@ -338,25 +339,127 @@ 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(
'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.',
'The walkthrough is ready. It opens in the Manager walkthrough panel when this session is open on desktop; otherwise the user can open it from this tool call.',
)
expect(result.metadata).toBeUndefined()
})
it('reports that the walkthrough is generating', async () => {
vi.stubGlobal('fetch', jsonResponse({ walkthrough: null, currentDiffHash: 'h', stale: false, generating: true, error: null }))
it('polls the walkthrough state until it is ready and encodes the staged source key', async () => {
const fetchMock = vi
.fn()
.mockResolvedValueOnce({
ok: true,
status: 200,
text: async () => JSON.stringify({ walkthrough: null, currentDiffHash: 'h', stale: false, generating: true, error: null }),
})
.mockResolvedValueOnce({
ok: true,
status: 200,
text: async () => JSON.stringify({ walkthrough: { status: 'ready' }, currentDiffHash: 'h', stale: false, generating: false, error: null }),
})
vi.stubGlobal('fetch', fetchMock)
const tool = await loadTool(configHome)
const result = await runToolResult(tool, { action: 'open_walkthrough', params: {} }, { sessionID: 'ses_abc' })
vi.useFakeTimers()
try {
const pending = runToolResult(tool, { action: 'open_walkthrough', params: { source: { kind: 'staged' } } }, { sessionID: 'ses_abc' })
await vi.advanceTimersByTimeAsync(2000)
const result = await pending
expect(result.content).toBe(
'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()
expect(fetchMock).toHaveBeenCalledTimes(2)
const [pollUrl, pollInit] = fetchMock.mock.calls[1] ?? []
expect(pollUrl).toBe('http://localhost:5003/api/internal/change-walkthroughs/ses_abc?source=staged')
expect(pollInit.method).toBe('GET')
expect(result.content).toBe(
'The walkthrough is ready. It opens in the Manager walkthrough panel when this session is open on desktop; otherwise the user can open it from this tool call.',
)
} finally {
vi.useRealTimers()
}
})
it('encodes a branch source key when polling', async () => {
const fetchMock = vi
.fn()
.mockResolvedValueOnce({
ok: true,
status: 200,
text: async () => JSON.stringify({ walkthrough: null, generating: true, error: null }),
})
.mockResolvedValueOnce({
ok: true,
status: 200,
text: async () => JSON.stringify({ walkthrough: { status: 'ready' }, generating: false, error: null }),
})
vi.stubGlobal('fetch', fetchMock)
const tool = await loadTool(configHome)
vi.useFakeTimers()
try {
const pending = runToolResult(
tool,
{ action: 'open_walkthrough', params: { source: { kind: 'branch', base: 'main' } } },
{ sessionID: 'ses_abc' },
)
await vi.advanceTimersByTimeAsync(2000)
await pending
expect(fetchMock.mock.calls[1]?.[0]).toBe('http://localhost:5003/api/internal/change-walkthroughs/ses_abc?source=branch%3Amain')
} finally {
vi.useRealTimers()
}
})
it('throws when the walkthrough fails', async () => {
const fetchMock = vi
.fn()
.mockResolvedValueOnce({
ok: true,
status: 200,
text: async () => JSON.stringify({ walkthrough: null, generating: true, error: null }),
})
.mockResolvedValueOnce({
ok: true,
status: 200,
text: async () => JSON.stringify({ walkthrough: { status: 'failed' }, generating: false, error: { message: 'the model crashed' } }),
})
vi.stubGlobal('fetch', fetchMock)
const tool = await loadTool(configHome)
vi.useFakeTimers()
try {
const pending = runTool(tool, { action: 'open_walkthrough', params: {} }, { sessionID: 'ses_abc' })
const assertion = expect(pending).rejects.toThrow('The walkthrough failed: the model crashed')
await vi.advanceTimersByTimeAsync(2000)
await assertion
} finally {
vi.useRealTimers()
}
})
it('throws when the walkthrough was cancelled before it was ready', async () => {
vi.stubGlobal('fetch', jsonResponse({ walkthrough: { status: 'cancelled' }, generating: false, error: null }))
const tool = await loadTool(configHome)
await expect(runTool(tool, { action: 'open_walkthrough', params: {} }, { sessionID: 'ses_abc' }))
.rejects.toThrow('The walkthrough was cancelled before it was ready.')
})
it('stops waiting when the signal is aborted', async () => {
const fetchMock = jsonResponse({ walkthrough: null, generating: true, error: null })
vi.stubGlobal('fetch', fetchMock)
const tool = await loadTool(configHome)
const controller = new AbortController()
const pending = runTool(tool, { action: 'open_walkthrough', params: {} }, { sessionID: 'ses_abc', signal: controller.signal })
controller.abort()
await expect(pending).rejects.toThrow(/aborted/)
expect(fetchMock).toHaveBeenCalledTimes(1)
})
it('opens the walkthrough without a body when no source is given', async () => {
const fetchMock = jsonResponse({ walkthrough: null, currentDiffHash: 'h', stale: false, generating: true, error: null })
const fetchMock = jsonResponse({ walkthrough: { status: 'ready' }, generating: false, error: null })
vi.stubGlobal('fetch', fetchMock)
const tool = await loadTool(configHome)