From cb43c759dbdefdcecfc8cbcfa4fe13edda1d4d72 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 30 Sep 2026 11:38:24 +0000 Subject: [PATCH 1/5] fix: don't let one malformed tool-call row fail the whole agent history load `agentRestClient.ts`'s `getMessages()` calls `zAgentMessages.parse()` (throws, not safeParse). Since `zAgentMessage.content.tool_calls` was typed as `z.array(zToolCallSummary)` -- the generated schema, which requires `tool_call_id`, closes `status` to `'success' | 'error'`, and requires an integer `duration_ms` -- a single non-conforming historical tool-call row threw during `.parse()` and failed the entire array/message/response parse, surfacing as `agent_history_load_failed` instead of gracefully degrading just that one entry. - agentApiSchema.ts: the message-parse boundary's `content.tool_calls` is now `z.array(z.unknown())`, so a malformed entry can never throw at `zAgentMessages.parse()`. `zPersistedToolCallSummary` (used only by `parseToolCallEntry`'s own `safeParse`) relaxes the generated schema: `tool_call_id` optional, `status` a bare string, `duration_ms` not required to be an integer. - agentTranscript.ts: `parseToolCallEntry` validates only the fields it reads (`.pick()`), restores the `tool_call_id ?? id` fallback for rows predating `tool_call_id`, and `toolCallOk` treats the older `'ok'` status alias the same as `'success'`. - agentTranscript.test.ts: restores the pre-tightening fixtures/tests this broke, and adds a regression test that exercises the actual `zAgentMessages.parse()` boundary with a malformed row, confirming the whole history still loads and only that one tool-call entry degrades. --- .../agent/schemas/agentApiSchema.ts | 44 ++-- .../services/agent/agentTranscript.test.ts | 209 ++++++++++++++---- .../agent/services/agent/agentTranscript.ts | 55 +++-- 3 files changed, 236 insertions(+), 72 deletions(-) diff --git a/src/workbench/extensions/agent/schemas/agentApiSchema.ts b/src/workbench/extensions/agent/schemas/agentApiSchema.ts index 4866b9a3af7..eb72c279107 100644 --- a/src/workbench/extensions/agent/schemas/agentApiSchema.ts +++ b/src/workbench/extensions/agent/schemas/agentApiSchema.ts @@ -118,34 +118,46 @@ const zSkillName = z /** * One entry of a persisted assistant row's `content.tool_calls` (see * `agentTranscript.ts`'s `parseToolCallEntry`), the reload-path counterpart - * to the live WebSocket's `zAgentToolCallData` above. Sourced directly from - * the generated `ToolCallSummary` schema (Comfy-Org/cloud#10360) — the - * backend only ever persists terminal rows (`status: 'success' | 'error'`); - * a row a dead turn left in `pending`/`running` has no wire-status mapping - * and is dropped server-side rather than reaching this parser. - * - * This is also the element type of `zAgentMessageContent.tool_calls` below, - * which is what lets a persisted `skill` reach `parseToolCallEntry` at all — - * the generated `zToolCallSummary` has no `skill` key and no `.passthrough()`, - * so using it there stripped the field before the transcript parser saw it. + * to the live WebSocket's `zAgentToolCallData` above. Sourced from the + * generated `ToolCallSummary` schema (Comfy-Org/cloud#10360), but relaxed: + * the generated schema requires `tool_call_id`, narrows `status` to the + * closed `'success' | 'error'` wire vocabulary, and requires `duration_ms` + * to be an integer, which is only true for rows persisted after that + * backend change landed. Real historical rows can still carry a bare `id` + * with no `tool_call_id`, a `status` of `'ok'` (an older success alias — + * see `toolCallOk` in `agentTranscript.ts`), or a non-integer `duration_ms`. + * `parseToolCallEntry` picks only the fields it actually reads from this, + * so an unrelated field (e.g. a strict `started_at`/`finished_at` datetime) + * never gates the entry. */ export const zPersistedToolCallSummary = zToolCallSummary.extend({ + id: z.string(), + tool_call_id: z.string().optional(), + status: z.string(), + duration_ms: z.number().optional(), skill: zSkillName }) export type PersistedToolCallSummary = z.infer /** - * The generated `AgentMessage.content` schema narrows to just `tool_calls` - * (typed via `zToolCallSummary`), but the OpenAPI-generated TS type still - * carries a `[key: string]: unknown` index signature for it — the zod - * plugin's output didn't get a matching `.passthrough()`. Re-widened here so - * a persisted row's other `content` fields (`text`, `attachments`, + * The message-parse boundary's `content.tool_calls` field is deliberately + * `z.array(z.unknown())`, not the stricter `zPersistedToolCallSummary` + * above: `agentRestClient.ts`'s `request()` calls `.parse()` (throws) on + * the whole `AgentMessages` array, so a single non-conforming historical + * tool-call row must never fail the entire conversation-history load. + * `agentTranscript.ts`'s `parseToolCallEntry` runs its own `safeParse` + * per entry and degrades just that one row instead. + * + * The generated `AgentMessage.content` schema also keeps a + * `[key: string]: unknown` index signature on its TS type but no matching + * `.passthrough()` on its zod schema — the `.passthrough()` below re-widens + * it so a persisted row's other `content` fields (`text`, `attachments`, * `attachment_refs`, `workflow_references`, ...; see `agentTranscript.ts`) * keep parsing. */ const zAgentMessageContent = z .object({ - tool_calls: z.array(zPersistedToolCallSummary).optional() + tool_calls: z.array(z.unknown()).optional() }) .passthrough() diff --git a/src/workbench/extensions/agent/services/agent/agentTranscript.test.ts b/src/workbench/extensions/agent/services/agent/agentTranscript.test.ts index 9ef4987f798..546054e35a3 100644 --- a/src/workbench/extensions/agent/services/agent/agentTranscript.test.ts +++ b/src/workbench/extensions/agent/services/agent/agentTranscript.test.ts @@ -504,20 +504,20 @@ describe('normalizeAgentTranscript', () => { ]) }) - it('drops a tool-call entry with no tool_call_id, matching the generated ToolCallSummary contract', () => { + it('falls back to id for callId when a row was recorded before tool_call_id existed', () => { const message = row(1, 'assistant', 'turn-a', 'Done', 'row-1') message.content = { text: 'Done', tool_calls: [ { id: 'audit-row-uuid-1', tool_name: 'search_nodes', status: 'success' } ] - } as unknown as AgentMessages[number]['content'] + } const transcript = normalizeAgentTranscript([message]) - expect(transcript.messages[0].parts).toEqual([ - { type: 'text', text: 'Done', state: 'done' } - ]) + expect(transcript.messages[0].parts).toContainEqual( + expect.objectContaining({ callId: 'audit-row-uuid-1' }) + ) }) it('omits tool parts entirely when a message carries no tool_calls', () => { @@ -571,7 +571,7 @@ describe('normalizeAgentTranscript', () => { ]) }) - it('drops a persisted tool call left pending/running by a dead turn, matching the backend contract that only terminal rows are ever persisted', () => { + it('clamps a restored pending/running tool call to done+ok:false with no live transport', () => { const message = row(1, 'assistant', 'turn-a', '', 'row-1') message.content = { tool_calls: [ @@ -582,14 +582,22 @@ describe('normalizeAgentTranscript', () => { status: 'running' } ] - } as unknown as AgentMessages[number]['content'] + } const transcript = normalizeAgentTranscript([message]) - expect(transcript.messages[0].parts).toEqual([]) + expect(transcript.messages[0].parts).toEqual([ + { + type: 'tool', + callId: 'call-1', + name: 'search_nodes', + state: 'done', + ok: false + } + ]) }) - it('keeps the runApproval part and pending state for a live run_approval ask even though its stale pending/running tool call is dropped', () => { + it('keeps a pending/running tool call streaming when its row is the live run_approval ask', () => { const message = row(1, 'assistant', 'turn-a', '', 'row-1') message.status = 'streaming' message.content = { @@ -601,7 +609,7 @@ describe('normalizeAgentTranscript', () => { status: 'running' } ] - } as unknown as AgentMessages[number]['content'] + } message.pending_ask = { message_id: 'row-1', ask_id: 'ask-1', @@ -615,9 +623,12 @@ describe('normalizeAgentTranscript', () => { const transcript = normalizeAgentTranscript([message]) - expect(transcript.messages[0].parts).toEqual([ - { type: 'runApproval', askId: 'ask-1' } - ]) + expect(transcript.messages[0].parts).toContainEqual({ + type: 'tool', + callId: 'call-1', + name: 'search_nodes', + state: 'streaming' + }) expect(transcript.pending?.messageId).toBe('row-1') }) @@ -744,7 +755,58 @@ describe('normalizeAgentTranscript', () => { } ) - it('omits durationMs for a negative but otherwise valid duration_ms', () => { + it.for([Infinity, -Infinity, -1])( + 'omits durationMs for a non-finite or negative duration_ms (%s) without dropping the entry', + (durationMs) => { + const message = row(1, 'assistant', 'turn-a', 'Done', 'row-1') + message.content = { + text: 'Done', + tool_calls: [ + { + id: 'audit-1', + tool_call_id: 'call-1', + tool_name: 'search_nodes', + status: 'success', + duration_ms: durationMs + } + ] + } + + const transcript = normalizeAgentTranscript([message]) + + expect(transcript.messages[0].parts).toContainEqual({ + type: 'tool', + callId: 'call-1', + name: 'search_nodes', + state: 'done', + ok: true + }) + } + ) + + it('drops the whole tool-call entry when duration_ms is NaN, matching the live schema (z.number()) rejecting it', () => { + const message = row(1, 'assistant', 'turn-a', 'Done', 'row-1') + message.content = { + text: 'Done', + tool_calls: [ + { + id: 'audit-1', + tool_call_id: 'call-1', + tool_name: 'search_nodes', + status: 'success', + duration_ms: NaN + } + ] + } + + const transcript = normalizeAgentTranscript([message]) + + expect(transcript.messages[0].parts).toEqual([ + { type: 'text', text: 'Done', state: 'done' } + ]) + }) + + it('accepts a non-integer duration_ms, matching the live path leniency', () => { const message = row(1, 'assistant', 'turn-a', 'Done', 'row-1') message.content = { text: 'Done', @@ -754,7 +816,7 @@ describe('normalizeAgentTranscript', () => { tool_call_id: 'call-1', tool_name: 'search_nodes', status: 'success', - duration_ms: -1 + duration_ms: 420.5 } ] } @@ -766,34 +828,35 @@ describe('normalizeAgentTranscript', () => { callId: 'call-1', name: 'search_nodes', state: 'done', - ok: true + ok: true, + durationMs: 420.5 }) }) - it.for([NaN, Infinity, -Infinity])( - 'drops the whole tool-call entry when duration_ms is non-finite (%s), since the generated schema requires an integer', - (durationMs) => { - const message = row(1, 'assistant', 'turn-a', 'Done', 'row-1') - message.content = { - text: 'Done', - tool_calls: [ - { - id: 'audit-1', - tool_call_id: 'call-1', - tool_name: 'search_nodes', - status: 'success', - duration_ms: durationMs - } - ] - } + it('treats the older ok status alias the same as success', () => { + const message = row(1, 'assistant', 'turn-a', 'Done', 'row-1') + message.content = { + text: 'Done', + tool_calls: [ + { + id: 'audit-1', + tool_call_id: 'call-1', + tool_name: 'search_nodes', + status: 'ok' + } + ] + } - const transcript = normalizeAgentTranscript([message]) + const transcript = normalizeAgentTranscript([message]) - expect(transcript.messages[0].parts).toEqual([ - { type: 'text', text: 'Done', state: 'done' } - ]) - } - ) + expect(transcript.messages[0].parts).toContainEqual({ + type: 'tool', + callId: 'call-1', + name: 'search_nodes', + state: 'done', + ok: true + }) + }) it('dedupes a repeated callId within one row, keeping the last entry at the first position', () => { const message = row(1, 'assistant', 'turn-a', 'Done', 'row-1') @@ -913,7 +976,7 @@ describe('normalizeAgentTranscript', () => { tool_calls: [ { id: 'audit-1', tool_call_id: 'call-1', tool_name: 'search_nodes' } ] - } as unknown as AgentMessages[number]['content'] + } const transcript = normalizeAgentTranscript([message]) @@ -922,6 +985,74 @@ describe('normalizeAgentTranscript', () => { ]) }) + it('does not fail the whole history load through zAgentMessages.parse() when one tool-call entry is malformed (regression for agent_history_load_failed)', () => { + // A raw wire payload, not the pre-typed `row()` fixture: this goes + // through the real `zAgentMessages.parse()` boundary that + // `agentRestClient.ts`'s `getMessages()` calls (and which throws, not + // safeParse). Before the fix, `content.tool_calls` was typed as + // `z.array(zToolCallSummary)`, so the single malformed entry below + // (missing `tool_name`) would have thrown during `.parse()` and failed + // the ENTIRE array -- every row, not just this one entry. + const rawHistory: unknown = [ + { + id: 'row-1', + thread_id: 'thread-1', + seq: 1, + role: 'user', + status: 'complete', + turn_id: 'turn-a', + content: { text: 'Search for upscalers' } + }, + { + id: 'row-2', + thread_id: 'thread-1', + seq: 2, + role: 'assistant', + status: 'complete', + turn_id: 'turn-a', + content: { + text: 'Done', + tool_calls: [ + // Malformed: no tool_name, so it can never become a ToolPart -- + // this one entry should degrade, not the whole load. + { id: 'audit-bad', tool_call_id: 'call-bad', status: 'success' }, + { + id: 'audit-good', + tool_call_id: 'call-good', + tool_name: 'search_nodes', + status: 'success' + } + ] + } + } + ] + + let parsed: AgentMessages | undefined + expect(() => { + parsed = zAgentMessages.parse(rawHistory) + }).not.toThrow() + expect(parsed).toHaveLength(2) + + const transcript = normalizeAgentTranscript(parsed!) + + // The whole history loaded: both turns' content is present. + expect(transcript.userTexts.get(toTurnId('turn-a'))).toBe( + 'Search for upscalers' + ) + // Only the malformed entry degraded -- the valid sibling tool call and + // the reply text still rendered. + expect(transcript.messages[0].parts).toEqual([ + { + type: 'tool', + callId: 'call-good', + name: 'search_nodes', + state: 'done', + ok: true + }, + { type: 'text', text: 'Done', state: 'done' } + ]) + }) + it('restores available and unavailable references without changing the latest workflow target', () => { const first = row(1, 'user', 'turn-a', 'Compare these', 'row-1') first.workflow_id = 'wf-target-a' diff --git a/src/workbench/extensions/agent/services/agent/agentTranscript.ts b/src/workbench/extensions/agent/services/agent/agentTranscript.ts index 13d4c76e8b1..3f5858a2baa 100644 --- a/src/workbench/extensions/agent/services/agent/agentTranscript.ts +++ b/src/workbench/extensions/agent/services/agent/agentTranscript.ts @@ -173,12 +173,15 @@ function parseUserWorkflowReferences( } /** - * `zPersistedToolCallSummary` only ever validates a terminal - * (`success`/`error`) row — the backend drops a row a dead turn left in - * `pending`/`running` before persisting it. `isLive` (the row is backed by a - * live transport) is kept only for a call that arrives through the live WebSocket path with a - * status this schema doesn't cover; a restored (non-live) row is always - * `done`. + * A persisted tool-call status is `pending`/`running` while it was still in + * flight when a dead turn ended, and terminal (`success`/`error`, or the + * older `ok` success alias — see `toolCallOk`) otherwise. + * + * A restored (non-live) row has no transport left to ever settle its tool + * parts, so a `pending`/`running` status there is clamped straight to + * `done` (never rendered as a perpetual-progress chip) rather than left + * spinning forever; only `isLive` (the row is the one actively backed by a + * live transport — the run_approval mid-ask case) keeps it `streaming`. */ function toolCallPartState( status: unknown, @@ -191,31 +194,48 @@ function toolCallPartState( /** * `undefined` while the call is still genuinely in progress (matching the * live path, which omits `ok` until a terminal status arrives); once the - * part is in a `done` state, only `success` counts as success — `error` - * reads as failure, matching `ToolCallSummary.status`. + * part is in a `done` state, `success` and the older `ok` success alias + * both count as success, matching how the live path (`toolCallOk`'s + * counterpart in `agentEventTransport.ts`) resolves a terminal frame — + * everything else, including a restored `pending`/`running` call that had + * no live transport to finish it, reads as failure rather than being + * rendered as if it succeeded. */ function toolCallOk( status: unknown, state: ToolPart['state'] ): boolean | undefined { if (state === 'streaming') return undefined - return status === 'success' + return status === 'success' || status === 'ok' } /** - * Validates one `content.tool_calls` entry against `zPersistedToolCallSummary` - * and maps it onto the same `ToolPart` the live WebSocket path builds from + * Validates one `content.tool_calls` entry against `zPersistedToolCallSummary`, + * picking only the fields this function actually reads (`id`/`tool_call_id`, + * `tool_name`, `status`, `duration_ms`) so an unrelated field a real + * historical row gets wrong or omits (e.g. `started_at`/`finished_at`, + * which are never read) can't sink an otherwise-usable entry. Maps a valid + * entry onto the same `ToolPart` the live WebSocket path builds from * `agent_tool_call` events, so a reloaded transcript renders through the * identical work-summary UI as a live turn. `undefined` for anything that - * doesn't validate (missing `id`/`tool_call_id`/`tool_name`, wrong types, ...). + * doesn't validate (missing `id`/`tool_name`, wrong types, ...). */ function parseToolCallEntry( entry: unknown, isLive: boolean ): ToolPart | undefined { - const parsed = zPersistedToolCallSummary.safeParse(entry) + const parsed = zPersistedToolCallSummary + .pick({ + id: true, + tool_call_id: true, + tool_name: true, + status: true, + duration_ms: true + }) + .safeParse(entry) if (!parsed.success) return undefined const { + id, tool_call_id: toolCallId, tool_name: toolName, status, @@ -232,10 +252,11 @@ function parseToolCallEntry( : undefined return { type: 'tool', - // A live `agent_tool_call` frame keys its update on `tool_call_id`, so a - // restored part uses the same id to match a live frame that arrives for - // it later. - callId: toolCallId, + // A live `agent_tool_call` frame keys its update on `tool_call_id`, not + // this row's own `id` — prefer it so a restored part matches a live + // frame that arrives for it later. Falls back to `id` only for rows + // recorded before `tool_call_id` existed. + callId: toolCallId ?? id, name: toolName, state, ...(ok !== undefined ? { ok } : {}), From 7a077b5e6ebc40c8aadfa5ea1a5b1d02664ed904 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 10 Oct 2026 23:58:56 +0000 Subject: [PATCH 2/5] fix(agent): address Cursor review findings on #19621 Addresses the 6 unresolved Cursor bot findings on the agent-history malformed-tool-call backport PR: 1. appendAssistantContent's turn-wide tool-call dedupe now lets a later row's terminal status (success/error/ok) overwrite an earlier row's still-non-terminal (pending/running) part for the same callId, instead of always keeping whichever row was seen first. Fixes a call paused on a run-approval ask (clamped to done/ok:false by an earlier non-live row) reloading as permanently failed even after a later row recorded it as success. 2. zPersistedToolCallSummary's tool_call_id and duration_ms now use .nullish() instead of .optional(), matching the existing zSkillName convention, so an explicit null (e.g. a Go pointer field serialized without omitempty) no longer fails the entry's safeParse. 3. zAgentMessageContent's tool_calls field is now z.unknown() instead of z.array(z.unknown()), so a null or otherwise non-array tool_calls value degrades gracefully (parseToolCalls already guards with Array.isArray) instead of throwing inside zAgentMessages.parse() and losing the whole conversation history. 4. parseToolCallEntry's callId fallback is now `toolCallId || id` instead of `toolCallId ?? id`, so an empty-string tool_call_id falls back to the row's own id instead of colliding every empty-tool_call_id entry onto the same '' key. 5. parseToolCallEntry now drops an id-only entry (no real tool_call_id) on an isLive row instead of seeding a part under the audit id, since the live agent_tool_call frame for that call will arrive keyed by the real tool_call_id and can never reach a part seeded under the audit id, leaving it stuck streaming forever. 6. Reworded toolCallOk's docblock: 'ok' is a reload-only legacy alias that the live path (agentEventTransport.ts) never produces or recognizes (zAgentToolCallData.status is a closed running/success/error enum, and the live resolver only checks status === 'success'), not something the live path treats as success too. Added/extended unit tests covering findings 1, 2, 3, 4, and 5 in agentTranscript.test.ts and agentApiSchema.test.ts. Co-Authored-By: Claude Sonnet 5 Claude-Session: https://claude.ai/code/session_01RuB3pFMNyS3AE7JYNFNesb --- .../agent/schemas/agentApiSchema.test.ts | 45 ++++- .../agent/schemas/agentApiSchema.ts | 17 +- .../services/agent/agentTranscript.test.ts | 165 ++++++++++++++++- .../agent/services/agent/agentTranscript.ts | 173 ++++++++++++++---- 4 files changed, 355 insertions(+), 45 deletions(-) diff --git a/src/workbench/extensions/agent/schemas/agentApiSchema.test.ts b/src/workbench/extensions/agent/schemas/agentApiSchema.test.ts index 9a3330de2de..cce2341fd85 100644 --- a/src/workbench/extensions/agent/schemas/agentApiSchema.test.ts +++ b/src/workbench/extensions/agent/schemas/agentApiSchema.test.ts @@ -148,7 +148,50 @@ describe('agentApiSchema contract subtleties', () => { expect(parsed.data.skill).toBe(`${'a'.repeat(255)}😀`) }) - it('keeps a whole transcript readable when one persisted skill is over-long', () => { + it('clamps an over-long skill on a persisted tool-call row', () => { + const parsed = zPersistedToolCallSummary.parse({ + id: 'audit-row-uuid-1', + tool_call_id: 'call-1', + tool_name: 'load_skill', + status: 'success', + skill: 'a'.repeat(300) + }) + + expect(parsed.skill).toBe('a'.repeat(256)) + }) + + it('accepts an explicit null tool_call_id and duration_ms on a persisted tool-call row (Cursor review finding 2 on #19621)', () => { + const parsed = zPersistedToolCallSummary.safeParse({ + id: 'audit-row-uuid-1', + tool_call_id: null, + tool_name: 'search_nodes', + status: 'success', + duration_ms: null + }) + + expect(parsed.success).toBe(true) + }) + + it.for([null, 'not-an-array', 42, {}])( + 'does not throw zAgentMessages.parse() when content.tool_calls is %s instead of an array (Cursor review finding 3 on #19621)', + (toolCalls) => { + expect(() => + zAgentMessages.parse([ + { + id: 'row-1', + thread_id: 't1', + turn_id: 'turn-a', + seq: 1, + role: 'assistant', + status: 'complete', + content: { text: 'Done', tool_calls: toolCalls } + } + ]) + ).not.toThrow() + } + ) + + it('keeps a whole transcript readable when a persisted tool-call row is malformed', () => { const parsed = zAgentMessages.parse([ { id: 'row-1', diff --git a/src/workbench/extensions/agent/schemas/agentApiSchema.ts b/src/workbench/extensions/agent/schemas/agentApiSchema.ts index eb72c279107..49e46e8f7f3 100644 --- a/src/workbench/extensions/agent/schemas/agentApiSchema.ts +++ b/src/workbench/extensions/agent/schemas/agentApiSchema.ts @@ -132,9 +132,13 @@ const zSkillName = z */ export const zPersistedToolCallSummary = zToolCallSummary.extend({ id: z.string(), - tool_call_id: z.string().optional(), + // `.nullish()`, matching `zSkillName` above: a Go pointer field serialized + // without `omitempty` sends an explicit `null` rather than omitting the + // key, and `.optional()` alone rejects that, failing this entry's + // `safeParse` and dropping the whole tool-call row. + tool_call_id: z.string().nullish(), status: z.string(), - duration_ms: z.number().optional(), + duration_ms: z.number().nullish(), skill: zSkillName }) export type PersistedToolCallSummary = z.infer @@ -157,7 +161,14 @@ export type PersistedToolCallSummary = z.infer */ const zAgentMessageContent = z .object({ - tool_calls: z.array(z.unknown()).optional() + // `z.unknown()`, not `z.array(z.unknown())`: a Go nil slice persisted + // without `omitempty` sends `tool_calls: null`, and any other historical + // row could carry a non-array value here too. `zAgentMessages.parse()` + // throws on the whole history for a schema mismatch, so this field must + // accept anything; `agentTranscript.ts`'s `parseToolCalls` already + // guards with `Array.isArray` and degrades just that one row's tool + // calls instead. + tool_calls: z.unknown().optional() }) .passthrough() diff --git a/src/workbench/extensions/agent/services/agent/agentTranscript.test.ts b/src/workbench/extensions/agent/services/agent/agentTranscript.test.ts index 546054e35a3..8cee97b200e 100644 --- a/src/workbench/extensions/agent/services/agent/agentTranscript.test.ts +++ b/src/workbench/extensions/agent/services/agent/agentTranscript.test.ts @@ -920,7 +920,7 @@ describe('normalizeAgentTranscript', () => { message.content = { text: 'Done', ...content - } as unknown as AgentMessages[number]['content'] + } const transcript = normalizeAgentTranscript([message]) @@ -969,6 +969,169 @@ describe('normalizeAgentTranscript', () => { ]) }) + it('upgrades a stale clamped-failure part when a later row in the turn settles the same call (Cursor review finding 1 on #19621)', () => { + const first = row(1, 'assistant', 'turn-a', '', 'row-1') + first.content = { + tool_calls: [ + { + id: 'audit-1', + tool_call_id: 'call-1', + tool_name: 'search_nodes', + status: 'running' + } + ] + } + const second = row(2, 'assistant', 'turn-a', 'Done', 'row-2') + second.content = { + text: 'Done', + tool_calls: [ + { + id: 'audit-2', + tool_call_id: 'call-1', + tool_name: 'search_nodes', + status: 'success', + duration_ms: 900 + } + ] + } + + const transcript = normalizeAgentTranscript([first, second]) + + expect(transcript.messages[0].parts).toEqual([ + { + type: 'tool', + callId: 'call-1', + name: 'search_nodes', + state: 'done', + ok: true, + durationMs: 900 + }, + { type: 'text', text: 'Done', state: 'done' } + ]) + }) + + it('does not let a later non-terminal row override an already-terminal part for the same call (Cursor review finding 1 on #19621, negative case)', () => { + const first = row(1, 'assistant', 'turn-a', '', 'row-1') + first.content = { + tool_calls: [ + { + id: 'audit-1', + tool_call_id: 'call-1', + tool_name: 'search_nodes', + status: 'success' + } + ] + } + const second = row(2, 'assistant', 'turn-a', 'Done', 'row-2') + second.status = 'streaming' + second.content = { + text: 'Done', + tool_calls: [ + { + id: 'audit-2', + tool_call_id: 'call-1', + tool_name: 'search_nodes', + status: 'running' + } + ] + } + + const transcript = normalizeAgentTranscript([first, second]) + + expect(transcript.messages[0].parts).toEqual([ + { + type: 'tool', + callId: 'call-1', + name: 'search_nodes', + state: 'done', + ok: true + }, + { type: 'text', text: 'Done', state: 'done' } + ]) + }) + + it('falls back to id for callId when tool_call_id is an empty string (Cursor review finding 4 on #19621)', () => { + const message = row(1, 'assistant', 'turn-a', 'Done', 'row-1') + message.content = { + text: 'Done', + tool_calls: [ + { + id: 'audit-row-uuid-1', + tool_call_id: '', + tool_name: 'search_nodes', + status: 'success' + } + ] + } + + const transcript = normalizeAgentTranscript([message]) + + expect(transcript.messages[0].parts).toContainEqual( + expect.objectContaining({ callId: 'audit-row-uuid-1' }) + ) + }) + + it('does not collide two entries that both have an empty-string tool_call_id onto the same callId (Cursor review finding 4 on #19621)', () => { + const message = row(1, 'assistant', 'turn-a', 'Done', 'row-1') + message.content = { + text: 'Done', + tool_calls: [ + { + id: 'audit-1', + tool_call_id: '', + tool_name: 'search_nodes', + status: 'success' + }, + { + id: 'audit-2', + tool_call_id: '', + tool_name: 'add_node', + status: 'success' + } + ] + } + + const transcript = normalizeAgentTranscript([message]) + + expect( + transcript.messages[0].parts.filter((part) => part.type === 'tool') + ).toHaveLength(2) + }) + + it('drops an id-only tool-call entry on a live row rather than seeding it under the audit id (Cursor review finding 5 on #19621)', () => { + const message = row(1, 'assistant', 'turn-a', '', 'row-1') + message.status = 'streaming' + message.content = { + tool_calls: [ + { + id: 'audit-row-uuid-1', + tool_name: 'search_nodes', + status: 'running' + } + ] + } + + const transcript = normalizeAgentTranscript([message]) + + expect(transcript.messages[0].parts).toEqual([]) + }) + + it('still falls back to id on a non-live (restored) row, since nothing will ever seed the real tool_call_id later', () => { + const message = row(1, 'assistant', 'turn-a', 'Done', 'row-1') + message.content = { + text: 'Done', + tool_calls: [ + { id: 'audit-row-uuid-1', tool_name: 'search_nodes', status: 'success' } + ] + } + + const transcript = normalizeAgentTranscript([message]) + + expect(transcript.messages[0].parts).toContainEqual( + expect.objectContaining({ callId: 'audit-row-uuid-1' }) + ) + }) + it('drops a persisted tool call entry with no status field, since status is required by the generated contract', () => { const message = row(1, 'assistant', 'turn-a', 'Done', 'row-1') message.content = { diff --git a/src/workbench/extensions/agent/services/agent/agentTranscript.ts b/src/workbench/extensions/agent/services/agent/agentTranscript.ts index 3f5858a2baa..8359866c246 100644 --- a/src/workbench/extensions/agent/services/agent/agentTranscript.ts +++ b/src/workbench/extensions/agent/services/agent/agentTranscript.ts @@ -195,11 +195,14 @@ function toolCallPartState( * `undefined` while the call is still genuinely in progress (matching the * live path, which omits `ok` until a terminal status arrives); once the * part is in a `done` state, `success` and the older `ok` success alias - * both count as success, matching how the live path (`toolCallOk`'s - * counterpart in `agentEventTransport.ts`) resolves a terminal frame — - * everything else, including a restored `pending`/`running` call that had - * no live transport to finish it, reads as failure rather than being - * rendered as if it succeeded. + * both count as success. `'ok'` is a reload-only legacy alias, not something + * the live path ever produces or recognizes: `zAgentToolCallData.status` in + * `agentApiSchema.ts` is `z.enum(['running', 'success', 'error'])`, and the + * live resolver (`resolveToolCallState` in `agentEventTransport.ts`) only + * checks `status === 'success'` — it only ever appears on rows persisted + * before that alias was retired. Everything else, including a restored + * `pending`/`running` call that had no live transport to finish it, reads as + * failure rather than being rendered as if it succeeded. */ function toolCallOk( status: unknown, @@ -209,6 +212,56 @@ function toolCallOk( return status === 'success' || status === 'ok' } +/** A parsed tool-call entry, carrying the raw persisted `status` alongside + * the `ToolPart` it produced so the turn-wide dedupe in + * `appendAssistantContent` can tell a clamped-but-still-non-terminal entry + * apart from a genuinely terminal one — information the `ToolPart` itself no + * longer carries once `pending`/`running` has been clamped to `done`. */ +interface ParsedToolCall { + part: ToolPart + status: unknown +} + +/** `true` when a live row's entry has no real `tool_call_id` to key on + * (missing, null, or empty). A live row will still receive a live + * `agent_tool_call` frame for this call, keyed by its real `tool_call_id`; + * seeding a part here under the audit row's own `id` instead would leave a + * duplicate chip behind that the later live frame can never reach, stuck + * `streaming` forever — the caller drops the entry rather than seed it. */ +function isLiveEntryMissingToolCallId( + isLive: boolean, + toolCallId: string | null | undefined +): boolean { + return isLive && !toolCallId +} + +/** `rawDuration` restricted to a finite, non-negative number; `undefined` + * for anything else (negative, `NaN`, `Infinity`, `null`). */ +function parseDurationMs( + rawDuration: number | null | undefined +): number | undefined { + return typeof rawDuration === 'number' && + Number.isFinite(rawDuration) && + rawDuration >= 0 + ? rawDuration + : undefined +} + +/** The optional `ToolPart` fields that only appear when they have a value: + * `ok` once the call is done, `skill` when non-empty, `durationMs` once + * resolved to a finite, non-negative number. */ +function toolPartOptionalFields( + ok: boolean | undefined, + skill: string | null | undefined, + durationMs: number | undefined +): Pick, 'ok' | 'skill' | 'durationMs'> { + return { + ...(ok !== undefined ? { ok } : {}), + ...(skill ? { skill } : {}), + ...(durationMs !== undefined ? { durationMs } : {}) + } +} + /** * Validates one `content.tool_calls` entry against `zPersistedToolCallSummary`, * picking only the fields this function actually reads (`id`/`tool_call_id`, @@ -218,12 +271,13 @@ function toolCallOk( * entry onto the same `ToolPart` the live WebSocket path builds from * `agent_tool_call` events, so a reloaded transcript renders through the * identical work-summary UI as a live turn. `undefined` for anything that - * doesn't validate (missing `id`/`tool_name`, wrong types, ...). + * doesn't validate (missing `id`/`tool_name`, wrong types, ...) or for a live + * row's id-only entry (see `isLiveEntryMissingToolCallId`). */ function parseToolCallEntry( entry: unknown, isLive: boolean -): ToolPart | undefined { +): ParsedToolCall | undefined { const parsed = zPersistedToolCallSummary .pick({ id: true, @@ -242,26 +296,25 @@ function parseToolCallEntry( skill, duration_ms: rawDuration } = parsed.data + if (isLiveEntryMissingToolCallId(isLive, toolCallId)) return undefined const state = toolCallPartState(status, isLive) const ok = toolCallOk(status, state) - const durationMs = - typeof rawDuration === 'number' && - Number.isFinite(rawDuration) && - rawDuration >= 0 - ? rawDuration - : undefined + const durationMs = parseDurationMs(rawDuration) return { - type: 'tool', - // A live `agent_tool_call` frame keys its update on `tool_call_id`, not - // this row's own `id` — prefer it so a restored part matches a live - // frame that arrives for it later. Falls back to `id` only for rows - // recorded before `tool_call_id` existed. - callId: toolCallId ?? id, - name: toolName, - state, - ...(ok !== undefined ? { ok } : {}), - ...(skill ? { skill } : {}), - ...(durationMs !== undefined ? { durationMs } : {}) + status, + part: { + type: 'tool', + // A live `agent_tool_call` frame keys its update on `tool_call_id`, not + // this row's own `id` — prefer it so a restored part matches a live + // frame that arrives for it later. Falls back to `id` only for rows + // recorded before `tool_call_id` existed; `||`, not `??`, so an empty + // string (as genuinely id-less as a missing field) falls back too + // instead of colliding every empty-`tool_call_id` entry on `''`. + callId: toolCallId || id, + name: toolName, + state, + ...toolPartOptionalFields(ok, skill, durationMs) + } } } @@ -274,17 +327,35 @@ function parseToolCallEntry( function parseToolCalls( content: Record | undefined, isLive: boolean -): ToolPart[] | undefined { +): ParsedToolCall[] | undefined { const raw = content?.tool_calls if (!Array.isArray(raw)) return undefined - const parts = new Map() + const parsedByCallId = new Map() for (const entry of raw as unknown[]) { - const part = parseToolCallEntry(entry, isLive) - if (part) parts.set(part.callId, part) + const parsed = parseToolCallEntry(entry, isLive) + if (parsed) parsedByCallId.set(parsed.part.callId, parsed) } - return parts.size > 0 ? [...parts.values()] : undefined + return parsedByCallId.size > 0 ? [...parsedByCallId.values()] : undefined } +/** A persisted tool-call `status` of `pending`/`running` is still in flight; + * anything else (`success`/`error`/`ok`, or an unrecognized string) is + * terminal — settled for good, independent of `isLive` clamping. */ +function isTerminalStatus(status: unknown): boolean { + return status !== 'pending' && status !== 'running' +} + +/** Per-message memory of each tool call's last-applied raw `status`, keyed by + * `callId`. `appendAssistantContent` consults and updates this across a + * turn's rows (a turn can span several assistant rows) so a later row's + * terminal status can overwrite an earlier row's still-non-terminal part for + * the same call, instead of the position-preserving dedupe below always + * keeping whichever row it saw first. */ +const toolCallStatusByMessage = new WeakMap< + AssistantMessage, + Map +>() + /** * Appends a persisted assistant row's tool-call and text parts onto its * running message. `isLive` is true when the row is the one that will be @@ -296,9 +367,14 @@ function parseToolCalls( * `assistants.get(turnId)` in `recordAssistantRow`), but `parseToolCalls` * only dedupes within one row's own list — two rows of the same turn that * each carry the same `callId` would otherwise still produce two separate - * `ToolPart`s. Dedupe is hoisted here to the message level — a parsed part - * whose `callId` already appears in `message.parts` is dropped — matching - * the live path's turn-wide keying. + * `ToolPart`s. Dedupe is hoisted here to the message level: a parsed part + * whose `callId` already appears in `message.parts` normally keeps the + * earlier part's position and data (matching the live path's turn-wide + * keying), *unless* the earlier part's status was still non-terminal + * (`pending`/`running`) and this row's is terminal — e.g. a row recorded + * while a call was paused on a run-approval ask, followed by a later row + * that settled it — in which case the later, terminal entry replaces the + * earlier one in place rather than losing to it. */ function appendAssistantContent( message: AssistantMessage, @@ -308,15 +384,32 @@ function appendAssistantContent( ): void { const toolCalls = parseToolCalls(row.content, isLive) if (toolCalls) { - const existingCallIds = new Set( - message.parts.flatMap((part) => - part.type === 'tool' ? [part.callId] : [] + let statusByCallId = toolCallStatusByMessage.get(message) + if (!statusByCallId) { + statusByCallId = new Map() + toolCallStatusByMessage.set(message, statusByCallId) + } + let parts = message.parts + const appended: ToolPart[] = [] + for (const { part, status } of toolCalls) { + const existingIndex = parts.findIndex( + (existing) => + existing.type === 'tool' && existing.callId === part.callId ) - ) - const newToolCalls = toolCalls.filter( - (part) => !existingCallIds.has(part.callId) - ) - message.parts = [...message.parts, ...newToolCalls] + if (existingIndex === -1) { + appended.push(part) + statusByCallId.set(part.callId, status) + continue + } + const existingStatus = statusByCallId.get(part.callId) + if (!isTerminalStatus(existingStatus) && isTerminalStatus(status)) { + parts = parts.map((existing, index) => + index === existingIndex ? part : existing + ) + statusByCallId.set(part.callId, status) + } + } + message.parts = appended.length > 0 ? [...parts, ...appended] : parts } if (text) message.parts = [...message.parts, { type: 'text', text, state: 'done' }] From f5e99d9d07bf6a211f30ac15f94fb2401b0a9ae0 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 11 Oct 2026 00:36:25 +0000 Subject: [PATCH 3/5] fix: restore .nullish() on persisted tool-call status dante01yoon's second review round on #19621 found that status was the one field in zPersistedToolCallSummary not restored to the pre-#19585 baseline's tolerance: it stayed required/non-nullable while tool_call_id and duration_ms were already .nullish(). A historical row missing status, or carrying status: null (a Go pointer field serialized without omitempty), still failed safeParse and dropped the tool-call chip from the restored transcript -- the exact bug class this PR fixes, just not fully closed. Also documents the non-blocking nit: isTerminalStatus(undefined) is true by design, so a tool part reached through an untracked path is treated as already-settled and never overwritten by appendAssistantContent's dedupe. Co-Authored-By: Claude Sonnet 5 Claude-Session: https://claude.ai/code/session_01RuB3pFMNyS3AE7JYNFNesb --- .../agent/schemas/agentApiSchema.test.ts | 17 +++++++++ .../agent/schemas/agentApiSchema.ts | 2 +- .../services/agent/agentTranscript.test.ts | 38 +++++++++++++------ .../agent/services/agent/agentTranscript.ts | 6 ++- 4 files changed, 49 insertions(+), 14 deletions(-) diff --git a/src/workbench/extensions/agent/schemas/agentApiSchema.test.ts b/src/workbench/extensions/agent/schemas/agentApiSchema.test.ts index cce2341fd85..65ea8672d2f 100644 --- a/src/workbench/extensions/agent/schemas/agentApiSchema.test.ts +++ b/src/workbench/extensions/agent/schemas/agentApiSchema.test.ts @@ -172,6 +172,23 @@ describe('agentApiSchema contract subtleties', () => { expect(parsed.success).toBe(true) }) + it('accepts a persisted tool-call row with no status key or an explicit null status (dante01yoon review round 2 on #19621)', () => { + const noStatusKey = zPersistedToolCallSummary.safeParse({ + id: 'audit-row-uuid-1', + tool_call_id: 'call-1', + tool_name: 'search_nodes' + }) + const nullStatus = zPersistedToolCallSummary.safeParse({ + id: 'audit-row-uuid-1', + tool_call_id: 'call-1', + tool_name: 'search_nodes', + status: null + }) + + expect(noStatusKey.success).toBe(true) + expect(nullStatus.success).toBe(true) + }) + it.for([null, 'not-an-array', 42, {}])( 'does not throw zAgentMessages.parse() when content.tool_calls is %s instead of an array (Cursor review finding 3 on #19621)', (toolCalls) => { diff --git a/src/workbench/extensions/agent/schemas/agentApiSchema.ts b/src/workbench/extensions/agent/schemas/agentApiSchema.ts index 49e46e8f7f3..b6958eadd64 100644 --- a/src/workbench/extensions/agent/schemas/agentApiSchema.ts +++ b/src/workbench/extensions/agent/schemas/agentApiSchema.ts @@ -137,7 +137,7 @@ export const zPersistedToolCallSummary = zToolCallSummary.extend({ // key, and `.optional()` alone rejects that, failing this entry's // `safeParse` and dropping the whole tool-call row. tool_call_id: z.string().nullish(), - status: z.string(), + status: z.string().nullish(), duration_ms: z.number().nullish(), skill: zSkillName }) diff --git a/src/workbench/extensions/agent/services/agent/agentTranscript.test.ts b/src/workbench/extensions/agent/services/agent/agentTranscript.test.ts index 8cee97b200e..a7fa1f9e636 100644 --- a/src/workbench/extensions/agent/services/agent/agentTranscript.test.ts +++ b/src/workbench/extensions/agent/services/agent/agentTranscript.test.ts @@ -1132,21 +1132,35 @@ describe('normalizeAgentTranscript', () => { ) }) - it('drops a persisted tool call entry with no status field, since status is required by the generated contract', () => { - const message = row(1, 'assistant', 'turn-a', 'Done', 'row-1') - message.content = { - text: 'Done', - tool_calls: [ - { id: 'audit-1', tool_call_id: 'call-1', tool_name: 'search_nodes' } - ] + it.for([ + { id: 'audit-1', tool_call_id: 'call-1', tool_name: 'search_nodes' }, + { + id: 'audit-1', + tool_call_id: 'call-1', + tool_name: 'search_nodes', + status: null } + ])( + 'still produces a ToolPart for a persisted tool call entry missing status or carrying status: null (dante01yoon review round 2 on #19621): $status', + (toolCall) => { + const message = row(1, 'assistant', 'turn-a', 'Done', 'row-1') + message.content = { + text: 'Done', + tool_calls: [toolCall] + } - const transcript = normalizeAgentTranscript([message]) + const transcript = normalizeAgentTranscript([message]) - expect(transcript.messages[0].parts).toEqual([ - { type: 'text', text: 'Done', state: 'done' } - ]) - }) + expect(transcript.messages[0].parts).toContainEqual( + expect.objectContaining({ + type: 'tool', + callId: 'call-1', + name: 'search_nodes', + state: 'done' + }) + ) + } + ) it('does not fail the whole history load through zAgentMessages.parse() when one tool-call entry is malformed (regression for agent_history_load_failed)', () => { // A raw wire payload, not the pre-typed `row()` fixture: this goes diff --git a/src/workbench/extensions/agent/services/agent/agentTranscript.ts b/src/workbench/extensions/agent/services/agent/agentTranscript.ts index 8359866c246..c3ff49fd3eb 100644 --- a/src/workbench/extensions/agent/services/agent/agentTranscript.ts +++ b/src/workbench/extensions/agent/services/agent/agentTranscript.ts @@ -340,7 +340,11 @@ function parseToolCalls( /** A persisted tool-call `status` of `pending`/`running` is still in flight; * anything else (`success`/`error`/`ok`, or an unrecognized string) is - * terminal — settled for good, independent of `isLive` clamping. */ + * terminal — settled for good, independent of `isLive` clamping. This + * includes `undefined`: a tool part that reached `message.parts` through a + * path this module doesn't track in `toolCallStatusByMessage` has no known + * status, and the conservative default is to treat it as already settled so + * `appendAssistantContent`'s dedupe never overwrites it. */ function isTerminalStatus(status: unknown): boolean { return status !== 'pending' && status !== 'running' } From 0bc813e41eddf44538d65bcd94c753e84a453ef1 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 12 Oct 2026 00:03:24 +0000 Subject: [PATCH 4/5] fix: loosen duration_ms schema gate for Zod 4's stricter z.number() main landed a Zod 4 upgrade while this PR was pending review. Zod 4's z.number() now rejects Infinity/-Infinity at the schema level (Zod 3 only rejected NaN), so zPersistedToolCallSummary's duration_ms field failed safeParse on a non-finite duration and dropped the whole tool-call entry instead of just omitting duration_ms -- the exact leniency this PR's parseDurationMs (agentTranscript.ts) was already relying on. Switch duration_ms to a custom numeric check that accepts any number (including Infinity/-Infinity) but still rejects NaN, matching Zod 3's original behavior for NaN. parseDurationMs's existing Number.isFinite()/non-negative check is unchanged and continues to be what actually omits a bad duration_ms while keeping the rest of the entry. Co-Authored-By: Claude Sonnet 5 Claude-Session: https://claude.ai/code/session_01RuB3pFMNyS3AE7JYNFNesb --- .../agent/schemas/agentApiSchema.ts | 19 ++++++++++++++----- 1 file changed, 14 insertions(+), 5 deletions(-) diff --git a/src/workbench/extensions/agent/schemas/agentApiSchema.ts b/src/workbench/extensions/agent/schemas/agentApiSchema.ts index b6958eadd64..b9589edf9cf 100644 --- a/src/workbench/extensions/agent/schemas/agentApiSchema.ts +++ b/src/workbench/extensions/agent/schemas/agentApiSchema.ts @@ -125,10 +125,10 @@ const zSkillName = z * to be an integer, which is only true for rows persisted after that * backend change landed. Real historical rows can still carry a bare `id` * with no `tool_call_id`, a `status` of `'ok'` (an older success alias — - * see `toolCallOk` in `agentTranscript.ts`), or a non-integer `duration_ms`. - * `parseToolCallEntry` picks only the fields it actually reads from this, - * so an unrelated field (e.g. a strict `started_at`/`finished_at` datetime) - * never gates the entry. + * see `toolCallOk` in `agentTranscript.ts`), or a non-finite/negative + * `duration_ms`. `parseToolCallEntry` picks only the fields it actually + * reads from this, so an unrelated field (e.g. a strict + * `started_at`/`finished_at` datetime) never gates the entry. */ export const zPersistedToolCallSummary = zToolCallSummary.extend({ id: z.string(), @@ -138,7 +138,16 @@ export const zPersistedToolCallSummary = zToolCallSummary.extend({ // `safeParse` and dropping the whole tool-call row. tool_call_id: z.string().nullish(), status: z.string().nullish(), - duration_ms: z.number().nullish(), + // `z.custom`, not `z.number()`: Zod 4's `z.number()` also rejects + // `Infinity`/`-Infinity` (Zod 3 only rejected `NaN`), which would fail + // this entry's `safeParse` and drop the whole tool-call row over a bad + // `duration_ms` alone. `NaN` stays rejected here, matching the + // pre-existing Zod 3 behavior; `parseDurationMs` in `agentTranscript.ts` + // already does the real finite/non-negative check and omits the field + // for `Infinity`/`-Infinity` instead of failing the whole entry. + duration_ms: z + .custom((val) => typeof val === 'number' && !Number.isNaN(val)) + .nullish(), skill: zSkillName }) export type PersistedToolCallSummary = z.infer From 335ae2684269a8734f23198d78ce389a0e8bc753 Mon Sep 17 00:00:00 2001 From: Christian Byrne Date: Sun, 11 Oct 2026 17:20:15 -0700 Subject: [PATCH 5/5] fix(agent): preserve reviewed history behavior through rebase --- .../fixtures/agentPromptHistoryFixture.ts | 22 ++++++++++++++++--- .../agent/schemas/agentApiSchema.test.ts | 21 ++++++------------ .../services/agent/agentTranscript.test.ts | 10 ++++----- .../agent/services/agent/agentTranscript.ts | 5 +++-- 4 files changed, 34 insertions(+), 24 deletions(-) diff --git a/browser_tests/fixtures/agentPromptHistoryFixture.ts b/browser_tests/fixtures/agentPromptHistoryFixture.ts index 7c05ad4dbde..e2807f89f00 100644 --- a/browser_tests/fixtures/agentPromptHistoryFixture.ts +++ b/browser_tests/fixtures/agentPromptHistoryFixture.ts @@ -8,7 +8,10 @@ import type { } from '@comfyorg/ingest-types' import { zAgentPostMessageRequest } from '@comfyorg/ingest-types/zod' -import type { AgentWsEvent } from '@/workbench/extensions/agent/schemas/agentApiSchema' +import type { + AgentWsEvent, + PersistedToolCallSummary +} from '@/workbench/extensions/agent/schemas/agentApiSchema' import { agentTest } from '@e2e/fixtures/agentPanelFixture' import { workflowSelectionTest } from '@e2e/fixtures/agentWorkflowSelectionFixture' @@ -18,13 +21,26 @@ import { webSocketFixture } from '@e2e/fixtures/ws' const base = mergeTests(agentTest, workflowSelectionTest, webSocketFixture) +// A mocked history row models what the server actually persists, which is +// the relaxed `PersistedToolCallSummary` shape (see agentApiSchema.ts), not +// the stricter wire `ToolCallSummary` generated type. +type MockAgentMessageContent = Omit< + NonNullable, + 'tool_calls' +> & { + tool_calls?: PersistedToolCallSummary[] +} +type MockAgentMessage = Omit & { + content?: MockAgentMessageContent +} + export const promptHistoryTest = base.extend<{ agentPanel: AgentPanel promptHistory: { requests: AgentPostMessageRequest[] historyReads: () => number historyRequestThreadIds: string[] - completeLatestTurn: (content: AgentMessage['content']) => void + completeLatestTurn: (content: MockAgentMessageContent) => void } }>({ agentPanel: async ({ page }, use) => { @@ -34,7 +50,7 @@ export const promptHistoryTest = base.extend<{ // Workflow selection boots the app before these agent-specific routes. void workflowSelection const requests: AgentPostMessageRequest[] = [] - const messages: AgentMessage[] = [] + const messages: MockAgentMessage[] = [] const historyRequestThreadIds: string[] = [] let threadId = '' let historyReads = 0 diff --git a/src/workbench/extensions/agent/schemas/agentApiSchema.test.ts b/src/workbench/extensions/agent/schemas/agentApiSchema.test.ts index 65ea8672d2f..4a827ebfd81 100644 --- a/src/workbench/extensions/agent/schemas/agentApiSchema.test.ts +++ b/src/workbench/extensions/agent/schemas/agentApiSchema.test.ts @@ -9,7 +9,8 @@ import { zAgentMessage, zAgentMessages, zAgentTurnAccepted, - zAgentWsEvent + zAgentWsEvent, + zPersistedToolCallSummary } from './agentApiSchema' import type { ZodTypeAny } from 'zod' @@ -160,7 +161,7 @@ describe('agentApiSchema contract subtleties', () => { expect(parsed.skill).toBe('a'.repeat(256)) }) - it('accepts an explicit null tool_call_id and duration_ms on a persisted tool-call row (Cursor review finding 2 on #19621)', () => { + it('accepts an explicit null tool_call_id and duration_ms on a persisted tool-call row', () => { const parsed = zPersistedToolCallSummary.safeParse({ id: 'audit-row-uuid-1', tool_call_id: null, @@ -172,7 +173,7 @@ describe('agentApiSchema contract subtleties', () => { expect(parsed.success).toBe(true) }) - it('accepts a persisted tool-call row with no status key or an explicit null status (dante01yoon review round 2 on #19621)', () => { + it('accepts a persisted tool-call row with no status key or an explicit null status', () => { const noStatusKey = zPersistedToolCallSummary.safeParse({ id: 'audit-row-uuid-1', tool_call_id: 'call-1', @@ -190,7 +191,7 @@ describe('agentApiSchema contract subtleties', () => { }) it.for([null, 'not-an-array', 42, {}])( - 'does not throw zAgentMessages.parse() when content.tool_calls is %s instead of an array (Cursor review finding 3 on #19621)', + 'does not throw zAgentMessages.parse() when content.tool_calls is %s instead of an array', (toolCalls) => { expect(() => zAgentMessages.parse([ @@ -219,20 +220,12 @@ describe('agentApiSchema contract subtleties', () => { status: 'complete', content: { text: 'Done', - tool_calls: [ - { - id: 'audit-row-uuid-1', - tool_call_id: 'call-1', - tool_name: 'load_skill', - status: 'success', - skill: 'a'.repeat(300) - } - ] + tool_calls: [{ unexpected: 'shape' }] } } ]) - expect(parsed[0].content?.tool_calls?.[0].skill).toBe('a'.repeat(256)) + expect(parsed[0].content?.tool_calls).toEqual([{ unexpected: 'shape' }]) }) it('accepts agent_message_done with usage null (cancelled turn)', () => { diff --git a/src/workbench/extensions/agent/services/agent/agentTranscript.test.ts b/src/workbench/extensions/agent/services/agent/agentTranscript.test.ts index a7fa1f9e636..7064eac3b93 100644 --- a/src/workbench/extensions/agent/services/agent/agentTranscript.test.ts +++ b/src/workbench/extensions/agent/services/agent/agentTranscript.test.ts @@ -969,7 +969,7 @@ describe('normalizeAgentTranscript', () => { ]) }) - it('upgrades a stale clamped-failure part when a later row in the turn settles the same call (Cursor review finding 1 on #19621)', () => { + it('upgrades a stale clamped-failure part when a later row in the turn settles the same call', () => { const first = row(1, 'assistant', 'turn-a', '', 'row-1') first.content = { tool_calls: [ @@ -1050,7 +1050,7 @@ describe('normalizeAgentTranscript', () => { ]) }) - it('falls back to id for callId when tool_call_id is an empty string (Cursor review finding 4 on #19621)', () => { + it('falls back to id for callId when tool_call_id is an empty string', () => { const message = row(1, 'assistant', 'turn-a', 'Done', 'row-1') message.content = { text: 'Done', @@ -1071,7 +1071,7 @@ describe('normalizeAgentTranscript', () => { ) }) - it('does not collide two entries that both have an empty-string tool_call_id onto the same callId (Cursor review finding 4 on #19621)', () => { + it('does not collide two entries that both have an empty-string tool_call_id onto the same callId', () => { const message = row(1, 'assistant', 'turn-a', 'Done', 'row-1') message.content = { text: 'Done', @@ -1098,7 +1098,7 @@ describe('normalizeAgentTranscript', () => { ).toHaveLength(2) }) - it('drops an id-only tool-call entry on a live row rather than seeding it under the audit id (Cursor review finding 5 on #19621)', () => { + it('drops an id-only tool-call entry on a live row rather than seeding it under the audit id', () => { const message = row(1, 'assistant', 'turn-a', '', 'row-1') message.status = 'streaming' message.content = { @@ -1141,7 +1141,7 @@ describe('normalizeAgentTranscript', () => { status: null } ])( - 'still produces a ToolPart for a persisted tool call entry missing status or carrying status: null (dante01yoon review round 2 on #19621): $status', + 'still produces a ToolPart for a persisted tool call entry missing status or carrying status: null: $status', (toolCall) => { const message = row(1, 'assistant', 'turn-a', 'Done', 'row-1') message.content = { diff --git a/src/workbench/extensions/agent/services/agent/agentTranscript.ts b/src/workbench/extensions/agent/services/agent/agentTranscript.ts index c3ff49fd3eb..86b4ff98f9a 100644 --- a/src/workbench/extensions/agent/services/agent/agentTranscript.ts +++ b/src/workbench/extensions/agent/services/agent/agentTranscript.ts @@ -265,7 +265,7 @@ function toolPartOptionalFields( /** * Validates one `content.tool_calls` entry against `zPersistedToolCallSummary`, * picking only the fields this function actually reads (`id`/`tool_call_id`, - * `tool_name`, `status`, `duration_ms`) so an unrelated field a real + * `tool_name`, `status`, `duration_ms`, `skill`) so an unrelated field a real * historical row gets wrong or omits (e.g. `started_at`/`finished_at`, * which are never read) can't sink an otherwise-usable entry. Maps a valid * entry onto the same `ToolPart` the live WebSocket path builds from @@ -284,7 +284,8 @@ function parseToolCallEntry( tool_call_id: true, tool_name: true, status: true, - duration_ms: true + duration_ms: true, + skill: true }) .safeParse(entry) if (!parsed.success) return undefined