diff --git a/browser_tests/fixtures/agentTurnLockFixture.ts b/browser_tests/fixtures/agentTurnLockFixture.ts index 857feadcfc2..6fc191088d7 100644 --- a/browser_tests/fixtures/agentTurnLockFixture.ts +++ b/browser_tests/fixtures/agentTurnLockFixture.ts @@ -16,7 +16,10 @@ import { import { z } from 'zod' import enMessages from '@/locales/en/main.json' with { type: 'json' } -import type { AgentWsEvent } from '@/workbench/extensions/agent/schemas/agentApiSchema' +import type { + AgentWsEvent, + zTurnInProgressError +} from '@/workbench/extensions/agent/schemas/agentApiSchema' import { agentTest } from '@e2e/fixtures/agentPanelFixture' import { workflowSelectionTest } from '@e2e/fixtures/agentWorkflowSelectionFixture' @@ -29,20 +32,23 @@ const zAnswerRequest = z.object({ selected: z.array(z.string()) }) const THREAD_ID = 'b9d0a2a1-0f2c-4f1a-9a5e-6b0f4f2c1d77' const TURN_ID = '2dd4f367-3399-4cb4-8127-547f531c289a' +const FOREIGN_TURN_ID = 'd3f2b1c0-8a4e-4d6f-9b11-0c7a5e2f4318' const WORKFLOW_ID = 'a81718a4-02ae-41e6-ae85-000000000001' const BACKGROUND_THREAD_TITLE = 'Audio workflow' const OTHER_THREAD_ID = '4ccb6603-4bbc-49e2-8b7d-b985230285e3' const OTHER_THREAD_TITLE = 'Earlier workflow' -/** - * Verbatim from `services/agent/server/agent_handler.go`, which answers a post - * to a thread whose assistant row is still `streaming` with HTTP 409 and this - * body. The client renders it as `agent.sendFailed` + ': ' + this text. - */ export const TURN_IN_PROGRESS_MESSAGE = 'a turn is already in progress for this thread' -const TURN_IN_PROGRESS: AgentError = { error: TURN_IN_PROGRESS_MESSAGE } +type TurnInProgressBody = AgentError & z.infer + +const TURN_IN_PROGRESS: TurnInProgressBody = { + error: TURN_IN_PROGRESS_MESSAGE, + type: 'TURN_IN_PROGRESS', + active_message_id: TURN_ID, + turn_id: TURN_ID +} const TURN_THINKING_TEXT = 'Wiring the audio output node.' export const POST_RECONNECT_TEXT = 'Reconnected, and the graph is ready.' @@ -80,6 +86,11 @@ export const TURN_DONE_EVENT: AgentWsEvent = { data: { message_id: TURN_ID, thread_id: THREAD_ID } } +const FOREIGN_TURN_DONE_EVENT: AgentWsEvent = { + type: 'agent_message_done', + data: { message_id: FOREIGN_TURN_ID, thread_id: THREAD_ID } +} + const RUN_APPROVAL_ASK_ID = `${TURN_ID}:call-run-workflow` /** @@ -163,6 +174,7 @@ function deferred(): Deferred { class TurnLockServer { private streaming = false private prompt = '' + private foreignPrompt: string | undefined private rejected = 0 private posts = 0 private readonly answered: string[][] = [] @@ -215,6 +227,7 @@ class TurnLockServer { completeTurn(): void { this.streaming = false + this.foreignPrompt = undefined } holdNextTranscript(): void { @@ -282,7 +295,7 @@ class TurnLockServer { content: { text: this.prompt } } ] - if (!this.streaming) { + if (!this.streaming || this.foreignPrompt !== undefined) { rows.push( { id: TURN_ID, @@ -324,6 +337,28 @@ class TurnLockServer { content: { text: PERSISTED_AFTER_TOOL_TEXT } } ) + if (this.foreignPrompt !== undefined) + rows.push( + { + id: 'user-2', + thread_id: THREAD_ID, + turn_id: FOREIGN_TURN_ID, + seq: 5, + role: 'user', + status: 'complete', + workflow_id: WORKFLOW_ID, + content: { text: this.foreignPrompt } + }, + { + id: FOREIGN_TURN_ID, + thread_id: THREAD_ID, + turn_id: FOREIGN_TURN_ID, + seq: 6, + role: 'assistant', + status: 'streaming', + workflow_id: WORKFLOW_ID + } + ) return rows } rows.push({ @@ -345,9 +380,20 @@ class TurnLockServer { return { message_id: TURN_ID, thread_id: THREAD_ID } } - rejectPost(): AgentError { + lockThreadElsewhere(prompt: string): void { + this.foreignPrompt = prompt + this.streaming = true + } + + rejectPost(): TurnInProgressBody { this.rejected++ - return TURN_IN_PROGRESS + return this.foreignPrompt === undefined + ? TURN_IN_PROGRESS + : { + ...TURN_IN_PROGRESS, + active_message_id: FOREIGN_TURN_ID, + turn_id: FOREIGN_TURN_ID + } } } @@ -464,6 +510,7 @@ export class AgentTurnLockHarness { public readonly workingRow: Locator public readonly liveProgressRow: Locator public readonly userBubbles: Locator + public readonly turnInProgressNotice: Locator private readonly entryButton: Locator private readonly dock: Locator private readonly agentPanel: AgentPanel @@ -516,6 +563,10 @@ export class AgentTurnLockHarness { .filter({ visible: true }) .first() this.userBubbles = this.panel.getByTestId('user-message-bubble') + this.turnInProgressNotice = this.panel.getByText( + enMessages.agent.sendTurnInProgress, + { exact: true } + ) this.entryButton = this.agentPanel.openButton this.dock = page.getByTestId('docked-agent-panel') } @@ -580,10 +631,31 @@ export class AgentTurnLockHarness { this.push(ws, TURN_DONE_EVENT) } + finishForeignTurn(ws: WebSocketRoute): void { + this.server.completeTurn() + this.push(ws, FOREIGN_TURN_DONE_EVENT) + } + + async waitForForeignTurnCancellation(): Promise { + const request = await this.page.waitForRequest( + '**/api/agent/threads/*/messages/*/cancel' + ) + const segments = new URL(request.url()).pathname + .split('/') + .map(decodeURIComponent) + expect(request.method()).toBe('POST') + expect(segments[segments.indexOf('threads') + 1]).toBe(THREAD_ID) + expect(segments[segments.indexOf('messages') + 1]).toBe(FOREIGN_TURN_ID) + } + finishTurnOnServer(): void { this.server.completeTurn() } + lockThreadFromAnotherClient(prompt: string): void { + this.server.lockThreadElsewhere(prompt) + } + /** Makes an ask available through transcript hydration, independently of WS delivery. */ primePendingAsk(event: AgentWsEvent): void { this.server.recordAsk(event) diff --git a/browser_tests/tests/agent/agentSendRefusedByRunningTurn.spec.ts b/browser_tests/tests/agent/agentSendRefusedByRunningTurn.spec.ts new file mode 100644 index 00000000000..97e180ba4c2 --- /dev/null +++ b/browser_tests/tests/agent/agentSendRefusedByRunningTurn.spec.ts @@ -0,0 +1,53 @@ +import { expect } from '@playwright/test' + +import { agentTurnLockTest as test } from '@e2e/fixtures/agentTurnLockFixture' + +test.use({ connectWebSocketToServer: false }) +test.describe.configure({ timeout: 120_000 }) + +test.describe( + 'a send refused because another client holds the thread', + { tag: ['@cloud', '@ui'] }, + () => { + test('re-attaches to the running turn and offers Stop instead of a dead end', async ({ + turnLock + }) => { + await turnLock.openOnBlankWorkflow() + const live = await turnLock.liveSocket() + await turnLock.startTurn('add an audio output node') + turnLock.finishTurn(live) + await expect(turnLock.sendButton).toBeVisible() + + await test.step('another client starts a turn on the same thread', async () => { + turnLock.lockThreadFromAnotherClient('run it again') + await expect(turnLock.sendButton).toBeVisible() + }) + + await test.step('the refused send re-attaches rather than dead-ending', async () => { + await turnLock.composer.fill('and now add a save node') + await turnLock.sendButton.click() + + await expect.poll(() => turnLock.rejectedPosts()).toBe(1) + await expect(turnLock.stopButton).toBeVisible({ timeout: 20_000 }) + await expect(turnLock.sendButton).toHaveCount(0) + await expect(turnLock.liveProgressRow).toBeVisible() + await expect(turnLock.panel.getByText('run it again')).toBeVisible() + await expect(turnLock.turnInProgressNotice).toBeVisible() + }) + + await test.step('stopping it unlocks the composer and the retry is accepted', async () => { + const foreignTurnCancelled = turnLock.waitForForeignTurnCancellation() + await turnLock.stopButton.click() + await foreignTurnCancelled + turnLock.finishForeignTurn(live) + + await expect(turnLock.sendButton).toBeVisible({ timeout: 20_000 }) + await turnLock.composer.fill('and now add a save node') + await turnLock.sendButton.click() + + await expect.poll(() => turnLock.postAttempts()).toBe(3) + expect(turnLock.rejectedPosts()).toBe(1) + }) + }) + } +) diff --git a/src/locales/en/main.json b/src/locales/en/main.json index 02e04f1ab4e..ce14000a2bf 100644 --- a/src/locales/en/main.json +++ b/src/locales/en/main.json @@ -5616,6 +5616,7 @@ "sendFailed": "Message failed to send", "recoveredTurnFailed": "The agent could not complete this response.", "sendBusy": "A message is already being sent", + "sendTurnInProgress": "This chat still has a response running. Wait for it to finish, or stop it, then send again.", "retryAfterSeconds": "You can try again in {seconds}s.", "malformedEvent": "The agent sent an event this panel could not read", "coachProgress": "{current} of {total}", diff --git a/src/workbench/extensions/agent/composables/agent/useAgentSession.test.ts b/src/workbench/extensions/agent/composables/agent/useAgentSession.test.ts index adb90b660ea..e5086916f82 100644 --- a/src/workbench/extensions/agent/composables/agent/useAgentSession.test.ts +++ b/src/workbench/extensions/agent/composables/agent/useAgentSession.test.ts @@ -598,6 +598,210 @@ describe('useAgentSession (v1 composition root)', () => { expect(conversation.activeTurnId).toBe('msg-1') }) + it('re-attaches to the running turn when a send is refused with TURN_IN_PROGRESS', async () => { + const conversation = useAgentConversationStore() + const postMessage = vi + .fn< + (threadId: string, req: PostMessageInput) => Promise + >() + .mockResolvedValueOnce({ thread_id: 'th-1', message_id: 'msg-1' }) + .mockRejectedValue( + new AgentApiError( + 'a turn is already in progress for this thread', + 409, + { + error: 'a turn is already in progress for this thread', + type: 'TURN_IN_PROGRESS', + active_message_id: 'msg-2', + turn_id: 'turn-2' + } + ) + ) + const rest = fakeRest({ + postMessage, + getMessages: vi.fn( + async (): Promise => [ + historyRow(1, 'user', 'turn-1', 'add an audio output node'), + historyRow(2, 'assistant', 'turn-1', 'Done.', 'msg-1'), + historyRow(3, 'user', 'turn-2', 'run it again', 'row-3'), + { + ...historyRow(4, 'assistant', 'turn-2', '', 'msg-2'), + content: {}, + status: 'streaming' + } + ] + ) + }) + const { source, emit } = fakeEvents() + const session = useAgentSession({ rest, events: source }) + session.start() + + await session.sendMessage('add an audio output node') + emit({ + type: 'agent_message_done', + data: { message_id: 'msg-1', thread_id: 'th-1' } + }) + expect(session.isStreaming.value).toBe(false) + + expect(await session.sendMessage('and now add a save node')).toBe(false) + + await vi.waitFor(() => expect(session.isStreaming.value).toBe(true)) + expect(conversation.activeTurnId).toBe('msg-2') + expect(session.entries.value.at(-1)).toMatchObject({ + role: 'assistant', + parts: [ + { + type: 'notice', + level: 'error', + text: 'This chat still has a response running. Wait for it to finish, or stop it, then send again.' + } + ] + }) + }) + + it('does not let a timed-out re-attachment replace a newer turn', async () => { + vi.useFakeTimers() + try { + let resolveHistory: ((history: AgentMessages) => void) | undefined + const postMessage = vi + .fn< + ( + threadId: string, + req: PostMessageInput + ) => Promise + >() + .mockResolvedValueOnce({ thread_id: 'th-1', message_id: 'msg-1' }) + .mockRejectedValueOnce( + new AgentApiError('turn in progress', 409, { + error: 'turn in progress', + type: 'TURN_IN_PROGRESS', + active_message_id: 'msg-2', + turn_id: 'turn-2' + }) + ) + .mockResolvedValueOnce({ thread_id: 'th-1', message_id: 'msg-3' }) + const getMessages = vi.fn( + () => + new Promise((resolve) => { + resolveHistory = resolve + }) + ) + const { source, emit } = fakeEvents() + const session = useAgentSession({ + rest: fakeRest({ postMessage, getMessages }), + events: source + }) + session.start() + await session.sendMessage('first') + emit(done('msg-1')) + + const refused = session.sendMessage('refused') + await vi.waitFor(() => expect(getMessages).toHaveBeenCalledOnce()) + await vi.advanceTimersByTimeAsync(5_000) + await refused + expect(session.entries.value.at(-1)).toMatchObject({ + role: 'assistant', + parts: [ + { + type: 'notice', + level: 'error', + text: 'Message failed to send: turn in progress' + } + ] + }) + await session.sendMessage('newer') + + resolveHistory?.([ + historyRow(1, 'user', 'turn-2', 'other client'), + { + ...historyRow(2, 'assistant', 'turn-2', '', 'msg-2'), + content: {}, + status: 'streaming' + } + ]) + await Promise.resolve() + + expect(useAgentConversationStore().activeTurnId).toBe('msg-3') + expect( + session.entries.value + .filter((entry) => entry.role === 'user') + .map((entry) => entry.text) + ).toEqual(['first', 'refused', 'newer']) + } finally { + vi.useRealTimers() + } + }) + + it('records no failed send when the re-read finds the refused thread deleted', async () => { + const postMessage = vi + .fn< + (threadId: string, req: PostMessageInput) => Promise + >() + .mockResolvedValueOnce({ thread_id: 'th-1', message_id: 'msg-1' }) + .mockRejectedValue( + new AgentApiError('turn in progress', 409, { + error: 'turn in progress', + type: 'TURN_IN_PROGRESS', + active_message_id: 'msg-2' + }) + ) + const getMessages = vi.fn(async (): Promise => { + throw new AgentApiError('thread not found', 404, { + error: 'thread not found' + }) + }) + const { source, emit } = fakeEvents() + const session = useAgentSession({ + rest: fakeRest({ postMessage, getMessages }), + events: source + }) + session.start() + await session.sendMessage('first') + emit(done('msg-1')) + + await session.sendMessage('refused') + + expect( + session.entries.value.filter((entry) => entry.role === 'user') + ).not.toContainEqual(expect.objectContaining({ text: 'refused' })) + }) + + it('leaves an undiscriminated 409 on an existing thread as a plain failure', async () => { + const postMessage = vi + .fn< + (threadId: string, req: PostMessageInput) => Promise + >() + .mockResolvedValueOnce({ thread_id: 'th-1', message_id: 'msg-1' }) + .mockRejectedValue( + new AgentApiError('conflict', 409, { error: 'conflict' }) + ) + const rest = fakeRest({ postMessage }) + const { source, emit } = fakeEvents() + const session = useAgentSession({ rest, events: source }) + session.start() + + await session.sendMessage('make a cat') + emit({ + type: 'agent_message_done', + data: { message_id: 'msg-1', thread_id: 'th-1' } + }) + + await session.sendMessage('make it orange') + + expect(rest.getMessages).not.toHaveBeenCalled() + expect(session.isStreaming.value).toBe(false) + expect(session.entries.value.at(-1)).toMatchObject({ + role: 'assistant', + parts: [ + { + type: 'notice', + level: 'error', + text: 'Message failed to send: conflict' + } + ] + }) + }) + // The other half of (b4a): `subscribe()` runs before the GET resolves, and // the reopen dropped its background turns, so a done arriving in that window // has nowhere to land. Lost, it would leave the restored turn running for @@ -3008,6 +3212,106 @@ describe('useAgentSession (v1 composition root)', () => { } ) + it('applies a pending stop to an active turn adopted after a refused send', async () => { + let rejectPost: ((error: unknown) => void) | undefined + const postMessage = vi + .fn< + (threadId: string, req: PostMessageInput) => Promise + >() + .mockResolvedValueOnce({ thread_id: 'th-1', message_id: 'msg-1' }) + .mockImplementationOnce( + () => + new Promise((_resolve, reject) => { + rejectPost = reject + }) + ) + const cancelMessage = vi.fn( + async (): Promise => ({ status: 'cancelling' }) + ) + const rest = fakeRest({ + postMessage, + cancelMessage, + getMessages: vi.fn( + async (): Promise => [ + historyRow(1, 'user', 'turn-2', 'other client'), + { + ...historyRow(2, 'assistant', 'turn-2', '', 'msg-2'), + content: {}, + status: 'streaming' + } + ] + ) + }) + const { source, emit } = fakeEvents() + const session = useAgentSession({ + rest, + events: source, + workflow: { + current: () => undefined, + adopted: vi.fn(), + restored: async () => false + } + }) + session.start() + await session.sendMessage('first') + emit(done('msg-1')) + + const refused = session.sendMessage('refused') + await session.stopTurn('button') + rejectPost?.( + new AgentApiError('turn in progress', 409, { + error: 'turn in progress', + type: 'TURN_IN_PROGRESS', + active_message_id: 'msg-2', + turn_id: 'turn-2' + }) + ) + await refused + + expect(cancelMessage).toHaveBeenCalledExactlyOnceWith('th-1', 'msg-2') + expect(session.entries.value.at(-1)).toMatchObject({ + role: 'assistant', + parts: [ + { + type: 'notice', + level: 'error', + text: 'This chat still has a response running. Wait for it to finish, or stop it, then send again.' + } + ] + }) + }) + + it('clears a pending stop when the send fails before adopting a turn', async () => { + let rejectPost: ((error: unknown) => void) | undefined + const postMessage = vi + .fn< + (threadId: string, req: PostMessageInput) => Promise + >() + .mockImplementationOnce( + () => + new Promise((_resolve, reject) => { + rejectPost = reject + }) + ) + .mockResolvedValueOnce({ thread_id: 'th-1', message_id: 'msg-2' }) + const cancelMessage = vi.fn( + async (): Promise => ({ status: 'cancelling' }) + ) + const session = useAgentSession({ + rest: fakeRest({ postMessage, cancelMessage }), + events: fakeEvents().source + }) + session.start() + + const failed = session.sendMessage('failed') + await session.stopTurn('button') + rejectPost?.(new TypeError('network down')) + await failed + await session.sendMessage('next') + + expect(cancelMessage).not.toHaveBeenCalled() + }) + it('(g) a socket blip keeps the turn live and re-checks the server once on the way back up', async () => { // PM-1199 / PM-1200. The server never learns the socket went away: it // keeps running the turn and keeps the row `streaming`. Aborting locally diff --git a/src/workbench/extensions/agent/composables/agent/useAgentSession.ts b/src/workbench/extensions/agent/composables/agent/useAgentSession.ts index 1130fd5956b..37cb84bdcd5 100644 --- a/src/workbench/extensions/agent/composables/agent/useAgentSession.ts +++ b/src/workbench/extensions/agent/composables/agent/useAgentSession.ts @@ -31,7 +31,8 @@ import { parseAgentWsEvent, toTurnId, zAgentAdmissionError, - zDisownedWorkflowError + zDisownedWorkflowError, + zTurnInProgressError } from '../../schemas/agentApiSchema' import { AgentApiError, @@ -361,6 +362,13 @@ function disownsWorkflow(error: unknown): boolean { ) } +function parseTurnInProgress(error: unknown) { + if (!(error instanceof AgentApiError) || error.status !== 409) + return undefined + const parsed = zTurnInProgressError.safeParse(error.body) + return parsed.success ? parsed.data : undefined +} + export function useAgentSession(deps: AgentSessionDeps) { const { rest, @@ -1001,6 +1009,10 @@ export function useAgentSession(deps: AgentSessionDeps) { conversationStore.startTurn(turnId) readyThreadId.value = ack.thread_id recordTurnStarted(turnId, startsThread) + stopPendingActiveTurn() + } + + function stopPendingActiveTurn(): void { const pendingStop = consumeStopPendingAck() if (pendingStop !== null) void stopTurn(pendingStop.method) } @@ -1008,7 +1020,8 @@ export function useAgentSession(deps: AgentSessionDeps) { function recordSendError( error: unknown, text: string, - accepted: boolean + accepted: boolean, + reattached: boolean ): void { const admission = parseAdmissionError(error) if (admission?.reason === 'no_funds') { @@ -1030,16 +1043,13 @@ export function useAgentSession(deps: AgentSessionDeps) { ) return } - const message = - error instanceof AgentApiError - ? error.message - : error instanceof Error - ? error.message - : String(error) + const message = error instanceof Error ? error.message : String(error) conversationStore.recordFailedSend( nextLocalErrorId(), text, - `${i18n.global.t('agent.sendFailed')}: ${message}` + reattached + ? i18n.global.t('agent.sendTurnInProgress') + : `${i18n.global.t('agent.sendFailed')}: ${message}` ) const turnAccepted = accepted || isUnreadableAckFailure(error) reportError(error, { @@ -1054,6 +1064,18 @@ export function useAgentSession(deps: AgentSessionDeps) { ) } + function recordCurrentSendError( + error: unknown, + text: string, + accepted: boolean, + reattached: boolean, + threadAtSend: string + ): void { + if (threadAtSend !== 'new' && conversationStore.threadId !== threadAtSend) + return + recordSendError(error, text, accepted, reattached) + } + /** * The server will not serve the id this turn was posted under, and the * binding that produced it outlives the page. Left in place it poisons the @@ -1076,6 +1098,35 @@ export function useAgentSession(deps: AgentSessionDeps) { if (rememberedWorkflowId === sent.id) rememberedWorkflowId = null } + async function reattachRefusedTurn( + error: unknown, + threadAtSend: string, + generation: number + ): Promise { + const conflict = parseTurnInProgress(error) + if (conflict === undefined || threadAtSend === 'new') return false + const reattachGeneration = ++refusedTurnReattachGeneration + const isCurrentReattachment = () => + reattachGeneration === refusedTurnReattachGeneration && + generation === loadGeneration && + ownedGeneration === sessionGeneration && + conversationStore.threadId === threadAtSend + await Promise.race([ + hydrateFromServer(threadAtSend, isCurrentReattachment), + new Promise((resolve) => setTimeout(resolve, RECONCILE_TIMEOUT_MS)) + ]) + const activeTurnId = conversationStore.activeTurnId + const adoptedActiveTurn = + isCurrentReattachment() && + activeTurnId !== null && + (conflict.active_message_id === undefined || + activeTurnId === conflict.active_message_id) + if (reattachGeneration === refusedTurnReattachGeneration) + refusedTurnReattachGeneration++ + if (adoptedActiveTurn) stopPendingActiveTurn() + return adoptedActiveTurn + } + async function performSend( text: string, attachments?: SentAttachment[], @@ -1121,7 +1172,13 @@ export function useAgentSession(deps: AgentSessionDeps) { // moved on still has to release, or the dead id survives the reload. releaseDisownedWorkflow(sentContext, error) if (generation !== loadGeneration) return false - recordSendError(error, text, accepted) + const reattached = await reattachRefusedTurn( + error, + threadAtSend, + generation + ) + if (generation !== loadGeneration) return false + recordCurrentSendError(error, text, accepted, reattached, threadAtSend) return false } } @@ -1155,7 +1212,7 @@ export function useAgentSession(deps: AgentSessionDeps) { sendInFlight = true stopPendingAck = null try { - return await performSend( + const sent = await performSend( text, attachments, tags, @@ -1163,6 +1220,8 @@ export function useAgentSession(deps: AgentSessionDeps) { selectionWorkflowId, clientMessageId ) + if (!sent) stopPendingAck = null + return sent } finally { sending.value = false sendInFlight = false @@ -1441,6 +1500,7 @@ export function useAgentSession(deps: AgentSessionDeps) { } let loadGeneration = 0 + let refusedTurnReattachGeneration = 0 function newChat( source?: Exclude diff --git a/src/workbench/extensions/agent/schemas/agentApiSchema.ts b/src/workbench/extensions/agent/schemas/agentApiSchema.ts index ec4277d472c..e492fb7129e 100644 --- a/src/workbench/extensions/agent/schemas/agentApiSchema.ts +++ b/src/workbench/extensions/agent/schemas/agentApiSchema.ts @@ -187,6 +187,27 @@ export const zAgentError = z.union([zGeneratedAgentError, zAgentAdmissionError]) export const zDisownedWorkflowError = z.object({ error: z.literal('workflow not found or access denied') }) + +/** + * The 409 body the agent service returns when the thread already has a turn in + * progress (`rejectTurnInProgress` in `services/agent/server/agent_handler.go`). + * `type` is the discriminator — a 409 from the cancel or answer endpoints + * carries no `type` at all — and the two ids name the turn that holds the + * thread, so the client can re-attach to it instead of reporting a dead end. + * + * Both ids are optional on the wire: the server resolves them best-effort and + * documents that a lookup failure "still yields the 409, just without the id". + * A conflict with no ids is still a conflict, so the discriminator alone has to + * be enough to recognise one. + */ +export const zTurnInProgressError = z + .object({ + type: z.literal('TURN_IN_PROGRESS'), + active_message_id: z.string().optional(), + turn_id: z.string().optional() + }) + .passthrough() + const zAgentThinkingData = z .object({ delta: z.string(),