diff --git a/apps/billing-web/src/checkout/payVerdict.test.ts b/apps/billing-web/src/checkout/payVerdict.test.ts index e3b3eba3185..b33e1f9e59c 100644 --- a/apps/billing-web/src/checkout/payVerdict.test.ts +++ b/apps/billing-web/src/checkout/payVerdict.test.ts @@ -124,7 +124,7 @@ describe('payVerdictOf', () => { }, { name: 'a stale subscription quote', - result: refusedWith('REQUEST_FAILED', 'SUBSCRIPTION_QUOTE_STALE'), + result: { status: 'error', code: 'QUOTE_STALE' }, expected: { kind: 'requote', because: 'quote_expired' } }, { diff --git a/apps/billing-web/src/checkout/payVerdict.ts b/apps/billing-web/src/checkout/payVerdict.ts index 85565b866b4..909b7f470f8 100644 --- a/apps/billing-web/src/checkout/payVerdict.ts +++ b/apps/billing-web/src/checkout/payVerdict.ts @@ -12,10 +12,7 @@ import { import type { InlineOutcome, OperationOutcome } from '@/checkout/checkoutPage' /** The server refused the quote the customer consented to; re-price before asking again. */ -const STALE_QUOTE_SERVER_CODES = [ - 'PRORATION_QUOTE_EXPIRED', - 'SUBSCRIPTION_QUOTE_STALE' -] as const +const STALE_QUOTE_SERVER_CODES = ['PRORATION_QUOTE_EXPIRED'] as const /** * What a Pay's result asks of the page. `settled` needs nothing from @@ -39,6 +36,8 @@ export function payVerdictOf(result: SubscriptionCommandResult): PayVerdict { ) return { kind: 'requote', because: 'quote_expired' } switch (result.code) { + case 'QUOTE_STALE': + return { kind: 'requote', because: 'quote_expired' } case 'REACTIVATION_CONFIRMATION_REQUIRED': return { kind: 'requote', because: 'reactivation_required' } case 'OPERATION_ALREADY_PENDING': diff --git a/apps/billing-web/src/views/FullPageCheckoutView.test.ts b/apps/billing-web/src/views/FullPageCheckoutView.test.ts index 2c8615542d4..da75d1ee4b5 100644 --- a/apps/billing-web/src/views/FullPageCheckoutView.test.ts +++ b/apps/billing-web/src/views/FullPageCheckoutView.test.ts @@ -2169,14 +2169,7 @@ describe('FullPageCheckoutView promo codes', () => { it('a code that lapsed before Pay: back to capture, chip gone, the expired card instead of a decline', async () => { const fake = await renderCheckout( { - subscribe: { - status: 'error', - code: 'REQUEST_FAILED', - serverCode: readBillingErrorCode({ - code: 'SUBSCRIPTION_QUOTE_STALE', - message: 'stale' - }) - } + subscribe: { status: 'error', code: 'QUOTE_STALE' } }, quotesByCode ) diff --git a/apps/website/src/config/router-providers.ts b/apps/website/src/config/router-providers.ts index fa77973d28f..0e6a84f08ed 100644 --- a/apps/website/src/config/router-providers.ts +++ b/apps/website/src/config/router-providers.ts @@ -36,10 +36,10 @@ export interface RouterProviderCoverageRow { const DOCS_MODELS_URL = 'https://docs.comfy.org/development/comfy-router/models' /** The day the rows and the catalog size were last checked against the docs. */ -export const ROUTER_PROVIDER_COVERAGE_VERIFIED_AT = '2026-09-25' +export const ROUTER_PROVIDER_COVERAGE_VERIFIED_AT = '2026-09-30' /** How many models the Router catalog lists, all served by Comfy. */ -export const ROUTER_CATALOG_MODEL_COUNT = 212 +export const ROUTER_CATALOG_MODEL_COUNT = 213 /** In the order the page shows them: alphabetical by `name`. */ export const ROUTER_PROVIDER_COVERAGE: readonly RouterProviderCoverageRow[] = [ diff --git a/browser_tests/tests/agent/agentToolCallHistoryPersistence.spec.ts b/browser_tests/tests/agent/agentToolCallHistoryPersistence.spec.ts index ade70062713..934240e9c5a 100644 --- a/browser_tests/tests/agent/agentToolCallHistoryPersistence.spec.ts +++ b/browser_tests/tests/agent/agentToolCallHistoryPersistence.spec.ts @@ -92,13 +92,14 @@ test( tool_calls: [ { id: 'call-1', + tool_call_id: 'call-1', tool_name: 'search_nodes', - status: 'ok', + status: 'success', duration_ms: 420 }, { - // Deliberately 'success' (not 'ok', like call-1) to cover both terminal vocabularies. id: 'call-2', + tool_call_id: 'call-2', tool_name: 'add_node', status: 'success', duration_ms: 180 diff --git a/packages/ingest-types/src/index.ts b/packages/ingest-types/src/index.ts index 0c7f39a9fc7..439d8673aa1 100644 --- a/packages/ingest-types/src/index.ts +++ b/packages/ingest-types/src/index.ts @@ -1074,6 +1074,7 @@ export type { TeamCreditStopPrice, TeamCreditStops, TeamCreditStopSummary, + ToolCallSummary, UpdateAssetData, UpdateAssetError, UpdateAssetErrors, diff --git a/packages/ingest-types/src/types.gen.ts b/packages/ingest-types/src/types.gen.ts index 3f953b7126c..0ef7039b507 100644 --- a/packages/ingest-types/src/types.gen.ts +++ b/packages/ingest-types/src/types.gen.ts @@ -504,6 +504,35 @@ export type UpdateHubProfileRequest = { website_urls?: Array } +/** + * One persisted tool call attached to an assistant message's content.tool_calls (services/agent/internal/persist.ToolCallSummary), so a chat reload can render the tool-call history a turn produced. Display data only — raw arguments/results are never projected here. Only terminal rows (status ok/error) are ever surfaced; a row a dead turn left in pending/running has no wire-status mapping and is dropped rather than shown as a perpetual-progress chip. + */ +export type ToolCallSummary = { + /** + * Omitted when zero. + */ + duration_ms?: number + /** + * Present only when status is error. + */ + error_code?: string + finished_at?: string + /** + * This tool-call row's own primary key. + */ + id: string + started_at?: string + /** + * The WIRE status vocabulary (api/agent_events.schema.json's agent_tool_call), translated from the audit-row vocabulary (pending/running/ok/error) via ToolCallWireStatus — the same function the live agent_tool_call broadcast uses, so reloaded history and a live frame for the same call never disagree on the vocabulary. "running" never appears here: only terminal rows are queried, so a call still in flight when its turn died is omitted rather than shown as a perpetually in-progress chip. + */ + status: 'success' | 'error' + /** + * The provider tool-use id, the same id a live agent_tool_call WebSocket frame carries as tool_call_id — the frontend keys its tool chip on this value so a reload and a resumed live frame for the same call render as one chip, not two. Rows recorded before this id existed have none; id (this row's own primary key) is emitted instead, so the field is never empty, though it then cannot match any live frame. + */ + tool_call_id: string + tool_name: string +} + /** * Credit-stop ladder for the pricing slider (BE-1254). Returned by GET /api/billing/plans for every workspace regardless of the caller's token or workspace type (the personal/team distinction was removed); omitted only when the catalog defines no stops. */ @@ -1204,7 +1233,7 @@ export type ResubscribeRequest = { } /** - * The newest open renewal invoice of the workspace's Stripe subscription (active, or canceled but not yet ended). Returned only to workspace owners on the stripe billing rail while billing_status is payment_failed, and not while a payment for it is processing. hosted_invoice_url is a bearer payment link. + * The newest open renewal invoice of the workspace's Stripe subscription (active, or canceled but not yet ended). Returned only to workspace owners on the stripe billing rail while billing_status is payment_failed or paused, and not while a payment for it is processing. hosted_invoice_url is a bearer payment link. */ export type RenewalInvoice = { /** @@ -4740,9 +4769,10 @@ export type AgentPendingAsk = { */ export type AgentMessage = { /** - * Message payload. User turns carry {text, attachments?, attachment_refs?, workflow_references?}. Attachments are the input-image filenames from the request. attachment_refs is the server's own resolution of those same filenames to library assets, as {name, id?, kind?} objects, and exists so a later turn in the thread can reach an earlier turn's file — clients should keep reading attachments. workflow_references is an optional array of explicit non-target references, each with workflow_id and name (an empty string when no name was supplied). An optional unavailable: true records that the reference could not be authorized at turn start, without distinguishing unknown IDs, inaccessible workflows, or lookup failures. These entries preserve the user's reference intent without exposing workflow content; the frontend restores reference chips from this metadata. The field is omitted when there are no references. Assistant turns carry {text} — the final answer text (or error copy on a failed turn). Omitted when empty (e.g. an assistant message still streaming). Per-turn token accounting is NOT included here; it is surfaced on the agent_message_done WebSocket broadcast. + * Message payload. User turns carry {text, attachments?, attachment_refs?, workflow_references?}. Attachments are the input-image filenames from the request. attachment_refs is the server's own resolution of those same filenames to library assets, as {name, id?, kind?} objects, and exists so a later turn in the thread can reach an earlier turn's file — clients should keep reading attachments. workflow_references is an optional array of explicit non-target references, each with workflow_id and name (an empty string when no name was supplied). An optional unavailable: true records that the reference could not be authorized at turn start, without distinguishing unknown IDs, inaccessible workflows, or lookup failures. These entries preserve the user's reference intent without exposing workflow content; the frontend restores reference chips from this metadata. The field is omitted when there are no references. Assistant turns carry {text} — the final answer text (or error copy on a failed turn). Omitted when empty (e.g. an assistant message still streaming). Per-turn token accounting is NOT included here; it is surfaced on the agent_message_done WebSocket broadcast. tool_calls is an optional array of ToolCallSummary, attached to an assistant message that has persisted terminal (ok/error) tool-call rows — it lets a chat reload render the tool history a turn produced instead of showing nothing until the next live turn. Omitted when the message has no such rows. */ content?: { + tool_calls?: Array [key: string]: unknown } id: string diff --git a/packages/ingest-types/src/zod.gen.ts b/packages/ingest-types/src/zod.gen.ts index 8520f88cf3f..39875cbf3f1 100644 --- a/packages/ingest-types/src/zod.gen.ts +++ b/packages/ingest-types/src/zod.gen.ts @@ -334,6 +334,20 @@ export const zUpdateHubProfileRequest = z.object({ website_urls: z.array(z.string()).optional() }) +/** + * One persisted tool call attached to an assistant message's content.tool_calls (services/agent/internal/persist.ToolCallSummary), so a chat reload can render the tool-call history a turn produced. Display data only — raw arguments/results are never projected here. Only terminal rows (status ok/error) are ever surfaced; a row a dead turn left in pending/running has no wire-status mapping and is dropped rather than shown as a perpetual-progress chip. + */ +export const zToolCallSummary = z.object({ + duration_ms: z.number().int().optional(), + error_code: z.string().optional(), + finished_at: z.string().datetime().optional(), + id: z.string(), + started_at: z.string().datetime().optional(), + status: z.enum(['success', 'error']), + tool_call_id: z.string(), + tool_name: z.string() +}) + /** * Pre/post-discount price for a team credit stop, in cents. */ @@ -767,7 +781,7 @@ export const zResubscribeRequest = z.object({ }) /** - * The newest open renewal invoice of the workspace's Stripe subscription (active, or canceled but not yet ended). Returned only to workspace owners on the stripe billing rail while billing_status is payment_failed, and not while a payment for it is processing. hosted_invoice_url is a bearer payment link. + * The newest open renewal invoice of the workspace's Stripe subscription (active, or canceled but not yet ended). Returned only to workspace owners on the stripe billing rail while billing_status is payment_failed or paused, and not while a payment for it is processing. hosted_invoice_url is a bearer payment link. */ export const zRenewalInvoice = z.object({ amount_due: z.coerce @@ -2829,7 +2843,11 @@ export const zAgentPendingAsk = z.object({ * A persisted message in an agent thread. */ export const zAgentMessage = z.object({ - content: z.record(z.unknown()).optional(), + content: z + .object({ + tool_calls: z.array(zToolCallSummary).optional() + }) + .optional(), id: z.string(), pending_ask: zAgentPendingAsk.optional(), role: z.enum(['user', 'assistant', 'tool', 'system']), diff --git a/src/workbench/extensions/agent/schemas/agentApiSchema.ts b/src/workbench/extensions/agent/schemas/agentApiSchema.ts index 54e43286d05..59e4601e661 100644 --- a/src/workbench/extensions/agent/schemas/agentApiSchema.ts +++ b/src/workbench/extensions/agent/schemas/agentApiSchema.ts @@ -7,6 +7,7 @@ import { zAgentRunMode as zGeneratedAgentRunMode, zAgentThreadListResponse as zGeneratedAgentThreadListResponse, zAgentTurnAccepted as zGeneratedAgentTurnAccepted, + zToolCallSummary, zWorkflowListResponse } from '@comfyorg/ingest-types/zod' import type { @@ -97,37 +98,50 @@ export type AgentRunModeValue = AgentRunModePreference['mode'] /** * 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. `status` is - * deliberately `z.string()` rather than a closed enum: an unrecognized value - * must still surface as a failed `ToolPart` (`toolCallOk` treats anything - * other than `pending`/`running`/`ok`/`success` as failure), so schema - * validation should reject a malformed *entry* (missing `id`/`tool_name`), - * not an unfamiliar *status* string or a bad `duration_ms` — `duration_ms` is - * `z.unknown().optional()` so a NaN/Infinity/negative value there doesn't - * sink the whole entry; `parseToolCallEntry` narrows it separately and just - * omits it. `status` is likewise `.optional()`: an entry that omits it - * entirely must still survive validation (`toolCallPartState`/`toolCallOk` - * already treat `undefined` as terminal-and-failed, matching the old - * parser's behavior for a status-less call). + * 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 = z +export const zPersistedToolCallSummary = zToolCallSummary.extend({ + id: z.string(), + tool_call_id: z.string().optional(), + status: z.string(), + duration_ms: z.number().optional() +}) + +/** + * 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({ - id: z.string(), - // The provider tool-use id a LIVE `agent_tool_call` frame carries as - // `tool_call_id` (see `zAgentToolCallData` above). `parseToolCallEntry` - // prefers this over `id` when building `callId` so a restored `ToolPart` - // is keyed the same way a live frame for the same call will be, and can - // be updated in place rather than rendered as an unmatched duplicate. - // Optional: rows recorded before `tool_call_id` existed have none. - tool_call_id: z.string().optional(), - tool_name: z.string(), - status: z.string().optional(), - duration_ms: z.unknown().optional() + tool_calls: z.array(z.unknown()).optional() }) .passthrough() export const zAgentMessage = zGeneratedAgentMessage .extend({ + content: zAgentMessageContent.optional(), pending_ask: zAgentPendingAsk.optional() }) .passthrough() diff --git a/src/workbench/extensions/agent/services/agent/agentEventTransport.test.ts b/src/workbench/extensions/agent/services/agent/agentEventTransport.test.ts index 0ab64d12dad..e478a8140ec 100644 --- a/src/workbench/extensions/agent/services/agent/agentEventTransport.test.ts +++ b/src/workbench/extensions/agent/services/agent/agentEventTransport.test.ts @@ -433,7 +433,7 @@ describe('agentEventTransport text and tool parts', () => { id: 'audit-row-uuid-1', tool_call_id: 'call-1', tool_name: 'run', - status: 'running' + status: 'error' } ] } diff --git a/src/workbench/extensions/agent/services/agent/agentTranscript.test.ts b/src/workbench/extensions/agent/services/agent/agentTranscript.test.ts index 649e263652e..1c1aa36fa69 100644 --- a/src/workbench/extensions/agent/services/agent/agentTranscript.test.ts +++ b/src/workbench/extensions/agent/services/agent/agentTranscript.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it } from 'vitest' import type { AgentMessages } from '../../schemas/agentApiSchema' -import { toTurnId } from '../../schemas/agentApiSchema' +import { toTurnId, zAgentMessages } from '../../schemas/agentApiSchema' import { normalizeAgentTranscript } from './agentTranscript' const row = ( @@ -209,9 +209,10 @@ describe('normalizeAgentTranscript', () => { text: 'Done', tool_calls: [ { - id: 'call-1', + id: 'audit-row-uuid-1', + tool_call_id: 'call-1', tool_name: 'search_nodes', - status: 'ok', + status: 'success', duration_ms: 420 } ] @@ -232,7 +233,7 @@ describe('normalizeAgentTranscript', () => { ]) }) - it('prefers tool_call_id over id when deriving callId, matching what live frames key on', () => { + it('keys callId on tool_call_id, matching what live frames key on', () => { const message = row(1, 'assistant', 'turn-a', 'Done', 'row-1') message.content = { text: 'Done', @@ -241,7 +242,7 @@ describe('normalizeAgentTranscript', () => { id: 'audit-row-uuid-1', tool_call_id: 'provider-call-1', tool_name: 'search_nodes', - status: 'ok' + status: 'success' } ] } @@ -265,7 +266,7 @@ describe('normalizeAgentTranscript', () => { message.content = { text: 'Done', tool_calls: [ - { id: 'audit-row-uuid-1', tool_name: 'search_nodes', status: 'ok' } + { id: 'audit-row-uuid-1', tool_name: 'search_nodes', status: 'success' } ] } @@ -291,8 +292,18 @@ describe('normalizeAgentTranscript', () => { message.content = { text: 'Done', tool_calls: [ - { id: 'call-1', tool_name: 'search_nodes', status: 'ok' }, - { id: 'call-2', tool_name: 'add_node', status: 'error' } + { + id: 'audit-1', + tool_call_id: 'call-1', + tool_name: 'search_nodes', + status: 'success' + }, + { + id: 'audit-2', + tool_call_id: 'call-2', + tool_name: 'add_node', + status: 'error' + } ] } @@ -321,7 +332,12 @@ describe('normalizeAgentTranscript', () => { const message = row(1, 'assistant', 'turn-a', '', 'row-1') message.content = { tool_calls: [ - { id: 'call-1', tool_name: 'search_nodes', status: 'running' } + { + id: 'audit-1', + tool_call_id: 'call-1', + tool_name: 'search_nodes', + status: 'running' + } ] } @@ -343,7 +359,12 @@ describe('normalizeAgentTranscript', () => { message.status = 'streaming' message.content = { tool_calls: [ - { id: 'call-1', tool_name: 'search_nodes', status: 'running' } + { + id: 'audit-1', + tool_call_id: 'call-1', + tool_name: 'search_nodes', + status: 'running' + } ] } message.pending_ask = { @@ -368,13 +389,20 @@ describe('normalizeAgentTranscript', () => { expect(transcript.pending?.messageId).toBe('row-1') }) - it.for(['success', 'failed', 'cancelled', 'timeout', 'unrecognized'])( - 'maps terminal tool-call status %s through the broadened vocabulary', + it.for(['success', 'error'] as const)( + 'maps terminal tool-call status %s to ok matching status === success', (status) => { const message = row(1, 'assistant', 'turn-a', 'Done', 'row-1') message.content = { text: 'Done', - tool_calls: [{ id: 'call-1', tool_name: 'search_nodes', status }] + tool_calls: [ + { + id: 'audit-1', + tool_call_id: 'call-1', + tool_name: 'search_nodes', + status + } + ] } const transcript = normalizeAgentTranscript([message]) @@ -389,17 +417,18 @@ describe('normalizeAgentTranscript', () => { } ) - it.for([NaN, Infinity, -Infinity, -1])( - 'rejects a non-finite or negative durationMs (%s)', + 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: 'call-1', + id: 'audit-1', + tool_call_id: 'call-1', tool_name: 'search_nodes', - status: 'ok', + status: 'success', duration_ms: durationMs } ] @@ -417,17 +446,102 @@ describe('normalizeAgentTranscript', () => { } ) + 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', + tool_calls: [ + { + id: 'audit-1', + tool_call_id: 'call-1', + tool_name: 'search_nodes', + status: 'success', + duration_ms: 420.5 + } + ] + } + + const transcript = normalizeAgentTranscript([message]) + + expect(transcript.messages[0].parts).toContainEqual({ + type: 'tool', + callId: 'call-1', + name: 'search_nodes', + state: 'done', + ok: true, + durationMs: 420.5 + }) + }) + + 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]) + + 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') message.content = { text: 'Done', tool_calls: [ - { id: 'call-1', tool_name: 'search_nodes', status: 'running' }, - { id: 'call-2', tool_name: 'add_node', status: 'ok' }, { - id: 'call-1', + id: 'audit-1', + tool_call_id: 'call-1', tool_name: 'search_nodes', - status: 'ok', + status: 'success' + }, + { + id: 'audit-2', + tool_call_id: 'call-2', + tool_name: 'add_node', + status: 'success' + }, + { + id: 'audit-3', + tool_call_id: 'call-1', + tool_name: 'search_nodes', + status: 'success', duration_ms: 420 } ] @@ -458,12 +572,17 @@ describe('normalizeAgentTranscript', () => { it.for([ { tool_calls: 'not-an-array' }, { tool_calls: [null, 17, 'a-string'] }, - { tool_calls: [{ tool_name: 'no_id', status: 'ok' }] }, - { tool_calls: [{ id: 'call-1', status: 'ok' }] }, + { tool_calls: [{ tool_name: 'no_id', status: 'success' }] }, + { + tool_calls: [{ id: 'call-1', tool_call_id: 'call-1', status: 'success' }] + }, { tool_calls: [] } ])('ignores malformed tool_calls metadata: $tool_calls', (content) => { const message = row(1, 'assistant', 'turn-a', 'Done', 'row-1') - message.content = { text: 'Done', ...content } + message.content = { + text: 'Done', + ...content + } as unknown as AgentMessages[number]['content'] const transcript = normalizeAgentTranscript([message]) @@ -475,14 +594,22 @@ describe('normalizeAgentTranscript', () => { it('dedupes a repeated callId across two assistant rows of the same turn', () => { const first = row(1, 'assistant', 'turn-a', '', 'row-1') first.content = { - tool_calls: [{ id: 'call-1', tool_name: 'search_nodes', status: 'ok' }] + 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.content = { text: 'Done', tool_calls: [ { - id: 'call-1', + id: 'audit-2', + tool_call_id: 'call-1', tool_name: 'search_nodes', status: 'error', duration_ms: 900 @@ -504,22 +631,85 @@ describe('normalizeAgentTranscript', () => { ]) }) - it('renders a persisted tool call with no status field as a failure, not a dropped entry', () => { + 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: 'call-1', tool_name: 'search_nodes' }] + tool_calls: [ + { id: 'audit-1', tool_call_id: 'call-1', tool_name: 'search_nodes' } + ] } const transcript = normalizeAgentTranscript([message]) + expect(transcript.messages[0].parts).toEqual([ + { type: 'text', text: 'Done', 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 + // 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-1', + callId: 'call-good', name: 'search_nodes', state: 'done', - ok: false + ok: true }, { type: 'text', text: 'Done', state: 'done' } ]) diff --git a/src/workbench/extensions/agent/services/agent/agentTranscript.ts b/src/workbench/extensions/agent/services/agent/agentTranscript.ts index dc2e266fec8..adf2135e1c7 100644 --- a/src/workbench/extensions/agent/services/agent/agentTranscript.ts +++ b/src/workbench/extensions/agent/services/agent/agentTranscript.ts @@ -103,16 +103,14 @@ function parseUserWorkflowReferences( /** * A persisted tool-call status is `pending`/`running` while it was still in - * flight when the turn ended, and some terminal string otherwise (`ok`, - * `success`, `error`, `failed`, `cancelled`, `timeout`, ...) — the exact - * terminal vocabulary is not yet settled between the backend's persisted and - * live wire formats, so anything other than `pending`/`running` is treated as - * terminal here. + * 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 would otherwise spin forever; - * only `isLive` (the row is the one actively backed by a live transport — - * the run_approval mid-ask case) keeps it in `streaming` state. + * 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, @@ -125,9 +123,11 @@ 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 `ok`/`success` counts as success — every - * other terminal string, including a restored `pending`/`running` call that - * had no live transport to finish it, reads as failure rather than being + * 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( @@ -135,12 +135,16 @@ function toolCallOk( state: ToolPart['state'] ): boolean | undefined { if (state === 'streaming') return undefined - return status === 'ok' || 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_name`, wrong types, ...). @@ -149,7 +153,15 @@ 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, diff --git a/src/workbench/extensions/agent/stores/agent/agentConversationStore.test.ts b/src/workbench/extensions/agent/stores/agent/agentConversationStore.test.ts index 3f2facdd3b2..02f3471de91 100644 --- a/src/workbench/extensions/agent/stores/agent/agentConversationStore.test.ts +++ b/src/workbench/extensions/agent/stores/agent/agentConversationStore.test.ts @@ -728,7 +728,14 @@ describe('useAgentConversationStore', () => { const assistant = historyRow(2, 'assistant', 'turn-a', 'Done') assistant.content = { text: 'Done', - tool_calls: [{ id: 'call-1', tool_name: 'search_nodes', status: 'ok' }] + tool_calls: [ + { + id: 'audit-1', + tool_call_id: 'call-1', + tool_name: 'search_nodes', + status: 'success' + } + ] } const store = useAgentConversationStore() @@ -748,7 +755,14 @@ describe('useAgentConversationStore', () => { const threadAAssistant = historyRow(2, 'assistant', 'turn-a', 'Done A') threadAAssistant.content = { text: 'Done A', - tool_calls: [{ id: 'call-a', tool_name: 'search_nodes', status: 'ok' }] + tool_calls: [ + { + id: 'audit-a', + tool_call_id: 'call-a', + tool_name: 'search_nodes', + status: 'success' + } + ] } const threadA = [ historyRow(1, 'user', 'turn-a', 'Find a node'),