diff --git a/backend/src/services/assistant-mode.ts b/backend/src/services/assistant-mode.ts index de669119..23b49426 100644 --- a/backend/src/services/assistant-mode.ts +++ b/backend/src/services/assistant-mode.ts @@ -12,12 +12,11 @@ import { fileExists, ensureDirectoryExists, } from './file-operations' -import { ASSISTANT_NOTIFICATION_LIMITS, AssistantSettingsPatchSchema, OpenCodeConfigSchema, DEFAULT_KEYBOARD_SHORTCUTS, DEFAULT_LEADER_KEY } from '@opencode-manager/shared/schemas' +import { ASSISTANT_NOTIFICATION_LIMITS, AssistantSettingsPatchSchema, OpenCodeConfigSchema, DEFAULT_KEYBOARD_SHORTCUTS, DEFAULT_LEADER_KEY, MANAGER_TOOL_NAME } from '@opencode-manager/shared/schemas' import { MANAGER_COLOR_THEME_ID, OPENCODE_THEMES } from '@opencode-manager/shared/themes' import { ASSISTANT_REPO_ID, ASSISTANT_REPO_PATH, ASSISTANT_OPENCODE_DIR_NAME } from '@opencode-manager/shared/utils' import { getAssistantModePath, getReposPath } from '@opencode-manager/shared/config/env' import type { Database } from 'bun:sqlite' -import { MANAGER_TOOL_NAME } from './opencode-manager-tool-plugin' import { ensureAssistantRepo } from '../db/queries' diff --git a/backend/src/services/change-walkthroughs.ts b/backend/src/services/change-walkthroughs.ts index 470c1e95..0b374577 100644 --- a/backend/src/services/change-walkthroughs.ts +++ b/backend/src/services/change-walkthroughs.ts @@ -1297,14 +1297,25 @@ export class ChangeWalkthroughService { } } + /** + * Resolves the model for one generation, waiting once for OpenCode's lazily-loaded global catalog so an explicit + * walkthrough model is registered before the first call. A failed wait is swallowed because generation proceeds and + * lets OpenCode surface its own error; the wait is per generation, never per stop. + */ private async resolveWalkthroughModel(session: SessionInfo): Promise { const configured = this.settingsService.getSettings().preferences.walkthroughModel?.trim() const parsed = configured ? parseOpenCodeModelRef(configured) : undefined const preferred = parsed ?? session.model if (preferred) { + try { + await resolveOpenCodeModel(this.openCodeClient, getOpenCodeGlobalConfigPath(), { + preferredModel: formatOpenCodeModelRef(preferred), + }) + } catch { + return preferred + } return preferred } - let resolved try { resolved = await resolveOpenCodeModel(this.openCodeClient, getOpenCodeGlobalConfigPath()) diff --git a/backend/src/services/opencode-manager-tool-plugin.ts b/backend/src/services/opencode-manager-tool-plugin.ts index b0b0952f..50b7e382 100644 --- a/backend/src/services/opencode-manager-tool-plugin.ts +++ b/backend/src/services/opencode-manager-tool-plugin.ts @@ -1,7 +1,5 @@ import { z } from 'zod' -import { ASSISTANT_NOTIFICATION_LIMITS, WalkthroughSourceSchema } from '@opencode-manager/shared/schemas' - -export const MANAGER_TOOL_NAME = 'ocm' +import { ASSISTANT_NOTIFICATION_LIMITS, MANAGER_TOOL_ACTIONS, MANAGER_TOOL_NAME, WalkthroughSourceSchema } from '@opencode-manager/shared/schemas' const MANAGER_TOOL_REQUEST_TIMEOUT_MS = 60000 @@ -40,8 +38,6 @@ export const MANAGER_TOOL_ALLOWED_ROUTES = [ const MANAGER_TOOL_ALLOWED_METHODS = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE'] as const -const MANAGER_TOOL_ACTION_NAMES = ['send_notification', 'request', 'open_walkthrough'] as const - const ManagerToolNotificationParamsSchema = z .object({ title: z.string().min(1).max(ASSISTANT_NOTIFICATION_LIMITS.TITLE_MAX).describe('The notification title.'), @@ -67,9 +63,9 @@ const ManagerToolWalkthroughParamsSchema = z source: WalkthroughSourceSchema.optional().describe('The change source to walk through. Defaults to the changes in this session.'), }) .strict() - .describe("Open the change Walkthrough for this session in the user's Manager window and start generating it if needed.") + .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.") -const MANAGER_TOOL_ACTION_PARAMS_SCHEMAS: Record<(typeof MANAGER_TOOL_ACTION_NAMES)[number], z.ZodType> = { +const MANAGER_TOOL_ACTION_PARAMS_SCHEMAS: Record<(typeof MANAGER_TOOL_ACTIONS)[number], z.ZodType> = { send_notification: ManagerToolNotificationParamsSchema, request: ManagerToolRequestParamsSchema, open_walkthrough: ManagerToolWalkthroughParamsSchema, @@ -100,7 +96,7 @@ function buildManagerToolInputJsonSchema(): Record { const jsonSchema: Record = z.toJSONSchema( z .object({ - action: z.enum(MANAGER_TOOL_ACTION_NAMES).describe('The OpenCode Manager action to perform.'), + action: z.enum(MANAGER_TOOL_ACTIONS).describe('The OpenCode Manager action to perform.'), params: z .union([ MANAGER_TOOL_ACTION_PARAMS_SCHEMAS.send_notification, @@ -116,7 +112,7 @@ function buildManagerToolInputJsonSchema(): Record { } function buildManagerToolActionRequiredKeys(): Record { - return Object.fromEntries(MANAGER_TOOL_ACTION_NAMES.map((name) => [name, requiredKeysOf(MANAGER_TOOL_ACTION_PARAMS_SCHEMAS[name])])) + return Object.fromEntries(MANAGER_TOOL_ACTIONS.map((name) => [name, requiredKeysOf(MANAGER_TOOL_ACTION_PARAMS_SCHEMAS[name])])) } function buildManagerToolDescription(): string { @@ -126,7 +122,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: open the change Walkthrough panel for the current session in the user's Manager window, generating it if needed; use when the user asks to walk through, review or explain the changes.", + "- 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.", 'Allowed request routes:', ] .concat(MANAGER_TOOL_ALLOWED_ROUTES.map((route) => `- ${route}`)) @@ -142,7 +138,7 @@ var ALLOWED_MATCHERS = ${JSON.stringify(buildRouteMatchers())}.map(function (mat return { method: matcher.method, pattern: new RegExp(matcher.source) } }) -var ACTION_NAMES = ${JSON.stringify(MANAGER_TOOL_ACTION_NAMES)} +var ACTION_NAMES = ${JSON.stringify(MANAGER_TOOL_ACTIONS)} var ACTION_REQUIRED_KEYS = ${JSON.stringify(buildManagerToolActionRequiredKeys())} @@ -238,21 +234,15 @@ var ACTIONS = { run: async function (params, context) { var body = params.source === undefined ? undefined : { source: params.source } var state = await postInternalApi('/change-walkthroughs/' + encodeURIComponent(context.sessionID), body, context.signal) - var metadata = { openPanel: 'walkthrough' } - if (params.source !== undefined) { - metadata.source = params.source - } + 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 { - content: 'Opened the walkthrough. It is generating; the user can page through it as stops are explained.', - metadata: metadata, - } + return 'Requested the walkthrough; it is generating.' + hint } var stops = state.walkthrough && Array.isArray(state.walkthrough.stops) ? state.walkthrough.stops.length : 0 if (state.walkthrough) { - return { content: 'Opened the walkthrough (' + stops + ' stops).', metadata: metadata } + return 'Requested the walkthrough (' + stops + ' stops).' + hint } - return { content: 'Opened the walkthrough.', metadata: metadata } + return 'Requested the walkthrough.' + hint }, }, } @@ -291,11 +281,7 @@ export default { input: INPUT_SCHEMA, options: { codemode: false }, execute: async function (input, context) { - var result = await runAction(input, context) - if (result !== null && typeof result === 'object' && typeof result.content === 'string') { - return result - } - return { content: result } + return { content: await runAction(input, context) } }, }) }) diff --git a/backend/src/services/opencode/generate-text.ts b/backend/src/services/opencode/generate-text.ts index ee81c0d3..8c2c8fe8 100644 --- a/backend/src/services/opencode/generate-text.ts +++ b/backend/src/services/opencode/generate-text.ts @@ -1,5 +1,4 @@ import type { ModelRef } from '@opencode-manager/shared/opencode' -import { formatOpenCodeModelRef } from '@opencode-manager/shared/opencode' import { getOpenCodeGlobalConfigPath } from '@opencode-manager/shared/config/env' import type { OpenCodeClient } from './client' import { resolveOpenCodeModel } from '../opencode-models' @@ -38,34 +37,10 @@ async function generateText( input: { prompt: string; model?: ModelRef }, signal: AbortSignal, ): Promise<{ text: string }> { - if (input.model) { - await waitForGenerateModel(client, input.model, signal) - return client.api.generate.text({ prompt: input.prompt, model: input.model }, { signal }) - } - - const model = await resolveGenerateModel(client, signal) + const model = input.model ?? await resolveGenerateModel(client, signal) return client.api.generate.text({ prompt: input.prompt, model }, { signal }) } -/** - * Waits for an explicitly requested model to appear in OpenCode's global config-location catalog, which loads lazily after OpenCode starts. - * Generation proceeds even if the wait times out or the model stays unconfigured, so OpenCode can surface its own error; an abort still propagates. - */ -async function waitForGenerateModel( - client: OpenCodeClient, - model: ModelRef, - signal: AbortSignal, -): Promise { - try { - await resolveOpenCodeModel(client, getOpenCodeGlobalConfigPath(), { - signal, - preferredModel: formatOpenCodeModelRef(model), - }) - } catch { - signal.throwIfAborted() - } -} - /** OpenCode serves generation from its global config location, so the model must be resolved there once its catalog has loaded. */ async function resolveGenerateModel(client: OpenCodeClient, signal: AbortSignal): Promise { const { providerID, id, variant } = await resolveOpenCodeModel(client, getOpenCodeGlobalConfigPath(), { signal }) diff --git a/backend/test/services/change-walkthroughs.test.ts b/backend/test/services/change-walkthroughs.test.ts index 6186d82c..1cc13528 100644 --- a/backend/test/services/change-walkthroughs.test.ts +++ b/backend/test/services/change-walkthroughs.test.ts @@ -1252,6 +1252,26 @@ describe('ChangeWalkthroughService', () => { ).toBe(true) }) + it('waits for an explicit model once per generation, not per stop', async () => { + sessions[SESSION_ID]!.changes = LARGE_CHANGES + sessions[SESSION_ID]!.info = { + id: SESSION_ID, + title: 'Title', + model: { providerID: 'openai', id: 'gpt-5-mini' }, + } as SessionInfo + fake.setGenerateImpl((prompt) => + Promise.resolve(prompt.includes(PLAN_MARKER) ? LARGE_PLAN_REPLY : EXPLANATION_REPLY), + ) + + await service.generate(SESSION_ID, {}) + + expect(fake.generateModels).toHaveLength(4) + expect( + fake.generateModels.every((model) => model?.providerID === 'openai' && model.id === 'gpt-5-mini'), + ).toBe(true) + expect(vi.mocked(fake.client.api.model.list)).toHaveBeenCalledTimes(1) + }) + it('includes the resolved default model in the explanation key', async () => { fake.setGenerateImpl(async () => modelReply([{ title: 'A', explanation: 'x', hunkIds: THREE_HUNK_IDS }])) diff --git a/backend/test/services/opencode-manager-tool-plugin.test.ts b/backend/test/services/opencode-manager-tool-plugin.test.ts index 173a872b..e826cbca 100644 --- a/backend/test/services/opencode-manager-tool-plugin.test.ts +++ b/backend/test/services/opencode-manager-tool-plugin.test.ts @@ -5,8 +5,8 @@ import http from 'http' import type { AddressInfo } from 'net' import path from 'path' import os from 'os' -import { ASSISTANT_NOTIFICATION_LIMITS, AssistantNotificationRequestSchema } from '@opencode-manager/shared/schemas' -import { MANAGER_TOOL_NAME, MANAGER_TOOL_ALLOWED_ROUTES, parseAllowedRoute } from '../../src/services/opencode-manager-tool-plugin' +import { ASSISTANT_NOTIFICATION_LIMITS, AssistantNotificationRequestSchema, MANAGER_TOOL_NAME } from '@opencode-manager/shared/schemas' +import { MANAGER_TOOL_ALLOWED_ROUTES, parseAllowedRoute } from '../../src/services/opencode-manager-tool-plugin' import { installManagedPlugins, getOpenCodePluginDir } from '../../src/services/opencode/plugin-registry' import { loadGeneratedPlugin, type GeneratedTool } from '../helpers/opencode-plugin-context' import { resolveOpenCode2Binary, runOpenCodeStandalone } from '../helpers/opencode-binary' @@ -132,7 +132,8 @@ describe('ocm-manager plugin', () => { const tool = await loadTool(configHome) expect(tool.description).toContain('open_walkthrough') - expect(tool.description).toContain("open the change Walkthrough panel for the current session in the user's Manager window") + expect(tool.description).toContain('request the change Walkthrough for the current session') + expect(tool.description).toContain('when this session is open on desktop') }) it('enforces the notification limits the internal API enforces', async () => { @@ -242,8 +243,10 @@ describe('ocm-manager plugin', () => { expect(init.headers.Authorization).toBe('Bearer secret-token') expect(init.headers['content-type']).toBe('application/json') expect(JSON.parse(init.body)).toEqual({ source: { kind: 'staged' } }) - expect(result.content).toBe('Opened the walkthrough (2 stops).') - expect(result.metadata).toEqual({ openPanel: 'walkthrough', 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.', + ) + expect(result.metadata).toBeUndefined() }) it('reports that the walkthrough is generating', async () => { @@ -252,8 +255,10 @@ describe('ocm-manager plugin', () => { const result = await runToolResult(tool, { action: 'open_walkthrough', params: {} }, { sessionID: 'ses_abc' }) - expect(result.content).toBe('Opened the walkthrough. It is generating; the user can page through it as stops are explained.') - expect(result.metadata).toEqual({ openPanel: 'walkthrough' }) + 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.', + ) + expect(result.metadata).toBeUndefined() }) it('opens the walkthrough without a body when no source is given', async () => { @@ -376,6 +381,8 @@ describe('ocm-manager plugin', () => { ['POST', '/multi-runs'], ['POST', '/multi-runs/1/fusions'], ['POST', '/multi-runs/1/entries/2/discard'], + ['GET', '/change-walkthroughs/x'], + ['POST', '/change-walkthroughs/x'], ] as const for (const [method, path] of deniedRoutes) { diff --git a/backend/test/services/opencode/generate-text.test.ts b/backend/test/services/opencode/generate-text.test.ts index e5ce02cd..bd0cc711 100644 --- a/backend/test/services/opencode/generate-text.test.ts +++ b/backend/test/services/opencode/generate-text.test.ts @@ -3,7 +3,7 @@ import { getOpenCodeGlobalConfigPath } from '@opencode-manager/shared/config/env import type { ModelInfo, ModelRef } from '@opencode-manager/shared/opencode' import type { OpenCodeClient } from '../../../src/services/opencode/client' import { GenerateTextTimeoutError, generateTextWithTimeout } from '../../../src/services/opencode/generate-text' -import { MODEL_LOAD_POLL_MS, MODEL_LOAD_TIMEOUT_MS } from '../../../src/services/opencode-models' +import { MODEL_LOAD_POLL_MS } from '../../../src/services/opencode-models' interface GenerateCall { input: { prompt: string; model?: ModelRef } @@ -77,35 +77,14 @@ describe('generateTextWithTimeout', () => { expect(calls[0]?.input.model).toEqual({ providerID: 'openai', id: 'gpt-5-mini' }) }) - it('waits for the provided model to load before generating', async () => { - vi.useFakeTimers() - const model: ModelRef = { providerID: 'anthropic', id: 'claude-sonnet-4', variant: 'high' } - const { client, calls } = makeClient(async () => ({ text: 'hello' }), [ - [], - [{ providerID: 'anthropic', id: 'claude-sonnet-4', enabled: true } as ModelInfo], - ]) - - const promise = generateTextWithTimeout(client, { prompt: 'write', model }, 10_000) - await vi.advanceTimersByTimeAsync(0) - expect(calls).toHaveLength(0) - - await vi.advanceTimersByTimeAsync(MODEL_LOAD_POLL_MS) - await expect(promise).resolves.toBe('hello') - expect(calls).toHaveLength(1) - expect(calls[0]?.input).toEqual({ prompt: 'write', model }) - }) - - it('generates with the provided model when its catalog never loads', async () => { - vi.useFakeTimers() + 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' } - const { client, calls } = makeClient(async () => ({ text: 'hello' }), [[]]) - const promise = generateTextWithTimeout(client, { prompt: 'write', model }, 100_000) - await vi.advanceTimersByTimeAsync(MODEL_LOAD_TIMEOUT_MS) - await expect(promise).resolves.toBe('hello') + await generateTextWithTimeout(client, { prompt: 'write', model }, 1000) - expect(calls).toHaveLength(1) expect(calls[0]?.input).toEqual({ prompt: 'write', model }) + expect(modelList).not.toHaveBeenCalled() }) it('rejects with GenerateTextTimeoutError and aborts the request after the timeout', async () => { diff --git a/frontend/src/components/session/ChangesWalkthroughSheet.test.tsx b/frontend/src/components/session/ChangesWalkthroughSheet.test.tsx index 5260b466..e9e991ce 100644 --- a/frontend/src/components/session/ChangesWalkthroughSheet.test.tsx +++ b/frontend/src/components/session/ChangesWalkthroughSheet.test.tsx @@ -385,7 +385,7 @@ describe('ChangesWalkthroughSheet', () => { it('applies an external source request to the walkthrough source', async () => { mocks.getChangeWalkthrough.mockResolvedValue(state({ walkthrough: null })) - renderSheet({ sourceRequest: { sessionId: 'ses_1', source: { kind: 'staged' }, nonce: 1 } }) + renderSheet({ sourceRequest: { sessionId: 'ses_1', source: { kind: 'staged' } } }) await waitFor(() => { expect(mocks.getChangeWalkthrough).toHaveBeenCalledWith('ses_1', { kind: 'staged' }) @@ -396,7 +396,7 @@ describe('ChangesWalkthroughSheet', () => { it('applies a pull request request with its number and base', async () => { mocks.getChangeWalkthrough.mockResolvedValue(state({ walkthrough: null })) renderSheet({ - sourceRequest: { sessionId: 'ses_1', source: { kind: 'pullRequest', number: 12 }, nonce: 1 }, + sourceRequest: { sessionId: 'ses_1', source: { kind: 'pullRequest', number: 12 } }, }) await waitFor(() => { @@ -409,7 +409,7 @@ describe('ChangesWalkthroughSheet', () => { const user = userEvent.setup() mocks.getChangeWalkthrough.mockResolvedValue(state({ walkthrough: null })) const { rerender, onOpenChange } = renderSheet({ - sourceRequest: { sessionId: 'ses_1', source: { kind: 'staged' }, nonce: 1 }, + sourceRequest: { sessionId: 'ses_1', source: { kind: 'staged' } }, }) await waitFor(() => { expect(mocks.getChangeWalkthrough).toHaveBeenCalledWith('ses_1', { kind: 'staged' }) @@ -426,7 +426,7 @@ describe('ChangesWalkthroughSheet', () => { sessionId="ses_1" open onOpenChange={onOpenChange} - sourceRequest={{ sessionId: 'ses_1', source: { kind: 'staged' }, nonce: 2 }} + sourceRequest={{ sessionId: 'ses_1', source: { kind: 'staged' } }} />, ) @@ -440,7 +440,7 @@ describe('ChangesWalkthroughSheet', () => { const user = userEvent.setup() mocks.getChangeWalkthrough.mockResolvedValue(state({ walkthrough: null })) const { rerender, onOpenChange } = renderSheet({ - sourceRequest: { sessionId: 'ses_1', source: { kind: 'staged' }, nonce: 1 }, + sourceRequest: { sessionId: 'ses_1', source: { kind: 'staged' } }, }) await waitFor(() => { expect(mocks.getChangeWalkthrough).toHaveBeenCalledWith('ses_1', { kind: 'staged' }) @@ -458,7 +458,7 @@ describe('ChangesWalkthroughSheet', () => { sessionId="ses_1" open onOpenChange={onOpenChange} - sourceRequest={{ sessionId: 'ses_1', source: undefined, nonce: 2 }} + sourceRequest={{ sessionId: 'ses_1', source: undefined }} />, ) @@ -467,16 +467,6 @@ describe('ChangesWalkthroughSheet', () => { expect(mocks.getChangeWalkthrough).not.toHaveBeenCalledWith('ses_1', { kind: 'staged' }) }) - it('ignores a request from another session', async () => { - mocks.getChangeWalkthrough.mockResolvedValue(state({ walkthrough: null })) - renderSheet({ sourceRequest: { sessionId: 'ses_other', source: { kind: 'staged' }, nonce: 1 } }) - - await waitFor(() => { - expect(mocks.getChangeWalkthrough).toHaveBeenCalledWith('ses_1', { kind: 'session' }) - }) - expect(mocks.getChangeWalkthrough).not.toHaveBeenCalledWith('ses_1', { kind: 'staged' }) - }) - it('clears a generation error when the source changes', async () => { const user = userEvent.setup() mocks.getChangeWalkthrough.mockResolvedValue(state({ walkthrough: null })) diff --git a/frontend/src/components/session/ChangesWalkthroughSheet.tsx b/frontend/src/components/session/ChangesWalkthroughSheet.tsx index 51f08867..dbbad664 100644 --- a/frontend/src/components/session/ChangesWalkthroughSheet.tsx +++ b/frontend/src/components/session/ChangesWalkthroughSheet.tsx @@ -239,13 +239,12 @@ const WalkthroughSourceInputs = memo(function WalkthroughSourceInputs() { }) /** - * A one-shot request to open the walkthrough on a given source. `nonce` makes a repeated request for - * the same source a distinct value, so it re-applies; `source` undefined leaves the selection alone. + * A one-shot request to open the walkthrough on a given source. A new request object re-applies, so a + * repeated request for the same source takes effect; `source` undefined leaves the selection alone. */ export interface WalkthroughSourceRequest { sessionId: string source?: WalkthroughSource - nonce: number } interface ChangesWalkthroughProviderProps { @@ -295,7 +294,7 @@ export function ChangesWalkthroughProvider({ }, [active, sessionId, sourceKey, walkthrough?.createdAt]) useEffect(() => { - if (!sourceRequest || sourceRequest.sessionId !== sessionId) return + if (!sourceRequest) return const requested = sourceRequest.source if (!requested) return setSource(requested) @@ -306,7 +305,7 @@ export function ChangesWalkthroughProvider({ if (requested.kind === 'pullRequest') { setNumberInput(String(requested.number)) } - }, [sourceRequest, sessionId]) + }, [sourceRequest]) const hunksById = new Map(walkthrough?.hunks.map((hunk) => [hunk.id, hunk]) ?? []) const stops = walkthrough?.stops ?? [] diff --git a/frontend/src/hooks/__tests__/useAutoOpenWalkthrough.test.tsx b/frontend/src/hooks/__tests__/useAutoOpenWalkthrough.test.tsx index ec9d6e27..f5f9d288 100644 --- a/frontend/src/hooks/__tests__/useAutoOpenWalkthrough.test.tsx +++ b/frontend/src/hooks/__tests__/useAutoOpenWalkthrough.test.tsx @@ -111,6 +111,44 @@ describe('useAutoOpenWalkthrough', () => { expect(onOpen).toHaveBeenCalledTimes(1) }) + it('opens once when a call completes in the last message across streaming updates', () => { + const onOpen = vi.fn() + const { rerender } = renderAutoOpen({ + sessionId: 's1', + messages: [assistantMessage('m1', otherToolPart('t1'))], + enabled: true, + loading: false, + onOpen, + }) + + rerender({ + sessionId: 's1', + messages: [ + assistantMessage('m1', otherToolPart('t1')), + assistantMessage('m2', openWalkthroughPart('t2', 'running')), + ], + enabled: true, + loading: false, + onOpen, + }) + + expect(onOpen).not.toHaveBeenCalled() + + rerender({ + sessionId: 's1', + messages: [ + assistantMessage('m1', otherToolPart('t1')), + assistantMessage('m2', openWalkthroughPart('t2', 'completed')), + ], + enabled: true, + loading: false, + onOpen, + }) + + expect(onOpen).toHaveBeenCalledTimes(1) + expect(onOpen).toHaveBeenCalledWith(undefined) + }) + it('passes the requested source to the opener', () => { const onOpen = vi.fn() const part: SessionMessageAssistantTool = { diff --git a/frontend/src/hooks/useAutoOpenWalkthrough.ts b/frontend/src/hooks/useAutoOpenWalkthrough.ts index 48211e01..d877324a 100644 --- a/frontend/src/hooks/useAutoOpenWalkthrough.ts +++ b/frontend/src/hooks/useAutoOpenWalkthrough.ts @@ -27,6 +27,7 @@ export function useAutoOpenWalkthrough({ }: UseAutoOpenWalkthroughOptions): void { const seenRef = useRef | null>(null) const frontierRef = useRef(null) + const lastScannedRef = useRef(null) const sessionRef = useRef(undefined) const onOpenRef = useRef(onOpen) onOpenRef.current = onOpen @@ -36,16 +37,33 @@ export function useAutoOpenWalkthrough({ sessionRef.current = sessionId seenRef.current = null frontierRef.current = null + lastScannedRef.current = null } if (loading) return if (seenRef.current === null) { seenRef.current = new Set(collectOpenWalkthroughCalls(messages).map((call) => call.id)) frontierRef.current = messages[0]?.id ?? null + lastScannedRef.current = messages[messages.length - 1]?.id ?? null return } - const frontier = frontierRef.current - const liveMessages = - frontier === null ? messages : messages.filter((message) => message.id >= frontier) + const lastScannedId = lastScannedRef.current + let scanFrom = -1 + if (lastScannedId !== null) { + for (let index = messages.length - 1; index >= 0; index -= 1) { + if (messages[index]?.id === lastScannedId) { + scanFrom = index + break + } + } + } + let liveMessages: SessionMessageInfo[] + if (scanFrom >= 0) { + liveMessages = messages.slice(scanFrom) + } else { + const frontier = frontierRef.current + liveMessages = frontier === null ? messages : messages.filter((message) => message.id >= frontier) + } + lastScannedRef.current = messages[messages.length - 1]?.id ?? null let opened = false for (const call of collectOpenWalkthroughCalls(liveMessages)) { if (seenRef.current.has(call.id)) continue diff --git a/frontend/src/lib/walkthroughTool.ts b/frontend/src/lib/walkthroughTool.ts index 497c298f..5b95a541 100644 --- a/frontend/src/lib/walkthroughTool.ts +++ b/frontend/src/lib/walkthroughTool.ts @@ -1,11 +1,8 @@ import type { SessionMessageAssistantTool, SessionMessageInfo } from '@opencode-manager/shared/opencode' -import { WalkthroughSourceSchema } from '@opencode-manager/shared/schemas' +import { MANAGER_TOOL_NAME, MANAGER_TOOL_OPEN_WALKTHROUGH_ACTION, WalkthroughSourceSchema } from '@opencode-manager/shared/schemas' import type { WalkthroughSource } from '@opencode-manager/shared/schemas' -export const OCM_TOOL_NAME = 'ocm' -export const OPEN_WALKTHROUGH_ACTION = 'open_walkthrough' - -export interface OpenWalkthroughCall { +interface OpenWalkthroughCall { id: string source?: WalkthroughSource } @@ -28,8 +25,8 @@ function readOpenWalkthroughSource(params: unknown): WalkthroughSource | undefin export function readOpenWalkthroughCall( part: SessionMessageAssistantTool, ): OpenWalkthroughCall | undefined { - if (part.name !== OCM_TOOL_NAME || part.state.status !== 'completed') return undefined - if (part.state.input.action !== OPEN_WALKTHROUGH_ACTION) return undefined + if (part.name !== MANAGER_TOOL_NAME || part.state.status !== 'completed') return undefined + if (part.state.input.action !== MANAGER_TOOL_OPEN_WALKTHROUGH_ACTION) return undefined return { id: part.id, source: readOpenWalkthroughSource(part.state.input.params) } } diff --git a/frontend/src/pages/SessionDetail.tsx b/frontend/src/pages/SessionDetail.tsx index fccb0c97..69c3502b 100644 --- a/frontend/src/pages/SessionDetail.tsx +++ b/frontend/src/pages/SessionDetail.tsx @@ -304,11 +304,10 @@ export function SessionDetail() { const handleShowMcpDialog = useCallback(() => setMcpDialogOpen(true), [setMcpDialogOpen]); const handleShowSkillsDialog = useCallback(() => setSkillsDialogOpen(true), [setSkillsDialogOpen]); const handleShowWalkthrough = useCallback((source?: WalkthroughSource) => { - setRequestedWalkthroughSource((current) => ({ + setRequestedWalkthroughSource({ sessionId: sessionId ?? '', source, - nonce: (current?.nonce ?? 0) + 1, - })); + }); setWalkthroughOpen(true); }, [sessionId, setWalkthroughOpen]); const handleShowWalkthroughCommand = useCallback(() => handleShowWalkthrough(), [handleShowWalkthrough]); diff --git a/shared/src/schemas/internal-assistant.ts b/shared/src/schemas/internal-assistant.ts index 9c00f595..056698a4 100644 --- a/shared/src/schemas/internal-assistant.ts +++ b/shared/src/schemas/internal-assistant.ts @@ -1,6 +1,12 @@ import { z } from 'zod' import { UserPreferencesSchema } from './settings' +export const MANAGER_TOOL_NAME = 'ocm' + +export const MANAGER_TOOL_OPEN_WALKTHROUGH_ACTION = 'open_walkthrough' + +export const MANAGER_TOOL_ACTIONS = ['send_notification', 'request', MANAGER_TOOL_OPEN_WALKTHROUGH_ACTION] as const + export const AssistantNotificationPrioritySchema = z.enum(['normal', 'high']) export const ASSISTANT_NOTIFICATION_LIMITS = {