From 9c4fe5c42c5e9f392c854d0aac91cba43fe2b32a Mon Sep 17 00:00:00 2001 From: Christian Byrne Date: Fri, 2 Oct 2026 05:50:08 -0700 Subject: [PATCH 01/14] fix(agent): re-attach to the running turn when a send is refused (FE-1998) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A `409 TURN_IN_PROGRESS` on send was terminal. The panel rendered the raw server string ("a turn is already in progress for this thread"), offered no stop control, and gave no way to tell a working turn from a dead one — the server's single-active-turn signal is a durable `status='streaming'` assistant row, so the thread stays locked until that row goes terminal and nothing the user could do from the panel cleared it. The server has carried the recovery since cloud#8275: the 409 body names the turn holding the thread (`type`, `active_message_id`, `turn_id`). The client never read any of it. Now a refused send re-reads the thread, which adopts the still-running turn as active and puts Stop where Send was; once that turn settles the composer unlocks on its own. The re-read goes through `hydrateFromServer` so WS frames landing during the GET are replayed rather than dropped, and it is bounded on the same reasoning as `reconcileSnapshotTurn` — the composer sits in `sending` until it returns, so a slow workflow restore must not hold the one control the user needs. Scope: this is the 409 route that composer gating does not close. A turn this client can see already renders Stop and never offers Send; a turn started from a second tab, window or device is invisible to it, which is what the new spec exercises. Fixture fidelity: `agentTurnLockFixture` sent only the 409's message, so no spec could distinguish a client that reads the conflict ids from one that does not. It now sends the whole body the service sends. The generated `AgentError` type describes only `error` — the OpenAPI schema does not cover this endpoint's conflict body (filed as an upstream hypothesis for the ingest schema). Red on parent, green here: browser_tests/tests/agent/agentSendRefusedByRunningTurn.spec.ts useAgentSession.test.ts › re-attaches to the running turn when a send is refused with TURN_IN_PROGRESS --- .../fixtures/agentTurnLockFixture.ts | 105 +++++++++++++++++- .../agentSendRefusedByRunningTurn.spec.ts | 72 ++++++++++++ src/locales/en/main.json | 1 + .../composables/agent/useAgentSession.test.ts | 99 +++++++++++++++++ .../composables/agent/useAgentSession.ts | 101 +++++++++++++++-- .../agent/schemas/agentApiSchema.ts | 21 ++++ 6 files changed, 387 insertions(+), 12 deletions(-) create mode 100644 browser_tests/tests/agent/agentSendRefusedByRunningTurn.spec.ts diff --git a/browser_tests/fixtures/agentTurnLockFixture.ts b/browser_tests/fixtures/agentTurnLockFixture.ts index 857feadcfc2..ff9e3c82a81 100644 --- a/browser_tests/fixtures/agentTurnLockFixture.ts +++ b/browser_tests/fixtures/agentTurnLockFixture.ts @@ -29,6 +29,8 @@ 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' +/** The turn another client started on the same thread — see `lockThreadElsewhere`. */ +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' @@ -37,12 +39,35 @@ 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. + * body. */ 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 } +/** + * The whole 409 body, not just its message. `rejectTurnInProgress` sends a + * `type` discriminator plus the ids of the turn holding the thread (cloud + * #8275), and those three fields are the client's only route from "refused" to + * "re-attached" — a fixture that sends the message alone cannot distinguish a + * client that reads them from one that does not. + * + * `AgentError` types only `error`, because the generated OpenAPI schema for this + * endpoint does not describe the conflict body; the intersection keeps the + * shared field checked while still sending what the service really sends. + * (Filed as an upstream hypothesis for the ingest schema.) + */ +type TurnInProgressBody = AgentError & { + type: string + active_message_id: string + turn_id: string +} + +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.' @@ -163,6 +188,13 @@ function deferred(): Deferred { class TurnLockServer { private streaming = false private prompt = '' + /** + * The prompt of a turn started by a *different* client on this same thread, + * when one holds the lock. Tracked apart from `prompt` because this browser + * never posted it: it exists in the transcript and in the active-turn guard, + * and nowhere in this client's own state. + */ + private foreignPrompt: string | undefined private rejected = 0 private posts = 0 private readonly answered: string[][] = [] @@ -215,6 +247,7 @@ class TurnLockServer { completeTurn(): void { this.streaming = false + this.foreignPrompt = undefined } holdNextTranscript(): void { @@ -324,6 +357,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 +400,31 @@ class TurnLockServer { return { message_id: TURN_ID, thread_id: THREAD_ID } } - rejectPost(): AgentError { + /** + * Locks the thread the way a second tab, window or device does: the assistant + * row goes `streaming` and the active-turn guard starts refusing posts, while + * this client posted nothing and holds no transport for it. + * + * This is the one route to a 409 that survives the composer gating — a client + * that can see the turn renders Stop and never offers Send — so it is what a + * spec has to use to exercise the refusal path at all. + */ + lockThreadElsewhere(prompt: string): void { + this.foreignPrompt = prompt + this.streaming = true + } + + rejectPost(): TurnInProgressBody { this.rejected++ - return TURN_IN_PROGRESS + // The ids name whichever turn actually holds the thread, as the server's + // own `ThreadActiveTurn` lookup does. + return this.foreignPrompt === undefined + ? TURN_IN_PROGRESS + : { + ...TURN_IN_PROGRESS, + active_message_id: FOREIGN_TURN_ID, + turn_id: FOREIGN_TURN_ID + } } } @@ -464,6 +541,10 @@ export class AgentTurnLockHarness { public readonly workingRow: Locator public readonly liveProgressRow: Locator public readonly userBubbles: Locator + /** The notice a send refused by the active-turn guard leaves behind. */ + public readonly turnInProgressNotice: Locator + /** The raw server string the pre-fix client rendered instead. */ + public readonly rawRefusalText: Locator private readonly entryButton: Locator private readonly dock: Locator private readonly agentPanel: AgentPanel @@ -516,6 +597,13 @@ 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.rawRefusalText = this.panel.getByText(TURN_IN_PROGRESS_MESSAGE, { + exact: false + }) this.entryButton = this.agentPanel.openButton this.dock = page.getByTestId('docked-agent-panel') } @@ -584,6 +672,15 @@ export class AgentTurnLockHarness { this.server.completeTurn() } + /** + * Locks the thread from outside this browser, so the next send is refused by + * the server's active-turn guard while this client's composer still offers + * Send. See `TurnLockServer.lockThreadElsewhere`. + */ + 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..5fc4c904c0b --- /dev/null +++ b/browser_tests/tests/agent/agentSendRefusedByRunningTurn.spec.ts @@ -0,0 +1,72 @@ +import { expect } from '@playwright/test' + +import { agentTurnLockTest as test } from '@e2e/fixtures/agentTurnLockFixture' + +test.use({ connectWebSocketToServer: false }) + +/** + * FE-1998, the half that composer gating does not reach. + * + * A turn this client can see renders Stop in place of Send, so it can never + * reach the server's active-turn guard. A turn started from a *second* tab, + * window or device can: this client's composer offers Send, the post is refused + * `409 TURN_IN_PROGRESS`, and before this change the user was left with the raw + * server string, no stop control, and no way to tell a working turn from a dead + * one — the dead end the ticket is named for. + * + * The server hands the client everything needed to recover (`type`, + * `active_message_id`, `turn_id`; cloud #8275). These assertions are about + * whether the panel acts on it. + */ +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') + // No local signal: nothing has told this panel the thread is busy, so + // Send is still the control on offer. That is what makes the next send + // reach the guard at all. + 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) + // The fix: the thread was re-read, the still-running turn adopted, and + // the composer's primary action is now the escape hatch. + await expect(turnLock.stopButton).toBeVisible({ timeout: 20_000 }) + await expect(turnLock.sendButton).toHaveCount(0) + await expect(turnLock.liveProgressRow).toBeVisible() + // The notice names the recovery; the raw server string described a + // control the user is already looking at. + await expect(turnLock.turnInProgressNotice).toBeVisible() + await expect(turnLock.rawRefusalText).toHaveCount(0) + }) + + await test.step('stopping it unlocks the composer and the retry is accepted', async () => { + await turnLock.stopButton.click() + + await expect(turnLock.sendButton).toBeVisible({ timeout: 40_000 }) + await turnLock.composer.fill('and now add a save node') + await turnLock.sendButton.click() + + await expect.poll(() => turnLock.postAttempts()).toBe(3) + // Still one: the retry was accepted, so no second refusal. This is the + // ticket's acceptance criterion — the next send succeeds with no reload. + 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..bea75410239 100644 --- a/src/workbench/extensions/agent/composables/agent/useAgentSession.test.ts +++ b/src/workbench/extensions/agent/composables/agent/useAgentSession.test.ts @@ -598,6 +598,105 @@ describe('useAgentSession (v1 composition root)', () => { expect(conversation.activeTurnId).toBe('msg-1') }) + // FE-1998. Composer gating closes the reload route to a 409, but not a turn + // started from a second tab: this client has no local signal, so it offers + // Send and the post is refused. Before this change the refusal was terminal + // -- a raw server string, no stop control, and no way to tell a working turn + // from a dead one. + 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' + } + ) + ) + // The thread as the other client left it: turn 1 settled, turn 2 running. + 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)) + // The turn the server named, not the one this client had started. + 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.' + } + ] + }) + }) + + // The discriminator is load-bearing: a 409 from any other endpoint, or one + // whose body this client cannot read, must stay an ordinary send failure + // rather than trigger a re-read of a thread that is not actually busy. + it('leaves a 409 without the TURN_IN_PROGRESS discriminator as a plain failure', async () => { + const postMessage = vi + .fn< + (threadId: string, req: PostMessageInput) => Promise + >() + .mockRejectedValue( + new AgentApiError('conflict', 409, { error: 'conflict' }) + ) + const rest = fakeRest({ postMessage }) + const session = useAgentSession({ rest, events: fakeEvents().source }) + session.start() + + await session.sendMessage('make a cat') + + 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 diff --git a/src/workbench/extensions/agent/composables/agent/useAgentSession.ts b/src/workbench/extensions/agent/composables/agent/useAgentSession.ts index 1130fd5956b..ce989506e2d 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,30 @@ function disownsWorkflow(error: unknown): boolean { ) } +/** + * The turn that holds the thread, when a send was refused because one is + * already running. `undefined` for anything else, including a 409 from another + * endpoint: only the message path carries the `TURN_IN_PROGRESS` discriminator. + * + * The ids are read but deliberately not required (see `zTurnInProgressError`): + * recognising the conflict is what lets this client re-read the thread and + * re-attach, and that re-read is keyed on the thread, not on the turn. The ids + * are returned so a caller can tell afterwards whether it adopted the turn the + * server actually named. + */ +function parseTurnInProgress( + error: unknown +): { activeMessageId?: string; turnId?: string } | undefined { + if (!(error instanceof AgentApiError) || error.status !== 409) + return undefined + const parsed = zTurnInProgressError.safeParse(error.body) + if (!parsed.success) return undefined + return { + activeMessageId: parsed.data.active_message_id, + turnId: parsed.data.turn_id + } +} + export function useAgentSession(deps: AgentSessionDeps) { const { rest, @@ -1005,6 +1030,22 @@ export function useAgentSession(deps: AgentSessionDeps) { if (pendingStop !== null) void stopTurn(pendingStop.method) } + /** + * The notice text for a send that failed for a reason admission does not own. + * + * A refused-because-busy send is the one failure whose cause is already on + * screen: `reattachRefusedTurn` has put the running turn back in the composer, + * so the raw server string ("a turn is already in progress for this thread") + * would be describing the Stop button the user is now looking at. The typed + * copy names the recovery instead. + */ + function sendFailureNotice(error: unknown): string { + if (parseTurnInProgress(error) !== undefined) + return i18n.global.t('agent.sendTurnInProgress') + const message = error instanceof Error ? error.message : String(error) + return `${i18n.global.t('agent.sendFailed')}: ${message}` + } + function recordSendError( error: unknown, text: string, @@ -1030,16 +1071,10 @@ export function useAgentSession(deps: AgentSessionDeps) { ) return } - const message = - error instanceof AgentApiError - ? error.message - : error instanceof Error - ? error.message - : String(error) conversationStore.recordFailedSend( nextLocalErrorId(), text, - `${i18n.global.t('agent.sendFailed')}: ${message}` + sendFailureNotice(error) ) const turnAccepted = accepted || isUnreadableAckFailure(error) reportError(error, { @@ -1076,6 +1111,51 @@ export function useAgentSession(deps: AgentSessionDeps) { if (rememberedWorkflowId === sent.id) rememberedWorkflowId = null } + /** + * FE-1998: re-attaches to the turn a `409 TURN_IN_PROGRESS` just named. + * + * The server's single-active-turn signal is a `status='streaming'` assistant + * row, durable in Postgres, so the thread stays locked until that row goes + * terminal — and a client that only reports the refusal leaves the user with + * no stop control and no way to tell a working turn from a dead one. Re-reading + * the thread is what adopts that row as the active turn, which is what renders + * Stop in place of Send; once the turn settles, the composer unlocks on its own. + * + * `hydrateFromServer` rather than a bare `getMessages` + `hydrate`: it is the + * one path that arms the hydration mailbox, so WS frames for the running turn + * that land during the GET are replayed instead of dropped. Reusing it also + * keeps one re-attach path rather than a second one that drifts. + * + * Bounded on the same reasoning as `reconcileSnapshotTurn`: `performSend` + * awaits this and the composer sits in `sending` until it returns, so an + * unbounded await would let a slow workflow restore hold the one control the + * user needs. If the bound wins, the in-flight hydrate can still land later + * and replace `messages`, which costs the notice below but not the Stop + * control — the re-attach is the part that matters. + * + * A failed re-read reports itself through `handleHistoryLoadError` and still + * leaves the original refusal for the caller to record. + */ + async function reattachRefusedTurn( + error: unknown, + threadAtSend: string, + generation: number + ): Promise { + if (parseTurnInProgress(error) === undefined) return + // 'new' is the sentinel for a thread the server had not minted yet, and a + // thread that does not exist cannot already be busy. + if (threadAtSend === 'new') return + await Promise.race([ + hydrateFromServer( + threadAtSend, + () => + generation === loadGeneration && + conversationStore.threadId === threadAtSend + ), + new Promise((resolve) => setTimeout(resolve, RECONCILE_TIMEOUT_MS)) + ]) + } + async function performSend( text: string, attachments?: SentAttachment[], @@ -1121,6 +1201,11 @@ 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 + // Before recordSendError, not after: the re-read rebuilds `messages` from + // the server transcript, which would discard a local failed-send row + // appended first. + await reattachRefusedTurn(error, threadAtSend, generation) + if (generation !== loadGeneration) return false recordSendError(error, text, accepted) return false } 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(), From fb5eb89cb3542936fce8406488b99978e5e65899 Mon Sep 17 00:00:00 2001 From: bymyself Date: Fri, 2 Oct 2026 13:06:55 +0000 Subject: [PATCH 02/14] test(agent): cover plain conflict on an existing thread Addresses review feedback: https://github.com/Comfy-Org/ComfyUI_frontend/pull/19901#discussion_r4165912210 --- .../agent/composables/agent/useAgentSession.test.ts | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/src/workbench/extensions/agent/composables/agent/useAgentSession.test.ts b/src/workbench/extensions/agent/composables/agent/useAgentSession.test.ts index bea75410239..929b75777df 100644 --- a/src/workbench/extensions/agent/composables/agent/useAgentSession.test.ts +++ b/src/workbench/extensions/agent/composables/agent/useAgentSession.test.ts @@ -669,19 +669,27 @@ describe('useAgentSession (v1 composition root)', () => { // The discriminator is load-bearing: a 409 from any other endpoint, or one // whose body this client cannot read, must stay an ordinary send failure // rather than trigger a re-read of a thread that is not actually busy. - it('leaves a 409 without the TURN_IN_PROGRESS discriminator as a plain failure', async () => { + 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 session = useAgentSession({ rest, events: fakeEvents().source }) + 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) From a92a509242b55d33acc1c7ecaa3268a8c7f5988d Mon Sep 17 00:00:00 2001 From: bymyself Date: Fri, 2 Oct 2026 13:07:52 +0000 Subject: [PATCH 03/14] fix: invalidate timed-out turn reattachments Addresses review feedback: https://github.com/Comfy-Org/ComfyUI_frontend/pull/19901#discussion_r4165912213 --- .../composables/agent/useAgentSession.test.ts | 63 +++++++++++++++++++ .../composables/agent/useAgentSession.ts | 5 ++ 2 files changed, 68 insertions(+) diff --git a/src/workbench/extensions/agent/composables/agent/useAgentSession.test.ts b/src/workbench/extensions/agent/composables/agent/useAgentSession.test.ts index 929b75777df..ed59593b8b6 100644 --- a/src/workbench/extensions/agent/composables/agent/useAgentSession.test.ts +++ b/src/workbench/extensions/agent/composables/agent/useAgentSession.test.ts @@ -666,6 +666,69 @@ describe('useAgentSession (v1 composition root)', () => { }) }) + 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 + 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() + } + }) + // The discriminator is load-bearing: a 409 from any other endpoint, or one // whose body this client cannot read, must stay an ordinary send failure // rather than trigger a re-read of a thread that is not actually busy. diff --git a/src/workbench/extensions/agent/composables/agent/useAgentSession.ts b/src/workbench/extensions/agent/composables/agent/useAgentSession.ts index ce989506e2d..54a2574c317 100644 --- a/src/workbench/extensions/agent/composables/agent/useAgentSession.ts +++ b/src/workbench/extensions/agent/composables/agent/useAgentSession.ts @@ -1145,15 +1145,19 @@ export function useAgentSession(deps: AgentSessionDeps) { // 'new' is the sentinel for a thread the server had not minted yet, and a // thread that does not exist cannot already be busy. if (threadAtSend === 'new') return + const reattachGeneration = ++refusedTurnReattachGeneration await Promise.race([ hydrateFromServer( threadAtSend, () => + reattachGeneration === refusedTurnReattachGeneration && generation === loadGeneration && conversationStore.threadId === threadAtSend ), new Promise((resolve) => setTimeout(resolve, RECONCILE_TIMEOUT_MS)) ]) + if (reattachGeneration === refusedTurnReattachGeneration) + refusedTurnReattachGeneration++ } async function performSend( @@ -1526,6 +1530,7 @@ export function useAgentSession(deps: AgentSessionDeps) { } let loadGeneration = 0 + let refusedTurnReattachGeneration = 0 function newChat( source?: Exclude From 90e8574d34b702507d81efd4e22cf2e3329c5348 Mon Sep 17 00:00:00 2001 From: bymyself Date: Fri, 2 Oct 2026 13:09:45 +0000 Subject: [PATCH 04/14] fix: retire pending stops after failed sends Addresses review feedback: https://github.com/Comfy-Org/ComfyUI_frontend/pull/19901#discussion_r4165912221 --- .../composables/agent/useAgentSession.test.ts | 82 +++++++++++++++++++ .../composables/agent/useAgentSession.ts | 12 ++- 2 files changed, 92 insertions(+), 2 deletions(-) diff --git a/src/workbench/extensions/agent/composables/agent/useAgentSession.test.ts b/src/workbench/extensions/agent/composables/agent/useAgentSession.test.ts index ed59593b8b6..87b6fe5b309 100644 --- a/src/workbench/extensions/agent/composables/agent/useAgentSession.test.ts +++ b/src/workbench/extensions/agent/composables/agent/useAgentSession.test.ts @@ -3178,6 +3178,88 @@ 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 }) + 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') + }) + + 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 54a2574c317..ddf2db38eb9 100644 --- a/src/workbench/extensions/agent/composables/agent/useAgentSession.ts +++ b/src/workbench/extensions/agent/composables/agent/useAgentSession.ts @@ -1026,6 +1026,11 @@ export function useAgentSession(deps: AgentSessionDeps) { conversationStore.startTurn(turnId) readyThreadId.value = ack.thread_id recordTurnStarted(turnId, startsThread) + stopPendingActiveTurn() + } + + function stopPendingActiveTurn(): void { + if (conversationStore.activeTurnId === null) return const pendingStop = consumeStopPendingAck() if (pendingStop !== null) void stopTurn(pendingStop.method) } @@ -1146,7 +1151,7 @@ export function useAgentSession(deps: AgentSessionDeps) { // thread that does not exist cannot already be busy. if (threadAtSend === 'new') return const reattachGeneration = ++refusedTurnReattachGeneration - await Promise.race([ + const reattached = await Promise.race([ hydrateFromServer( threadAtSend, () => @@ -1158,6 +1163,7 @@ export function useAgentSession(deps: AgentSessionDeps) { ]) if (reattachGeneration === refusedTurnReattachGeneration) refusedTurnReattachGeneration++ + if (reattached === true) stopPendingActiveTurn() } async function performSend( @@ -1244,7 +1250,7 @@ export function useAgentSession(deps: AgentSessionDeps) { sendInFlight = true stopPendingAck = null try { - return await performSend( + const sent = await performSend( text, attachments, tags, @@ -1252,6 +1258,8 @@ export function useAgentSession(deps: AgentSessionDeps) { selectionWorkflowId, clientMessageId ) + if (!sent) stopPendingAck = null + return sent } finally { sending.value = false sendInFlight = false From 6359e9c7428ef3ca6f65d4247b2e068cfd713b10 Mon Sep 17 00:00:00 2001 From: Christian Byrne Date: Fri, 2 Oct 2026 06:21:12 -0700 Subject: [PATCH 05/14] test(agent): exercise the foreign running turn Addresses review feedback: https://github.com/Comfy-Org/ComfyUI_frontend/pull/19901#discussion_r4165984345 --- browser_tests/fixtures/agentTurnLockFixture.ts | 12 +++++++++++- .../agent/agentSendRefusedByRunningTurn.spec.ts | 2 ++ 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/browser_tests/fixtures/agentTurnLockFixture.ts b/browser_tests/fixtures/agentTurnLockFixture.ts index ff9e3c82a81..0337c6d25a7 100644 --- a/browser_tests/fixtures/agentTurnLockFixture.ts +++ b/browser_tests/fixtures/agentTurnLockFixture.ts @@ -105,6 +105,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` /** @@ -315,7 +320,7 @@ class TurnLockServer { content: { text: this.prompt } } ] - if (!this.streaming) { + if (!this.streaming || this.foreignPrompt !== undefined) { rows.push( { id: TURN_ID, @@ -668,6 +673,11 @@ export class AgentTurnLockHarness { this.push(ws, TURN_DONE_EVENT) } + finishForeignTurn(ws: WebSocketRoute): void { + this.server.completeTurn() + this.push(ws, FOREIGN_TURN_DONE_EVENT) + } + finishTurnOnServer(): void { this.server.completeTurn() } diff --git a/browser_tests/tests/agent/agentSendRefusedByRunningTurn.spec.ts b/browser_tests/tests/agent/agentSendRefusedByRunningTurn.spec.ts index 5fc4c904c0b..1719876a10a 100644 --- a/browser_tests/tests/agent/agentSendRefusedByRunningTurn.spec.ts +++ b/browser_tests/tests/agent/agentSendRefusedByRunningTurn.spec.ts @@ -49,6 +49,7 @@ test.describe( 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() // The notice names the recovery; the raw server string described a // control the user is already looking at. await expect(turnLock.turnInProgressNotice).toBeVisible() @@ -57,6 +58,7 @@ test.describe( await test.step('stopping it unlocks the composer and the retry is accepted', async () => { await turnLock.stopButton.click() + turnLock.finishForeignTurn(live) await expect(turnLock.sendButton).toBeVisible({ timeout: 40_000 }) await turnLock.composer.fill('and now add a save node') From c450ab070afcc0cd3dbbdce7ff8b3d9310748a11 Mon Sep 17 00:00:00 2001 From: Christian Byrne Date: Fri, 2 Oct 2026 06:23:36 -0700 Subject: [PATCH 06/14] fix(agent): report failed turn reattachment honestly Addresses review feedback: https://github.com/Comfy-Org/ComfyUI_frontend/pull/19901#discussion_r4165984356 --- .../composables/agent/useAgentSession.test.ts | 10 +++++ .../composables/agent/useAgentSession.ts | 38 ++++++++++++++----- 2 files changed, 38 insertions(+), 10 deletions(-) diff --git a/src/workbench/extensions/agent/composables/agent/useAgentSession.test.ts b/src/workbench/extensions/agent/composables/agent/useAgentSession.test.ts index 87b6fe5b309..33d91423d76 100644 --- a/src/workbench/extensions/agent/composables/agent/useAgentSession.test.ts +++ b/src/workbench/extensions/agent/composables/agent/useAgentSession.test.ts @@ -706,6 +706,16 @@ describe('useAgentSession (v1 composition root)', () => { 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?.([ diff --git a/src/workbench/extensions/agent/composables/agent/useAgentSession.ts b/src/workbench/extensions/agent/composables/agent/useAgentSession.ts index ddf2db38eb9..46ddf75c41d 100644 --- a/src/workbench/extensions/agent/composables/agent/useAgentSession.ts +++ b/src/workbench/extensions/agent/composables/agent/useAgentSession.ts @@ -1044,9 +1044,8 @@ export function useAgentSession(deps: AgentSessionDeps) { * would be describing the Stop button the user is now looking at. The typed * copy names the recovery instead. */ - function sendFailureNotice(error: unknown): string { - if (parseTurnInProgress(error) !== undefined) - return i18n.global.t('agent.sendTurnInProgress') + function sendFailureNotice(error: unknown, reattached: boolean): string { + if (reattached) return i18n.global.t('agent.sendTurnInProgress') const message = error instanceof Error ? error.message : String(error) return `${i18n.global.t('agent.sendFailed')}: ${message}` } @@ -1054,7 +1053,8 @@ export function useAgentSession(deps: AgentSessionDeps) { function recordSendError( error: unknown, text: string, - accepted: boolean + accepted: boolean, + reattached = false ): void { const admission = parseAdmissionError(error) if (admission?.reason === 'no_funds') { @@ -1079,7 +1079,7 @@ export function useAgentSession(deps: AgentSessionDeps) { conversationStore.recordFailedSend( nextLocalErrorId(), text, - sendFailureNotice(error) + sendFailureNotice(error, reattached) ) const turnAccepted = accepted || isUnreadableAckFailure(error) reportError(error, { @@ -1094,6 +1094,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 @@ -1145,11 +1157,11 @@ export function useAgentSession(deps: AgentSessionDeps) { error: unknown, threadAtSend: string, generation: number - ): Promise { - if (parseTurnInProgress(error) === undefined) return + ): Promise { + if (parseTurnInProgress(error) === undefined) return false // 'new' is the sentinel for a thread the server had not minted yet, and a // thread that does not exist cannot already be busy. - if (threadAtSend === 'new') return + if (threadAtSend === 'new') return false const reattachGeneration = ++refusedTurnReattachGeneration const reattached = await Promise.race([ hydrateFromServer( @@ -1157,6 +1169,7 @@ export function useAgentSession(deps: AgentSessionDeps) { () => reattachGeneration === refusedTurnReattachGeneration && generation === loadGeneration && + ownedGeneration === sessionGeneration && conversationStore.threadId === threadAtSend ), new Promise((resolve) => setTimeout(resolve, RECONCILE_TIMEOUT_MS)) @@ -1164,6 +1177,7 @@ export function useAgentSession(deps: AgentSessionDeps) { if (reattachGeneration === refusedTurnReattachGeneration) refusedTurnReattachGeneration++ if (reattached === true) stopPendingActiveTurn() + return reattached === true && conversationStore.activeTurnId !== null } async function performSend( @@ -1214,9 +1228,13 @@ export function useAgentSession(deps: AgentSessionDeps) { // Before recordSendError, not after: the re-read rebuilds `messages` from // the server transcript, which would discard a local failed-send row // appended first. - await reattachRefusedTurn(error, threadAtSend, generation) + const reattached = await reattachRefusedTurn( + error, + threadAtSend, + generation + ) if (generation !== loadGeneration) return false - recordSendError(error, text, accepted) + recordCurrentSendError(error, text, accepted, reattached, threadAtSend) return false } } From d0e5a9fad9dcb6626b19a78f35f31b3b1a9c190a Mon Sep 17 00:00:00 2001 From: Christian Byrne Date: Fri, 2 Oct 2026 06:25:16 -0700 Subject: [PATCH 07/14] test(agent): share the turn-conflict runtime schema Addresses review feedback: https://github.com/Comfy-Org/ComfyUI_frontend/pull/19901#discussion_r4165912204 --- browser_tests/fixtures/agentTurnLockFixture.ts | 15 +++++---------- 1 file changed, 5 insertions(+), 10 deletions(-) diff --git a/browser_tests/fixtures/agentTurnLockFixture.ts b/browser_tests/fixtures/agentTurnLockFixture.ts index 0337c6d25a7..c01f27d0057 100644 --- a/browser_tests/fixtures/agentTurnLockFixture.ts +++ b/browser_tests/fixtures/agentTurnLockFixture.ts @@ -4,7 +4,6 @@ import type { Locator, Page, WebSocketRoute } from '@playwright/test' import type { AgentAnswerAccepted, AgentCancelAccepted, - AgentError, AgentMessage, AgentPendingAsk, AgentTurnAccepted @@ -17,6 +16,7 @@ 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 { zTurnInProgressError } from '@/workbench/extensions/agent/schemas/agentApiSchema' import { agentTest } from '@e2e/fixtures/agentPanelFixture' import { workflowSelectionTest } from '@e2e/fixtures/agentWorkflowSelectionFixture' @@ -51,16 +51,11 @@ export const TURN_IN_PROGRESS_MESSAGE = * "re-attached" — a fixture that sends the message alone cannot distinguish a * client that reads them from one that does not. * - * `AgentError` types only `error`, because the generated OpenAPI schema for this - * endpoint does not describe the conflict body; the intersection keeps the - * shared field checked while still sending what the service really sends. - * (Filed as an upstream hypothesis for the ingest schema.) + * The generated OpenAPI schema does not describe this endpoint's conflict + * body, so the fixture consumes the same runtime schema as the client until + * that upstream contract includes the response. */ -type TurnInProgressBody = AgentError & { - type: string - active_message_id: string - turn_id: string -} +type TurnInProgressBody = z.infer const TURN_IN_PROGRESS: TurnInProgressBody = { error: TURN_IN_PROGRESS_MESSAGE, From 2e55a649154a58a24ffe73cf097e0d450b3057cc Mon Sep 17 00:00:00 2001 From: GitHub Action Date: Fri, 2 Oct 2026 13:29:31 +0000 Subject: [PATCH 08/14] [automated] Apply ESLint and Oxfmt fixes --- browser_tests/fixtures/agentTurnLockFixture.ts | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/browser_tests/fixtures/agentTurnLockFixture.ts b/browser_tests/fixtures/agentTurnLockFixture.ts index c01f27d0057..75ab55288ad 100644 --- a/browser_tests/fixtures/agentTurnLockFixture.ts +++ b/browser_tests/fixtures/agentTurnLockFixture.ts @@ -15,8 +15,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 { zTurnInProgressError } 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' From 96401ec83175725e543e4500cd1a231f97a47deb Mon Sep 17 00:00:00 2001 From: Christian Byrne Date: Fri, 2 Oct 2026 07:16:14 -0700 Subject: [PATCH 09/14] fix: preserve stop through partial reattachment --- .../fixtures/agentTurnLockFixture.ts | 11 ++++++++ .../agentSendRefusedByRunningTurn.spec.ts | 2 ++ .../composables/agent/useAgentSession.test.ts | 10 +++++++- .../composables/agent/useAgentSession.ts | 25 +++++++++++-------- 4 files changed, 37 insertions(+), 11 deletions(-) diff --git a/browser_tests/fixtures/agentTurnLockFixture.ts b/browser_tests/fixtures/agentTurnLockFixture.ts index 75ab55288ad..c93cadccea6 100644 --- a/browser_tests/fixtures/agentTurnLockFixture.ts +++ b/browser_tests/fixtures/agentTurnLockFixture.ts @@ -675,6 +675,17 @@ export class AgentTurnLockHarness { 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('messages') + 1]).toBe(FOREIGN_TURN_ID) + } + finishTurnOnServer(): void { this.server.completeTurn() } diff --git a/browser_tests/tests/agent/agentSendRefusedByRunningTurn.spec.ts b/browser_tests/tests/agent/agentSendRefusedByRunningTurn.spec.ts index 1719876a10a..3ace4d8c16a 100644 --- a/browser_tests/tests/agent/agentSendRefusedByRunningTurn.spec.ts +++ b/browser_tests/tests/agent/agentSendRefusedByRunningTurn.spec.ts @@ -57,7 +57,9 @@ test.describe( }) 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: 40_000 }) diff --git a/src/workbench/extensions/agent/composables/agent/useAgentSession.test.ts b/src/workbench/extensions/agent/composables/agent/useAgentSession.test.ts index 33d91423d76..4035fec9b25 100644 --- a/src/workbench/extensions/agent/composables/agent/useAgentSession.test.ts +++ b/src/workbench/extensions/agent/composables/agent/useAgentSession.test.ts @@ -3219,7 +3219,15 @@ describe('useAgentSession (v1 composition root)', () => { ) }) const { source, emit } = fakeEvents() - const session = useAgentSession({ rest, events: source }) + 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')) diff --git a/src/workbench/extensions/agent/composables/agent/useAgentSession.ts b/src/workbench/extensions/agent/composables/agent/useAgentSession.ts index 46ddf75c41d..58e56226674 100644 --- a/src/workbench/extensions/agent/composables/agent/useAgentSession.ts +++ b/src/workbench/extensions/agent/composables/agent/useAgentSession.ts @@ -1158,25 +1158,30 @@ export function useAgentSession(deps: AgentSessionDeps) { threadAtSend: string, generation: number ): Promise { - if (parseTurnInProgress(error) === undefined) return false + const conflict = parseTurnInProgress(error) + if (conflict === undefined) return false // 'new' is the sentinel for a thread the server had not minted yet, and a // thread that does not exist cannot already be busy. if (threadAtSend === 'new') return false const reattachGeneration = ++refusedTurnReattachGeneration + const isCurrentReattachment = () => + reattachGeneration === refusedTurnReattachGeneration && + generation === loadGeneration && + ownedGeneration === sessionGeneration && + conversationStore.threadId === threadAtSend const reattached = await Promise.race([ - hydrateFromServer( - threadAtSend, - () => - reattachGeneration === refusedTurnReattachGeneration && - generation === loadGeneration && - ownedGeneration === sessionGeneration && - conversationStore.threadId === threadAtSend - ), + hydrateFromServer(threadAtSend, isCurrentReattachment), new Promise((resolve) => setTimeout(resolve, RECONCILE_TIMEOUT_MS)) ]) + const activeTurnId = conversationStore.activeTurnId + const adoptedActiveTurn = + isCurrentReattachment() && + activeTurnId !== null && + (conflict.activeMessageId === undefined || + activeTurnId === conflict.activeMessageId) if (reattachGeneration === refusedTurnReattachGeneration) refusedTurnReattachGeneration++ - if (reattached === true) stopPendingActiveTurn() + if (adoptedActiveTurn) stopPendingActiveTurn() return reattached === true && conversationStore.activeTurnId !== null } From eab5068bb1ac332a6149af52759f824954fd44e3 Mon Sep 17 00:00:00 2001 From: Christian Byrne Date: Fri, 2 Oct 2026 08:17:53 -0700 Subject: [PATCH 10/14] test(agent): assert the cancelled turn's thread, not just its message The cancel waiter checked the message id alone, so a Stop that sent the foreign turn id to the wrong thread satisfied it, and the route glob accepts any thread and completes the turn regardless. stopTurn reads the thread and the turn from the conversation store independently, so that pairing is the contract a reattachment can get wrong. --- browser_tests/fixtures/agentTurnLockFixture.ts | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/browser_tests/fixtures/agentTurnLockFixture.ts b/browser_tests/fixtures/agentTurnLockFixture.ts index c93cadccea6..f1a07272580 100644 --- a/browser_tests/fixtures/agentTurnLockFixture.ts +++ b/browser_tests/fixtures/agentTurnLockFixture.ts @@ -675,6 +675,13 @@ export class AgentTurnLockHarness { this.push(ws, FOREIGN_TURN_DONE_EVENT) } + /** + * Both ids, because the cancel contract is the pair: `stopTurn` reads the + * thread and the turn from the conversation store independently, so a + * reattachment that adopts the foreign turn while the thread is stale sends + * the right message id to the wrong thread. The route glob accepts any + * thread, so this waiter is what holds that half of the contract. + */ async waitForForeignTurnCancellation(): Promise { const request = await this.page.waitForRequest( '**/api/agent/threads/*/messages/*/cancel' @@ -683,6 +690,7 @@ export class AgentTurnLockHarness { .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) } From 1dc423dfe1c31e9290e5f9220e9811503ac331c6 Mon Sep 17 00:00:00 2001 From: Christian Byrne Date: Fri, 2 Oct 2026 09:43:03 -0700 Subject: [PATCH 11/14] fix(agent): report the re-attach the pending Stop acted on reattachRefusedTurn decided the pending Stop from adoptedActiveTurn but returned hydrateFromServer's result, and hydrateFromServer installs the transcript before awaiting the workflow restore. A restore that resolves false, or a bound that wins while it is still running, left the foreign turn adopted and Stop on screen next to the raw server string the typed copy exists to replace. The opposite mismatch was reachable too: an active row whose id is not the one the 409 named returned true while the pending Stop was skipped. One definition now answers both, and the notice assertion is added to the test that already runs restored() as false. --- .../composables/agent/useAgentSession.test.ts | 16 +++++--- .../composables/agent/useAgentSession.ts | 38 ++++++++----------- 2 files changed, 26 insertions(+), 28 deletions(-) diff --git a/src/workbench/extensions/agent/composables/agent/useAgentSession.test.ts b/src/workbench/extensions/agent/composables/agent/useAgentSession.test.ts index 4035fec9b25..9adf5b93ff9 100644 --- a/src/workbench/extensions/agent/composables/agent/useAgentSession.test.ts +++ b/src/workbench/extensions/agent/composables/agent/useAgentSession.test.ts @@ -598,11 +598,6 @@ describe('useAgentSession (v1 composition root)', () => { expect(conversation.activeTurnId).toBe('msg-1') }) - // FE-1998. Composer gating closes the reload route to a 409, but not a turn - // started from a second tab: this client has no local signal, so it offers - // Send and the post is refused. Before this change the refusal was terminal - // -- a raw server string, no stop control, and no way to tell a working turn - // from a dead one. it('re-attaches to the running turn when a send is refused with TURN_IN_PROGRESS', async () => { const conversation = useAgentConversationStore() const postMessage = vi @@ -622,7 +617,6 @@ describe('useAgentSession (v1 composition root)', () => { } ) ) - // The thread as the other client left it: turn 1 settled, turn 2 running. const rest = fakeRest({ postMessage, getMessages: vi.fn( @@ -3245,6 +3239,16 @@ describe('useAgentSession (v1 composition root)', () => { 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 () => { diff --git a/src/workbench/extensions/agent/composables/agent/useAgentSession.ts b/src/workbench/extensions/agent/composables/agent/useAgentSession.ts index 58e56226674..9d3c7128c63 100644 --- a/src/workbench/extensions/agent/composables/agent/useAgentSession.ts +++ b/src/workbench/extensions/agent/composables/agent/useAgentSession.ts @@ -369,21 +369,18 @@ function disownsWorkflow(error: unknown): boolean { * * The ids are read but deliberately not required (see `zTurnInProgressError`): * recognising the conflict is what lets this client re-read the thread and - * re-attach, and that re-read is keyed on the thread, not on the turn. The ids - * are returned so a caller can tell afterwards whether it adopted the turn the - * server actually named. + * re-attach, and that re-read is keyed on the thread, not on the turn. The + * active message id is returned so a caller can tell afterwards whether it + * adopted the turn the server actually named. */ function parseTurnInProgress( error: unknown -): { activeMessageId?: string; turnId?: string } | undefined { +): { activeMessageId?: string } | undefined { if (!(error instanceof AgentApiError) || error.status !== 409) return undefined const parsed = zTurnInProgressError.safeParse(error.body) if (!parsed.success) return undefined - return { - activeMessageId: parsed.data.active_message_id, - turnId: parsed.data.turn_id - } + return { activeMessageId: parsed.data.active_message_id } } export function useAgentSession(deps: AgentSessionDeps) { @@ -1035,15 +1032,6 @@ export function useAgentSession(deps: AgentSessionDeps) { if (pendingStop !== null) void stopTurn(pendingStop.method) } - /** - * The notice text for a send that failed for a reason admission does not own. - * - * A refused-because-busy send is the one failure whose cause is already on - * screen: `reattachRefusedTurn` has put the running turn back in the composer, - * so the raw server string ("a turn is already in progress for this thread") - * would be describing the Stop button the user is now looking at. The typed - * copy names the recovery instead. - */ function sendFailureNotice(error: unknown, reattached: boolean): string { if (reattached) return i18n.global.t('agent.sendTurnInProgress') const message = error instanceof Error ? error.message : String(error) @@ -1146,9 +1134,15 @@ export function useAgentSession(deps: AgentSessionDeps) { * Bounded on the same reasoning as `reconcileSnapshotTurn`: `performSend` * awaits this and the composer sits in `sending` until it returns, so an * unbounded await would let a slow workflow restore hold the one control the - * user needs. If the bound wins, the in-flight hydrate can still land later - * and replace `messages`, which costs the notice below but not the Stop - * control — the re-attach is the part that matters. + * user needs. If the bound wins before the transcript lands, the reattachment + * is invalidated and the late snapshot is discarded; if it wins after, the + * turn is already adopted and only the restore is outstanding. + * + * Returns whether the turn the server named is now this session's active turn, + * which is the single answer both the pending Stop and the caller's notice + * read. `hydrateFromServer` installs the snapshot before awaiting the workflow + * restore, so its own result says nothing about whether the re-attach + * happened. * * A failed re-read reports itself through `handleHistoryLoadError` and still * leaves the original refusal for the caller to record. @@ -1169,7 +1163,7 @@ export function useAgentSession(deps: AgentSessionDeps) { generation === loadGeneration && ownedGeneration === sessionGeneration && conversationStore.threadId === threadAtSend - const reattached = await Promise.race([ + await Promise.race([ hydrateFromServer(threadAtSend, isCurrentReattachment), new Promise((resolve) => setTimeout(resolve, RECONCILE_TIMEOUT_MS)) ]) @@ -1182,7 +1176,7 @@ export function useAgentSession(deps: AgentSessionDeps) { if (reattachGeneration === refusedTurnReattachGeneration) refusedTurnReattachGeneration++ if (adoptedActiveTurn) stopPendingActiveTurn() - return reattached === true && conversationStore.activeTurnId !== null + return adoptedActiveTurn } async function performSend( From 58039f85dbe5c986cc3261401967cf6a488d415f Mon Sep 17 00:00:00 2001 From: Christian Byrne Date: Fri, 2 Oct 2026 09:43:23 -0700 Subject: [PATCH 12/14] test(agent): type the 409 fixture body and give the spec a real budget AgentError & z.infer keeps `error` checked: zTurnInProgressError is .passthrough() and does not declare it, so the field was only typed through the index signature and `error: 123` compiled. The cloud project's test timeout is 15s and this spec had no describe.configure, so its 20s and 40s assertion timeouts could never take effect and the happy path already spends two thirds of that budget. The siblings that do comparable multi-turn work set 120s; this one now does too, which is what makes those assertion bounds mean anything. Drops the docblocks and inline comments that restate the code. --- .../fixtures/agentTurnLockFixture.ts | 31 ++++--------------- .../agentSendRefusedByRunningTurn.spec.ts | 26 ++-------------- 2 files changed, 8 insertions(+), 49 deletions(-) diff --git a/browser_tests/fixtures/agentTurnLockFixture.ts b/browser_tests/fixtures/agentTurnLockFixture.ts index f1a07272580..4c00f7e02c7 100644 --- a/browser_tests/fixtures/agentTurnLockFixture.ts +++ b/browser_tests/fixtures/agentTurnLockFixture.ts @@ -4,6 +4,7 @@ import type { Locator, Page, WebSocketRoute } from '@playwright/test' import type { AgentAnswerAccepted, AgentCancelAccepted, + AgentError, AgentMessage, AgentPendingAsk, AgentTurnAccepted @@ -31,33 +32,28 @@ 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' -/** The turn another client started on the same thread — see `lockThreadElsewhere`. */ 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 verbatim `error` message in `rejectTurnInProgress`'s HTTP 409 body. */ export const TURN_IN_PROGRESS_MESSAGE = 'a turn is already in progress for this thread' /** * The whole 409 body, not just its message. `rejectTurnInProgress` sends a * `type` discriminator plus the ids of the turn holding the thread (cloud - * #8275), and those three fields are the client's only route from "refused" to - * "re-attached" — a fixture that sends the message alone cannot distinguish a - * client that reads them from one that does not. + * #8275). The discriminator is what makes the client re-read the thread, and + * `active_message_id` is how it confirms it adopted the named turn; a fixture + * that sends the message alone exercises neither. * * The generated OpenAPI schema does not describe this endpoint's conflict * body, so the fixture consumes the same runtime schema as the client until * that upstream contract includes the response. */ -type TurnInProgressBody = z.infer +type TurnInProgressBody = AgentError & z.infer const TURN_IN_PROGRESS: TurnInProgressBody = { error: TURN_IN_PROGRESS_MESSAGE, @@ -190,12 +186,6 @@ function deferred(): Deferred { class TurnLockServer { private streaming = false private prompt = '' - /** - * The prompt of a turn started by a *different* client on this same thread, - * when one holds the lock. Tracked apart from `prompt` because this browser - * never posted it: it exists in the transcript and in the active-turn guard, - * and nowhere in this client's own state. - */ private foreignPrompt: string | undefined private rejected = 0 private posts = 0 @@ -418,8 +408,6 @@ class TurnLockServer { rejectPost(): TurnInProgressBody { this.rejected++ - // The ids name whichever turn actually holds the thread, as the server's - // own `ThreadActiveTurn` lookup does. return this.foreignPrompt === undefined ? TURN_IN_PROGRESS : { @@ -543,9 +531,7 @@ export class AgentTurnLockHarness { public readonly workingRow: Locator public readonly liveProgressRow: Locator public readonly userBubbles: Locator - /** The notice a send refused by the active-turn guard leaves behind. */ public readonly turnInProgressNotice: Locator - /** The raw server string the pre-fix client rendered instead. */ public readonly rawRefusalText: Locator private readonly entryButton: Locator private readonly dock: Locator @@ -698,11 +684,6 @@ export class AgentTurnLockHarness { this.server.completeTurn() } - /** - * Locks the thread from outside this browser, so the next send is refused by - * the server's active-turn guard while this client's composer still offers - * Send. See `TurnLockServer.lockThreadElsewhere`. - */ lockThreadFromAnotherClient(prompt: string): void { this.server.lockThreadElsewhere(prompt) } diff --git a/browser_tests/tests/agent/agentSendRefusedByRunningTurn.spec.ts b/browser_tests/tests/agent/agentSendRefusedByRunningTurn.spec.ts index 3ace4d8c16a..b4a5c327758 100644 --- a/browser_tests/tests/agent/agentSendRefusedByRunningTurn.spec.ts +++ b/browser_tests/tests/agent/agentSendRefusedByRunningTurn.spec.ts @@ -3,21 +3,8 @@ import { expect } from '@playwright/test' import { agentTurnLockTest as test } from '@e2e/fixtures/agentTurnLockFixture' test.use({ connectWebSocketToServer: false }) +test.describe.configure({ timeout: 120_000 }) -/** - * FE-1998, the half that composer gating does not reach. - * - * A turn this client can see renders Stop in place of Send, so it can never - * reach the server's active-turn guard. A turn started from a *second* tab, - * window or device can: this client's composer offers Send, the post is refused - * `409 TURN_IN_PROGRESS`, and before this change the user was left with the raw - * server string, no stop control, and no way to tell a working turn from a dead - * one — the dead end the ticket is named for. - * - * The server hands the client everything needed to recover (`type`, - * `active_message_id`, `turn_id`; cloud #8275). These assertions are about - * whether the panel acts on it. - */ test.describe( 'a send refused because another client holds the thread', { tag: ['@cloud', '@ui'] }, @@ -33,9 +20,6 @@ test.describe( await test.step('another client starts a turn on the same thread', async () => { turnLock.lockThreadFromAnotherClient('run it again') - // No local signal: nothing has told this panel the thread is busy, so - // Send is still the control on offer. That is what makes the next send - // reach the guard at all. await expect(turnLock.sendButton).toBeVisible() }) @@ -44,14 +28,10 @@ test.describe( await turnLock.sendButton.click() await expect.poll(() => turnLock.rejectedPosts()).toBe(1) - // The fix: the thread was re-read, the still-running turn adopted, and - // the composer's primary action is now the escape hatch. 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() - // The notice names the recovery; the raw server string described a - // control the user is already looking at. await expect(turnLock.turnInProgressNotice).toBeVisible() await expect(turnLock.rawRefusalText).toHaveCount(0) }) @@ -62,13 +42,11 @@ test.describe( await foreignTurnCancelled turnLock.finishForeignTurn(live) - await expect(turnLock.sendButton).toBeVisible({ timeout: 40_000 }) + 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) - // Still one: the retry was accepted, so no second refusal. This is the - // ticket's acceptance criterion — the next send succeeds with no reload. expect(turnLock.rejectedPosts()).toBe(1) }) }) From f7c62a2327005e0814052fd6cd03309f6b64a93f Mon Sep 17 00:00:00 2001 From: Alexander Brown Date: Tue, 6 Oct 2026 00:39:55 +0000 Subject: [PATCH 13/14] refactor(agent): drop narration and one-caller helpers from the re-attach path --- .../fixtures/agentTurnLockFixture.ts | 32 -------- .../agentSendRefusedByRunningTurn.spec.ts | 1 - .../composables/agent/useAgentSession.ts | 75 +++---------------- 3 files changed, 10 insertions(+), 98 deletions(-) diff --git a/browser_tests/fixtures/agentTurnLockFixture.ts b/browser_tests/fixtures/agentTurnLockFixture.ts index 4c00f7e02c7..6fc191088d7 100644 --- a/browser_tests/fixtures/agentTurnLockFixture.ts +++ b/browser_tests/fixtures/agentTurnLockFixture.ts @@ -38,21 +38,9 @@ const BACKGROUND_THREAD_TITLE = 'Audio workflow' const OTHER_THREAD_ID = '4ccb6603-4bbc-49e2-8b7d-b985230285e3' const OTHER_THREAD_TITLE = 'Earlier workflow' -/** The verbatim `error` message in `rejectTurnInProgress`'s HTTP 409 body. */ export const TURN_IN_PROGRESS_MESSAGE = 'a turn is already in progress for this thread' -/** - * The whole 409 body, not just its message. `rejectTurnInProgress` sends a - * `type` discriminator plus the ids of the turn holding the thread (cloud - * #8275). The discriminator is what makes the client re-read the thread, and - * `active_message_id` is how it confirms it adopted the named turn; a fixture - * that sends the message alone exercises neither. - * - * The generated OpenAPI schema does not describe this endpoint's conflict - * body, so the fixture consumes the same runtime schema as the client until - * that upstream contract includes the response. - */ type TurnInProgressBody = AgentError & z.infer const TURN_IN_PROGRESS: TurnInProgressBody = { @@ -392,15 +380,6 @@ class TurnLockServer { return { message_id: TURN_ID, thread_id: THREAD_ID } } - /** - * Locks the thread the way a second tab, window or device does: the assistant - * row goes `streaming` and the active-turn guard starts refusing posts, while - * this client posted nothing and holds no transport for it. - * - * This is the one route to a 409 that survives the composer gating — a client - * that can see the turn renders Stop and never offers Send — so it is what a - * spec has to use to exercise the refusal path at all. - */ lockThreadElsewhere(prompt: string): void { this.foreignPrompt = prompt this.streaming = true @@ -532,7 +511,6 @@ export class AgentTurnLockHarness { public readonly liveProgressRow: Locator public readonly userBubbles: Locator public readonly turnInProgressNotice: Locator - public readonly rawRefusalText: Locator private readonly entryButton: Locator private readonly dock: Locator private readonly agentPanel: AgentPanel @@ -589,9 +567,6 @@ export class AgentTurnLockHarness { enMessages.agent.sendTurnInProgress, { exact: true } ) - this.rawRefusalText = this.panel.getByText(TURN_IN_PROGRESS_MESSAGE, { - exact: false - }) this.entryButton = this.agentPanel.openButton this.dock = page.getByTestId('docked-agent-panel') } @@ -661,13 +636,6 @@ export class AgentTurnLockHarness { this.push(ws, FOREIGN_TURN_DONE_EVENT) } - /** - * Both ids, because the cancel contract is the pair: `stopTurn` reads the - * thread and the turn from the conversation store independently, so a - * reattachment that adopts the foreign turn while the thread is stale sends - * the right message id to the wrong thread. The route glob accepts any - * thread, so this waiter is what holds that half of the contract. - */ async waitForForeignTurnCancellation(): Promise { const request = await this.page.waitForRequest( '**/api/agent/threads/*/messages/*/cancel' diff --git a/browser_tests/tests/agent/agentSendRefusedByRunningTurn.spec.ts b/browser_tests/tests/agent/agentSendRefusedByRunningTurn.spec.ts index b4a5c327758..97e180ba4c2 100644 --- a/browser_tests/tests/agent/agentSendRefusedByRunningTurn.spec.ts +++ b/browser_tests/tests/agent/agentSendRefusedByRunningTurn.spec.ts @@ -33,7 +33,6 @@ test.describe( await expect(turnLock.liveProgressRow).toBeVisible() await expect(turnLock.panel.getByText('run it again')).toBeVisible() await expect(turnLock.turnInProgressNotice).toBeVisible() - await expect(turnLock.rawRefusalText).toHaveCount(0) }) await test.step('stopping it unlocks the composer and the retry is accepted', async () => { diff --git a/src/workbench/extensions/agent/composables/agent/useAgentSession.ts b/src/workbench/extensions/agent/composables/agent/useAgentSession.ts index 9d3c7128c63..37cb84bdcd5 100644 --- a/src/workbench/extensions/agent/composables/agent/useAgentSession.ts +++ b/src/workbench/extensions/agent/composables/agent/useAgentSession.ts @@ -362,25 +362,11 @@ function disownsWorkflow(error: unknown): boolean { ) } -/** - * The turn that holds the thread, when a send was refused because one is - * already running. `undefined` for anything else, including a 409 from another - * endpoint: only the message path carries the `TURN_IN_PROGRESS` discriminator. - * - * The ids are read but deliberately not required (see `zTurnInProgressError`): - * recognising the conflict is what lets this client re-read the thread and - * re-attach, and that re-read is keyed on the thread, not on the turn. The - * active message id is returned so a caller can tell afterwards whether it - * adopted the turn the server actually named. - */ -function parseTurnInProgress( - error: unknown -): { activeMessageId?: string } | undefined { +function parseTurnInProgress(error: unknown) { if (!(error instanceof AgentApiError) || error.status !== 409) return undefined const parsed = zTurnInProgressError.safeParse(error.body) - if (!parsed.success) return undefined - return { activeMessageId: parsed.data.active_message_id } + return parsed.success ? parsed.data : undefined } export function useAgentSession(deps: AgentSessionDeps) { @@ -1027,22 +1013,15 @@ export function useAgentSession(deps: AgentSessionDeps) { } function stopPendingActiveTurn(): void { - if (conversationStore.activeTurnId === null) return const pendingStop = consumeStopPendingAck() if (pendingStop !== null) void stopTurn(pendingStop.method) } - function sendFailureNotice(error: unknown, reattached: boolean): string { - if (reattached) return i18n.global.t('agent.sendTurnInProgress') - const message = error instanceof Error ? error.message : String(error) - return `${i18n.global.t('agent.sendFailed')}: ${message}` - } - function recordSendError( error: unknown, text: string, accepted: boolean, - reattached = false + reattached: boolean ): void { const admission = parseAdmissionError(error) if (admission?.reason === 'no_funds') { @@ -1064,10 +1043,13 @@ export function useAgentSession(deps: AgentSessionDeps) { ) return } + const message = error instanceof Error ? error.message : String(error) conversationStore.recordFailedSend( nextLocalErrorId(), text, - sendFailureNotice(error, reattached) + reattached + ? i18n.global.t('agent.sendTurnInProgress') + : `${i18n.global.t('agent.sendFailed')}: ${message}` ) const turnAccepted = accepted || isUnreadableAckFailure(error) reportError(error, { @@ -1116,47 +1098,13 @@ export function useAgentSession(deps: AgentSessionDeps) { if (rememberedWorkflowId === sent.id) rememberedWorkflowId = null } - /** - * FE-1998: re-attaches to the turn a `409 TURN_IN_PROGRESS` just named. - * - * The server's single-active-turn signal is a `status='streaming'` assistant - * row, durable in Postgres, so the thread stays locked until that row goes - * terminal — and a client that only reports the refusal leaves the user with - * no stop control and no way to tell a working turn from a dead one. Re-reading - * the thread is what adopts that row as the active turn, which is what renders - * Stop in place of Send; once the turn settles, the composer unlocks on its own. - * - * `hydrateFromServer` rather than a bare `getMessages` + `hydrate`: it is the - * one path that arms the hydration mailbox, so WS frames for the running turn - * that land during the GET are replayed instead of dropped. Reusing it also - * keeps one re-attach path rather than a second one that drifts. - * - * Bounded on the same reasoning as `reconcileSnapshotTurn`: `performSend` - * awaits this and the composer sits in `sending` until it returns, so an - * unbounded await would let a slow workflow restore hold the one control the - * user needs. If the bound wins before the transcript lands, the reattachment - * is invalidated and the late snapshot is discarded; if it wins after, the - * turn is already adopted and only the restore is outstanding. - * - * Returns whether the turn the server named is now this session's active turn, - * which is the single answer both the pending Stop and the caller's notice - * read. `hydrateFromServer` installs the snapshot before awaiting the workflow - * restore, so its own result says nothing about whether the re-attach - * happened. - * - * A failed re-read reports itself through `handleHistoryLoadError` and still - * leaves the original refusal for the caller to record. - */ async function reattachRefusedTurn( error: unknown, threadAtSend: string, generation: number ): Promise { const conflict = parseTurnInProgress(error) - if (conflict === undefined) return false - // 'new' is the sentinel for a thread the server had not minted yet, and a - // thread that does not exist cannot already be busy. - if (threadAtSend === 'new') return false + if (conflict === undefined || threadAtSend === 'new') return false const reattachGeneration = ++refusedTurnReattachGeneration const isCurrentReattachment = () => reattachGeneration === refusedTurnReattachGeneration && @@ -1171,8 +1119,8 @@ export function useAgentSession(deps: AgentSessionDeps) { const adoptedActiveTurn = isCurrentReattachment() && activeTurnId !== null && - (conflict.activeMessageId === undefined || - activeTurnId === conflict.activeMessageId) + (conflict.active_message_id === undefined || + activeTurnId === conflict.active_message_id) if (reattachGeneration === refusedTurnReattachGeneration) refusedTurnReattachGeneration++ if (adoptedActiveTurn) stopPendingActiveTurn() @@ -1224,9 +1172,6 @@ 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 - // Before recordSendError, not after: the re-read rebuilds `messages` from - // the server transcript, which would discard a local failed-send row - // appended first. const reattached = await reattachRefusedTurn( error, threadAtSend, From ac9f26076b2a273467633f26146b7067b4befc79 Mon Sep 17 00:00:00 2001 From: Alexander Brown Date: Tue, 6 Oct 2026 00:40:40 +0000 Subject: [PATCH 14/14] test(agent): pin the deleted-thread re-read guard --- .../composables/agent/useAgentSession.test.ts | 38 +++++++++++++++++-- 1 file changed, 34 insertions(+), 4 deletions(-) diff --git a/src/workbench/extensions/agent/composables/agent/useAgentSession.test.ts b/src/workbench/extensions/agent/composables/agent/useAgentSession.test.ts index 9adf5b93ff9..e5086916f82 100644 --- a/src/workbench/extensions/agent/composables/agent/useAgentSession.test.ts +++ b/src/workbench/extensions/agent/composables/agent/useAgentSession.test.ts @@ -646,7 +646,6 @@ describe('useAgentSession (v1 composition root)', () => { expect(await session.sendMessage('and now add a save node')).toBe(false) await vi.waitFor(() => expect(session.isStreaming.value).toBe(true)) - // The turn the server named, not the one this client had started. expect(conversation.activeTurnId).toBe('msg-2') expect(session.entries.value.at(-1)).toMatchObject({ role: 'assistant', @@ -733,9 +732,40 @@ describe('useAgentSession (v1 composition root)', () => { } }) - // The discriminator is load-bearing: a 409 from any other endpoint, or one - // whose body this client cannot read, must stay an ordinary send failure - // rather than trigger a re-read of a thread that is not actually busy. + 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<