From ee1e6ae7c2ffffad8859b5c671ac32e41eecf7d2 Mon Sep 17 00:00:00 2001 From: Junmo Kim Date: Sat, 7 Nov 2026 12:27:04 +0900 Subject: [PATCH] feat(opencode): show round usage and tokens per second (#1668) --- .../messageConverter.roundSummary.test.ts | 36 ++ cli/src/agent/messageConverter.ts | 30 + cli/src/agent/types.ts | 19 + cli/src/copilot/copilotRemoteLauncher.ts | 2 + cli/src/dsh/dshRemoteLauncher.ts | 1 + cli/src/grok/grokRemoteLauncher.ts | 2 + cli/src/kimi/kimiRemoteLauncher.ts | 2 + .../opencode/opencodeRemoteLauncher.test.ts | 558 +++++++++++++++--- cli/src/opencode/opencodeRemoteLauncher.ts | 140 ++++- .../utils/opencodeCompactBridge.test.ts | 12 + .../opencode/utils/opencodeCompactBridge.ts | 2 +- .../opencodeRoundSummary.boundaries.test.ts | 73 +++ .../opencodeRoundSummary.prototype.test.ts | 30 + .../utils/opencodeRoundSummary.test.ts | 167 ++++++ .../opencode/utils/opencodeRoundSummary.ts | 295 +++++++++ .../utils/opencodeRoundSummary.v2.test.ts | 161 +++++ web/e2e-fixtures/concise-summary-fixture.html | 1 + web/e2e-fixtures/concise-summary-fixture.tsx | 46 ++ .../chat/conciseView.roundSummary.test.tsx | 261 ++++++++ web/src/chat/conciseView.ts | 16 + .../chat/normalizeAgent.roundSummary.test.ts | 111 ++++ web/src/chat/normalizeAgent.ts | 65 ++ web/src/chat/reconcile.roundSummary.test.ts | 31 + web/src/chat/reconcile.ts | 2 + web/src/chat/reducer.test.ts | 59 ++ web/src/chat/reducerTimeline.ts | 16 +- web/src/chat/responseGroups.ts | 52 ++ web/src/chat/types.ts | 2 + .../messages/MessageMetadata.test.ts | 19 +- .../messages/MessageMetadata.tsx | 19 +- .../SessionChat.projection-boundary.test.tsx | 167 ++++++ web/src/components/SessionChat.tsx | 86 ++- 32 files changed, 2375 insertions(+), 108 deletions(-) create mode 100644 cli/src/agent/messageConverter.roundSummary.test.ts create mode 100644 cli/src/opencode/utils/opencodeRoundSummary.boundaries.test.ts create mode 100644 cli/src/opencode/utils/opencodeRoundSummary.prototype.test.ts create mode 100644 cli/src/opencode/utils/opencodeRoundSummary.test.ts create mode 100644 cli/src/opencode/utils/opencodeRoundSummary.ts create mode 100644 cli/src/opencode/utils/opencodeRoundSummary.v2.test.ts create mode 100644 web/e2e-fixtures/concise-summary-fixture.html create mode 100644 web/e2e-fixtures/concise-summary-fixture.tsx create mode 100644 web/src/chat/conciseView.roundSummary.test.tsx create mode 100644 web/src/chat/normalizeAgent.roundSummary.test.ts create mode 100644 web/src/chat/reconcile.roundSummary.test.ts create mode 100644 web/src/chat/responseGroups.ts create mode 100644 web/src/components/SessionChat.projection-boundary.test.tsx diff --git a/cli/src/agent/messageConverter.roundSummary.test.ts b/cli/src/agent/messageConverter.roundSummary.test.ts new file mode 100644 index 00000000..0d37d5cf --- /dev/null +++ b/cli/src/agent/messageConverter.roundSummary.test.ts @@ -0,0 +1,36 @@ +import { describe, expect, it } from 'vitest'; +import { convertAgentMessage } from './messageConverter'; + +describe('convertAgentMessage round summary', () => { + it('converts the generic carrier into the HAPI-owned round-summary wire contract', () => { + const converted = convertAgentMessage({ + type: 'round_summary', + summary: { + usage: { inputTokens: 120, outputTokens: 30, cacheReadInputTokens: 90, cacheCreationInputTokens: 10 }, + modelUsage: { + 'openai/gpt-5.4': { inputTokens: 120, outputTokens: 30, cacheReadInputTokens: 90, cacheCreationInputTokens: 10 } + }, + totalCostUsd: 0.034, + numTurns: 2, + durationMs: 1_250, + generationMs: 500, + generationOutputTokens: 25 + } + } as never); + + expect(converted).toEqual({ + type: 'round-summary', + summary: { + usage: { input_tokens: 120, output_tokens: 30, cache_read_input_tokens: 90, cache_creation_input_tokens: 10 }, + modelUsage: { + 'openai/gpt-5.4': { inputTokens: 120, outputTokens: 30, cacheReadInputTokens: 90, cacheCreationInputTokens: 10 } + }, + total_cost_usd: 0.034, + num_turns: 2, + duration_ms: 1_250, + generation_ms: 500, + generation_output_tokens: 25 + } + }); + }); +}); diff --git a/cli/src/agent/messageConverter.ts b/cli/src/agent/messageConverter.ts index 549dc62f..84814db7 100644 --- a/cli/src/agent/messageConverter.ts +++ b/cli/src/agent/messageConverter.ts @@ -42,6 +42,18 @@ export type CodexMessage = } | { type: 'plan'; entries: PlanItem[] } | { type: 'error'; message: string } + | { + type: 'round-summary'; + summary: { + usage: { input_tokens: number; output_tokens: number; cache_read_input_tokens: number; cache_creation_input_tokens: number }; + modelUsage: Record; + total_cost_usd?: number; + num_turns: number; + duration_ms: number; + generation_ms?: number; + generation_output_tokens?: number; + }; + } | { type: 'generated-image'; imageId: string; @@ -121,6 +133,24 @@ export function convertAgentMessage(message: AgentMessage, model?: string | null type: 'plan', entries: message.items }; + case 'round_summary': + return { + type: 'round-summary', + summary: { + usage: { + input_tokens: message.summary.usage.inputTokens, + output_tokens: message.summary.usage.outputTokens, + cache_read_input_tokens: message.summary.usage.cacheReadInputTokens, + cache_creation_input_tokens: message.summary.usage.cacheCreationInputTokens + }, + modelUsage: message.summary.modelUsage, + ...(message.summary.totalCostUsd !== undefined ? { total_cost_usd: message.summary.totalCostUsd } : {}), + num_turns: message.summary.numTurns, + duration_ms: message.summary.durationMs, + ...(message.summary.generationMs !== undefined && message.summary.generationOutputTokens !== undefined + ? { generation_ms: message.summary.generationMs, generation_output_tokens: message.summary.generationOutputTokens } : {}) + } + }; case 'generated_image': return { type: 'generated-image', diff --git a/cli/src/agent/types.ts b/cli/src/agent/types.ts index 6a394946..9cff3e6c 100644 --- a/cli/src/agent/types.ts +++ b/cli/src/agent/types.ts @@ -29,6 +29,24 @@ export type PlanItem = { status: 'pending' | 'in_progress' | 'completed'; }; +export type AgentRoundModelUsage = { + inputTokens: number; + outputTokens: number; + cacheReadInputTokens: number; + cacheCreationInputTokens: number; +}; + +export type AgentRoundSummary = { + usage: AgentRoundModelUsage; + modelUsage: Record; + totalCostUsd?: number; + numTurns: number; + durationMs: number; + /** Assistant output + reasoning and provider-active time, excluding tools/compaction. */ + generationMs?: number; + generationOutputTokens?: number; +}; + export type AgentMessage = | { type: 'text'; text: string; id?: string; live?: boolean; streamSnapshot?: boolean } | { type: 'reasoning'; text: string; id?: string; live?: boolean } @@ -57,6 +75,7 @@ export type AgentMessage = | { type: 'plan'; items: PlanItem[] } | { type: 'generated_image'; imageId: string; fileName: string; mimeType: string; source?: InlineMediaSource } | { type: 'turn_complete'; stopReason: string } + | { type: 'round_summary'; summary: AgentRoundSummary } | { type: 'error'; message: string }; export type PermissionOption = { diff --git a/cli/src/copilot/copilotRemoteLauncher.ts b/cli/src/copilot/copilotRemoteLauncher.ts index f80d1c6a..57d94848 100644 --- a/cli/src/copilot/copilotRemoteLauncher.ts +++ b/cli/src/copilot/copilotRemoteLauncher.ts @@ -276,6 +276,8 @@ export class CopilotRemoteLauncher extends RemoteLauncherBase { case 'turn_complete': this.messageBuffer.addMessage('Turn complete', 'status'); break; + case 'round_summary': + break; default: { const _exhaustive: never = message; return _exhaustive; diff --git a/cli/src/dsh/dshRemoteLauncher.ts b/cli/src/dsh/dshRemoteLauncher.ts index d6d79e24..92864027 100644 --- a/cli/src/dsh/dshRemoteLauncher.ts +++ b/cli/src/dsh/dshRemoteLauncher.ts @@ -261,6 +261,7 @@ export class DshRemoteLauncher extends RemoteLauncherBase { case 'tool_call': case 'tool_result': case 'plan': + case 'round_summary': break default: { const _exhaustive: never = message diff --git a/cli/src/grok/grokRemoteLauncher.ts b/cli/src/grok/grokRemoteLauncher.ts index 175b2697..8d200878 100644 --- a/cli/src/grok/grokRemoteLauncher.ts +++ b/cli/src/grok/grokRemoteLauncher.ts @@ -422,6 +422,8 @@ class GrokRemoteLauncher extends RemoteLauncherBase { case 'turn_complete': this.messageBuffer.addMessage('Turn complete', 'status') break + case 'round_summary': + break case 'usage': break default: { diff --git a/cli/src/kimi/kimiRemoteLauncher.ts b/cli/src/kimi/kimiRemoteLauncher.ts index ff8f94a9..4a6d158b 100644 --- a/cli/src/kimi/kimiRemoteLauncher.ts +++ b/cli/src/kimi/kimiRemoteLauncher.ts @@ -265,6 +265,8 @@ class KimiRemoteLauncher extends RemoteLauncherBase { case 'turn_complete': this.messageBuffer.addMessage('Turn complete', 'status'); break; + case 'round_summary': + break; default: { const _exhaustive: never = message; return _exhaustive; diff --git a/cli/src/opencode/opencodeRemoteLauncher.test.ts b/cli/src/opencode/opencodeRemoteLauncher.test.ts index a9357f92..14815dea 100644 --- a/cli/src/opencode/opencodeRemoteLauncher.test.ts +++ b/cli/src/opencode/opencodeRemoteLauncher.test.ts @@ -2,10 +2,14 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { MessageQueue2 } from '@/utils/MessageQueue2'; import { MessageBuffer } from '@/ui/ink/messageBuffer'; import type { OpencodeMode, PermissionMode } from './types'; +import { RPC_METHODS } from '@hapi/protocol/rpcMethods'; +import { getOpencodeNativeToolInstruction } from './utils/systemPrompt'; import type { PromptContent } from '@/agent/types'; import { ACP_INDETERMINATE_SYMBOL } from '@/agent/backends/acp/AcpStdioTransport'; + const harness = vi.hoisted(() => ({ + transcriptFetchImpl: null as null | (() => Promise), servePid: null as number | null, servePidCalls: [] as number[][], setModelArgs: [] as Array<{ sessionId: string; modelId: string; flavor?: string }>, @@ -291,7 +295,9 @@ vi.mock('./utils/opencodeNativeTranscript', async (importOriginal) => { const actual = await importOriginal(); return { OpencodeNativeTranscript: class extends actual.OpencodeNativeTranscript { constructor(options: ConstructorParameters[0]) { - super({ ...options, fetchImpl: (async () => Response.json([])) }); + super({ ...options, fetchImpl: async () => harness.transcriptFetchImpl + ? await harness.transcriptFetchImpl() + : Response.json([]) }); } } }; }); @@ -380,6 +386,40 @@ vi.mock('./utils/opencodeCompactBridge', () => ({ }) })); +const roundSummaryHarness = vi.hoisted(() => ({ + snapshotCalls: [] as Array<{ baseUrl: string; sessionId: string }>, + summaryCalls: [] as Array<{ promptText: string; durationMs: number; snapshot: { messageIds: string[] } }>, + snapshot: { messageIds: [] } as { messageIds: string[] } | null, + snapshotImpl: null as null | (() => Promise), + summary: { + usage: { inputTokens: 10, outputTokens: 2, cacheReadInputTokens: 0, cacheCreationInputTokens: 0 }, + modelUsage: { 'openai/gpt-5.4': { inputTokens: 10, outputTokens: 2, cacheReadInputTokens: 0, cacheCreationInputTokens: 0 } }, + numTurns: 1, + durationMs: 10 + } as unknown | null, + summaryImpl: null as null | ((opts: { promptText: string }) => Promise) +})); + +vi.mock('./utils/opencodeRoundSummary', () => ({ + captureOpencodeRoundSnapshot: vi.fn(async (opts: { baseUrl: string; sessionId: string }) => { + roundSummaryHarness.snapshotCalls.push(opts); + if (roundSummaryHarness.snapshotImpl) return roundSummaryHarness.snapshotImpl(); + return roundSummaryHarness.snapshot; + }), + fetchOpencodeRoundSummary: vi.fn(async (opts: { promptText: string; durationMs: number; snapshot: { messageIds: string[] } }) => { + roundSummaryHarness.summaryCalls.push(opts); + const summary = roundSummaryHarness.summaryImpl + ? await roundSummaryHarness.summaryImpl(opts) + : harness.events.lastIndexOf('prompt:start') > harness.events.lastIndexOf('prompt:end') + ? null + : roundSummaryHarness.summary; + return { + snapshot: { messageIds: [...opts.snapshot.messageIds, 'post-' + roundSummaryHarness.summaryCalls.length] }, + summary + }; + }) +})); + vi.mock('@/ui/logger', () => ({ logger: { debug: vi.fn(), @@ -440,6 +480,7 @@ function createSessionStub( const sessionEvents: Array<{ type: string; [key: string]: unknown }> = []; const sentAgentMessages: unknown[] = []; + const deliveryEvents: string[] = []; const claudeSessionMessages: unknown[] = []; const rpcHandlers = new Map unknown>(); const setModelReasoningEffort = vi.fn(); @@ -477,6 +518,7 @@ function createSessionStub( sendUserMessage(_text: string) {}, sendSessionEvent(event: { type: string; [key: string]: unknown }) { sessionEvents.push(event); + deliveryEvents.push('ready'); }, emitMessagesConsumed(localIds: string[], options?: { clearQueuedThinkingGrace?: boolean; steered?: boolean }) { emitMessagesConsumedCalls.push({ localIds, options }); @@ -517,6 +559,7 @@ function createSessionStub( }, sendAgentMessage(message: unknown) { sentAgentMessages.push(message); + deliveryEvents.push('agent'); }, sendSessionEvent(event: { type: string; [key: string]: unknown }) { client.sendSessionEvent(event); @@ -524,7 +567,8 @@ function createSessionStub( sendUserMessage(_text: string) {} }; - return { session, sessionEvents, sentAgentMessages, agentMessages: sentAgentMessages, claudeSessionMessages, rpcHandlers, setModel, setModelReasoningEffort, pushKeepAlive, emitMessagesConsumedCalls, thinkingChangeCalls, steeringActiveCalls, steerIndeterminateCalls, steerStateImpl }; + return { session, sessionEvents, sentAgentMessages, deliveryEvents, agentMessages: sentAgentMessages, claudeSessionMessages, rpcHandlers, setModel, setModelReasoningEffort, pushKeepAlive, emitMessagesConsumedCalls, thinkingChangeCalls, steeringActiveCalls, steerIndeterminateCalls, steerStateImpl }; + } function createCompactMode(model?: string): OpencodeMode { @@ -542,79 +586,91 @@ function createClearMode(): OpencodeMode { }; } -describe('opencodeRemoteLauncher inline model switch', () => { - afterEach(async () => { - harness.setModelArgs = []; - harness.setConfigOptionArgs = []; - harness.promptCount = 0; - harness.promptContents = []; - harness.refreshSessionInfoCalls = []; - harness.bridgeOptions = null; - harness.events = []; - harness.cleanupEvents = []; - harness.setModelImpl = null; - harness.setConfigOptionImpl = null; - harness.thoughtLevelOption = null; - harness.thoughtLevelLookups = []; - harness.stderrHandler = null; - harness.servePid = null; - harness.servePidCalls = []; - harness.hangPrompt = false; - harness.resolvePrompt = null; - harness.cancelPrompt.mockClear(); - compactHarness.calls = []; - compactHarness.v2Calls = []; - compactHarness.v2VerifyCalls = []; - compactHarness.v2VerifyResult = { status: 'success', text: 'v2 summary text' }; - compactHarness.triggerImpl = null; - compactHarness.pollImpl = null; - compactHarness.operationEvents = []; - compactHarness.result = { ok: true }; - compactHarness.markerSnapshotCalls = []; - compactHarness.markerSnapshot = { markerIds: ['before-this-request'] }; - compactHarness.snapshotImpl = null; - compactHarness.resultCalls = []; - compactHarness.compactionResult = { status: 'success', text: '## Objective\n- Did the thing' }; - compactHarness.triggerImpl = null; - compactHarness.resultImpl = null; - harness.promptImpl = null; - harness.promptOnMessage = null; - harness.sessionModelsMetadata = undefined; - harness.cancelPromptImpl = null; - harness.newSessionImpl = null; - harness.disconnectImpl = null; - harness.permissionCancelError = null; - harness.serverStopError = null; - harness.eventStreamOptions = []; - harness.eventStreamCloseCount = 0; - harness.stderrHandler = null; - harness.softSteerCalls = []; - harness.softSteerDispatchError = null; - harness.deferSoftSteerDispatch = null; - harness.deferSoftSteer = null; - harness.softSteerThrow = null; - harness.deferSteerState = null; - harness.steerStateCalls = []; - harness.steerStateResult = true; - harness.promptGeneration = 1; - harness.abortSoftSteersCalls = 0; - harness.promptRequestInFlight = null; - harness.detectedVersion = null; - harness.loopbackListeners = []; - harness.discoveredPort = null; - harness.discoveredPassword = null; - harness.backendPid = 4242; - harness.createBackendArgs = []; - harness.v2DiscoveryCalls = []; - harness.v2PasswordCalls = []; - inkHarness.lastRenderProps = null; - const backendModule = await import('./utils/opencodeBackend'); - const backendModuleFns = backendModule as unknown as Record>; - for (const name of ['createOpencodeBackend', 'detectOpencodeFlavorVersion', 'discoverOpencodeV2RestPort', 'listLoopbackListeners']) { - backendModuleFns[name]?.mockClear(); - } - }); +afterEach(async () => { + harness.transcriptFetchImpl = null; + harness.setModelArgs = []; + harness.setConfigOptionArgs = []; + harness.promptCount = 0; + harness.promptContents = []; + harness.refreshSessionInfoCalls = []; + harness.bridgeOptions = null; + harness.events = []; + harness.cleanupEvents = []; + harness.setModelImpl = null; + harness.setConfigOptionImpl = null; + harness.thoughtLevelOption = null; + harness.thoughtLevelLookups = []; + harness.stderrHandler = null; + harness.servePid = null; + harness.servePidCalls = []; + harness.hangPrompt = false; + harness.resolvePrompt = null; + harness.cancelPrompt.mockClear(); + compactHarness.calls = []; + compactHarness.v2Calls = []; + compactHarness.v2VerifyCalls = []; + compactHarness.v2VerifyResult = { status: 'success', text: 'v2 summary text' }; + compactHarness.triggerImpl = null; + compactHarness.pollImpl = null; + compactHarness.operationEvents = []; + compactHarness.result = { ok: true }; + compactHarness.markerSnapshotCalls = []; + compactHarness.markerSnapshot = { markerIds: ['before-this-request'] }; + compactHarness.snapshotImpl = null; + compactHarness.resultCalls = []; + compactHarness.compactionResult = { status: 'success', text: '## Objective\n- Did the thing' }; + compactHarness.triggerImpl = null; + compactHarness.resultImpl = null; + harness.promptImpl = null; + harness.promptOnMessage = null; + harness.sessionModelsMetadata = undefined; + harness.cancelPromptImpl = null; + harness.newSessionImpl = null; + harness.disconnectImpl = null; + harness.permissionCancelError = null; + harness.serverStopError = null; + harness.eventStreamOptions = []; + harness.eventStreamCloseCount = 0; + roundSummaryHarness.snapshotCalls = []; + roundSummaryHarness.summaryCalls = []; + roundSummaryHarness.snapshot = { messageIds: [] }; + roundSummaryHarness.snapshotImpl = null; + roundSummaryHarness.summary = { + usage: { inputTokens: 10, outputTokens: 2, cacheReadInputTokens: 0, cacheCreationInputTokens: 0 }, + modelUsage: { 'openai/gpt-5.4': { inputTokens: 10, outputTokens: 2, cacheReadInputTokens: 0, cacheCreationInputTokens: 0 } }, + numTurns: 1, + durationMs: 10 + }; + roundSummaryHarness.summaryImpl = null; + harness.softSteerCalls = []; + harness.softSteerDispatchError = null; + harness.deferSoftSteerDispatch = null; + harness.deferSoftSteer = null; + harness.softSteerThrow = null; + harness.deferSteerState = null; + harness.steerStateCalls = []; + harness.steerStateResult = true; + harness.promptGeneration = 1; + harness.abortSoftSteersCalls = 0; + harness.promptRequestInFlight = null; + harness.detectedVersion = null; + harness.loopbackListeners = []; + harness.discoveredPort = null; + harness.discoveredPassword = null; + harness.backendPid = 4242; + harness.createBackendArgs = []; + harness.v2DiscoveryCalls = []; + harness.v2PasswordCalls = []; + inkHarness.lastRenderProps = null; + const backendModule = await import('./utils/opencodeBackend'); + const backendModuleFns = backendModule as unknown as Record>; + for (const name of ['createOpencodeBackend', 'detectOpencodeFlavorVersion', 'discoverOpencodeV2RestPort', 'listLoopbackListeners']) { + backendModuleFns[name]?.mockClear(); + } +}); + +describe('opencodeRemoteLauncher inline model switch', () => { it('reaches /clear only after the earlier prompt settles, without starting another OpenCode turn', async () => { let resolvePrompt: (() => void) | null = null; harness.promptImpl = () => new Promise((resolve) => { @@ -2636,6 +2692,275 @@ describe('selectAbortStatusMessage', () => { expect(decision).toEqual({ message: 'Turn aborted', shouldClearThinking: true }); }); + + it('sends the round summary before ready after a prompt settles', async () => { + const { session, sentAgentMessages, sessionEvents, deliveryEvents } = createSessionStub([{ message: 'round prompt', mode: createMode() }]); + + await opencodeRemoteLauncher(session as never); + + expect(roundSummaryHarness.snapshotCalls).toHaveLength(1); + expect(roundSummaryHarness.summaryCalls).toEqual([expect.objectContaining({ promptText: expect.stringContaining('round prompt') })]); + expect(sentAgentMessages).toEqual([expect.objectContaining({ type: 'round-summary' })]); + expect(sessionEvents).toEqual([{ type: 'ready' }]); + expect(deliveryEvents).toEqual(['agent', 'ready']); + }); + + it('reuses the previous post-fetch snapshot instead of blocking a second prompt on another pre-fetch', async () => { + roundSummaryHarness.snapshotCalls = []; + roundSummaryHarness.summaryCalls = []; + const { session } = createSessionStub([ + { message: 'first round', mode: createMode() }, + { message: 'second round', mode: createMode() } + ]); + + await opencodeRemoteLauncher(session as never); + + expect(roundSummaryHarness.summaryCalls.map((call) => call.snapshot.messageIds)).toEqual([[], ['post-1']]); + expect(roundSummaryHarness.snapshotCalls).toHaveLength(1); + expect(roundSummaryHarness.summaryCalls).toHaveLength(2); + }); + + it('recaptures after an explicit compact invalidates the previous post-fetch snapshot', async () => { + roundSummaryHarness.snapshotCalls = []; + roundSummaryHarness.summaryCalls = []; + harness.sessionModelsMetadata = { currentModelId: 'ollama/x', availableModels: [] }; + const { session } = createSessionStub([ + { message: 'first round', mode: createMode('ollama/x') }, + { message: '', mode: createCompactMode('ollama/x') }, + { message: 'second round', mode: createMode('ollama/x') } + ]); + + await opencodeRemoteLauncher(session as never); + + expect(compactHarness.calls).toHaveLength(1); + expect(roundSummaryHarness.snapshotCalls).toHaveLength(2); + expect(roundSummaryHarness.summaryCalls.map((call) => call.snapshot.messageIds)).toEqual([[], []]); + }); + + it('keeps prompt completion and ready when post-fetch summary aggregation fails', async () => { + roundSummaryHarness.summary = null; + const { session, sentAgentMessages, sessionEvents } = createSessionStub([{ message: 'no summary', mode: createMode() }]); + + await opencodeRemoteLauncher(session as never); + + expect(sentAgentMessages).toEqual([]); + expect(sessionEvents).toEqual([{ type: 'ready' }]); + }); + it('keeps the dequeued prompt and ready when pre-prompt snapshot metadata throws', async () => { + roundSummaryHarness.snapshotImpl = async () => { + throw new TypeError('malformed optional message metadata'); + }; + const promptCountBefore = harness.promptCount; + const { session, sentAgentMessages, sessionEvents } = createSessionStub([ + { message: 'prompt survives malformed snapshot', mode: createMode() } + ]); + + try { + await opencodeRemoteLauncher(session as never); + } finally { + roundSummaryHarness.snapshotImpl = null; + } + + expect(harness.promptCount).toBe(promptCountBefore + 1); + expect(JSON.stringify(harness.promptContents)).toContain('prompt survives malformed snapshot'); + expect(sentAgentMessages).toEqual([]); + expect(sessionEvents).toEqual([{ type: 'ready' }]); + }); + + it('keeps ready unblocked when a summary fetch never settles', async () => { + roundSummaryHarness.summaryImpl = () => new Promise(() => {}); + const { session, sentAgentMessages, sessionEvents } = createSessionStub([{ message: 'stalled summary', mode: createMode() }]); + + await opencodeRemoteLauncher(session as never); + + expect(sentAgentMessages).toEqual([]); + expect(sessionEvents).toEqual([{ type: 'ready' }]); + }); + + it('preserves queued prompts when Stop arrives during post-prompt native transcript refresh', async () => { + const transcriptRead: { release: (() => void) | null } = { release: null }; + let readHeld = false; + harness.transcriptFetchImpl = async () => { + if (!readHeld && harness.events.includes('prompt:end')) { + readHeld = true; + return new Promise((resolve) => { + transcriptRead.release = () => resolve(Response.json([])); + }); + } + return Response.json([]); + }; + const addMessage = vi.spyOn(MessageBuffer.prototype, 'addMessage'); + const { session, rpcHandlers } = createSessionStub([ + { message: 'first prompt before transcript read', mode: createMode() } + ], { keepOpen: true }); + const launchPromise = opencodeRemoteLauncher(session as never); + while (!transcriptRead.release || !rpcHandlers.has(RPC_METHODS.Abort)) { + await new Promise((resolve) => setImmediate(resolve)); + } + session.queue.push('queued after transcript read', createMode()); + await (rpcHandlers.get(RPC_METHODS.Abort) as () => Promise)(); + transcriptRead.release(); + for (let attempt = 0; attempt < 50 && !JSON.stringify(harness.promptContents).includes('queued after transcript read'); attempt++) { + await new Promise((resolve) => setImmediate(resolve)); + } + session.queue.close(); + await launchPromise; + try { + expect(JSON.stringify(harness.promptContents)).toContain('queued after transcript read'); + expect(harness.cancelPrompt).not.toHaveBeenCalled(); + expect(addMessage).not.toHaveBeenCalledWith('Turn aborted', 'status'); + } finally { + addMessage.mockRestore(); + } + }); + + it('excludes native transcript read latency from round prompt duration', async () => { + let clock = 0; + const now = vi.spyOn(performance, 'now').mockImplementation(() => clock); + harness.promptImpl = async () => { clock = 25; }; + harness.transcriptFetchImpl = async () => { + if (harness.events.includes('prompt:end')) clock = 5025; + return Response.json([]); + }; + const { session } = createSessionStub([{ message: 'duration before transcript read', mode: createMode() }]); + try { + await opencodeRemoteLauncher(session as never); + expect(roundSummaryHarness.summaryCalls[0]?.durationMs).toBe(25); + } finally { + now.mockRestore(); + } + }); + + it('plain Stop during post-prompt summary settlement preserves the queued next prompt without reporting a false abort', async () => { + roundSummaryHarness.summaryImpl = ({ promptText }) => { + return promptText.includes('completed first prompt') + ? new Promise(() => {}) + : Promise.resolve(null); + }; + const addMessage = vi.spyOn(MessageBuffer.prototype, 'addMessage'); + const { session, rpcHandlers } = createSessionStub([ + { message: 'completed first prompt', mode: createMode() } + ], { keepOpen: true }); + + const launchPromise = opencodeRemoteLauncher(session as never); + while ( + !rpcHandlers.has(RPC_METHODS.Abort) + || !roundSummaryHarness.summaryCalls.some(({ promptText }) => promptText.includes('completed first prompt')) + ) { + await new Promise((resolve) => setImmediate(resolve)); + } + expect(harness.events).toContain('prompt:end'); + + session.queue.push('queued second prompt', createMode()); + const abortHandler = rpcHandlers.get(RPC_METHODS.Abort) as (() => Promise) | undefined; + expect(abortHandler).toBeDefined(); + await abortHandler!(); + for (let attempt = 0; attempt < 50 && !JSON.stringify(harness.promptContents).includes('queued second prompt'); attempt++) { + await new Promise((resolve) => setImmediate(resolve)); + } + session.queue.close(); + await launchPromise; + + expect(JSON.stringify(harness.promptContents)).toContain('queued second prompt'); + expect(harness.cancelPrompt).not.toHaveBeenCalled(); + expect(addMessage).not.toHaveBeenCalledWith('Turn aborted', 'status'); + addMessage.mockRestore(); + }); + + it('attempts and delivers a summary after a caught prompt error', async () => { + harness.promptImpl = async () => { throw new Error('fixture prompt failure'); }; + roundSummaryHarness.summaryImpl = async () => ({ + usage: { inputTokens: 10, outputTokens: 2, cacheReadInputTokens: 0, cacheCreationInputTokens: 0 }, + modelUsage: { 'openai/gpt-5.4': { inputTokens: 10, outputTokens: 2, cacheReadInputTokens: 0, cacheCreationInputTokens: 0 } }, + numTurns: 1, + durationMs: 10 + }); + const { session, agentMessages, sessionEvents } = createSessionStub([{ message: 'error summary', mode: createMode() }]); + + await opencodeRemoteLauncher(session as never); + expect(roundSummaryHarness.snapshotCalls.length).toBeGreaterThan(0); + expect(roundSummaryHarness.summaryCalls.length).toBeGreaterThan(0); + + expect(agentMessages).toEqual([ + expect.objectContaining({ type: 'error' }), + expect.objectContaining({ type: 'round-summary' }) + ]); + expect(sessionEvents).toEqual([{ type: 'ready' }]); + }); + + + it('keeps native instructions for the first actual prompt after a snapshot Abort', async () => { + roundSummaryHarness.snapshotCalls = [] + harness.promptCount = 0 + harness.promptContents = [] + let snapshotCount = 0 + let releaseFirstSnapshot: ((value: unknown) => void) | null = null + roundSummaryHarness.snapshotImpl = () => { + snapshotCount += 1 + return snapshotCount === 1 + ? new Promise((resolve) => { releaseFirstSnapshot = resolve }) + : Promise.resolve({ messageIds: [] }) + } + const { session, rpcHandlers } = createSessionStub([{ message: 'aborted before prompt', mode: createMode() }], { keepOpen: true }) + const launchPromise = opencodeRemoteLauncher(session as never) + await new Promise((resolve) => setImmediate(resolve)) + expect(roundSummaryHarness.snapshotCalls).toHaveLength(1) + + const abortHandler = rpcHandlers.get(RPC_METHODS.Abort) as (() => Promise) | undefined + expect(abortHandler).toBeDefined() + await abortHandler!() + session.queue.push('actual second prompt', createMode()) + releaseFirstSnapshot!({ messageIds: [] }) + session.queue.close() + await launchPromise + + expect(harness.promptCount).toBe(1) + const text = (harness.promptContents[0] as Array<{ type: string; text?: string }>)[0]?.text + expect(text).toContain(getOpencodeNativeToolInstruction()) + expect(text).toContain('actual second prompt') + }) + + it('does not start a backend prompt when Switch arrives during the blocking pre-prompt snapshot', async () => { + roundSummaryHarness.snapshotCalls = [] + harness.promptCount = 0 + let releaseSnapshot: ((value: unknown) => void) | null = null + roundSummaryHarness.snapshotImpl = () => new Promise((resolve) => { releaseSnapshot = resolve }) + const { session, rpcHandlers, sessionEvents } = createSessionStub([{ message: 'snapshot switch', mode: createMode() }]) + const launchPromise = opencodeRemoteLauncher(session as never) + await new Promise((resolve) => setImmediate(resolve)) + expect(roundSummaryHarness.snapshotCalls).toHaveLength(1) + + const switchHandler = rpcHandlers.get(RPC_METHODS.Switch) as (() => Promise) | undefined + expect(switchHandler).toBeDefined() + await switchHandler!() + releaseSnapshot!({ messageIds: [] }) + session.queue.close() + await launchPromise + + expect(harness.promptCount).toBe(0) + expect(sessionEvents).toEqual([]) + }) + + it('does not start a backend prompt when Abort arrives during the blocking pre-prompt snapshot', async () => { + roundSummaryHarness.snapshotCalls = [] + harness.promptCount = 0 + let releaseSnapshot: ((value: unknown) => void) | null = null + roundSummaryHarness.snapshotImpl = () => new Promise((resolve) => { releaseSnapshot = resolve }) + const { session, rpcHandlers, sessionEvents } = createSessionStub([{ message: 'snapshot abort', mode: createMode() }]) + const launchPromise = opencodeRemoteLauncher(session as never) + await new Promise((resolve) => setImmediate(resolve)) + expect(roundSummaryHarness.snapshotCalls).toHaveLength(1) + + const abortHandler = rpcHandlers.get('abort') as (() => Promise) | undefined + expect(abortHandler).toBeDefined() + await abortHandler!() + releaseSnapshot!({ messageIds: [] }) + session.queue.close() + await launchPromise + + expect(harness.promptCount).toBe(0) + expect(sessionEvents).toEqual([{ type: 'ready' }]) + }) }); function indeterminateError(message: string): Error { @@ -3217,6 +3542,57 @@ describe('opencodeRemoteLauncher mid-turn steer', () => { } }); + it('cancels and detaches a deferred steer when Stop follows foreground completion', async () => { + let releaseSteer!: () => void; + harness.deferSoftSteer = new Promise(resolve => { releaseSteer = resolve; }); + const { stub, releasePrompt, runPromise } = await startTurn(); + try { + stub.session.queue.push('correction', createMode(), 'steer'); + await expect(steerHandlerOf(stub)({ localId: 'steer' })).resolves.toEqual({ steered: true }); + releasePrompt(); + await vi.waitFor(() => expect(stub.steeringActiveCalls.at(-1)).toBe(false)); + expect(stub.sessionEvents.filter(event => event.type === 'ready')).toEqual([]); + await (stub.rpcHandlers.get('abort') as () => Promise)(); + expect(harness.cancelPrompt).toHaveBeenCalledWith('acp-session-1'); + expect(harness.abortSoftSteersCalls).toBe(1); + await vi.waitFor(() => expect(stub.steerIndeterminateCalls).toContainEqual(['steer'])); + expect(stub.emitMessagesConsumedCalls).toEqual([]); + } finally { + releaseSteer(); harness.deferSoftSteer = null; + stub.session.queue.close(); await runPromise; + } + }); + + it('reconciles a retained unknown v2 steer when Stop follows foreground completion', async () => { + harness.detectedVersion = 'v2'; harness.discoveredPort = 48274; harness.discoveredPassword = 'test-only'; + let id = ''; let visible = false; let deleted = false; let posts = 0; + const nativeFetch = vi.spyOn(globalThis, 'fetch').mockImplementation(async (url, init) => { + if (init?.method === 'POST') { posts++; id = JSON.parse(String(init.body)).id; throw new Error('response lost'); } + if (init?.method === 'DELETE') { deleted = true; return new Response(null, { status: 204 }); } + const item = { id, sessionID: 'acp-session-1', type: 'user', delivery: 'steer', payload: { text: 'correction' } }; + return String(url).endsWith('/inbox') ? Response.json({ data: visible && !deleted ? [item] : [] }) : new Response(null, { status: 404 }); + }); + roundSummaryHarness.summaryImpl = () => new Promise(() => {}); + const { stub, releasePrompt, runPromise } = await startTurn(); + try { + stub.session.queue.push('correction', createMode(), 'v2-steer'); + await expect(steerHandlerOf(stub)({ localId: 'v2-steer' })).resolves.toEqual({ steered: false, error: 'Steer outcome is being reconciled' }); + expect(stub.steerIndeterminateCalls).toContainEqual(['v2-steer']); + releasePrompt(); + await vi.waitFor(() => expect(roundSummaryHarness.summaryCalls).toHaveLength(1)); + visible = true; + await (stub.rpcHandlers.get('abort') as () => Promise)(); + expect(deleted).toBe(true); + expect(posts).toBe(1); + expect(stub.emitMessagesConsumedCalls).toEqual([]); + expect(harness.steerStateCalls).not.toContainEqual({ localIds: ['v2-steer'], state: 'queued' }); + expect(stub.session.queue.peekByLocalId('v2-steer')).toBeNull(); + expect(stub.session.queue.cancelByLocalId('v2-steer')).toBe(true); + } finally { + nativeFetch.mockRestore(); stub.session.queue.close(); await runPromise; + } + }); + it('injects a compatible queued message into the active turn without cancelling it', async () => { let releaseSoftSteer!: () => void; harness.deferSoftSteer = new Promise((resolve) => { releaseSoftSteer = resolve; }); @@ -4805,8 +5181,42 @@ function backendCreateArgsIncludePortFlags(): boolean { } describe('opencodeRemoteLauncher v2 flavor wiring', () => { + it('collects a v2 round through the discovered authenticated API before ready', async () => { + harness.detectedVersion = 'v2'; + harness.discoveredPort = 41234; + harness.discoveredPassword = 'fixture-password'; + const { session, sentAgentMessages, sessionEvents, deliveryEvents } = createSessionStub([{ message: 'v2 round', mode: createMode() }]); + + await opencodeRemoteLauncher(session as never); + + expect(roundSummaryHarness.snapshotCalls).toEqual([expect.objectContaining({ + baseUrl: 'http://127.0.0.1:41234', api: { version: 'v2', password: 'fixture-password' } + })]); + expect(roundSummaryHarness.summaryCalls).toEqual([expect.objectContaining({ + baseUrl: 'http://127.0.0.1:41234', api: { version: 'v2', password: 'fixture-password' } + })]); + expect(sentAgentMessages).toEqual([expect.objectContaining({ type: 'round-summary' })]); + expect(sessionEvents).toEqual([{ type: 'ready' }]); + expect(deliveryEvents).toEqual(['agent', 'ready']); + }); + + it('preserves the v2 prompt and ready when API discovery fails', async () => { + harness.detectedVersion = 'v2'; + const { session, sentAgentMessages, sessionEvents } = createSessionStub([{ message: 'v2 without discovery', mode: createMode() }]); + + await opencodeRemoteLauncher(session as never); + + expect(JSON.stringify(harness.promptContents)).toContain('v2 without discovery'); + expect(roundSummaryHarness.snapshotCalls).toEqual([]); + expect(roundSummaryHarness.summaryCalls).toEqual([]); + expect(sentAgentMessages).toEqual([]); + expect(sessionEvents).toContainEqual({ type: 'ready' }); + }); + + beforeEach(() => { harness.eventStreamOptions = []; + }); afterEach(async () => { diff --git a/cli/src/opencode/opencodeRemoteLauncher.ts b/cli/src/opencode/opencodeRemoteLauncher.ts index 40e2c26a..89a7e25e 100644 --- a/cli/src/opencode/opencodeRemoteLauncher.ts +++ b/cli/src/opencode/opencodeRemoteLauncher.ts @@ -17,6 +17,7 @@ import type { OpencodeMode, PermissionMode } from './types'; import type { QueueReservation } from '@/utils/MessageQueue2'; import { admitOpencodeV2Steer, cancelOpencodeV2Steer, opencodeV2InputId, readOpencodeV2Input, steerOpencodeV2Inbox, type OpencodeSteerCancelHandler, type OpencodeSteerCancelResult } from './utils/opencodeV2Steer'; import { RPC_METHODS } from '@hapi/protocol/rpcMethods'; +import { captureOpencodeRoundSnapshot, fetchOpencodeRoundSummary, type OpencodeRoundSnapshot } from './utils/opencodeRoundSummary'; import { allocateFreePort, createOpencodeBackend, @@ -84,6 +85,29 @@ export type AbortStatusDecision = { }; type CompactOperationPhase = 'idle' | 'snapshot' | 'summarize' | 'post-summarize' | 'verification'; +type RoundSummaryPhase = 'idle' | 'snapshot' | 'prompt' | 'settle'; + +const ROUND_SUMMARY_SETTLE_TIMEOUT_MS = 1_000; + +async function settleRoundSummary(promise: Promise, controller: AbortController): Promise { + return await new Promise((resolve) => { + let settled = false; + const settle = (value: T | null) => { + if (settled) return; + settled = true; + clearTimeout(timeout); + controller.signal.removeEventListener('abort', onAbort); + resolve(value); + }; + const onAbort = () => settle(null); + const timeout = setTimeout(() => { + controller.abort(); + settle(null); + }, ROUND_SUMMARY_SETTLE_TIMEOUT_MS); + controller.signal.addEventListener('abort', onAbort, { once: true }); + void promise.then((summary) => settle(summary), () => settle(null)); + }); +} /** * One steer operation the launcher still tracks. Deliberately distinct from @@ -178,6 +202,11 @@ class OpencodeRemoteLauncher extends RemoteLauncherBase { // deliberately unbounded (see triggerOpencodeCompact's doc comment) and // the launcher stays wedged until it eventually settles on its own. private compactAbortController: AbortController | null = null; + private roundSummaryAbortController: AbortController | null = null; + /** Distinguishes an active prompt from read-only post-prompt work for Stop semantics. */ + private roundSummaryPhase: RoundSummaryPhase = 'idle'; + /** Validated ID boundary returned by the previous post-prompt fetch; explicit history mutations clear it. */ + private nextRoundSnapshot: OpencodeRoundSnapshot | null = null; // A plain Stop must keep waiting only while the summarize POST is // actually in flight. That POST can outlive a client-side abort while // continuing to mutate the shared OpenCode session, so advancing to a @@ -879,6 +908,7 @@ class OpencodeRemoteLauncher extends RemoteLauncherBase { continue; } + this.nextRoundSnapshot = null; session.onThinkingChange(true); try { await this.runCompactOperation(acpSessionId, compactAbortController, compactLocalId); @@ -896,17 +926,55 @@ class OpencodeRemoteLauncher extends RemoteLauncherBase { if (batch.mode.permissionMode === 'plan') { messageText = `${PLAN_MODE_INSTRUCTION}\n\n${messageText}`; } - if (!this.instructionsSent) { - messageText = `${getOpencodeNativeToolInstruction()}\n\n${messageText}`; - this.instructionsSent = true; + + this.stallErrorReportedForPrompt = false; + const roundSummaryAbortController = new AbortController(); + this.roundSummaryAbortController = roundSummaryAbortController; + this.roundSummaryPhase = 'snapshot'; + const roundApi = this.v2RestInfo + ? { baseUrl: this.v2RestInfo.baseUrl, api: { version: 'v2' as const, password: this.v2RestInfo.password } } + : this.baseUrl ? { baseUrl: this.baseUrl } : null; + const roundSnapshot = this.nextRoundSnapshot ?? (roundApi + ? await captureOpencodeRoundSnapshot({ + ...roundApi, + sessionId: acpSessionId, + signal: roundSummaryAbortController.signal + }).catch((error) => { + logger.debug('[opencode-remote] round snapshot unavailable', error); + return null; + }) + : null); + this.nextRoundSnapshot = null; + if ( + this.roundSummaryAbortController !== roundSummaryAbortController + || roundSummaryAbortController.signal.aborted + || this.shouldExit + ) { + if (this.roundSummaryAbortController === roundSummaryAbortController) { + this.roundSummaryAbortController = null; + this.roundSummaryPhase = 'idle'; + } + session.onThinkingChange(false); + if (session.queue.size() === 0 && !this.shouldExit) { + sendReady(); + } + continue; } + if (!this.instructionsSent) { + messageText = `${getOpencodeNativeToolInstruction()} + +${messageText}`; + this.instructionsSent = true; + } const promptContent: PromptContent[] = [{ type: 'text', text: messageText, }]; - this.stallErrorReportedForPrompt = false; + const promptStartedAt = performance.now(); + let promptDurationMs = 0; + this.roundSummaryPhase = 'prompt'; session.onThinkingChange(true); // Only a normal prompt is steerable: /compact and /clear leave this // false, so a steer arriving during either is rejected rather than @@ -921,9 +989,14 @@ class OpencodeRemoteLauncher extends RemoteLauncherBase { const nativeInput = { uncertain: false }; this.nativeInputWriters.add(nativeInput); try { - await backend.prompt(acpSessionId, promptContent, (message: AgentMessage) => { - this.handleAgentMessage(message); - }); + try { + await backend.prompt(acpSessionId, promptContent, (message: AgentMessage) => { + this.handleAgentMessage(message); + }); + } finally { + promptDurationMs = performance.now() - promptStartedAt; + this.roundSummaryPhase = 'settle'; + } this.completeNativeInput(nativeInput); await this.nativeTranscript?.refresh(); void backend.refreshSessionInfo(acpSessionId, session.path); @@ -947,10 +1020,40 @@ class OpencodeRemoteLauncher extends RemoteLauncherBase { // steer that settled (or is still restoring) cannot cross the // turn boundary into the next prompt or a /compact. await this.drainSteerOperations(); - session.onThinkingChange(false); - await this.permissionHandler?.cancelAll('Prompt finished'); - if (session.queue.size() === 0 && !this.shouldExit) { - sendReady(); + if ( + this.roundSummaryAbortController === roundSummaryAbortController + && !roundSummaryAbortController.signal.aborted + && !this.shouldExit + && roundApi + && roundSnapshot + ) { + const result = await settleRoundSummary( + fetchOpencodeRoundSummary({ + ...roundApi, + sessionId: acpSessionId, + promptText: messageText, + snapshot: roundSnapshot, + durationMs: promptDurationMs, + signal: roundSummaryAbortController.signal + }), + roundSummaryAbortController + ); + if (result) { + this.nextRoundSnapshot = result.snapshot; + if (result.summary) this.handleAgentMessage({ type: 'round_summary', summary: result.summary }); + } + } + if (this.roundSummaryAbortController === roundSummaryAbortController) { + this.roundSummaryAbortController = null; + } + try { + session.onThinkingChange(false); + await this.permissionHandler?.cancelAll('Prompt finished'); + if (session.queue.size() === 0 && !this.shouldExit) { + sendReady(); + } + } finally { + this.roundSummaryPhase = 'idle'; } } } @@ -2136,6 +2239,8 @@ class OpencodeRemoteLauncher extends RemoteLauncherBase { case 'turn_complete': this.messageBuffer.addMessage('Turn complete', 'status'); break; + case 'round_summary': + break; default: { const _exhaustive: never = message; return _exhaustive; @@ -2163,6 +2268,19 @@ class OpencodeRemoteLauncher extends RemoteLauncherBase { * disconnects the ACP subprocess right after. */ private async handleAbort(leavingRemote = false): Promise { + this.roundSummaryAbortController?.abort(); + // Only abandon metadata when no steer or cancellation still owns work. + if ( + !leavingRemote + && this.roundSummaryPhase === 'settle' + && this.pendingSteerOperations.size === 0 + && this.v2Steers.size === 0 + && !Array.from(this.backendSoftSteerOwnership).some(entry => + entry.backend === this.backend && entry.turnEpoch === this.steerTurnEpoch + ) + && !this.v2AbortInProgress + ) return; + if (this.majorVersion !== 'v2') return this.performAbort(leavingRemote); if (this.v2AbortInProgress) { // One overlapping Stop/switch owns queue.reset. A later reset diff --git a/cli/src/opencode/utils/opencodeCompactBridge.test.ts b/cli/src/opencode/utils/opencodeCompactBridge.test.ts index 2dad49ad..ec3e2af4 100644 --- a/cli/src/opencode/utils/opencodeCompactBridge.test.ts +++ b/cli/src/opencode/utils/opencodeCompactBridge.test.ts @@ -188,6 +188,18 @@ const summary = (id: string, parentID: string, overrides: Record { + it('fails closed when the message API array contains a null entry', async () => { + const fetchImpl = vi.fn(async () => new Response(JSON.stringify([null]), { status: 200 })); + + await expect(captureCompactionMarkerSnapshot({ + baseUrl: 'http://127.0.0.1:48273', sessionId: 'ses_abc', fetchImpl, signal: noSignal + })).resolves.toBeNull(); + + await expect(fetchCompactionResult({ + baseUrl: 'http://127.0.0.1:48273', sessionId: 'ses_abc', markerIdsBefore: ['old-marker'], fetchImpl, signal: noSignal + })).resolves.toEqual({ status: 'unverified', reason: 'Compaction result could not be verified.' }); + }); + it('records only pre-existing manual marker IDs before POST so a later result cannot reuse them', async () => { const fetchImpl = vi.fn(async (url: string, init?: RequestInit) => { expect(url).toBe('http://127.0.0.1:48273/session/ses_abc/message'); diff --git a/cli/src/opencode/utils/opencodeCompactBridge.ts b/cli/src/opencode/utils/opencodeCompactBridge.ts index dc8acca2..57e11fb1 100644 --- a/cli/src/opencode/utils/opencodeCompactBridge.ts +++ b/cli/src/opencode/utils/opencodeCompactBridge.ts @@ -492,7 +492,7 @@ async function fetchSessionMessages(opts: OpencodeCompactCallOpts & { fetchImpl? const response = await fetchFn(url, { method: 'GET', signal: opts.signal }); if (!response.ok) return null; const data: unknown = await response.json().catch(() => null); - return Array.isArray(data) ? data as OpencodeMessageEntry[] : null; + return Array.isArray(data) && data.every(isObjectRecord) ? data as OpencodeMessageEntry[] : null; } catch { return null; } diff --git a/cli/src/opencode/utils/opencodeRoundSummary.boundaries.test.ts b/cli/src/opencode/utils/opencodeRoundSummary.boundaries.test.ts new file mode 100644 index 00000000..476b53fa --- /dev/null +++ b/cli/src/opencode/utils/opencodeRoundSummary.boundaries.test.ts @@ -0,0 +1,73 @@ +import { describe, expect, it, vi } from 'vitest'; +import { captureOpencodeRoundSnapshot, fetchOpencodeRoundSummary } from './opencodeRoundSummary'; + +const signal = new AbortController().signal; +const base = { baseUrl: 'http://127.0.0.1:48273', sessionId: 'ses_abc', signal }; + +const user = (id: string, text: string) => ({ info: { id, role: 'user' }, parts: [{ type: 'text', text }] }); +const assistant = (id: string) => ({ + info: { + id, + role: 'assistant', + providerID: 'openai', + modelID: 'gpt-5.4', + tokens: { input: 1, output: 1, reasoning: 0, cache: { read: 0, write: 0 } }, + cost: 0 + } +}); + +describe('OpenCode round message identity boundary', () => { + it('fails closed when the message API array contains a null entry', async () => { + const fetchImpl = vi.fn(async () => new Response(JSON.stringify([null]), { status: 200 })); + + await expect(captureOpencodeRoundSnapshot({ + ...base, + fetchImpl + })).resolves.toBeNull(); + + await expect(fetchOpencodeRoundSummary({ + ...base, + promptText: 'prompt', + snapshot: { messageIds: ['old'] }, + durationMs: 1, + fetchImpl + })).resolves.toBeNull(); + }); + + it('fails closed for duplicate message ids in the pre-snapshot or post-fetch response', async () => { + await expect(captureOpencodeRoundSnapshot({ + ...base, + fetchImpl: vi.fn(async () => new Response(JSON.stringify([user('same', 'one'), user('same', 'two')]), { status: 200 })) + })).resolves.toBeNull(); + + await expect(fetchOpencodeRoundSummary({ + ...base, + promptText: 'prompt', + snapshot: { messageIds: ['old'] }, + durationMs: 1, + fetchImpl: vi.fn(async () => new Response(JSON.stringify([ + user('old', 'earlier'), user('prompt-user', 'prompt'), assistant('assistant-1'), assistant('assistant-1') + ]), { status: 200 })) + })).resolves.toBeNull(); + }); + + it('abandons a stalled message API request after its bounded timeout', async () => { + const fetchImpl = vi.fn((_url: string, _init?: RequestInit) => new Promise(() => {})); + + await expect(captureOpencodeRoundSnapshot({ ...base, timeoutMs: 1, fetchImpl })).resolves.toBeNull(); + expect(fetchImpl).toHaveBeenCalledTimes(1); + }); + + it('bounds the whole response parse, including a response whose json never settles', async () => { + const fetchImpl = vi.fn(async () => ({ ok: true, json: () => new Promise(() => {}) })); + await expect(captureOpencodeRoundSnapshot({ ...base, timeoutMs: 1, fetchImpl: fetchImpl as never })).resolves.toBeNull(); + }); + + it('checks a large snapshot identity list with a Set-backed duplicate invariant', async () => { + const messages = Array.from({ length: 10_000 }, (_, index) => user('message-' + index, 'fixture')); + await expect(captureOpencodeRoundSnapshot({ + ...base, + fetchImpl: vi.fn(async () => new Response(JSON.stringify(messages), { status: 200 })) + })).resolves.toMatchObject({ messageIds: expect.arrayContaining(['message-0', 'message-9999']) }); + }); +}); diff --git a/cli/src/opencode/utils/opencodeRoundSummary.prototype.test.ts b/cli/src/opencode/utils/opencodeRoundSummary.prototype.test.ts new file mode 100644 index 00000000..a62a41c0 --- /dev/null +++ b/cli/src/opencode/utils/opencodeRoundSummary.prototype.test.ts @@ -0,0 +1,30 @@ +import { describe, expect, it, vi } from 'vitest'; +import { fetchOpencodeRoundSummary } from './opencodeRoundSummary'; + +describe('OpenCode round model key isolation', () => { + it('aggregates hostile provider/model identifiers without touching the object prototype', async () => { + const result = await fetchOpencodeRoundSummary({ + baseUrl: 'http://127.0.0.1:48273', + sessionId: 'ses_abc', + promptText: 'prompt', + snapshot: { messageIds: ['old'] }, + durationMs: 1, + signal: new AbortController().signal, + fetchImpl: vi.fn(async () => new Response(JSON.stringify([ + { info: { id: 'old', role: 'user' }, parts: [{ type: 'text', text: 'old' }] }, + { info: { id: 'prompt', role: 'user' }, parts: [{ type: 'text', text: 'prompt' }] }, + { + info: { + id: 'assistant', role: 'assistant', providerID: '__proto__', modelID: '__proto__', cost: 0, + tokens: { input: 1, output: 2, reasoning: 0, cache: { read: 0, write: 0 } } + } + } + ]), { status: 200 })) + }); + + expect(result?.summary?.modelUsage).toEqual({ + '__proto__/__proto__': { inputTokens: 1, outputTokens: 2, cacheReadInputTokens: 0, cacheCreationInputTokens: 0 } + }); + expect(Object.prototype).not.toHaveProperty('inputTokens'); + }); +}); diff --git a/cli/src/opencode/utils/opencodeRoundSummary.test.ts b/cli/src/opencode/utils/opencodeRoundSummary.test.ts new file mode 100644 index 00000000..89e6fe26 --- /dev/null +++ b/cli/src/opencode/utils/opencodeRoundSummary.test.ts @@ -0,0 +1,167 @@ +import { describe, expect, it, vi } from 'vitest'; +import { captureOpencodeRoundSnapshot, fetchOpencodeRoundSummary } from './opencodeRoundSummary'; + +const noSignal = new AbortController().signal; + +function user(id: string, text: string) { + return { info: { id, role: 'user' }, parts: [{ type: 'text', text }] }; +} + +function assistant(id: string, parentID: string, overrides: Record = {}) { + return { + info: { + id, + role: 'assistant', + parentID, + providerID: 'openai', + modelID: 'gpt-5.4', + tokens: { input: 10, output: 2, reasoning: 0, cache: { read: 0, write: 0 } }, + cost: 0, + ...overrides + }, + parts: [{ type: 'step-finish' }] + }; +} + +function options(messages: unknown[], promptText = 'original prompt') { + return { + baseUrl: 'http://127.0.0.1:48273', + sessionId: 'ses_abc', + promptText, + snapshot: { messageIds: ['old-user', 'old-assistant'] }, + durationMs: 1_250, + signal: noSignal, + fetchImpl: vi.fn(async () => new Response(JSON.stringify(messages), { status: 200 })) + }; +} + +describe('captureOpencodeRoundSnapshot', () => { + it('captures only valid persisted message IDs before a prompt', async () => { + const fetchImpl = vi.fn(async (url: string, init?: RequestInit) => { + expect(url).toBe('http://127.0.0.1:48273/session/ses_abc/message?limit=512'); + expect(init).toMatchObject({ method: 'GET', signal: noSignal }); + return new Response(JSON.stringify([user('old-user', 'earlier'), assistant('old-assistant', 'old-user')]), { status: 200 }); + }); + + await expect(captureOpencodeRoundSnapshot({ + baseUrl: 'http://127.0.0.1:48273', sessionId: 'ses_abc', signal: noSignal, fetchImpl + })).resolves.toEqual({ messageIds: ['old-user', 'old-assistant'] }); + }); + + it('fails closed for a non-2xx response or malformed message id', async () => { + await expect(captureOpencodeRoundSnapshot({ + baseUrl: 'http://127.0.0.1:48273', sessionId: 'ses_abc', signal: noSignal, + fetchImpl: vi.fn(async () => new Response('nope', { status: 404 })) + })).resolves.toBeNull(); + await expect(captureOpencodeRoundSnapshot({ + baseUrl: 'http://127.0.0.1:48273', sessionId: 'ses_abc', signal: noSignal, + fetchImpl: vi.fn(async () => new Response(JSON.stringify([{ info: { id: 9, role: 'user' } }]), { status: 200 })) + })).resolves.toBeNull(); + }); +}); + +describe('fetchOpencodeRoundSummary', () => { + it('aggregates multi-step and multi-model assistant rows, including cache, reasoning, and positive cost', async () => { + const messages = [ + user('old-user', 'earlier'), + assistant('old-assistant', 'old-user'), + user('prompt-user', 'original prompt'), + assistant('tool-step', 'prompt-user', { + tokens: { input: 100, output: 20, reasoning: 5, cache: { read: 50, write: 10 } }, cost: 0.01 + }), + assistant('stop-step', 'prompt-user', { + tokens: { input: 40, output: 7, reasoning: 3, cache: { read: 5, write: 0 } }, cost: 0.024 + }), + assistant('other-model', 'prompt-user', { + providerID: 'anthropic', modelID: 'claude-opus-4-1', + tokens: { input: 80, output: 9, reasoning: 0, cache: { read: 20, write: 0 } }, cost: 0 + }) + ]; + + const request = options(messages); + const result = await fetchOpencodeRoundSummary(request); + expect(request.fetchImpl).toHaveBeenCalledWith( + 'http://127.0.0.1:48273/session/ses_abc/message?limit=512', + expect.objectContaining({ method: 'GET' }) + ); + expect(result?.snapshot.messageIds).toEqual([ + 'old-user', 'old-assistant', 'prompt-user', 'tool-step', 'stop-step', 'other-model' + ]); + expect(result?.summary).toEqual({ + usage: { + inputTokens: 220, + outputTokens: 44, + cacheReadInputTokens: 75, + cacheCreationInputTokens: 10 + }, + modelUsage: { + 'openai/gpt-5.4': { + inputTokens: 140, + outputTokens: 35, + cacheReadInputTokens: 55, + cacheCreationInputTokens: 10 + }, + 'anthropic/claude-opus-4-1': { + inputTokens: 80, + outputTokens: 9, + cacheReadInputTokens: 20, + cacheCreationInputTokens: 0 + } + }, + totalCostUsd: 0.034, + numTurns: 3, + durationMs: 1_250 + }); + }); + + it('includes tool-only, auto-compaction summary, and continuation assistants from every new parent', async () => { + const messages = [ + user('old-user', 'earlier'), + assistant('old-assistant', 'old-user'), + user('prompt-user', 'original prompt'), + assistant('tool-only', 'prompt-user'), + user('compact-user', 'automatic compact'), + assistant('compact-summary', 'compact-user', { summary: true, tokens: { input: 20, output: 3, reasoning: 0, cache: { read: 0, write: 0 } } }), + user('continuation-user', 'continue'), + assistant('continuation', 'continuation-user', { tokens: { input: 30, output: 4, reasoning: 0, cache: { read: 0, write: 0 } } }) + ]; + + const result = await fetchOpencodeRoundSummary(options(messages)); + expect(result?.summary).toMatchObject({ numTurns: 3, usage: { inputTokens: 60, outputTokens: 9 } }); + }); + + it('omits zero cost while preserving a valid free round', async () => { + const messages = [user('old-user', 'earlier'), assistant('old-assistant', 'old-user'), user('prompt-user', 'original prompt'), assistant('new', 'prompt-user')]; + const result = await fetchOpencodeRoundSummary(options(messages)); + expect(result?.summary).toMatchObject({ numTurns: 1 }); + expect(result?.summary).not.toHaveProperty('totalCostUsd'); + }); + + it('returns the validated post-fetch snapshot when malformed usage omits only the summary', async () => { + const messages = [ + user('old-user', 'earlier'), + assistant('old-assistant', 'old-user'), + user('prompt-user', 'original prompt'), + assistant('bad-model', 'prompt-user', { modelID: '' }) + ]; + + await expect(fetchOpencodeRoundSummary(options(messages))).resolves.toEqual({ + snapshot: { messageIds: ['old-user', 'old-assistant', 'prompt-user', 'bad-model'] }, + summary: null + }); + }); + + it('fails closed for missing original prompt, no assistant, malformed model/token shapes, unsafe counters, and non-finite numbers', async () => { + const base = [user('old-user', 'earlier'), assistant('old-assistant', 'old-user')]; + expect((await fetchOpencodeRoundSummary(options([...base, assistant('new', 'unknown')])))?.summary ?? null).toBeNull(); + expect((await fetchOpencodeRoundSummary(options([...base, user('prompt-user', 'original prompt')])))?.summary ?? null).toBeNull(); + expect((await fetchOpencodeRoundSummary(options([...base, user('prompt-user', 'original prompt'), assistant('bad-model', 'prompt-user', { modelID: '' })])))?.summary ?? null).toBeNull(); + expect((await fetchOpencodeRoundSummary(options([...base, user('prompt-user', 'original prompt'), assistant('unsafe', 'prompt-user', { tokens: { input: Number.MAX_SAFE_INTEGER + 1, output: 2, reasoning: 0, cache: { read: 0, write: 0 } } })])))?.summary ?? null).toBeNull(); + expect((await fetchOpencodeRoundSummary(options([...base, user('prompt-user', 'original prompt'), assistant('infinite-cost', 'prompt-user', { cost: Infinity })])))?.summary ?? null).toBeNull(); + }); + + it('fails closed for a post-fetch API or parse failure without exposing the response body', async () => { + await expect(fetchOpencodeRoundSummary({ ...options([]), fetchImpl: vi.fn(async () => new Response('provider secret', { status: 500 })) })).resolves.toBeNull(); + await expect(fetchOpencodeRoundSummary({ ...options([]), fetchImpl: vi.fn(async () => new Response('{', { status: 200 })) })).resolves.toBeNull(); + }); +}); diff --git a/cli/src/opencode/utils/opencodeRoundSummary.ts b/cli/src/opencode/utils/opencodeRoundSummary.ts new file mode 100644 index 00000000..bf2673aa --- /dev/null +++ b/cli/src/opencode/utils/opencodeRoundSummary.ts @@ -0,0 +1,295 @@ +import { Buffer } from 'node:buffer'; +import type { FetchLike } from './opencodeCompactBridge'; + +export type OpencodeRoundSnapshot = { + messageIds: string[]; +}; + +export type OpencodeRoundModelUsage = { + inputTokens: number; + outputTokens: number; + cacheReadInputTokens: number; + cacheCreationInputTokens: number; +}; + +export type OpencodeRoundSummary = { + usage: OpencodeRoundModelUsage; + modelUsage: Record; + totalCostUsd?: number; + numTurns: number; + durationMs: number; + /** Assistant output + reasoning and provider-active time, excluding tools/compaction. */ + generationMs?: number; + generationOutputTokens?: number; +}; + +export type OpencodeRoundSummaryResult = { + snapshot: OpencodeRoundSnapshot; + summary: OpencodeRoundSummary | null; +}; + +type OpencodeMessage = { + info?: { + id?: unknown; + role?: unknown; + providerID?: unknown; + modelID?: unknown; + tokens?: unknown; + cost?: unknown; + time?: unknown; + isCompaction?: boolean; + }; + parts?: unknown; +}; + +type RoundFetchOptions = { + baseUrl: string; + sessionId: string; + signal: AbortSignal; + fetchImpl?: FetchLike; + timeoutMs?: number; + api?: { version: 'v2'; password: string }; +}; + +const ROUND_FETCH_TIMEOUT_MS = 1_000; +const ROUND_MESSAGE_LIMIT = 512; +// OpenCode v2's SessionMessagesQuery allows at most 200 messages per page. +const V2_MESSAGE_PAGE_LIMIT = 200; + +function isRecord(value: unknown): value is Record { + return typeof value === 'object' && value !== null && !Array.isArray(value); +} + +function normalizeV2Messages(payload: unknown): OpencodeMessage[] | null { + if (!isRecord(payload) || !Array.isArray(payload.data)) return null; + const messages: OpencodeMessage[] = []; + for (const entry of payload.data) { + if (!isRecord(entry)) return null; + const hasUsage = entry.type === 'assistant' + || (entry.type === 'compaction' && (entry.tokens !== undefined || entry.cost !== undefined)); + if (hasUsage && entry.type === 'compaction' && entry.status !== 'completed' && entry.status !== 'failed') return null; + const model = isRecord(entry.model) ? entry.model : null; + messages.push({ + info: { + id: entry.id, + role: hasUsage ? 'assistant' : entry.type === 'user' ? 'user' : undefined, + providerID: model?.providerID, + modelID: model?.id, + tokens: entry.tokens, + cost: entry.cost, + time: entry.time, + isCompaction: entry.type === 'compaction' + }, + parts: entry.type === 'user' ? [{ type: 'text', text: entry.text }] : undefined + }); + } + return messages; +} + +function safeInteger(value: unknown): number | null { + return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0 ? value : null; +} + +function finiteNonNegative(value: unknown): number | null { + return typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : null; +} + +function messageId(message: unknown): string | null { + if (!isRecord(message) || !isRecord(message.info)) return null; + return typeof message.info.id === 'string' && message.info.id.length > 0 ? message.info.id : null; +} + +function messageText(message: OpencodeMessage): string | null { + if (!Array.isArray(message.parts)) return null; + const text = message.parts + .filter(isRecord) + .filter((part) => part.type === 'text' && typeof part.text === 'string') + .map((part) => part.text) + .join(''); + return text || null; +} + +async function fetchMessages(options: RoundFetchOptions): Promise { + const fetchFn = options.fetchImpl ?? fetch; + const controller = new AbortController(); + const abort = () => controller.abort(); + if (options.signal.aborted) return null; + options.signal.addEventListener('abort', abort, { once: true }); + let timeout: ReturnType | undefined; + const timedOut = new Promise((resolve) => { + timeout = setTimeout(() => { + controller.abort(); + resolve(null); + }, options.timeoutMs ?? ROUND_FETCH_TIMEOUT_MS); + }); + try { + const request = (async (): Promise => { + const api = options.api; + const response = await fetchFn( + options.baseUrl + (api ? '/api/session/' : '/session/') + encodeURIComponent(options.sessionId) + + '/message?limit=' + (api ? V2_MESSAGE_PAGE_LIMIT : ROUND_MESSAGE_LIMIT), + { + method: 'GET', signal: controller.signal, + ...(api ? { headers: { authorization: 'Basic ' + Buffer.from(`opencode:${api.password}`).toString('base64') } } : {}) + } + ); + if (!response.ok) return null; + const parsed: unknown = await response.json(); + if (api) return normalizeV2Messages(parsed); + return Array.isArray(parsed) ? parsed as OpencodeMessage[] : null; + })(); + return await Promise.race([request, timedOut]); + } catch { + return null; + } finally { + if (timeout) clearTimeout(timeout); + options.signal.removeEventListener('abort', abort); + } +} + +/** Captures the persisted-message identity boundary immediately before a prompt. */ +export async function captureOpencodeRoundSnapshot(options: RoundFetchOptions): Promise { + const messages = await fetchMessages(options); + if (!messages) return null; + const messageIds: string[] = []; + const seen = new Set(); + for (const message of messages) { + const id = messageId(message); + if (!id || seen.has(id)) return null; + seen.add(id); + messageIds.push(id); + } + return { messageIds }; +} + +function parseAssistantUsage(message: OpencodeMessage, allowMissingCost: boolean): { key: string; usage: OpencodeRoundModelUsage; cost: number | undefined } | null { + if (message.info?.role !== 'assistant') return null; + const providerID = message.info.providerID; + const modelID = message.info.modelID; + const tokens = message.info.tokens; + if (typeof providerID !== 'string' || providerID.length === 0 || typeof modelID !== 'string' || modelID.length === 0 || !isRecord(tokens)) return null; + + const cache = tokens.cache; + if (!isRecord(cache)) return null; + const inputTokens = safeInteger(tokens.input); + const outputTokens = safeInteger(tokens.output); + const reasoningTokens = safeInteger(tokens.reasoning); + const cacheReadInputTokens = safeInteger(cache.read); + const cacheCreationInputTokens = safeInteger(cache.write); + const cost = allowMissingCost && message.info.cost === undefined ? undefined : finiteNonNegative(message.info.cost); + if (inputTokens === null || outputTokens === null || reasoningTokens === null || cacheReadInputTokens === null || cacheCreationInputTokens === null || cost === null) return null; + + const displayOutputTokens = outputTokens + reasoningTokens; + if (!Number.isSafeInteger(displayOutputTokens)) return null; + + return { + key: providerID + '/' + modelID, + usage: { + inputTokens, + outputTokens: displayOutputTokens, + cacheReadInputTokens, + cacheCreationInputTokens + }, + cost + }; +} + +function addUsage(total: OpencodeRoundModelUsage, next: OpencodeRoundModelUsage): boolean { + total.inputTokens += next.inputTokens; + total.outputTokens += next.outputTokens; + total.cacheReadInputTokens += next.cacheReadInputTokens; + total.cacheCreationInputTokens += next.cacheCreationInputTokens; + return Object.values(total).every(Number.isSafeInteger); +} + +/** + * Loads the post-prompt message list and aggregates every new assistant row. + * The prompt text anchors the original user row; assistant parent IDs are + * deliberately ignored because auto-compaction creates synthetic parents. + */ +export async function fetchOpencodeRoundSummary(options: RoundFetchOptions & { + promptText: string; + snapshot: OpencodeRoundSnapshot; + durationMs: number; +}): Promise { + if (finiteNonNegative(options.durationMs) === null) return null; + const messages = await fetchMessages(options); + if (!messages) return null; + + const before = new Set(options.snapshot.messageIds); + if (before.size !== options.snapshot.messageIds.length) return null; + const seen = new Set(); + const messageIds: string[] = []; + const delta: OpencodeMessage[] = []; + for (const message of messages) { + const id = messageId(message); + if (!id || seen.has(id)) return null; + seen.add(id); + messageIds.push(id); + if (!before.has(id)) delta.push(message); + } + + const hasOriginalPrompt = delta.some((message) => message.info?.role === 'user' && messageText(message) === options.promptText); + if (!hasOriginalPrompt) return null; + const snapshot = { messageIds }; + + const usage: OpencodeRoundModelUsage = { + inputTokens: 0, + outputTokens: 0, + cacheReadInputTokens: 0, + cacheCreationInputTokens: 0 + }; + const modelUsage = new Map(); + let totalCostUsd = 0; + let hasCompleteCost = true; + let numTurns = 0; + let generationMs = 0; + let generationOutputTokens = 0; + let hasCompleteGeneration = options.api?.version === 'v2'; + for (const message of delta) { + if (message.info?.role !== 'assistant') continue; + const parsed = parseAssistantUsage(message, options.api?.version === 'v2'); + if (!parsed) return { snapshot, summary: null }; + let perModel = modelUsage.get(parsed.key); + if (!perModel) { + perModel = { + inputTokens: 0, + outputTokens: 0, + cacheReadInputTokens: 0, + cacheCreationInputTokens: 0 + }; + modelUsage.set(parsed.key, perModel); + } + if (!addUsage(perModel, parsed.usage) || !addUsage(usage, parsed.usage)) return { snapshot, summary: null }; + if (parsed.cost === undefined) hasCompleteCost = false; + else totalCostUsd += parsed.cost; + if (!message.info.isCompaction) { + // Match OpenCode v2 turnTokensPerSecond: assistant steps only, with + // the provider body boundary (before tool settlement) on every step. + const time = message.info.time; + const created = isRecord(time) ? safeInteger(time.created) : null; + const streamed = isRecord(time) ? safeInteger(time.streamed) : null; + if (created === null || streamed === null || streamed <= created) hasCompleteGeneration = false; + else generationMs += streamed - created; + generationOutputTokens += parsed.usage.outputTokens; + } + numTurns++; + } + if (numTurns === 0 || !Number.isSafeInteger(numTurns) || !Number.isFinite(totalCostUsd)) { + return { snapshot, summary: null }; + } + + return { + snapshot, + summary: { + usage, + modelUsage: Object.fromEntries(modelUsage), + ...(hasCompleteCost && totalCostUsd > 0 ? { totalCostUsd } : {}), + numTurns, + durationMs: options.durationMs, + ...(hasCompleteGeneration && Number.isSafeInteger(generationMs) && generationMs > 0 + && Number.isSafeInteger(generationOutputTokens) && generationOutputTokens > 0 + ? { generationMs, generationOutputTokens } : {}) + } + }; +} diff --git a/cli/src/opencode/utils/opencodeRoundSummary.v2.test.ts b/cli/src/opencode/utils/opencodeRoundSummary.v2.test.ts new file mode 100644 index 00000000..5b3fe0e0 --- /dev/null +++ b/cli/src/opencode/utils/opencodeRoundSummary.v2.test.ts @@ -0,0 +1,161 @@ +import { describe, expect, it, vi } from 'vitest'; +import { captureOpencodeRoundSnapshot, fetchOpencodeRoundSummary } from './opencodeRoundSummary'; + +const signal = new AbortController().signal; +const api = { version: 'v2' as const, password: 'fixture-password' }; +const base = { baseUrl: 'http://127.0.0.1:48273', sessionId: 'session/id', signal, api }; +const user = { id: 'prompt', type: 'user', text: 'round prompt' }; +const assistant = (id: string, overrides: Record = {}) => ({ + id, type: 'assistant', model: { providerID: 'fixture', id: 'model' }, + tokens: { input: 10, output: 2, reasoning: 1, cache: { read: 5, write: 3 } }, cost: 0, + ...overrides +}); +function request(data: unknown) { + return { + ...base, promptText: user.text, snapshot: { messageIds: ['old'] }, durationMs: 100, + fetchImpl: vi.fn(async () => Response.json({ data })) + }; +} + +describe('OpenCode v2 round usage', () => { + it('captures flat IDs using the authenticated v2 endpoint at its server page limit', async () => { + const opts = request([{ id: 'old', type: 'idle' }]); + await expect(captureOpencodeRoundSnapshot(opts)).resolves.toEqual({ messageIds: ['old'] }); + expect(opts.fetchImpl).toHaveBeenCalledWith( + 'http://127.0.0.1:48273/api/session/session%2Fid/message?limit=200', + expect.objectContaining({ method: 'GET', headers: { authorization: 'Basic b3BlbmNvZGU6Zml4dHVyZS1wYXNzd29yZA==' } }) + ); + }); + + it('aggregates assistant and billed compaction calls while excluding native compaction and control rows', async () => { + const opts = request([ + assistant('final', { cost: 0.03 }), + { id: 'synthetic', type: 'synthetic', text: 'continue' }, + assistant('compact', { type: 'compaction', status: 'completed', cost: 0.01 }), + { id: 'native-compact', type: 'compaction', status: 'completed', native: { messages: [] } }, + assistant('tool'), user, { id: 'old', type: 'idle' } + ]); + const result = await fetchOpencodeRoundSummary(opts); + expect(result?.summary).toEqual({ + usage: { inputTokens: 30, outputTokens: 9, cacheReadInputTokens: 15, cacheCreationInputTokens: 9 }, + modelUsage: { 'fixture/model': { inputTokens: 30, outputTokens: 9, cacheReadInputTokens: 15, cacheCreationInputTokens: 9 } }, + totalCostUsd: 0.04, numTurns: 3, durationMs: 100 + }); + expect(opts.fetchImpl).toHaveBeenCalledWith( + 'http://127.0.0.1:48273/api/session/session%2Fid/message?limit=200', expect.anything() + ); + }); + + it('preserves valid tokens but omits round cost if any v2 call has no cost', async () => { + const result = await fetchOpencodeRoundSummary(request([user, assistant('one', { cost: 0.03 }), assistant('two', { cost: undefined })])); + expect(result?.summary).toMatchObject({ numTurns: 2, usage: { inputTokens: 20, outputTokens: 6 } }); + expect(result?.summary).not.toHaveProperty('totalCostUsd'); + }); + + it.each([ + [null], [user, { id: 'bad', type: 'assistant' }], [user, assistant('same'), assistant('same')], + [assistant('outside-window')], [user, assistant('bad', { tokens: { input: -1 } })], + [user, assistant('bad', { cost: null })], [user, assistant('bad', { model: [] })], + [user, assistant('bad', { type: 'compaction', status: 'running' })] + ])('fails closed for malformed or unassociated messages %j', async (...data) => { + const result = await fetchOpencodeRoundSummary(request(data)); + expect(result?.summary ?? null).toBeNull(); + }); + + it('rejects malformed envelope and pre-snapshot identity failures without throwing', async () => { + for (const data of [[null], [user, user]]) { + await expect(captureOpencodeRoundSnapshot(request(data))).resolves.toBeNull(); + } + await expect(captureOpencodeRoundSnapshot({ ...base, fetchImpl: vi.fn(async () => Response.json([])) })).resolves.toBeNull(); + }); + + it('omits optional metadata on unauthorized, malformed, or stalled v2 responses', async () => { + for (const response of [new Response('not authorized', { status: 401 }), new Response('{', { status: 200 })]) { + await expect(captureOpencodeRoundSnapshot({ ...base, fetchImpl: vi.fn(async () => response) })).resolves.toBeNull(); + } + await expect(captureOpencodeRoundSnapshot({ + ...base, timeoutMs: 10, + fetchImpl: vi.fn(async () => ({ ok: true, json: () => new Promise(() => {}) }) as Response) + })).resolves.toBeNull(); + }); +}); + + +describe('OpenCode v2 provider throughput', () => { + const step = (id: string, time: unknown = { created: 1_000, streamed: 1_500, completed: 9_000 }) => assistant(id, { time }); + + it('weights all assistant steps including reasoning, excluding tool settlement and billed compaction', async () => { + const result = await fetchOpencodeRoundSummary(request([ + user, step('tool'), step('final', { created: 10_000, streamed: 11_000 }), + assistant('compact', { type: 'compaction', status: 'completed' }) + ])); + expect(result?.summary).toMatchObject({ + usage: { outputTokens: 9 }, numTurns: 3, durationMs: 100, + generationMs: 1_500, generationOutputTokens: 6 + }); + }); + + it.each([ + { interval: 'zero', time: { created: 1_000, streamed: 1_000 }, invalidFirst: true }, + { interval: 'zero', time: { created: 1_000, streamed: 1_000 }, invalidFirst: false }, + { interval: 'reversed', time: { created: 1_000, streamed: 999 }, invalidFirst: true }, + { interval: 'reversed', time: { created: 1_000, streamed: 999 }, invalidFirst: false } + ])('omits both generation fields for a mixed $interval interval (invalid first: $invalidFirst)', async ({ time, invalidFirst }) => { + const invalid = { ...step('invalid', time), cost: 0.01 }; + const valid = { ...step('valid'), cost: 0.02 }; + const result = await fetchOpencodeRoundSummary(request([user, ...(invalidFirst ? [invalid, valid] : [valid, invalid])])); + expect(result?.summary).not.toHaveProperty('generationMs'); + expect(result?.summary).not.toHaveProperty('generationOutputTokens'); + expect(result?.summary).toEqual({ + usage: { inputTokens: 20, outputTokens: 6, cacheReadInputTokens: 10, cacheCreationInputTokens: 6 }, + modelUsage: { 'fixture/model': { inputTokens: 20, outputTokens: 6, cacheReadInputTokens: 10, cacheCreationInputTokens: 6 } }, + totalCostUsd: 0.03, numTurns: 2, durationMs: 100 + }); + }); + + it('ignores invalid compaction timing while preserving the positive assistant-only pair and billed totals', async () => { + const result = await fetchOpencodeRoundSummary(request([ + user, { ...step('valid'), cost: 0.02 }, + assistant('compact', { type: 'compaction', status: 'completed', cost: 0.01, time: { created: 10, streamed: 9 } }) + ])); + expect(result?.summary).toEqual({ + usage: { inputTokens: 20, outputTokens: 6, cacheReadInputTokens: 10, cacheCreationInputTokens: 6 }, + modelUsage: { 'fixture/model': { inputTokens: 20, outputTokens: 6, cacheReadInputTokens: 10, cacheCreationInputTokens: 6 } }, + totalCostUsd: 0.03, numTurns: 2, durationMs: 100, + generationMs: 500, generationOutputTokens: 3 + }); + }); + + it.each([ + undefined, null, [], {}, { streamed: 20 }, { created: 10 }, + { created: -1, streamed: 20 }, { created: 10, streamed: Infinity }, + { created: NaN, streamed: 20 }, { created: 1, streamed: Number.MAX_SAFE_INTEGER + 1 }, { created: '10', streamed: 20 }, + { created: 10, streamed: 10 }, { created: 20, streamed: 10 } + ])('preserves usage while omitting throughput for incomplete or zero time %j', async (time) => { + const result = await fetchOpencodeRoundSummary(request([user, assistant('one', { time })])); + expect(result?.summary).toMatchObject({ usage: { outputTokens: 3 } }); + expect(result?.summary).not.toHaveProperty('generationMs'); + expect(result?.summary).not.toHaveProperty('generationOutputTokens'); + }); + + it('hides the whole rate when just one assistant boundary is missing', async () => { + const result = await fetchOpencodeRoundSummary(request([user, step('valid'), step('missing', {})])); + expect(result?.summary).toMatchObject({ numTurns: 2 }); + expect(result?.summary).not.toHaveProperty('generationMs'); + }); + + it('omits throughput for zero output and v1 even if timestamps are present', async () => { + const zero = await fetchOpencodeRoundSummary(request([user, assistant('zero', { + time: { created: 1, streamed: 100 }, + tokens: { input: 1, output: 0, reasoning: 0, cache: { read: 0, write: 0 } } + })])); + expect(zero?.summary).not.toHaveProperty('generationMs'); + const opts = request([]); + const v1 = await fetchOpencodeRoundSummary({ ...opts, api: undefined, fetchImpl: async () => Response.json([ + { info: { id: user.id, role: 'user' }, parts: [{ type: 'text', text: user.text }] }, + { info: { ...step('one'), role: 'assistant', providerID: 'fixture', modelID: 'model' } } + ]) }); + expect(v1?.summary).toMatchObject({ numTurns: 1 }); + expect(v1?.summary).not.toHaveProperty('generationMs'); + }); +}); diff --git a/web/e2e-fixtures/concise-summary-fixture.html b/web/e2e-fixtures/concise-summary-fixture.html new file mode 100644 index 00000000..aa1f4d3b --- /dev/null +++ b/web/e2e-fixtures/concise-summary-fixture.html @@ -0,0 +1 @@ +Concise summary fixture
diff --git a/web/e2e-fixtures/concise-summary-fixture.tsx b/web/e2e-fixtures/concise-summary-fixture.tsx new file mode 100644 index 00000000..0a87a0d9 --- /dev/null +++ b/web/e2e-fixtures/concise-summary-fixture.tsx @@ -0,0 +1,46 @@ +import { useState } from 'react' +import { createRoot } from 'react-dom/client' +import { normalizeDecryptedMessage } from '../src/chat/normalize' +import { reduceChatBlocks } from '../src/chat/reducer' +import { reconcileChatBlocks } from '../src/chat/reconcile' +import { filterConciseChatBlocks } from '../src/chat/conciseView' +import { buildVisibleChatBlocks } from '../src/chat/toolGroups' +import { aggregateResponseGroups } from '../src/lib/assistant-runtime' +import { MessageMetadata } from '../src/components/AssistantChat/messages/MessageMetadata' +import type { NormalizedMessage } from '../src/chat/types' +import '../src/index.css' + +const messages: NormalizedMessage[] = [ + { id: 'user', localId: null, createdAt: 1, role: 'user', isSidechain: false, content: { type: 'text', text: 'Inspect the fixture and report the result.' } }, + { id: 'work', localId: null, createdAt: 2, role: 'agent', isSidechain: false, content: [{ type: 'tool-call', id: 'read', name: 'Read', input: { path: 'fixture.txt' }, description: null, uuid: 'read', parentUUID: null }] }, + { id: 'final', localId: null, createdAt: 3, role: 'agent', isSidechain: false, content: [{ type: 'text', text: 'The fixture is ready.', uuid: 'final', parentUUID: null }] } +] +const summary = normalizeDecryptedMessage({ id: 'summary', seq: 4, localId: null, createdAt: 4, + content: { role: 'agent', content: { type: 'codex', data: { type: 'round-summary', summary: { + usage: { input_tokens: 100, output_tokens: 30, cache_read_input_tokens: 0, cache_creation_input_tokens: 0 }, + modelUsage: { 'fixture/model': { inputTokens: 100, outputTokens: 30, cacheReadInputTokens: 0, cacheCreationInputTokens: 0 } }, + total_cost_usd: 0.02, num_turns: 2, duration_ms: 9000, generation_ms: 1500, generation_output_tokens: 30 + } } } } })! + +function Fixture() { + const [concise, setConcise] = useState(true) + const [late, setLate] = useState(false) + const canonical = reconcileChatBlocks(reduceChatBlocks(late ? messages : [...messages, summary], null).blocks, new Map()).blocks + const snapshot = JSON.stringify(canonical) + const projected = concise ? filterConciseChatBlocks(canonical) : canonical + const visible = buildVisibleChatBlocks(projected, { hasMoreMessages: false }) + const aggregates = aggregateResponseGroups(visible) + return
+

Concise response summary

+

Isolated synthetic rendering fixture using the production chat pipeline.

+ + +
+ {visible.map(block =>
+

{block.kind === 'user-text' || block.kind === 'agent-text' ? block.text : 'Read fixture.txt'}

+ {aggregates.has(block.id) &&
} +
)} +
+
+} +createRoot(document.getElementById('root')!).render() diff --git a/web/src/chat/conciseView.roundSummary.test.tsx b/web/src/chat/conciseView.roundSummary.test.tsx new file mode 100644 index 00000000..e3bbb3dc --- /dev/null +++ b/web/src/chat/conciseView.roundSummary.test.tsx @@ -0,0 +1,261 @@ +import { createElement } from 'react' +import { renderToStaticMarkup } from 'react-dom/server' +import { describe, expect, it } from 'vitest' +import { filterConciseChatBlocks } from './conciseView' +import { normalizeDecryptedMessage } from './normalize' +import { reduceChatBlocks } from './reducer' +import { reconcileChatBlocks, type ChatBlocksById } from './reconcile' +import { buildVisibleChatBlocks } from './toolGroups' +import type { AgentEvent, ChatBlock, NormalizedMessage } from './types' +import { aggregateResponseGroups, assignThreadMessageIds, buildSourceMessageIdsByBlock } from '@/lib/assistant-runtime' +import { buildMessageMetadataLabels, MessageMetadata } from '@/components/AssistantChat/messages/MessageMetadata' + +const wireSummary = { + usage: { input_tokens: 100, output_tokens: 30, cache_read_input_tokens: 0, cache_creation_input_tokens: 0 }, + modelUsage: { 'fixture/model': { inputTokens: 100, outputTokens: 30, cacheReadInputTokens: 0, cacheCreationInputTokens: 0 } }, + total_cost_usd: 0.02, num_turns: 2, duration_ms: 9000, + generation_ms: 1500, generation_output_tokens: 30 +} +function carrier(prefix: string, summary = wireSummary): NormalizedMessage { + const message = normalizeDecryptedMessage({ + id: `${prefix}-summary`, seq: 9, localId: null, createdAt: 9, + content: { role: 'agent', content: { type: 'codex', data: { type: 'round-summary', summary } } } + }) + if (!message) throw new Error('Invalid test summary carrier') + return message +} +function user(id: string): NormalizedMessage { + return { id, localId: null, createdAt: 1, role: 'user', isSidechain: false, content: { type: 'text', text: id } } +} +function text(id: string, kind: 'text' | 'reasoning' = 'text', turnId?: string): NormalizedMessage { + return { id, localId: null, createdAt: 3, role: 'agent', isSidechain: false, + meta: turnId ? { codexTurnId: turnId } : undefined, + content: [{ type: kind, text: id, uuid: id, streamId: id, parentUUID: null }] } +} +function tool(id: string, name = 'Read'): NormalizedMessage { + return { id, localId: null, createdAt: 2, role: 'agent', isSidechain: false, + content: [{ type: 'tool-call', id, name, input: {}, description: null, uuid: id, parentUUID: null }] } +} +function event(id: string, content: AgentEvent): NormalizedMessage { + return { id, localId: null, createdAt: 4, role: 'event', isSidechain: false, content } +} +function round(prefix: string, first: 'tool' | 'reasoning' | 'narration' = 'tool', summary = wireSummary): NormalizedMessage[] { + const work = first === 'tool' ? [tool(`${prefix}-tool`)] + : first === 'reasoning' ? [text(`${prefix}-reason`, 'reasoning')] + : [text(`${prefix}-narration`), tool(`${prefix}-tool`)] + return [user(`${prefix}-user`), ...work, text(`${prefix}-final`), carrier(prefix, summary), event(`${prefix}-ready`, { type: 'ready' })] +} +function project(blocks: ChatBlock[], concise = true) { + const projected = concise ? filterConciseChatBlocks(blocks) : blocks + const visible = buildVisibleChatBlocks(projected, { hasMoreMessages: false }) + const aggregates = aggregateResponseGroups(visible) + const labels = [...aggregates.values()].map(meta => buildMessageMetadataLabels(meta)) + const rendered = [...aggregates.values()].map(meta => renderToStaticMarkup(createElement(MessageMetadata, meta))).join('') + return { projected, visible, aggregates, labels, rendered } +} +function pipeline(messages: NormalizedMessage[], previous: ChatBlocksById = new Map()) { + const reconciled = reconcileChatBlocks(reduceChatBlocks(messages, null).blocks, previous) + return { ...project(reconciled.blocks), canonical: reconciled.blocks, byId: reconciled.byId } +} +function freeze(blocks: readonly ChatBlock[]): void { + for (const block of blocks) { + if (block.kind === 'tool-call') { freeze(block.children); Object.freeze(block.tool); Object.freeze(block.children) } + Object.freeze(block) + } + Object.freeze(blocks) +} + +describe('concise summary through reducer, reconcile, grouping and runtime metadata', () => { + it.each(['tool', 'reasoning', 'narration'] as const)('preserves the whole common summary from hidden %s on the retained final reply', first => { + const result = pipeline(round('one', first)) + expect(result.projected.map(block => block.kind)).toEqual(['user-text', 'agent-text']) + expect(result.labels).toEqual([['Model: fixture/model', 'Tokens: 130 (100 in · 30 out)', 'Cost: $0.020', 'Round: 9s · 2 turns · 20.0 tok/s']]) + expect(result.rendered).toContain('20.0 tok/s') + const original = result.canonical.find(block => block.kind === 'agent-text' && block.text === 'one-final') + const final = result.projected[1] + expect(final.id).toBe(original?.id) + expect(final.kind === 'agent-text' ? final.sourceMessageIds : null).toEqual(original?.kind === 'agent-text' ? original.sourceMessageIds : null) + const source = result.canonical.find(block => 'roundSummary' in block) + const canonicalSummary = source && 'roundSummary' in source ? source.roundSummary : undefined + expect('roundSummary' in final ? final.roundSummary : undefined).toBe(canonicalSummary) + }) + + it('reacts to late S and each generation field change/removal through reconciliation', () => { + const messages = round('late') + let result = pipeline(messages.filter(message => message.id !== 'late-summary')) + expect(result.rendered).not.toContain('tok/s') + for (const summary of [wireSummary, + { ...wireSummary, generation_ms: 750 }, + { ...wireSummary, generation_output_tokens: 60 }, + { ...wireSummary, generation_ms: undefined }, + { ...wireSummary, generation_output_tokens: undefined }, + wireSummary]) { + result = pipeline(round('late', 'tool', summary as typeof wireSummary), result.byId) + const hasPair = summary.generation_ms !== undefined && summary.generation_output_tokens !== undefined + const expected = hasPair ? `${(summary.generation_output_tokens! / (summary.generation_ms! / 1000)).toFixed(1)} tok/s` : null + if (expected) expect(result.rendered).toContain(expected) + else expect(result.rendered).not.toContain('tok/s') + expect(result.rendered).toContain('Cost: $0.020') + expect(result.rendered).toContain('Round: 9s') + } + result = pipeline(messages.filter(message => message.id !== 'late-summary'), result.byId) + expect(result.rendered).not.toContain('tok/s') + expect(result.aggregates.size).toBe(0) + }) + + it('toggles off/on without mutating canonical blocks or changing final source/message IDs', () => { + const { canonical } = pipeline(round('toggle')) + const before = JSON.stringify(canonical) + freeze(canonical) + const off = project(canonical, false) + const on = project(canonical) + const offAgain = project(canonical, false) + const onAgain = project(canonical) + expect(off.projected).toBe(canonical) + expect(offAgain.projected).toBe(canonical) + expect(on.labels).toEqual(off.labels) + expect(onAgain.labels).toEqual(on.labels) + expect(JSON.stringify(canonical)).toBe(before) + const sources = buildSourceMessageIdsByBlock(on.visible) + const final = on.visible[1] + expect(sources.get(final)).toContain('toggle-final') + expect(assignThreadMessageIds(on.visible).map(row => row.threadMessageId)).toEqual(assignThreadMessageIds(onAgain.visible).map(row => row.threadMessageId)) + }) + + it('retains a visible interactive summary owner once rather than duplicating it onto final text', () => { + const messages = round('interactive') + messages[1] = tool('interactive-tool', 'AskUserQuestion') + const result = pipeline(messages) + expect(result.projected.map(block => block.kind)).toEqual(['user-text', 'tool-call', 'agent-text']) + expect(result.projected.filter(block => 'roundSummary' in block && block.roundSummary)).toHaveLength(1) + expect(result.labels.flat().filter(label => label.includes('tok/s'))).toHaveLength(1) + }) + + it('keeps summaries in their user rounds and does not duplicate them over multiple final text blocks', () => { + const messages = round('first') + messages.splice(3, 0, text('first-final-more')) + const result = pipeline([...messages, ...round('second', 'reasoning', { ...wireSummary, generation_ms: 3000 })]) + expect(result.labels.flat().filter(label => label.includes('tok/s'))).toEqual(['Round: 9s · 2 turns · 20.0 tok/s', 'Round: 9s · 2 turns · 10.0 tok/s']) + expect(result.projected.filter(block => 'roundSummary' in block && block.roundSummary)).toHaveLength(2) + }) + + it.each(['compact-summary', 'message', 'title-changed'] as const)('attaches a late summary to the latest canonical response after a %s boundary', type => { + const boundary: AgentEvent = type === 'compact-summary' + ? { type, summary: 'compacted', compactionId: 'compact-1' } + : type === 'message' ? { type, message: 'separate response' } : { type, title: 'new title' } + const result = pipeline([user('u'), tool('hidden'), event('boundary', boundary), + text('other-final'), carrier('boundary')]) + expect(result.rendered).toContain('20.0 tok/s') + const owner = result.canonical.filter(block => 'roundSummary' in block && block.roundSummary) + expect(owner).toHaveLength(1) + expect(owner[0]).toMatchObject({ kind: 'agent-text', text: 'other-final' }) + expect(result.projected.filter(block => 'roundSummary' in block && block.roundSummary)).toHaveLength(1) + }) + + it('keeps auto-compaction metadata on the post-compaction reply through late arrival, replay and toggles', () => { + const normalize = (id: string, content: unknown): NormalizedMessage => { + const message = normalizeDecryptedMessage({ id, seq: 4, localId: null, createdAt: 4, content }) + if (!message) throw new Error('Invalid auto-compaction fixture') + return message + } + // Actual OpenCode native callbacks publish these two event shapes. + const messages = [user('u'), tool('before-compact'), + normalize('started', { role: 'agent', content: { type: 'event', data: { type: 'message', message: '📦 Compaction started' } } }), + normalize('compact', { role: 'agent', content: { type: 'codex', data: { type: 'compact-summary', summary: 'compacted' } } }), + text('post-compact-reason', 'reasoning'), text('post-compact-final'), + event('title', { type: 'title-changed', title: 'done' })] + let result = pipeline(messages) + expect(result.rendered).not.toContain('tok/s') + for (const summary of [wireSummary, { ...wireSummary, generation_ms: 750 }, + { ...wireSummary, generation_output_tokens: 60 }, + { ...wireSummary, generation_ms: undefined }, { ...wireSummary, generation_output_tokens: undefined }, wireSummary]) { + result = pipeline([...messages, carrier('auto', summary as typeof wireSummary)], result.byId) + const owners = result.canonical.filter(block => 'roundSummary' in block && block.roundSummary) + expect(owners).toHaveLength(1) + expect(owners[0]).toMatchObject({ kind: 'agent-reasoning', text: 'post-compact-reason' }) + expect(result.labels.flat()).toContain('Cost: $0.020') + const paired = summary.generation_ms !== undefined && summary.generation_output_tokens !== undefined + if (paired) expect(result.rendered).toContain(`${(summary.generation_output_tokens! / (summary.generation_ms! / 1000)).toFixed(1)} tok/s`) + else expect(result.rendered).not.toContain('tok/s') + const before = JSON.stringify(result.canonical) + freeze(result.canonical) + expect(project(result.canonical, false).labels).toEqual(result.labels) + expect(project(result.canonical).labels).toEqual(result.labels) + expect(JSON.stringify(result.canonical)).toBe(before) + const final = result.visible.find(block => block.kind === 'agent-text')! + expect(buildSourceMessageIdsByBlock(result.visible).get(final)).toEqual(['post-compact-final']) + expect(assignThreadMessageIds(result.visible).find(row => row.block === final)?.threadMessageId).toBe(`agent-text:${final.id}`) + } + result = pipeline(messages, result.byId) + expect(result.rendered).not.toContain('tok/s') + expect(result.aggregates.size).toBe(0) + }) + + it.each(['compact-summary', 'message'] as const)('does not transfer an earlier summary across a later %s boundary', type => { + const result = pipeline([user('u'), tool('hidden'), carrier('earlier'), event('boundary', type === 'compact-summary' + ? { type, summary: 'compacted' } : { type, message: 'separate response' }), text('other-final')]) + expect(result.rendered).not.toContain('tok/s') + expect(result.projected.filter(block => 'roundSummary' in block && block.roundSummary)).toHaveLength(0) + }) + + it.each(['user', 'cli-user'] as const)('does not search past a newer %s with only trailing events', boundary => { + const next = user('next') + if (boundary === 'cli-user') { + next.meta = { sentFrom: 'cli' } + next.content = { type: 'text', text: '/help' } + } + const result = pipeline([user('u'), text('old-final'), next, + event('notice', { type: 'message', message: 'no new reply' }), carrier('unowned')]) + expect(result.canonical.some(block => 'roundSummary' in block && block.roundSummary)).toBe(false) + expect(result.rendered).not.toContain('tok/s') + }) + + it('preserves separate summaries and a single visible interactive owner after compaction', () => { + const result = pipeline([user('u'), tool('before', 'AskUserQuestion'), carrier('before'), + event('started', { type: 'message', message: '📦 Compaction started' }), + event('compact', { type: 'compact-summary', summary: 'compacted' }), tool('after', 'AskUserQuestion'), + text('final'), carrier('after', { ...wireSummary, generation_ms: 3000 })]) + expect(result.canonical.filter(block => 'roundSummary' in block && block.roundSummary)).toHaveLength(2) + expect(result.projected.filter(block => 'roundSummary' in block && block.roundSummary)).toHaveLength(2) + expect(result.labels.flat().filter(label => label.includes('tok/s'))).toEqual([ + 'Round: 9s · 2 turns · 20.0 tok/s', 'Round: 9s · 2 turns · 10.0 tok/s']) + }) + + it('preserves the legacy Claude summary contract on the post-event response without inventing TPS', () => { + const legacy = normalizeDecryptedMessage({ id: 'claude-summary', seq: 9, localId: null, createdAt: 9, + content: { role: 'agent', content: { type: 'output', data: { type: 'system', subtype: 'turn_duration', + resultSummary: { modelUsage: wireSummary.modelUsage, total_cost_usd: 0.02, num_turns: 2, duration_ms: 9000 } } } } }) + if (!legacy) throw new Error('Invalid legacy Claude carrier') + const result = pipeline([user('u'), tool('hidden'), event('compact', { type: 'compact-summary', summary: 'compacted' }), + text('claude-final'), legacy]) + expect(result.labels.flat()).toContain('Round: 9s · 2 turns') + expect(result.rendered).not.toContain('tok/s') + expect(result.canonical.filter(block => 'roundSummary' in block && block.roundSummary)).toEqual([ + expect.objectContaining({ kind: 'agent-text', text: 'claude-final' })]) + }) + + it('does not borrow a summary from a distinct native response owner', () => { + const a = text('old-reason', 'reasoning', 'response-a') + const b = text('new-final', 'text', 'response-b') + const result = pipeline([user('u'), a, b, carrier('owners')]) + expect(result.rendered).not.toContain('tok/s') + }) + + it('does not invent an empty reply or borrow a following user round when no target survives', () => { + const result = pipeline([user('first'), tool('hidden'), carrier('empty'), user('second'), text('second-final')]) + expect(result.projected.map(block => block.kind)).toEqual(['user-text', 'user-text', 'agent-text']) + expect(result.rendered).not.toContain('tok/s') + }) + + it('leaves conflicting summary carriers untouched and does not choose or merge one into the reply', () => { + // Defensive projection input: two canonical carriers cannot identify one round owner. + const left = reduceChatBlocks(round('left', 'reasoning'), null).blocks + const right = reduceChatBlocks(round('right', 'tool', { ...wireSummary, generation_ms: 3000 }), null).blocks + const inputs = [left[0], left[1], right[1], left[2]] + const canonical = reconcileChatBlocks(inputs, new Map()).blocks + const before = JSON.stringify(canonical) + const result = project(canonical) + expect(result.rendered).not.toContain('tok/s') + expect(JSON.stringify(canonical)).toBe(before) + }) +}) diff --git a/web/src/chat/conciseView.ts b/web/src/chat/conciseView.ts index b2fccfa4..dd40f897 100644 --- a/web/src/chat/conciseView.ts +++ b/web/src/chat/conciseView.ts @@ -1,5 +1,6 @@ import type { AgentEvent, ChatBlock, ToolCallBlock } from '@/chat/types' import { isInteractiveToolBlock } from '@/chat/toolGroups' +import { getAssistantResponseGroups, hasUnambiguousResponseOwner } from '@/chat/responseGroups' import { getInputStringAny } from '@/lib/toolInputUtils' // Plan proposals are decisions the user acts on, not intermediate work. @@ -53,6 +54,19 @@ function isConciseVisibleEvent(event: AgentEvent): boolean { } } +// Projection must preserve metadata within the original runtime response group, +// even when a hidden event would otherwise join two visible assistant runs. +function preserveRoundSummaries(round: readonly ChatBlock[], output: ChatBlock[], start: number): void { + const kept = new Map(output.slice(start).map((block, index) => [block, start + index])) + for (const group of getAssistantResponseGroups(round)) { + const sources = group.blocks.filter(block => block.roundSummary) + // Never choose between carriers or invent a reply without a target. + if (sources.length !== 1 || kept.has(sources[0]) || !hasUnambiguousResponseOwner(group)) continue + const target = group.blocks.find(block => kept.has(block)) + if (target) output[kept.get(target)!] = { ...target, roundSummary: sources[0].roundSummary } + } +} + function filterRound(round: readonly ChatBlock[], output: ChatBlock[]): void { // Agent text after the round's last tool call or reasoning is the reply; // text before it is narration of the work in progress. @@ -65,6 +79,7 @@ function filterRound(round: readonly ChatBlock[], output: ChatBlock[]): void { } } + const outputStart = output.length round.forEach((block, index) => { switch (block.kind) { case 'agent-text': @@ -82,6 +97,7 @@ function filterRound(round: readonly ChatBlock[], output: ChatBlock[]): void { output.push(block) } }) + preserveRoundSummaries(round, output, outputStart) } /** diff --git a/web/src/chat/normalizeAgent.roundSummary.test.ts b/web/src/chat/normalizeAgent.roundSummary.test.ts new file mode 100644 index 00000000..a7c6420d --- /dev/null +++ b/web/src/chat/normalizeAgent.roundSummary.test.ts @@ -0,0 +1,111 @@ +import { describe, expect, it } from 'vitest'; +import { normalizeDecryptedMessage } from './normalize'; + +describe('OpenCode round summary carrier', () => { + it('reuses the existing turn-summary normalization contract', () => { + const normalized = normalizeDecryptedMessage({ + id: 'round-summary', + seq: 1, + localId: null, + createdAt: 1, + content: { + role: 'agent', + content: { + type: 'codex', + data: { + type: 'round-summary', + summary: { + usage: { input_tokens: 120, output_tokens: 30, cache_read_input_tokens: 90, cache_creation_input_tokens: 10 }, + modelUsage: { + 'openai/gpt-5.4': { inputTokens: 120, outputTokens: 30, cacheReadInputTokens: 90, cacheCreationInputTokens: 10 } + }, + total_cost_usd: 0.034, + num_turns: 2, + duration_ms: 1_250, + generation_ms: 500, + generation_output_tokens: 25 + } + } + } + } + }); + + expect(normalized).toMatchObject({ + role: 'event', + content: { + type: 'turn-summary', + summary: { + modelUsage: { + 'openai/gpt-5.4': { inputTokens: 120, outputTokens: 30, cacheReadInputTokens: 90, cacheCreationInputTokens: 10 } + }, + totalCostUsd: 0.034, + numTurns: 2, + durationMs: 1_250, + generationMs: 500, + generationOutputTokens: 25 + } + } + }); + }); + + it('fails closed for incomplete OpenCode aggregates while preserving permissive legacy summaries', () => { + const valid = { + usage: { input_tokens: 1, output_tokens: 2, cache_read_input_tokens: 3, cache_creation_input_tokens: 4 }, + modelUsage: { 'fixture/model': { inputTokens: 1, outputTokens: 2, cacheReadInputTokens: 3, cacheCreationInputTokens: 4 } }, + num_turns: 1, + duration_ms: 0 + } + const normalizeCarrier = (summary: unknown) => normalizeDecryptedMessage({ + id: 'strict-round-summary', seq: 1, localId: null, createdAt: 1, + content: { role: 'agent', content: { type: 'codex', data: { type: 'round-summary', summary } } } + }) + + expect(normalizeCarrier(valid)).not.toBeNull() + for (const malformed of [ + {}, + { ...valid, usage: undefined }, + { ...valid, modelUsage: {} }, + { ...valid, modelUsage: { 'fixture/model': { inputTokens: 1 } } }, + { ...valid, usage: { input_tokens: 1, output_tokens: 2, cache_read_input_tokens: 3 } }, + { ...valid, num_turns: 0 }, + { ...valid, duration_ms: Infinity }, + { ...valid, total_cost_usd: 0 }, + { ...valid, total_cost_usd: Number.NaN }, + { ...valid, modelUsage: [valid.modelUsage['fixture/model']] }, + { ...valid, modelUsage: { 'fixture/model': Object.assign([], valid.modelUsage['fixture/model']) } }, + Object.assign([], valid) + ]) { + expect(normalizeCarrier(malformed)).toBeNull() + } + + const legacy = normalizeDecryptedMessage({ + id: 'legacy-turn-duration', seq: 2, localId: null, createdAt: 2, + content: { role: 'agent', content: { type: 'output', data: { type: 'system', subtype: 'turn_duration', resultSummary: { duration_ms: 5 } } } } + }) + expect(legacy).toMatchObject({ content: { type: 'turn-summary', summary: { durationMs: 5 } } }) + }) +}); + + +it('omits only the throughput pair for absent, partial or invalid optional generation data', () => { + const valid = { + usage: { input_tokens: 1, output_tokens: 2, cache_read_input_tokens: 0, cache_creation_input_tokens: 0 }, + modelUsage: { 'fixture/model': { inputTokens: 1, outputTokens: 2, cacheReadInputTokens: 0, cacheCreationInputTokens: 0 } }, + num_turns: 1, duration_ms: 100 + } + for (const generation of [ + {}, { generation_ms: 1 }, { generation_output_tokens: 2 }, + ...[0, -1, NaN, Infinity, '5', 0.5, Number.MAX_SAFE_INTEGER + 1].flatMap(value => [ + { generation_ms: value, generation_output_tokens: 2 }, + { generation_ms: 10, generation_output_tokens: value } + ]) + ]) { + const normalized = normalizeDecryptedMessage({ + id: 'summary', seq: 1, localId: null, createdAt: 1, + content: { role: 'agent', content: { type: 'codex', data: { type: 'round-summary', summary: { ...valid, ...generation } } } } + }) + expect(normalized).toMatchObject({ content: { type: 'turn-summary', summary: { durationMs: 100, numTurns: 1 } } }) + expect(normalized?.content).not.toHaveProperty('summary.generationMs') + expect(normalized?.content).not.toHaveProperty('summary.generationOutputTokens') + } +}) diff --git a/web/src/chat/normalizeAgent.ts b/web/src/chat/normalizeAgent.ts index 07ba9569..bdcb1279 100644 --- a/web/src/chat/normalizeAgent.ts +++ b/web/src/chat/normalizeAgent.ts @@ -95,6 +95,57 @@ function normalizeRoundSummary(value: unknown): RoundSummary | undefined { } } +function normalizeOpencodeRoundSummary(value: unknown): RoundSummary | undefined { + if (!isObject(value) || Array.isArray(value)) return undefined + const usage = normalizeResultUsage(value.usage) + if ( + !usage + || usage.cache_creation_input_tokens === undefined + || usage.cache_read_input_tokens === undefined + ) return undefined + + if (!isObject(value.modelUsage) || Array.isArray(value.modelUsage)) return undefined + const entries: Array<[string, RoundModelUsage]> = [] + for (const [model, rawUsage] of Object.entries(value.modelUsage)) { + if (!model || !isObject(rawUsage) || Array.isArray(rawUsage)) return undefined + const inputTokens = nonNegativeSafeInteger(rawUsage.inputTokens) + const outputTokens = nonNegativeSafeInteger(rawUsage.outputTokens) + const cacheReadInputTokens = nonNegativeSafeInteger(rawUsage.cacheReadInputTokens) + const cacheCreationInputTokens = nonNegativeSafeInteger(rawUsage.cacheCreationInputTokens) + if ( + inputTokens === undefined + || outputTokens === undefined + || cacheReadInputTokens === undefined + || cacheCreationInputTokens === undefined + ) return undefined + entries.push([model, { inputTokens, outputTokens, cacheReadInputTokens, cacheCreationInputTokens }]) + } + if (entries.length === 0) return undefined + + const numTurns = nonNegativeSafeInteger(value.num_turns) + const durationMs = nonNegativeNumber(value.duration_ms) + if (numTurns === undefined || numTurns <= 0 || durationMs === undefined) return undefined + + const hasCost = Object.prototype.hasOwnProperty.call(value, 'total_cost_usd') + const totalCostUsd = hasCost ? nonNegativeNumber(value.total_cost_usd) : undefined + if (hasCost && (totalCostUsd === undefined || totalCostUsd <= 0)) return undefined + + const generationMs = nonNegativeSafeInteger(value.generation_ms) + const generationOutputTokens = nonNegativeSafeInteger(value.generation_output_tokens) + const generation = generationMs !== undefined && generationMs > 0 + && generationOutputTokens !== undefined && generationOutputTokens > 0 + ? { generationMs, generationOutputTokens } : {} + + return { + ...generation, + usage, + modelUsage: Object.fromEntries(entries), + totalCostUsd, + numTurns, + durationMs + } +} + function normalizeThreadGoal(value: unknown) { if (!isObject(value)) return null const threadId = asString(value.threadId ?? value.thread_id) @@ -1032,6 +1083,20 @@ export function normalizeAgentRecord( } } + if (data.type === 'round-summary') { + const summary = normalizeOpencodeRoundSummary(data.summary) + if (!summary) return null + return { + id: messageId, + localId, + createdAt, + role: 'event', + content: { type: 'turn-summary', summary }, + isSidechain: false, + meta + } + } + if (data.type === 'generated-image') { const imageId = asString(data.imageId ?? data.image_id) if (!imageId) return null diff --git a/web/src/chat/reconcile.roundSummary.test.ts b/web/src/chat/reconcile.roundSummary.test.ts new file mode 100644 index 00000000..fea708e9 --- /dev/null +++ b/web/src/chat/reconcile.roundSummary.test.ts @@ -0,0 +1,31 @@ +import { describe, expect, it } from 'vitest' +import { reconcileChatBlocks } from './reconcile' +import type { AgentTextBlock, RoundSummary } from './types' + +const summary: RoundSummary = { + modelUsage: {}, numTurns: 1, durationMs: 2_000, + generationMs: 1_000, generationOutputTokens: 20 +} +const block = (roundSummary: RoundSummary): AgentTextBlock => ({ + kind: 'agent-text', id: 'answer', localId: null, createdAt: 1, text: 'answer', roundSummary +}) + +describe('round throughput reconciliation', () => { + it.each([ + { ...summary, generationMs: 500 }, + { ...summary, generationOutputTokens: 40 }, + { ...summary, generationMs: undefined, generationOutputTokens: undefined } + ])('updates the visible rate when only provider generation data changes: %j', (nextSummary) => { + const previous = block(summary) + const next = block(nextSummary) + const result = reconcileChatBlocks([next], new Map([[previous.id, previous]])) + expect(result.blocks[0]).toBe(next) + expect(result.blocks[0]).not.toBe(previous) + }) + + it('retains stable references for unchanged provider generation data', () => { + const previous = block(summary) + const result = reconcileChatBlocks([block({ ...summary })], new Map([[previous.id, previous]])) + expect(result.blocks[0]).toBe(previous) + }) +}) diff --git a/web/src/chat/reconcile.ts b/web/src/chat/reconcile.ts index 7d533501..4920fadc 100644 --- a/web/src/chat/reconcile.ts +++ b/web/src/chat/reconcile.ts @@ -56,6 +56,8 @@ function areRoundSummariesEqual(left?: RoundSummary, right?: RoundSummary): bool return left.totalCostUsd === right.totalCostUsd && left.numTurns === right.numTurns && left.durationMs === right.durationMs + && left.generationMs === right.generationMs + && left.generationOutputTokens === right.generationOutputTokens && areUsageDataEqual(left.usage, right.usage) && leftModels.length === rightModels.length && leftModels.every(model => right.modelUsage[model] !== undefined diff --git a/web/src/chat/reducer.test.ts b/web/src/chat/reducer.test.ts index 84dba435..f1a162f3 100644 --- a/web/src/chat/reducer.test.ts +++ b/web/src/chat/reducer.test.ts @@ -1,6 +1,8 @@ import { describe, expect, it } from 'vitest' import { reduceChatBlocks } from './reducer' import { reconcileChatBlocks } from './reconcile' +import { buildVisibleChatBlocks, type VisibleChatBlock } from './toolGroups' +import { aggregateResponseGroups, assignThreadMessageIdsWithStableWrappers, type BlockWithThreadMessageId } from '@/lib/assistant-runtime' import { normalizeDecryptedMessage } from './normalize' import type { AgentTextBlock, NormalizedMessage } from './types' import type { DecryptedMessage } from '@/types/api' @@ -554,6 +556,10 @@ describe('reduceChatBlocks', () => { id: 'a2', localId: 'turn-2', createdAt: 3, role: 'agent', isSidechain: false, content: [{ type: 'text', text: 'answer', uuid: 'a2', parentUUID: 'a1' }] }, + { + id: 'title-event', localId: null, createdAt: 4, role: 'event', isSidechain: false, + content: { type: 'message', message: 'fixture title' } as any + }, { id: 'summary', localId: null, createdAt: 4, role: 'event', isSidechain: false, content: { type: 'turn-summary', summary } as any @@ -639,6 +645,59 @@ describe('reduceChatBlocks', () => { const assistant = reconciled.blocks.find(block => block.kind === 'agent-text') expect(assistant?.kind === 'agent-text' ? assistant.roundSummary : undefined).toEqual(summary) }) + it('keeps a late Codex round summary on the first visible response block through tool updates and title event', () => { + const wire = [ + decryptedMessage('u', { role: 'user', content: { type: 'text', text: 'prompt' } }, 1), + decryptedMessage('tool-pending', { role: 'agent', content: { type: 'codex', data: { type: 'tool-call', name: 'unknown', callId: 'call_fixture', input: {}, status: 'pending' } } }, 2), + decryptedMessage('tool-running-1', { role: 'agent', content: { type: 'codex', data: { type: 'tool-call', name: 'read_file', callId: 'call_fixture', input: { path: 'fixture.txt' }, status: 'in_progress' } } }, 3), + decryptedMessage('tool-running-2', { role: 'agent', content: { type: 'codex', data: { type: 'tool-call', name: 'read_file', callId: 'call_fixture', input: { path: 'fixture.txt' }, progress: { completed: 1 }, status: 'in_progress' } } }, 4), + decryptedMessage('tool-running-3', { role: 'agent', content: { type: 'codex', data: { type: 'tool-call', name: 'Read', callId: 'call_fixture', input: { path: 'fixture.txt' }, status: 'in_progress' } } }, 5), + decryptedMessage('result', { role: 'agent', content: { type: 'codex', data: { type: 'tool-call-result', callId: 'call_fixture', output: 'ok' } } }, 6), + decryptedMessage('usage1', { role: 'agent', content: { type: 'codex', data: { type: 'token_count', info: { total: { inputTokens: 1, outputTokens: 1 } } } } }, 7), + decryptedMessage('answer', { role: 'agent', content: { type: 'codex', data: { type: 'message', message: 'fixture final answer' } } }, 8), + decryptedMessage('usage2', { role: 'agent', content: { type: 'codex', data: { type: 'token_count', info: { total: { inputTokens: 2, outputTokens: 2 } } } } }, 9), + decryptedMessage('title', { role: 'agent', content: { type: 'output', data: { type: 'summary', summary: 'title' } } }, 10), + decryptedMessage('round', { role: 'agent', content: { type: 'codex', data: { type: 'round-summary', summary: { usage: { input_tokens: 3, output_tokens: 2, cache_read_input_tokens: 0, cache_creation_input_tokens: 0 }, modelUsage: { 'fixture/model': { inputTokens: 3, outputTokens: 2, cacheReadInputTokens: 0, cacheCreationInputTokens: 0 } }, num_turns: 2, duration_ms: 10, generation_ms: 500, generation_output_tokens: 2 } } } }, 11), + decryptedMessage('ready', { role: 'agent', content: { type: 'codex', data: { type: 'ready' } } }, 12) + ].map(normalizeDecryptedMessage).filter((message): message is NormalizedMessage => message !== null) + const before = reduceChatBlocks(wire.slice(0, -2), null) + const after = reduceChatBlocks(wire, null) + const reconciled = reconcileChatBlocks(after.blocks, new Map(before.blocks.map(block => [block.id, block]))) + const beforeVisible = buildVisibleChatBlocks(before.blocks, { hasMoreMessages: false }) + const visible = buildVisibleChatBlocks(reconciled.blocks, { hasMoreMessages: false }) + + expect(visible.map(block => block.kind)).toEqual(['user-text', 'tool-call', 'agent-text', 'agent-event']) + const firstVisibleAssistant = visible.find(block => block.kind === 'tool-call') + expect(firstVisibleAssistant?.kind === 'tool-call' ? firstVisibleAssistant.id : null).toBe('call_fixture') + expect(firstVisibleAssistant?.kind === 'tool-call' ? firstVisibleAssistant.tool.name : null).toBe('Read') + expect(firstVisibleAssistant?.kind === 'tool-call' ? firstVisibleAssistant.tool.state : null).toBe('completed') + expect(firstVisibleAssistant?.kind === 'tool-call' ? firstVisibleAssistant.roundSummary : undefined).toMatchObject({ numTurns: 2, durationMs: 10, generationMs: 500, generationOutputTokens: 2 }) + + const aggregate = aggregateResponseGroups(visible).get('call_fixture') + expect(aggregate?.roundSummary).toMatchObject({ numTurns: 2, durationMs: 10, generationMs: 500, generationOutputTokens: 2 }) + + const beforeFirst = beforeVisible.find(block => block.kind === 'tool-call') + const afterFirst = visible.find(block => block.kind === 'tool-call') + expect(afterFirst).not.toBe(beforeFirst) + const wrapperCache = new WeakMap() + const beforeWrapper = assignThreadMessageIdsWithStableWrappers(beforeVisible, wrapperCache).find(({ block }) => block.kind === 'tool-call') + const afterWrapper = assignThreadMessageIdsWithStableWrappers(visible, wrapperCache).find(({ block }) => block.kind === 'tool-call') + expect(afterWrapper).not.toBe(beforeWrapper) + }) + + it('does not attach a summary across the latest user boundary', () => { + const summary = { modelUsage: { 'fixture/model': { inputTokens: 3, outputTokens: 2 } }, numTurns: 2, durationMs: 10 } + const reduced = reduceChatBlocks([ + userMessage('first-user', 'first prompt', 1), + { id: 'first-answer', localId: null, createdAt: 2, role: 'agent', isSidechain: false, content: [{ type: 'text', text: 'first answer', uuid: 'first-answer', parentUUID: null }] }, + userMessage('second-user', 'second prompt', 3), + eventMessage('title-event', 'fixture title', 4), + { id: 'summary', localId: null, createdAt: 5, role: 'event', isSidechain: false, content: { type: 'turn-summary', summary } as any } + ], null) + const firstAnswer = reduced.blocks.find(block => block.kind === 'agent-text' && block.text === 'first answer') + expect(firstAnswer?.kind === 'agent-text' ? firstAnswer.roundSummary : undefined).toBeUndefined() + }) + it('keeps terminal stream source IDs when reconciling unchanged text', () => { const previous: AgentTextBlock = { diff --git a/web/src/chat/reducerTimeline.ts b/web/src/chat/reducerTimeline.ts index 0d7f6ee3..5484a838 100644 --- a/web/src/chat/reducerTimeline.ts +++ b/web/src/chat/reducerTimeline.ts @@ -572,14 +572,20 @@ export function reduceTimeline( && !(block.kind === 'cli-output' && block.source === 'user') let firstIndex = -1 for (let index = blocks.length - 1; index >= 0; index -= 1) { - if (!isSummaryTarget(blocks[index])) break + const block = blocks[index] + if (block.kind === 'user-text' || (block.kind === 'cli-output' && block.source === 'user')) break + // Ignore trailing notices, but never cross a rendered response + // boundary after locating the latest assistant group. + if (block.kind === 'agent-event') { + if (firstIndex !== -1) break + continue + } + if (!isSummaryTarget(block)) break firstIndex = index } if (firstIndex !== -1) { - const firstBlock = blocks[firstIndex] - if (isSummaryTarget(firstBlock)) { - firstBlock.roundSummary = summary - } + const summaryTarget = blocks[firstIndex] + if (isSummaryTarget(summaryTarget)) summaryTarget.roundSummary = summary } continue } diff --git a/web/src/chat/responseGroups.ts b/web/src/chat/responseGroups.ts new file mode 100644 index 00000000..3778baf2 --- /dev/null +++ b/web/src/chat/responseGroups.ts @@ -0,0 +1,52 @@ +import { isObject } from '@hapi/protocol' +import type { ChatBlock, RoundSummary } from './types' +import { visibleBlockRole } from './toolGroups' + +export type AssistantResponseGroup = { + blocks: Exclude[] + before: ChatBlock | null + after: ChatBlock | null +} + +// Use the original runtime boundaries, including events hidden by projection. +export function getAssistantResponseGroups(blocks: readonly ChatBlock[]): AssistantResponseGroup[] { + const groups: AssistantResponseGroup[] = [] + let group: AssistantResponseGroup | null = null + let before: ChatBlock | null = null + for (const block of blocks) { + if (block.kind !== 'user-text' && block.kind !== 'agent-event' && visibleBlockRole(block) === 'assistant') { + group ??= { blocks: [], before, after: null } + group.blocks.push(block) + } else { + if (group) { group.after = block; groups.push(group); group = null } + before = block + } + } + if (group) groups.push(group) + return groups +} + +export function hasUnambiguousResponseOwner(group: AssistantResponseGroup): boolean { + const owners = new Set(group.blocks.map(block => isObject(block.meta) && typeof block.meta.codexTurnId === 'string' + ? block.meta.codexTurnId : undefined)) + const summaries: RoundSummary[] = group.blocks.flatMap(block => block.roundSummary ? [block.roundSummary] : []) + return owners.size === 1 && summaries.length <= 1 + && summaries.every(summary => !summary.turnId || owners.has(summary.turnId)) +} + +export function responseBlockKey(block: ChatBlock): string { + return `${block.kind}:${block.id}` +} + +// Stable source identity, not presentation text, summary values or local indices. +export function responseBlockIdentity(block: ChatBlock): unknown { + return [responseBlockKey(block), 'localId' in block ? block.localId : null, + block.invokedAt, block.kind === 'agent-event' ? block.event.type : null, + 'sourceMessageIds' in block ? block.sourceMessageIds : null, + isObject(block.meta) ? block.meta.codexTurnId : null] +} + +export function responseGroupIdentity(group: AssistantResponseGroup): string { + return JSON.stringify([group.before && responseBlockIdentity(group.before), + group.blocks.map(responseBlockIdentity), group.after && responseBlockIdentity(group.after)]) +} diff --git a/web/src/chat/types.ts b/web/src/chat/types.ts index b3e2cce6..843625bf 100644 --- a/web/src/chat/types.ts +++ b/web/src/chat/types.ts @@ -29,6 +29,8 @@ export type RoundSummary = { totalCostUsd?: number numTurns?: number durationMs?: number + generationMs?: number + generationOutputTokens?: number } export type AgentEvent = diff --git a/web/src/components/AssistantChat/messages/MessageMetadata.test.ts b/web/src/components/AssistantChat/messages/MessageMetadata.test.ts index 9f74b196..a9c314da 100644 --- a/web/src/components/AssistantChat/messages/MessageMetadata.test.ts +++ b/web/src/components/AssistantChat/messages/MessageMetadata.test.ts @@ -212,7 +212,7 @@ describe('buildMessageMetadataLabels', () => { 'Models: claude-opus-5, claude-haiku-4-5, claude-empty-5', 'Tokens: 24 (10 in · 14 out)', 'Cost: <$0.0001', - 'Round: 0.0s' + 'Round: 0s' ]) }) }) @@ -271,3 +271,20 @@ describe('Codex cached input metadata', () => { expect(labels(input, cached).join(' ')).not.toMatch(/NaN|Infinity/) }) }) + + +describe('provider throughput metadata', () => { + const summary = { + modelUsage: { 'fixture/model': { outputTokens: 1_000 } }, + durationMs: 9_000, numTurns: 2, generationMs: 1_500, generationOutputTokens: 30 + } + it('uses provider time and assistant-only output instead of wall time or compaction usage', () => { + expect(buildMessageMetadataLabels({ roundSummary: summary })).toContain('Round: 9s · 2 turns · 20.0 tok/s') + }) + it.each([undefined, 0, -1, NaN, Infinity, Number.MIN_VALUE])('hides invalid or overflowing duration %s', (generationMs) => { + expect(buildMessageMetadataLabels({ roundSummary: { ...summary, generationMs } }).join(' ')).not.toContain('tok/s') + }) + it.each([undefined, 0, -1, NaN, Infinity, 1.5])('hides invalid output %s', (generationOutputTokens) => { + expect(buildMessageMetadataLabels({ roundSummary: { ...summary, generationOutputTokens } }).join(' ')).not.toContain('tok/s') + }) +}) diff --git a/web/src/components/AssistantChat/messages/MessageMetadata.tsx b/web/src/components/AssistantChat/messages/MessageMetadata.tsx index ce8d77df..ddf24472 100644 --- a/web/src/components/AssistantChat/messages/MessageMetadata.tsx +++ b/web/src/components/AssistantChat/messages/MessageMetadata.tsx @@ -21,10 +21,19 @@ function formatCompactTokenCount(value: number): string { return `${(Math.round((value / divisor) * 10) / 10).toString()}${suffix}` } -function formatPercentage(value: number): string { +function formatOneDecimal(value: number): string { return (Math.round(value * 10) / 10).toString() } +function formatPercentage(value: number): string { + return formatOneDecimal(value) +} + +function formatRoundDuration(durationMs: number): string { + if (durationMs < 60_000) return formatOneDecimal(durationMs / 1000) + 's' + return formatDuration(durationMs) +} + function formatUsd(value: number): string { if (value < 0.0001) return '<$0.0001' return value >= 0.01 ? `$${value.toFixed(3)}` : `$${value.toFixed(4)}` @@ -80,10 +89,16 @@ function buildRoundSummaryLabels(summary: RoundSummary, fallbackModel?: string | } const round: string[] = [] - if (summary.durationMs !== undefined && summary.durationMs >= 0) round.push(formatDuration(summary.durationMs)) + if (summary.durationMs !== undefined && summary.durationMs >= 0) round.push(formatRoundDuration(summary.durationMs)) if (summary.numTurns !== undefined && summary.numTurns > 0) { round.push(`${summary.numTurns} turn${summary.numTurns === 1 ? '' : 's'}`) } + const { generationMs, generationOutputTokens } = summary + if (generationMs !== undefined && Number.isSafeInteger(generationMs) && generationMs > 0 + && generationOutputTokens !== undefined && Number.isSafeInteger(generationOutputTokens) && generationOutputTokens > 0) { + const tokensPerSecond = generationOutputTokens / (generationMs / 1_000) + if (Number.isFinite(tokensPerSecond)) round.push(`${tokensPerSecond.toFixed(1)} tok/s`) + } if (round.length > 0) parts.push(`Round: ${round.join(' · ')}`) return parts } diff --git a/web/src/components/SessionChat.projection-boundary.test.tsx b/web/src/components/SessionChat.projection-boundary.test.tsx new file mode 100644 index 00000000..98adcb8a --- /dev/null +++ b/web/src/components/SessionChat.projection-boundary.test.tsx @@ -0,0 +1,167 @@ +import { useEffect, useMemo, useRef, useState } from 'react' +import { act, render, screen, waitFor } from '@testing-library/react' +import { AssistantRuntimeProvider, ThreadPrimitive } from '@assistant-ui/react' +import { QueryClient, QueryClientProvider } from '@tanstack/react-query' +import { afterEach, describe, expect, it, vi } from 'vitest' +import { resolveLatestCompletedBoundaryIdForView } from './SessionChat' +import { HappyChatProvider } from './AssistantChat/context' +import { HappyAssistantMessage } from './AssistantChat/messages/AssistantMessage' +import { I18nProvider } from '@/lib/i18n-context' +import { normalizeDecryptedMessage } from '@/chat/normalize' +import { reduceChatBlocks } from '@/chat/reducer' +import { reconcileChatBlocks } from '@/chat/reconcile' +import { filterConciseChatBlocks } from '@/chat/conciseView' +import { buildVisibleChatBlocks, type VisibleChatBlock } from '@/chat/toolGroups' +import { findLatestCompletedBoundaryId, useHappyRuntime } from '@/lib/assistant-runtime' +import { clearMessageWindow, getMessageWindowState, loadMessageContext, setMessageViewMode, syncTailMessages, type MessageWindowState } from '@/lib/message-window-store' +import type { ChatBlock, NormalizedMessage } from '@/chat/types' +import type { ApiClient } from '@/api/client' +import type { DecryptedMessage, MessageContextResponse, MessagesResponse, Session, SessionMetadataSummary } from '@/types/api' + +function conversation(prefix: string, seq: number, work: 'tool' | 'reasoning'): DecryptedMessage[] { + const wire = (id: string, data: unknown): DecryptedMessage => ({ id, seq: ++seq, localId: `${id}-local`, createdAt: seq * 1000, + content: { role: 'agent', content: { type: 'codex', data } } }) + return [ + { id: `${prefix}-user`, seq, localId: `${prefix}-user-local`, createdAt: seq * 1000, invokedAt: seq * 1000, + content: { role: 'user', content: { type: 'text', text: `${prefix} prompt` } } }, + ...(work === 'tool' ? [wire(`${prefix}-work`, { type: 'tool-call', callId: `${prefix}-tool`, name: 'Read', input: {} }), + wire(`${prefix}-result`, { type: 'tool-call-result', callId: `${prefix}-tool`, output: 'ok' })] + : [wire(`${prefix}-work`, { type: 'reasoning', message: `${prefix} nonempty reasoning` })]), + wire(`${prefix}-final`, { type: 'message', message: `${prefix} final answer` }) + ] +} +function latest(messages: DecryptedMessage[]): MessagesResponse { + const last = messages.at(-1)! + return { messages, page: { direction: 'latest', limit: 200, epoch: 0, reset: false, nextBeforeAt: messages[0].createdAt, + nextBeforeSeq: messages[0].seq, nextAfterAt: null, nextAfterSeq: null, + snapshotHeadAt: last.createdAt, snapshotHeadSeq: last.seq, hasMore: true } } +} +function context(messages: DecryptedMessage[], head: DecryptedMessage, targetMessageId: string): MessageContextResponse { + return { messages, targetMessageId, page: { epoch: 0, hasMore: true, nextBeforeAt: messages[0].createdAt, + nextBeforeSeq: messages[0].seq, snapshotHeadAt: head.createdAt, snapshotHeadSeq: head.seq } } +} + +type Memory = { id: string | null; tailRevision: number; sessionId: string; canonicalBlocks: readonly ChatBlock[]; visibleBlocks: readonly VisibleChatBlock[] } +type Props = { state: MessageWindowState; api: ApiClient; concise: boolean; search?: boolean; running?: boolean; sessionId?: string; revision?: number } +function Pipeline({ state, api, concise, search, running = false, sessionId = state.sessionId, revision = state.tailRevision }: Props) { + const prior = useRef(new Map()) + const canonical = useMemo(() => { + const normalized = state.messages.map(normalizeDecryptedMessage).filter((message): message is NormalizedMessage => message !== null) + const reconciled = reconcileChatBlocks(reduceChatBlocks(normalized, null).blocks, prior.current) + prior.current = reconciled.byId + return reconciled.blocks + }, [state.messages]) + const canonicalSnapshot = JSON.stringify(canonical) + const visible = useMemo(() => buildVisibleChatBlocks(concise && !search ? filterConciseChatBlocks(canonical) : canonical, + { hasMoreMessages: state.hasMore }), [canonical, concise, search, state.hasMore]) + const current = state.viewMode === 'tail' ? findLatestCompletedBoundaryId(visible, running, running ? 1 : null) : null + const [memory, setMemory] = useState(null) + // Exercise the existing tail-only observation protocol, with real source and + // runtime views attached. The resolver is the production SessionChat function. + useEffect(() => { + if (state.viewMode === 'tail') setMemory({ id: current, tailRevision: revision, sessionId, canonicalBlocks: canonical, visibleBlocks: visible }) + }, [state.viewMode, current, revision, sessionId, canonical, visible]) + const scope = { sessionId, canonicalBlocks: canonical, visibleBlocks: visible, isRunning: running, activeTurnStartedAt: running ? 1 : null } + const boundary = resolveLatestCompletedBoundaryIdForView(state.viewMode, current, memory, revision, scope) + const session = { id: sessionId, active: true, thinking: running, activeTurnStartedAt: running ? 1 : null } as Session + const runtime = useHappyRuntime({ session, blocks: visible, messagesVersion: state.messagesVersion, historyVersion: state.historyVersion, + viewMode: state.viewMode, isSending: false, isRunning: running, onSendMessage: () => {}, onAbort: async () => {} }) + return {}, onForkConversation: async () => {}, isLatestCompletedBoundary: id => id === boundary, + hasMoreMessages: state.hasMore, isSyncingTail: false, isLoadingMoreMessages: false, + loadOlderMessagesPreservingScroll: async () => 'terminal-stop' }}> + {boundary ?? 'none'} + {canonicalSnapshot === JSON.stringify(canonical) ? 'true' : 'false'} + null, AssistantMessage: HappyAssistantMessage }} /> + +} +const sessions: string[] = [] +afterEach(() => { for (const id of sessions) clearMessageWindow(id); sessions.length = 0 }) +async function setup(work: 'tool' | 'reasoning', concise: boolean) { + const id = `projection-${work}-${sessions.length}` + sessions.push(id) + const current = conversation('latest', 1000, work) + const older = conversation('older', 1, 'reasoning') + let contextMessages = current + const api = { getMessages: vi.fn(async () => latest(current)), + getMessageContext: vi.fn(async (_session: string, target: string) => context(contextMessages, current.at(-1)!, target)) } as unknown as ApiClient + await syncTailMessages(api, id) + const client = new QueryClient({ defaultOptions: { queries: { retry: false } } }) + let props: Props = { state: getMessageWindowState(id), api, concise } + const node = () => + const rendered = render(node()) + await waitFor(() => expect(screen.getByRole('button', { name: 'Fork' })).toBeTruthy()) + const update = (patch: Partial) => { props = { ...props, ...patch }; rendered.rerender(node()) } + const load = async (messages: DecryptedMessage[], target = messages.at(-1)!.id) => { + contextMessages = messages + await act(async () => { expect(await loadMessageContext(api, id, target)).toBe(true) }) + update({ state: getMessageWindowState(id) }) + } + return { id, current, older, update, load } +} +function forkAnchor(): string | null { + return screen.getByRole('button', { name: 'Fork' }).closest('[data-hapi-message-role="assistant"]')?.id ?? null +} + +describe('completed response identity across projections and real context windows', () => { + it('preserves current Fork through full tail → history → concise off/on on the same actual runtime card', async () => { + const test = await setup('tool', false) + const before = forkAnchor() + act(() => setMessageViewMode(test.id, 'history')) + test.update({ state: getMessageWindowState(test.id), concise: true }) + await waitFor(() => expect(screen.getByRole('button', { name: 'Fork' })).toBeTruthy()) + expect(screen.getByTestId('immutable').textContent).toBe('true') + expect(forkAnchor()).not.toBe(before) + test.update({ concise: false }) + await waitFor(() => expect(forkAnchor()).toBe(before)) + }) + + it('restores current Fork on reverse search reload and on search dismissal at unchanged tailRevision', async () => { + const test = await setup('reasoning', true) + const initial = getMessageWindowState(test.id) + const before = forkAnchor() + await test.load(test.older) + expect(screen.queryByRole('button', { name: 'Fork' })).toBeNull() + expect(getMessageWindowState(test.id).messages.some(message => message.id === 'latest-final')).toBe(false) + test.update({ search: true }) + await test.load(test.current, 'latest-final') + const restored = getMessageWindowState(test.id) + expect(restored.viewMode).toBe('history') + expect(restored.tailRevision).toBe(initial.tailRevision) + expect(restored.historyVersion).toBeGreaterThan(initial.historyVersion) + await waitFor(() => expect(screen.getByRole('button', { name: 'Fork' })).toBeTruthy()) + expect(screen.getByTestId('immutable').textContent).toBe('true') + expect(forkAnchor()).not.toBe(before) + test.update({ search: false }) + await waitFor(() => expect(forkAnchor()).toBe(before)) + expect(test.current.map(message => [message.id, message.localId])).toEqual(restored.messages.map(message => [message.id, message.localId])) + }) + + it.each(['absent', 'revision', 'session', 'active', 'user', 'event', 'compaction', 'source', 'partial', 'owner'] as const)('hides current Fork for unproven %s identity', async negative => { + const test = await setup('tool', false) + act(() => setMessageViewMode(test.id, 'history')) + test.update({ state: getMessageWindowState(test.id) }) + if (negative === 'absent') { + await test.load(test.older) + expect(getMessageWindowState(test.id).messages.some(message => message.id === 'latest-final')).toBe(false) + } + else if (negative === 'partial') await test.load([test.current.at(-1)!]) + else if (negative === 'revision') test.update({ revision: getMessageWindowState(test.id).tailRevision + 1 }) + else if (negative === 'session') test.update({ sessionId: 'different-session' }) + else if (negative === 'active') test.update({ running: true }) + else { + const changed = [...test.current] + if (negative === 'owner') changed[changed.length - 1] = { ...changed.at(-1)!, content: { role: 'agent', content: { type: 'codex', data: { type: 'message', message: 'latest final answer', turn_id: 'different-response' } } } } + else if (negative === 'source') changed[changed.length - 1] = { ...changed.at(-1)!, id: 'different-final-source' } + else if (negative === 'user') changed.splice(-1, 0, { ...changed[0], id: 'other-user', localId: 'other-local', createdAt: 1003500, invokedAt: 1003500 }) + else changed.splice(-1, 0, { id: 'separator', localId: null, seq: 1002.5, createdAt: 1002500, + content: { role: 'agent', content: { type: 'codex', data: negative === 'compaction' + ? { type: 'compact-summary', summary: 'compacted', compactionId: 'compact' } + : { type: 'error', message: 'response separator' } } } }) + await test.load(changed) + } + expect(screen.queryByRole('button', { name: 'Fork' })).toBeNull() + }) +}) diff --git a/web/src/components/SessionChat.tsx b/web/src/components/SessionChat.tsx index 572bd2a1..946ffc07 100644 --- a/web/src/components/SessionChat.tsx +++ b/web/src/components/SessionChat.tsx @@ -25,8 +25,9 @@ import { normalizeDecryptedMessage } from '@/chat/normalize' import { reduceChatBlocks } from '@/chat/reducer' import { reconcileChatBlocks } from '@/chat/reconcile' import { buildConversationOutline } from '@/chat/outline' -import { buildVisibleChatBlocks, isToolGroupBlock, type ToolGroupBlock } from '@/chat/toolGroups' +import { buildVisibleChatBlocks, isToolGroupBlock, type ToolGroupBlock, type VisibleChatBlock, visibleBlockRole } from '@/chat/toolGroups' import { filterConciseChatBlocks } from '@/chat/conciseView' +import { getAssistantResponseGroups, hasUnambiguousResponseOwner, responseBlockKey, responseBlockIdentity, responseGroupIdentity } from '@/chat/responseGroups' import { useUnseenBlockCount } from '@/hooks/useUnseenBlockCount' import { useCodexExplorationCollapse } from '@/hooks/useCodexExplorationCollapse' import { isQueuedForInvocation } from '@/lib/messages' @@ -56,7 +57,7 @@ import { classifySessionAttention, getSessionAttentionLabelKey } from '@/lib/ses import { getSessionLastSeenAt } from '@/lib/sessionLastSeen' import { formatRelativeTime } from '@/lib/relativeTime' import { ScratchlistMigrationBanner } from '@/components/AssistantChat/ScratchlistMigrationBanner' -import { findLatestCompletedBoundaryId, useHappyRuntime } from '@/lib/assistant-runtime' +import { assignThreadMessageIds, findLatestCompletedBoundaryId, useHappyRuntime } from '@/lib/assistant-runtime' import { getRestoredComposerSendIntent, resolveMessageDeliveryMode, @@ -557,17 +558,72 @@ export function buildGoalStateMessages( * A live tail revision invalidates the remembered boundary until tail view * observes the authoritative current boundary again. */ +type CompletedBoundaryMemory = { + id: string | null + tailRevision: number + sessionId?: string + canonicalBlocks?: readonly ChatBlock[] + visibleBlocks?: readonly VisibleChatBlock[] +} + +type BoundaryProjection = { + sessionId: string + canonicalBlocks: readonly ChatBlock[] + visibleBlocks: readonly VisibleChatBlock[] + isRunning: boolean +} + +function renderedResponseGroups(blocks: readonly VisibleChatBlock[]): { id: string; keys: string[] }[] { + const groups: { id: string; keys: string[] }[] = [] + let group: { id: string; keys: string[] } | null = null + for (const { block, threadMessageId } of assignThreadMessageIds(blocks)) { + if (visibleBlockRole(block) !== 'assistant') { group = null; continue } + if (!group) { group = { id: threadMessageId, keys: [] }; groups.push(group) } + group.keys.push(...(block.kind === 'tool-group' ? block.tools.map(responseBlockKey) : [responseBlockKey(block)])) + } + return groups +} + export function resolveLatestCompletedBoundaryIdForView( viewMode: 'tail' | 'history', currentTailBoundaryId: string | null, - rememberedTailBoundary: { id: string | null; tailRevision: number } | null, - currentTailRevision: number + rememberedTailBoundary: CompletedBoundaryMemory | null, + currentTailRevision: number, + projection?: BoundaryProjection ): string | null { if (viewMode === 'tail') return currentTailBoundaryId - if (!rememberedTailBoundary || rememberedTailBoundary.tailRevision !== currentTailRevision) { - return null + const memory = rememberedTailBoundary + if (!memory || memory.tailRevision !== currentTailRevision) return null + if (!projection) return memory.id + if (projection.isRunning || memory.sessionId !== projection.sessionId + || !memory.id || !memory.canonicalBlocks || !memory.visibleBlocks) return null + + // User boundaries retain their canonical identity through either projection. + const rememberedUser = assignThreadMessageIds(memory.visibleBlocks).find(({ block, threadMessageId }) => + threadMessageId === memory.id && visibleBlockRole(block) === 'user') + if (rememberedUser && rememberedUser.block.kind !== 'tool-group') { + const identity = JSON.stringify(responseBlockIdentity(rememberedUser.block)) + const matches = assignThreadMessageIds(projection.visibleBlocks).filter(({ block }) => + block.kind !== 'tool-group' && visibleBlockRole(block) === 'user' + && JSON.stringify(responseBlockIdentity(block)) === identity) + return matches.length === 1 ? matches[0].threadMessageId : null } - return rememberedTailBoundary.id + + const rememberedCard = renderedResponseGroups(memory.visibleBlocks).find(group => group.id === memory.id) + if (!rememberedCard) return null + const originals = getAssistantResponseGroups(memory.canonicalBlocks).filter(group => + rememberedCard.keys.every(key => group.blocks.some(block => responseBlockKey(block) === key))) + if (originals.length !== 1 || !hasUnambiguousResponseOwner(originals[0])) return null + const signature = responseGroupIdentity(originals[0]) + const matches = getAssistantResponseGroups(projection.canonicalBlocks).filter(group => + hasUnambiguousResponseOwner(group) && responseGroupIdentity(group) === signature) + if (matches.length !== 1) return null + const keys = new Set(matches[0].blocks.map(responseBlockKey)) + if (keys.size !== matches[0].blocks.length || matches[0].blocks.some(block => !block.id.trim())) return null + const cards = renderedResponseGroups(projection.visibleBlocks).filter(group => group.keys.every(key => keys.has(key))) + // A hidden event can join distinct original groups into one card. Its extra + // keys fail the subset check above; do not invent current ownership. + return cards.length === 1 ? cards[0].id : null } function hasAbortableAgentRun(blocks: readonly ChatBlock[]): boolean { @@ -743,10 +799,7 @@ function SessionChatInner(props: SessionChatProps) { const blocksByIdRef = useRef>(new Map()) const visibleGroupsRef = useRef([]) const visibleGroupsModeRef = useRef(toolGroupingMode) - const [rememberedTailBoundary, setRememberedTailBoundary] = useState<{ - id: string | null - tailRevision: number - } | null>(null) + const [rememberedTailBoundary, setRememberedTailBoundary] = useState(null) const [forceScrollToken, setForceScrollToken] = useState(0) const uploadDraftSnapshotRef = useRef<{ text: string; attachments: AttachmentDraftInput[] }>({ text: '', @@ -1636,16 +1689,21 @@ function SessionChatInner(props: SessionChatProps) { if (props.viewMode !== 'tail') return setRememberedTailBoundary((previous) => ( previous?.id === currentTailBoundaryId && previous.tailRevision === props.tailRevision + && previous.sessionId === props.session.id && previous.canonicalBlocks === reconciled.blocks + && previous.visibleBlocks === visibleBlocks ? previous - : { id: currentTailBoundaryId, tailRevision: props.tailRevision } + : { id: currentTailBoundaryId, tailRevision: props.tailRevision, sessionId: props.session.id, + canonicalBlocks: reconciled.blocks, visibleBlocks } )) - }, [currentTailBoundaryId, props.tailRevision, props.viewMode]) + }, [currentTailBoundaryId, props.tailRevision, props.viewMode, props.session.id, reconciled.blocks, visibleBlocks]) const latestCompletedBoundaryId = resolveLatestCompletedBoundaryIdForView( props.viewMode, currentTailBoundaryId, rememberedTailBoundary, - props.tailRevision + props.tailRevision, + { sessionId: props.session.id, canonicalBlocks: reconciled.blocks, visibleBlocks, + isRunning: props.session.thinking } ) const isLatestCompletedBoundary = useCallback((messageId: string) => {