From e076a683a3cf5b551ef5e28443c302b30a76de80 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Thu, 5 Nov 2026 10:25:23 -0800 Subject: [PATCH] fix(acp): permission prompts from an agent's own work wait for you (#38488) * fix(acp): permission prompts from an agent's own work wait for you A permission or question that an ACP agent (OMP, Grok, OpenCode, others) asks during work it started itself, such as picking up a finished background job, was answered "cancelled" at once and never shown. It now shows as a card, raises the needs-input alert, and waits for the answer, unless Stop, a steer or teardown cuts it short. While OMP refuses a sent message as busy, a request from its own turn now appears at thread level instead of being cancelled, so it never lands in the held message's turn. Tracked in STA-13625. * fix(acp): keep later requests askable after a Stop, and honor the agent's withdrawal A Stop or a card's Cancel left the chat refusing every later permission request until the session ended; the stop now covers only the work it interrupted. A request the agent withdraws with $/cancel_request now withdraws its card. Cancel on a card from the agent's own work reaches the agent even when no message is running. * test(acp): narrow approval rows before reading their resolution * fix(acp): a live request's card outlives its turn instead of being cancelled with it Requests group with the active turn again, as before. A permission or question the agent is still waiting on now stays pending and answerable when its turn ends, is replaced, or is settled by the host; only the person's answer, the agent's withdrawal, Stop, a steer or the session ending settles it. Settled requests are pruned at turn end. Stop covers only Orca's running message, so later requests from the agent's own work can still ask. Cancel on a card with no running turn now reaches the host from desktop and phone for every agent, and a question the agent withdraws before its card opens no longer leaves a stuck card. * fix(acp): never strand a live request without a card, and scope Cancel to it A request the agent still waits on now always gets an answerable card, even when its turn settled before the card was written, and answering it releases the timeline's hold. Cancel on a card from an agent's own turn refuses further requests from that turn until it ends. Desktop never turns Cancel on a card into a whole-chat Stop on hosts that can't take a card cancel. * fix(acp): a new message is never covered by a Stop of the agent's earlier turn * fix(native-chat): a card's Cancel with no running turn passes the RPC schema The cancel params required a turn whenever a card was named, so Cancel on a card from an agent's own work (and Pi's turnless card Cancel) was rejected before it reached the host. A background-task cancel still names its turn. * test(rpc): a card with no running turn cancels by itself --- .../mobile-structured-agent-session-cancel.ts | 11 +- ...uctured-agent-session-unnamed-stop.test.ts | 15 +++ src/main/acp/acp-incoming-requests.ts | 17 ++- src/main/acp/acp-json-rpc-peer.ts | 4 + src/main/acp/acp-session-runtime.test.ts | 19 ++-- src/main/acp/acp-session-runtime.ts | 15 +-- src/main/acp/acp-structured-acquire.ts | 9 +- .../acp/acp-structured-busy-prompt.test.ts | 67 +++++++++++- src/main/acp/acp-structured-prompts.ts | 14 +-- .../acp-structured-request-admission.test.ts | 100 ++++++++++++++++-- .../acp-structured-session-adapter.test.ts | 15 --- .../acp/acp-structured-session-adapter.ts | 2 +- src/main/acp/acp-structured-stop.ts | 8 +- src/main/acp/acp-structured-turns.ts | 22 +++- src/main/acp/acp-timeline-dialect.test.ts | 15 ++- src/main/acp/acp-timeline-recovery.test.ts | 10 +- src/main/acp/acp-timeline-requests.ts | 4 +- ...der-timeline-assembler-attribution.test.ts | 26 +++++ .../provider-timeline-assembler-stop.test.ts | 20 ++++ .../provider-timeline-decision.ts | 2 +- .../provider-timeline-event.ts | 8 +- .../provider-timeline-item-decisions.ts | 10 +- .../provider-timeline-settlement.ts | 6 +- .../provider-timeline-state.ts | 31 +++++- .../provider-timeline-turn-decisions.ts | 24 ++++- .../NativeChatStructuredSession.tsx | 2 +- .../native-chat-structured-stop-controls.ts | 8 +- ...tructured-agent-session-prompt-response.ts | 4 + ...ed-agent-session-question-answers.test.tsx | 19 ++++ ...uctured-agent-session-agent-params.test.ts | 12 +++ .../structured-agent-session-params.ts | 5 +- 31 files changed, 424 insertions(+), 100 deletions(-) diff --git a/mobile/src/session/mobile-structured-agent-session-cancel.ts b/mobile/src/session/mobile-structured-agent-session-cancel.ts index 1be14e7e8ee..84fd37c1ff8 100644 --- a/mobile/src/session/mobile-structured-agent-session-cancel.ts +++ b/mobile/src/session/mobile-structured-agent-session-cancel.ts @@ -43,11 +43,18 @@ export async function requestMobileStructuredAgentSessionCancel(args: { const prompt = args.prompt && args.promptCancelSupported === true ? args.prompt : undefined // Conversation Stop also covers un-echoed sends; card Cancel must still name its originating turn. const unnamed = args.hostStopsConversation === true && !args.prompt - if (!client || !sessionId || !enabled || current.fence === null || (!turnId && !unnamed)) { + // A card with no running turn names only itself; the host routes it. + if ( + !client || + !sessionId || + !enabled || + current.fence === null || + (!turnId && !unnamed && !prompt) + ) { onSendError('Stop not sent') return false } - const fields = unnamed ? {} : { turnId, ...(prompt ? { prompt } : {}) } + const fields = unnamed ? {} : { ...(turnId ? { turnId } : {}), ...(prompt ? { prompt } : {}) } // Mint an id for each Stop so the ledger cannot replay an earlier press instead of stopping work. const fence = current.fence const stop = () => sendStop({ client, sessionId, fence, fields, onSendError }) diff --git a/mobile/src/session/mobile-structured-agent-session-unnamed-stop.test.ts b/mobile/src/session/mobile-structured-agent-session-unnamed-stop.test.ts index a24e6b72352..5c61ede2260 100644 --- a/mobile/src/session/mobile-structured-agent-session-unnamed-stop.test.ts +++ b/mobile/src/session/mobile-structured-agent-session-unnamed-stop.test.ts @@ -76,6 +76,21 @@ describe('phone Stop against a host that stops what the chat has in flight', () expect(sent[0]).toMatchObject({ turnId: 'turn-1', prompt }) }) + it('cancels a card with no running turn by naming only the card', async () => { + const sent: SentParams[] = [] + const prompt = { itemId: 'prompt-1', expectedRevision: 2 } + const { pressed, onSendError } = press({ + sent, + turnId: null, + hostStopsConversation: true, + prompt + }) + expect(await pressed).toBe(true) + expect(onSendError).not.toHaveBeenCalled() + expect(sent[0]).toMatchObject({ prompt }) + expect(sent[0]).not.toHaveProperty('turnId') + }) + it("keeps naming a card's turn when the host cannot take the card's identity", async () => { const sent: SentParams[] = [] const prompt = { itemId: 'prompt-1', expectedRevision: 2 } diff --git a/src/main/acp/acp-incoming-requests.ts b/src/main/acp/acp-incoming-requests.ts index b542724d418..7264ee3e2bf 100644 --- a/src/main/acp/acp-incoming-requests.ts +++ b/src/main/acp/acp-incoming-requests.ts @@ -1,6 +1,9 @@ +import { z } from 'zod' import { AcpRpcError } from './acp-errors' import type { AcpJsonRpcMessage, AcpPeerHandlers } from './acp-json-rpc-peer' +const cancelRequestSchema = z.looseObject({ requestId: z.union([z.string(), z.number()]) }) + type OpenRequest = { controller: AbortController abandon: () => void @@ -29,15 +32,23 @@ export class AcpIncomingRequests { } // Handlers own cancellation replies; do not preempt an answer still being saved. - cancel(): void { - for (const request of this.open.values()) { - if (!request.cancelled) { + cancel(id?: string | number): void { + for (const [openId, request] of this.open) { + if ((id === undefined || id === openId) && !request.cancelled) { request.cancelled = true request.controller.abort(new AcpRpcError(-32800, 'Request cancelled')) } } } + /** The agent withdrew one request with `$/cancel_request`; its handler still answers it. */ + cancelRequested(params: unknown): void { + const parsed = cancelRequestSchema.safeParse(params) + if (parsed.success) { + this.cancel(parsed.data.requestId) + } + } + handle(id: string | number | null, method: string, params: unknown): void { if (this.open.has(id)) { this.diagnose('Ignored duplicate ACP incoming request id') diff --git a/src/main/acp/acp-json-rpc-peer.ts b/src/main/acp/acp-json-rpc-peer.ts index 09defd97acd..0caac23d113 100644 --- a/src/main/acp/acp-json-rpc-peer.ts +++ b/src/main/acp/acp-json-rpc-peer.ts @@ -294,6 +294,10 @@ export class AcpJsonRpcPeer { this.incoming.handle(frame.id, frame.method, frame.params) return } + if (frame.method === '$/cancel_request') { + this.incoming.cancelRequested(frame.params) + return + } try { this.handlers.onNotification?.(frame.method, frame.params) } catch (error) { diff --git a/src/main/acp/acp-session-runtime.test.ts b/src/main/acp/acp-session-runtime.test.ts index 5f3e7287e52..c601238bccf 100644 --- a/src/main/acp/acp-session-runtime.test.ts +++ b/src/main/acp/acp-session-runtime.test.ts @@ -98,12 +98,16 @@ describe('ACP session runtime', () => { } ) - it('denies autonomous permissions between attempts and allows the admitted retry to ask', async () => { + it('lets the agent ask from its own turn while a busy refusal holds the prompt', async () => { + const asked: string[] = [] const { runtime, agent } = fixture( {}, { retryBusyPrompts: true, - onPermission: () => ({ outcome: { outcome: 'selected', optionId: 'allow' } }) + onPermission: (request) => { + asked.push(request.toolCall.toolCallId) + return { outcome: { outcome: 'selected', optionId: 'allow' } } + } } ) await runtime.start(startOptions) @@ -125,21 +129,16 @@ describe('ACP session runtime', () => { const pending = runtime.prompt([...textPrompt]) await tick() expect(agent.frames.find((frame) => frame.id === 'same-chunk')).toMatchObject({ - result: { outcome: { outcome: 'cancelled' } } - }) - expect(await agent.request('waiting', 'session/request_permission', permission)).toMatchObject({ - result: { outcome: { outcome: 'cancelled' } } + result: { outcome: { outcome: 'selected', optionId: 'allow' } } }) agent.on('session/prompt', (frame) => { - void agent.request('admitted', 'session/request_permission', permission).then((response) => { - expect(response).toMatchObject({ - result: { outcome: { outcome: 'selected', optionId: 'allow' } } - }) + void agent.request('admitted', 'session/request_permission', permission).then(() => { agent.reply(frame, { stopReason: 'end_turn' }) }) }) await vi.advanceTimersByTimeAsync(1_000) expect(await pending).toEqual({ stopReason: 'end_turn' }) + expect(asked).toHaveLength(2) }) it.each(['close', 'EOF'] as const)('ends delayed busy recovery on %s', async (action) => { diff --git a/src/main/acp/acp-session-runtime.ts b/src/main/acp/acp-session-runtime.ts index ce008176a24..cf1dd4287ce 100644 --- a/src/main/acp/acp-session-runtime.ts +++ b/src/main/acp/acp-session-runtime.ts @@ -276,22 +276,11 @@ export class AcpSessionRuntime { if (!request) { throw new AcpRpcError(-32602, 'Invalid ACP permission request') } - // The caller decides whether agent-initiated turns may request permission. + // Only the started session asks the caller; the caller decides who can answer. if (request.sessionId !== this.started?.sessionId) { return { outcome: { outcome: 'cancelled' } } } - // Defer the decision so a preceding refusal in the same chunk takes effect. - return answerAcpPermission( - request, - context, - (request, context) => - this.prompts.waitingToRetry - ? { outcome: { outcome: 'cancelled' } } - : (this.options.onPermission?.(request, context) ?? { - outcome: { outcome: 'cancelled' } - }), - diagnose - ) + return answerAcpPermission(request, context, this.options.onPermission, diagnose) } private diagnose(message: string): void { diff --git a/src/main/acp/acp-structured-acquire.ts b/src/main/acp/acp-structured-acquire.ts index 6e8c6a3594b..fcc63fa6728 100644 --- a/src/main/acp/acp-structured-acquire.ts +++ b/src/main/acp/acp-structured-acquire.ts @@ -73,14 +73,9 @@ export async function acquireAcpStructuredSession(input: { history: AcpLoadHistory | null } = { lane: null, reattaching: false, history: null } const options = new AcpStructuredOptions(launch.spec.dialect) - // Agent-initiated turns cannot open interactive requests; settled request content may still show. const prompts = new AcpStructuredPrompts( () => slot.lane, - () => isAcpReadySession(session) && session.turns?.acceptsRequests === true, - () => - isAcpReadySession(session) && - (session.turns.acceptsRequests || - (!session.turns.running && !session.turns.stopped && session.lane.openTurnId !== null)) + () => isAcpReadySession(session) && session.turns?.acceptsRequests === true ) const early: (() => void)[] = [] const whenLane = (deliver: () => void): void => { @@ -108,7 +103,7 @@ export async function acquireAcpStructuredSession(input: { ...(spec.signIn ? { signIn: spec.signIn } : {}), onPermission: (request, context) => { if (!isAcpReadySession(session) || !session.turns?.acceptsRequests) { - // No interactive prompt remains during Stop, steering or an agent-initiated turn. + // Nobody can answer during Stop, a steer or teardown. return { outcome: { outcome: 'cancelled' } } } // Do not auto-approve questions or permissions enforced by the agent's own mode. diff --git a/src/main/acp/acp-structured-busy-prompt.test.ts b/src/main/acp/acp-structured-busy-prompt.test.ts index f6b3fc973c0..f39f7415564 100644 --- a/src/main/acp/acp-structured-busy-prompt.test.ts +++ b/src/main/acp/acp-structured-busy-prompt.test.ts @@ -9,8 +9,9 @@ import { HOST_TEST_SESSION as SESSION, hostTestAttachParams } from '../native-chat/agent-session-wire/structured-agent-session-host-test-data' +import { CancelParams } from '../../shared/rpc-contract/structured-agent-session-params' import { acpLaunchSpecFor } from './acp-launch-specs' -import { waitFor } from './acp-structured-adapter.test-support' +import { PROVIDER_SESSION, waitFor } from './acp-structured-adapter.test-support' import { message, openHostRig, stop } from './acp-structured-host.test-support' let opened: Awaited> | undefined @@ -119,3 +120,67 @@ it.each(['Stop', 'close'] as const)( ) } ) + +const ownPermission = (toolCallId: string) => ({ + sessionId: PROVIDER_SESSION, + toolCall: { toolCallId, title: 'orca worktree set --unread' }, + options: [{ optionId: 'allow', name: 'Allow', kind: 'allow_once' }] +}) + +async function pendingCard(host: Awaited>['host']) { + return waitFor(async () => { + await host.flushStreamedEvents(SESSION) + const found = (await host.history({ sessionId: SESSION, direction: 'tail' })).page.items.find( + (row) => row.body.kind === 'approval' + ) + expect(found?.body).toMatchObject({ resolution: { state: 'pending' } }) + return found! + }) +} + +it('keeps OMP own permission answerable after the held message fails', async () => { + const { rig, host, send, fence } = await fixture() + await send('first') + await rig.frame('session/prompt') + await rig.settle() + const { agent } = rig.child() + const asked = agent.request('own-turn', 'session/request_permission', ownPermission('own-call')) + const card = await pendingCard(host) + agent.on('session/prompt', (frame) => agent.fail(frame, -32603, 'model unavailable')) + await vi.advanceTimersByTimeAsync(1_000) + await waitFor(async () => { + await host.flushStreamedEvents(SESSION) + const turns = ( + await host.history({ sessionId: SESSION, direction: 'tail' }) + ).page.items.flatMap((row) => readAgentJournalTurn(row.body) ?? []) + expect(turns).toMatchObject([{ state: 'completed' }]) + }) + expect((await pendingCard(host)).itemId).toBe(card.itemId) + await rig.adapter.answerPrompt({ + sessionId: SESSION, + itemId: card.itemId, + kind: 'approval', + response: { kind: 'option', optionId: 'allow' }, + fence: fence(), + commit: async () => {} + }) + expect(await asked).toMatchObject({ + result: { outcome: { outcome: 'selected', optionId: 'allow' } } + }) +}) + +it('Cancel on a card from OMP own work, with no message running, cancels that request', async () => { + const { rig, host } = await fixture() + const asked = rig + .child() + .agent.request('own-cancel', 'session/request_permission', ownPermission('own-cancel')) + const card = await pendingCard(host) + const fields = { prompt: { itemId: card.itemId, expectedRevision: card.revision } } + // Clients send exactly this over RPC, so it must pass the wire schema. + const params = CancelParams.parse({ + envelope: envelope('agentSession.cancel', fields), + ...fields + }) + expect(await host.cancel(CALLER, params)).toMatchObject({ ok: true, value: { cancelled: true } }) + expect(await asked).toMatchObject({ result: { outcome: { outcome: 'cancelled' } } }) +}) diff --git a/src/main/acp/acp-structured-prompts.ts b/src/main/acp/acp-structured-prompts.ts index a6c1a0290cb..db49bd564a2 100644 --- a/src/main/acp/acp-structured-prompts.ts +++ b/src/main/acp/acp-structured-prompts.ts @@ -27,10 +27,8 @@ export class AcpStructuredPrompts { constructor( private readonly lane: () => AcpStructuredLane | null, - /** Allows interactive requests for the current turn. */ - private readonly admits: () => boolean, - /** Allows content from requests that settled immediately. */ - private readonly shows: () => boolean + /** Allows interactive requests and content from requests that settled immediately. */ + private readonly admits: () => boolean ) {} get size(): number { @@ -44,13 +42,13 @@ export class AcpStructuredPrompts { } const translated = lane.translator.request(method, params, context.id) if (translated.settled) { - if (this.shows()) { + if (this.admits()) { lane.apply(translated.events) } return Promise.resolve(translated.settled.reply) } - if (translated.presentation && !this.admits()) { - // Reply cancelled without opening a card when the turn can no longer ask. + if (translated.presentation && (!this.admits() || context.signal.aborted)) { + // Reply cancelled without opening a card when nobody can answer. return Promise.resolve(translated.presentation.reply(null)) } lane.apply(translated.events) @@ -117,6 +115,8 @@ export class AcpStructuredPrompts { throw error } entry.settle(reply) + // Release the timeline's hold; withdrawal keeps the committed answer. + this.lane()?.apply([{ type: 'request.withdrawn', request: entry.key }]) if (entry.permission && entry.signal.aborted) { // Protocol cancellation already replied while the permission answer was being saved. throw new Error(`the agent stopped waiting for the answer to ${input.itemId}`) diff --git a/src/main/acp/acp-structured-request-admission.test.ts b/src/main/acp/acp-structured-request-admission.test.ts index 61045a63d7f..722ef64858d 100644 --- a/src/main/acp/acp-structured-request-admission.test.ts +++ b/src/main/acp/acp-structured-request-admission.test.ts @@ -7,7 +7,8 @@ import { openAcpAdapterRig, PROVIDER_SESSION, replyChunk, - sendHello + sendHello, + waitFor } from './acp-structured-adapter.test-support' afterEach(async () => { @@ -89,15 +90,13 @@ describe('Grok requests and the turn they belong to', () => { expect(await cards()).toEqual([]) }) - it('refuses a question during a turn Grok began itself, opening no card, yet shows its plan', async () => { + it('shows a question during a turn Grok began itself, and its plan', async () => { const rig = await openAcpAdapterRig() await rig.acquire() const { agent } = rig.child() agent.notify('session/update', replyChunk('task-completed-background-1', 'Build finished; now')) await rig.settle() - expect(await agent.request(7, 'x.ai/ask_user_question', question('call-7'))).toMatchObject({ - result: { outcome: 'cancelled' } - }) + void agent.request(7, 'x.ai/ask_user_question', question('call-7')) expect( await agent.request(8, 'x.ai/exit_plan_mode', { sessionId: PROVIDER_SESSION, @@ -107,19 +106,102 @@ describe('Grok requests and the turn they belong to', () => { ).toMatchObject({ result: { outcome: 'abandoned' } }) await rig.settle() const rows = await rig.rig.rows() - expect(rows.filter((row) => row.body.kind === 'question')).toEqual([]) + expect(rows.filter((row) => row.body.kind === 'question').map((row) => row.body)).toMatchObject( + [{ resolution: { state: 'pending' } }] + ) expect(rows.map((row) => row.body)).toContainEqual( expect.objectContaining({ kind: 'status', presentation: 'plan-document', text: '# Plan' }) ) }) - it('refuses a question when no turn is open', async () => { + it('waits for the answer to a permission the agent asks with no prompt of Orca running', async () => { const rig = await openAcpAdapterRig() await rig.acquire() const { agent } = rig.child() - expect(await agent.request(5, 'x.ai/ask_user_question', question('call-5'))).toMatchObject({ + const asked = agent.request(5, 'session/request_permission', permission('call-5')) + const card = await waitFor(async () => { + const found = (await rig.rig.rows()).find((row) => row.body.kind === 'approval') + expect(found?.body).toMatchObject({ resolution: { state: 'pending' } }) + return found! + }) + await rig.adapter.answerPrompt({ + sessionId: SESSION, + itemId: card.itemId, + kind: 'approval', + response: { kind: 'option', optionId: 'allow-once' }, + fence: 1, + commit: async () => {} + }) + expect(await asked).toMatchObject({ + result: { outcome: { outcome: 'selected', optionId: 'allow-once' } } + }) + }) + + it('shows a later permission after a Stop cancelled an earlier card', async () => { + const rig = await openAcpAdapterRig() + await rig.acquire() + const { agent } = rig.child() + const first = agent.request(9, 'session/request_permission', permission('call-9')) + await waitFor(async () => expect(await cards()).toHaveLength(1)) + await rig.adapter.cancelTurn({ sessionId: SESSION, fence: 1 }) + expect(await first).toMatchObject({ result: { outcome: { outcome: 'cancelled' } } }) + await sendHello(rig, 'next') + await rig.frame('session/prompt') + void agent.request(10, 'session/request_permission', permission('call-10')) + await waitFor(async () => + expect((await cards()).map((row) => row.body)).toMatchObject([ + { resolution: { state: 'cancelled' } }, + { resolution: { state: 'pending' } } + ]) + ) + + async function cards() { + return (await rig.rig.rows()).filter((row) => row.body.kind === 'approval') + } + }) + + it('withdraws the card when the agent cancels its own permission request', async () => { + const rig = await openAcpAdapterRig() + await rig.acquire() + const { agent } = rig.child() + const asked = agent.request(11, 'session/request_permission', permission('call-11')) + const approvals = async () => + (await rig.rig.rows()).filter((row) => row.body.kind === 'approval') + await waitFor(async () => expect(await approvals()).toHaveLength(1)) + agent.notify('$/cancel_request', { requestId: 11 }) + expect(await asked).toMatchObject({ result: { outcome: { outcome: 'cancelled' } } }) + await waitFor(async () => + expect((await approvals()).map((row) => row.body)).toMatchObject([ + { resolution: { state: 'cancelled' } } + ]) + ) + }) + + it('refuses further questions from a turn Grok began itself once its card was cancelled', async () => { + const rig = await openAcpAdapterRig() + await rig.acquire() + const { agent } = rig.child() + agent.notify('session/update', replyChunk('task-completed-background-1', 'Build finished; now')) + await rig.settle() + const first = agent.request(12, 'x.ai/ask_user_question', question('call-12')) + await waitFor(async () => + expect((await rig.rig.rows()).some((row) => row.body.kind === 'question')).toBe(true) + ) + await rig.adapter.cancelTurn({ sessionId: SESSION, fence: 1 }) + expect(await first).toMatchObject({ result: { outcome: 'cancelled' } }) + expect(await agent.request(13, 'x.ai/ask_user_question', question('call-13'))).toMatchObject({ result: { outcome: 'cancelled' } }) - expect((await rig.rig.rows()).filter((row) => row.body.kind === 'question')).toEqual([]) + await sendHello(rig, 'next') + await rig.frame('session/prompt') + void agent.request(14, 'x.ai/ask_user_question', question('call-14')) + await waitFor(async () => + expect( + (await rig.rig.rows()).filter((row) => row.body.kind === 'question').map((row) => row.body) + ).toMatchObject([ + { resolution: { state: 'cancelled' } }, + { resolution: { state: 'pending' } } + ]) + ) }) }) diff --git a/src/main/acp/acp-structured-session-adapter.test.ts b/src/main/acp/acp-structured-session-adapter.test.ts index d4ace0da6c4..27964496140 100644 --- a/src/main/acp/acp-structured-session-adapter.test.ts +++ b/src/main/acp/acp-structured-session-adapter.test.ts @@ -603,21 +603,6 @@ describe('ACP structured session adapter: approvals', () => { }) ).rejects.toThrow(/no longer waiting/) }) - - it('answers cancelled a permission Grok asks during a turn it began itself, with no card', async () => { - const rig = await openAcpAdapterRig() - await rig.acquire() - const { agent } = rig.child() - agent.notify('session/update', chunk('task-completed-background-1', 'Build finished; now')) - await rig.settle() - const reply = await agent.request(3, 'session/request_permission', { - sessionId: PROVIDER_SESSION, - toolCall: { toolCallId: 'call-1', title: 'Write file' }, - options: [{ optionId: 'allow-once', name: 'Allow', kind: 'allow_once' }] - }) - expect(reply).toMatchObject({ result: { outcome: { outcome: 'cancelled' } } }) - expect((await rig.rig.rows()).some((row) => row.body.kind === 'approval')).toBe(false) - }) }) describe('ACP structured session adapter: requests a Stop cancels', () => { diff --git a/src/main/acp/acp-structured-session-adapter.ts b/src/main/acp/acp-structured-session-adapter.ts index 3a3378cc19a..60e3ad798df 100644 --- a/src/main/acp/acp-structured-session-adapter.ts +++ b/src/main/acp/acp-structured-session-adapter.ts @@ -230,7 +230,7 @@ export class AcpStructuredSessionAdapter implements SessionAdapter { if (input.turnId !== undefined && liveTurnId !== null && input.turnId !== liveTurnId) { return { cancelled: false, refusal: { turnNotRunning: true } } } - if (!session.turns.running && session.lane.openTurnId === null && !session.turns.holdsSteers) { + if (!stop.acpStopHasWork(session)) { return { cancelled: false, refusal: { turnNotRunning: true } } } // The host waits for turn completion or grace expiry, never for the cancel write. diff --git a/src/main/acp/acp-structured-stop.ts b/src/main/acp/acp-structured-stop.ts index b519768016e..fa169a1caea 100644 --- a/src/main/acp/acp-structured-stop.ts +++ b/src/main/acp/acp-structured-stop.ts @@ -9,10 +9,16 @@ function acpTurnInFlight(session: AcpStoppableSession): boolean { return session.turns.running || session.lane.openTurnId !== null } +/** Stop reaches a running turn, held steers, or requests from the agent's own work. */ +export function acpStopHasWork(session: AcpStoppableSession): boolean { + return acpTurnInFlight(session) || session.turns.holdsSteers || session.prompts.size > 0 +} + /** Do not await the cancel write; grace expiry must still close an unresponsive child. */ export function interruptAcpTurn(session: AcpStoppableSession): void { session.turns.stop(Date.now()) - if (!acpTurnInFlight(session)) { + // An open request means the agent's own work is waiting on the person. + if (!acpTurnInFlight(session) && session.prompts.size === 0) { return } session.prompts.withdrawAll() diff --git a/src/main/acp/acp-structured-turns.ts b/src/main/acp/acp-structured-turns.ts index 38f5070820b..0a571a68be7 100644 --- a/src/main/acp/acp-structured-turns.ts +++ b/src/main/acp/acp-structured-turns.ts @@ -60,12 +60,11 @@ export class AcpStructuredTurns { return this.active !== null } - /** Interactive requests require an active Orca prompt with no Stop or steer cancellation. */ + /** Interactive requests wait for the person, including in turns the agent began itself, unless Stop or a steer cuts them short. */ get acceptsRequests(): boolean { return ( this.stopAt === null && - this.active !== null && - this.steerCancelled !== this.active && + (this.active === null || this.steerCancelled !== this.active) && !this.ended ) } @@ -87,8 +86,19 @@ export class AcpStructuredTurns { return this.stopAt } + /** A Stop covers the running prompt or the agent's own open turn; later work may ask again. */ stop(at: number): boolean { - this.stopAt ??= at + const agentTurn = this.active ? null : this.deps.lane.openTurnId + if ((this.active || agentTurn !== null) && this.stopAt === null) { + this.stopAt = at + if (agentTurn !== null) { + void this.deps.lane.whenTurnLeaves(agentTurn).then(() => { + if (this.stopAt === at) { + this.stopAt = null + } + }) + } + } return this.withdrawSteers() } @@ -139,6 +149,7 @@ export class AcpStructuredTurns { requestedAt: this.deps.now() } lane.beginCommand(command) + this.stopAt = null try { const opened = lane.translator.openPrompt( send.clientMessageId, @@ -193,6 +204,8 @@ export class AcpStructuredTurns { private start(send: Send): void { const { lane } = this.deps + // A new message is not covered by a Stop of the agent's own earlier turn. + this.stopAt = null this.active = send const opened = lane.translator.openPrompt(send.clientMessageId, send.requestedAt) lane.apply(opened.events) @@ -268,6 +281,7 @@ export class AcpStructuredTurns { private finish(send: Send): void { if (this.active === send) { this.active = null + this.stopAt = null } if (this.steerCancelled === send) { this.steerCancelled = null diff --git a/src/main/acp/acp-timeline-dialect.test.ts b/src/main/acp/acp-timeline-dialect.test.ts index 8be8071cb9c..cc21425f079 100644 --- a/src/main/acp/acp-timeline-dialect.test.ts +++ b/src/main/acp/acp-timeline-dialect.test.ts @@ -65,7 +65,7 @@ describe('ACP dialect request and turn boundaries', () => { expect(await rig.turns()).toHaveLength(1) }) - it('preserves provider permission labels, validates selected ids, and cancels unanswered rows on turn end', async () => { + it('preserves provider permission labels, validates selected ids, and keeps unanswered rows until withdrawn', async () => { const { rig, translator, apply } = await dialectRig() apply(translator.openPrompt('send-1', 1000).events) apply( @@ -103,9 +103,16 @@ describe('ACP dialect request and turn boundaries', () => { 'offered option' ) apply(translator.promptResult('send-1', { stopReason: 'cancelled' }, 1200)) - expect((await rig.rows()).find((row) => row.body.kind === 'approval')?.body).toMatchObject({ - resolution: { state: 'cancelled' } - }) + const approval = async () => + (await rig.rows()).find((row) => row.body.kind === 'approval')?.body + expect(await approval()).toMatchObject({ resolution: { state: 'pending' } }) + const opened = request.events.find((event) => event.type === 'request.open') + apply( + opened?.type === 'request.open' + ? [{ type: 'request.withdrawn', request: opened.request }] + : [] + ) + expect(await approval()).toMatchObject({ resolution: { state: 'cancelled' } }) }) it('encodes labels and free text under the question text, validates grouped choices, and settles a plan without a gate', async () => { diff --git a/src/main/acp/acp-timeline-recovery.test.ts b/src/main/acp/acp-timeline-recovery.test.ts index 07dfa305dfa..8eb982a7900 100644 --- a/src/main/acp/acp-timeline-recovery.test.ts +++ b/src/main/acp/acp-timeline-recovery.test.ts @@ -189,7 +189,15 @@ describe('ACP reviewed traffic and recovery', () => { 'late-permission' ).events ) - expect(await f.rig.rows()).toEqual(before) + const toolTurn = before.find((row) => row.body.kind === 'tool-call')?.turnScope + expect(toolTurn).toMatchObject({ kind: 'turn' }) + const added = (await f.rig.rows()).filter( + (row) => !before.some((earlier) => earlier.itemId === row.itemId) + ) + // The agent still waits on it, so its card stays answerable in the tool's ended turn. + expect(added.map((row) => [row.body, row.turnScope])).toMatchObject([ + [{ kind: 'approval', resolution: { state: 'pending' } }, toolTurn] + ]) } ) diff --git a/src/main/acp/acp-timeline-requests.ts b/src/main/acp/acp-timeline-requests.ts index 4c5570485d9..3e6c3bad52d 100644 --- a/src/main/acp/acp-timeline-requests.ts +++ b/src/main/acp/acp-timeline-requests.ts @@ -122,7 +122,9 @@ export function translateAcpRequest( type: 'request.open', request: `${method}:${JSON.stringify(id)}`, body: presentation.body, - join + join, + // The live exchange ends only by answer or withdrawal, not with the turn that shows it. + outlivesTurn: true } ] } diff --git a/src/main/native-chat/agent-session-timeline/provider-timeline-assembler-attribution.test.ts b/src/main/native-chat/agent-session-timeline/provider-timeline-assembler-attribution.test.ts index ea7cc36a825..443253103bc 100644 --- a/src/main/native-chat/agent-session-timeline/provider-timeline-assembler-attribution.test.ts +++ b/src/main/native-chat/agent-session-timeline/provider-timeline-assembler-attribution.test.ts @@ -106,6 +106,32 @@ describe('a request key reused in another turn', () => { }) }) + it('still shows a live request whose turn another writer ended while the open was queued', async () => { + const rig = await answeredInAnEarlierTurn() + const { assembler, bind } = openUnboundProviderTimelineAssembler(rig.journal) + const join = { turn: 't2' } + assembler.apply({ + type: 'request.open', + request: 'p1', + body: pendingApproval, + join, + outlivesTurn: true + }) + const running = await rig.turn('t2') + if (!running) { + throw new Error('t2 is running') + } + await rig.journal.appendItem( + identityOf(providerTurnItemId('t2')), + agentJournalTurnBody({ ...running, state: 'interrupted', completedAt: 4_000 }), + { fence: 1, turnScope: { kind: 'thread' } } + ) + await bind() + expect( + (await rig.row(providerItemId('request', 'p1', { generation: 'gen-unbound' })))?.body + ).toMatchObject({ resolution: { state: 'pending' } }) + }) + it('asks nothing in a turn another writer ended while the open was queued', async () => { const rig = await answeredInAnEarlierTurn() const { assembler, bind } = openUnboundProviderTimelineAssembler(rig.journal) diff --git a/src/main/native-chat/agent-session-timeline/provider-timeline-assembler-stop.test.ts b/src/main/native-chat/agent-session-timeline/provider-timeline-assembler-stop.test.ts index d6ab097b5f2..05ba59207fe 100644 --- a/src/main/native-chat/agent-session-timeline/provider-timeline-assembler-stop.test.ts +++ b/src/main/native-chat/agent-session-timeline/provider-timeline-assembler-stop.test.ts @@ -80,6 +80,26 @@ describe('a turn another writer settled stops its text and prompts; its tools wa expect(await rig.turn('t1')).toMatchObject({ state: 'interrupted', completedAt: 2_100 }) }) + it('leaves a request that outlives its turn pending through settlement until it is withdrawn', async () => { + const rig = await openProviderTimelineRig() + rig.assembler.apply({ type: 'turn.open', turn: 't1', at: 1_000 }) + rig.assembler.apply({ + type: 'request.open', + request: '7', + body: pendingApproval, + outlivesTurn: true + }) + await stop(rig, 't1') + rig.assembler.apply({ type: 'activity', text: 'Thinking' }) + rig.assembler.apply({ type: 'turn.end', turn: 't1', at: 2_100, state: 'interrupted' }) + rig.assembler.flush() + const request = async () => (await rig.row(providerItemId('request', '7')))?.body + expect(await request()).toMatchObject({ resolution: { state: 'pending' } }) + rig.assembler.apply({ type: 'request.withdrawn', request: '7' }) + rig.assembler.flush() + expect(await request()).toMatchObject({ resolution: { state: 'cancelled' } }) + }) + it('cancels the prompt even when the next event writes nothing, and leaves the tool running', async () => { const rig = await openProviderTimelineRig() rig.assembler.apply({ type: 'turn.open', turn: 't1', at: 1_000 }) diff --git a/src/main/native-chat/agent-session-timeline/provider-timeline-decision.ts b/src/main/native-chat/agent-session-timeline/provider-timeline-decision.ts index d0e27555f97..d2ceed029c9 100644 --- a/src/main/native-chat/agent-session-timeline/provider-timeline-decision.ts +++ b/src/main/native-chat/agent-session-timeline/provider-timeline-decision.ts @@ -99,7 +99,7 @@ export function decideProviderTimelineEvent( case 'turn.end': return decideTurnEnd(input, event) case 'turn.settled': - return decideTurnSettled(event) + return decideTurnSettled(input, event) case 'item.open': case 'item.update': case 'item.close': diff --git a/src/main/native-chat/agent-session-timeline/provider-timeline-event.ts b/src/main/native-chat/agent-session-timeline/provider-timeline-event.ts index 082acaaad22..3be641b5d96 100644 --- a/src/main/native-chat/agent-session-timeline/provider-timeline-event.ts +++ b/src/main/native-chat/agent-session-timeline/provider-timeline-event.ts @@ -73,7 +73,13 @@ export type ProviderTimelineEvent = Joined) /** Final text overrides accumulated deltas; join must match the same item. */ | ({ type: 'text.close'; item: ProviderTimelineTextItem; text?: string } & Joined) - | ({ type: 'request.open'; request: string; body: ProviderTimelineRequestBody } & Produced & + /** A request that outlives its turn stays pending until answered or withdrawn. */ + | ({ + type: 'request.open' + request: string + body: ProviderTimelineRequestBody + outlivesTurn?: true + } & Produced & Joined) /** Withdraw only unanswered requests. */ | { type: 'request.withdrawn'; request: string } diff --git a/src/main/native-chat/agent-session-timeline/provider-timeline-item-decisions.ts b/src/main/native-chat/agent-session-timeline/provider-timeline-item-decisions.ts index 437bdc2636b..a91ca127e65 100644 --- a/src/main/native-chat/agent-session-timeline/provider-timeline-item-decisions.ts +++ b/src/main/native-chat/agent-session-timeline/provider-timeline-item-decisions.ts @@ -128,7 +128,8 @@ export function decideRequest( const opened: ProviderTimelineOpenItem = { kind: 'request', row: null, - turnItemId: turn + turnItemId: turn, + ...(event.outlivesTurn ? { outlivesTurn: true as const } : {}) } return { writes: [ @@ -143,7 +144,12 @@ export function decideRequest( // Reused request IDs need new incarnations; never overwrite existing rows. const row = context.rows.nextRequest(event.request, at) opened.row = row - if (turn !== null && providerTimelineTurnRowState(at, turn) === 'settled') { + // A live request outliving its turn still needs its card. + if ( + turn !== null && + !event.outlivesTurn && + providerTimelineTurnRowState(at, turn) === 'settled' + ) { return null } return { identity: row.identity, body: event.body } diff --git a/src/main/native-chat/agent-session-timeline/provider-timeline-settlement.ts b/src/main/native-chat/agent-session-timeline/provider-timeline-settlement.ts index e92b5be041a..8a95a3b2752 100644 --- a/src/main/native-chat/agent-session-timeline/provider-timeline-settlement.ts +++ b/src/main/native-chat/agent-session-timeline/provider-timeline-settlement.ts @@ -72,10 +72,14 @@ export type ProviderTimelineSettlementEnding = { export function providerTimelineSettlement( journal: StructuredAgentSessionTransitionJournal, scope: ProviderTimelineSettlementScope, - ending?: ProviderTimelineSettlementEnding + ending?: ProviderTimelineSettlementEnding, + keep?: ReadonlySet ): JournalLifecycleMutationInput[] { const mutations: JournalLifecycleMutationInput[] = [] journal.visitItemsWithLinkage((itemId, _sequence, body, attribution) => { + if (keep?.has(itemId)) { + return + } const turnScope = attribution.turnScope ?? AGENT_JOURNAL_THREAD_SCOPE const historical = scope === 'session' && journal.item(itemId) if (historical && isHistoricalProviderTimelineItem(historical, (key) => journal.item(key))) { diff --git a/src/main/native-chat/agent-session-timeline/provider-timeline-state.ts b/src/main/native-chat/agent-session-timeline/provider-timeline-state.ts index b37bf555a76..e3b5219909f 100644 --- a/src/main/native-chat/agent-session-timeline/provider-timeline-state.ts +++ b/src/main/native-chat/agent-session-timeline/provider-timeline-state.ts @@ -35,6 +35,8 @@ export type ProviderTimelineOpenItem = { /** Request rows are chosen later by their queued write. */ row: ProviderTimelineRowId | null turnItemId: string | null + /** Requests whose live exchange settles them, not their turn's end. */ + outlivesTurn?: true } export class ProviderTimelineState { @@ -111,7 +113,7 @@ export class ProviderTimelineState { } } - endTurn(turn: ProviderTimelineTurnRef): void { + endTurn(turn: ProviderTimelineTurnRef, journal?: StructuredAgentSessionTransitionJournal): void { if (this.open?.itemId === turn.itemId) { this.open = null this.latest = turn @@ -119,7 +121,10 @@ export class ProviderTimelineState { if (this.stopped?.itemId === turn.itemId) { this.stopped = null } - this.forget(turn, () => true) + this.forget(turn, (entry) => !entry.outlivesTurn) + if (journal) { + this.forgetSettledRequests(journal) + } for (const [key, turnItemId] of this.closedItems) { if (turnItemId === turn.itemId) { this.closedItems.delete(key) @@ -134,7 +139,27 @@ export class ProviderTimelineState { this.latest = turn this.stopped = turn } - this.forget(turn, (entry) => entry.kind === 'request') + this.forget(turn, (entry) => entry.kind === 'request' && !entry.outlivesTurn) + } + + /** Kept requests leave once answered or withdrawn, so the kept set stays live-sized. */ + private forgetSettledRequests(journal: StructuredAgentSessionTransitionJournal): void { + for (const [key, entry] of this.items) { + if (entry.outlivesTurn && this.settledInJournal(key, journal)) { + this.items.delete(key) + } + } + } + + /** Rows a turn's end must leave pending. */ + liveRequestRows(turnItemId: string): Set { + const rows = new Set() + for (const entry of this.items.values()) { + if (entry.outlivesTurn && entry.row && entry.turnItemId === turnItemId) { + rows.add(entry.row.itemId) + } + } + return rows } endSession(): void { diff --git a/src/main/native-chat/agent-session-timeline/provider-timeline-turn-decisions.ts b/src/main/native-chat/agent-session-timeline/provider-timeline-turn-decisions.ts index 60275f3f595..95674d4c9f4 100644 --- a/src/main/native-chat/agent-session-timeline/provider-timeline-turn-decisions.ts +++ b/src/main/native-chat/agent-session-timeline/provider-timeline-turn-decisions.ts @@ -81,7 +81,8 @@ export function decideTurnOpen( { turns: [superseded], end: { state: 'interrupted', completedAt: event.at, outcome: 'superseded' } - } + }, + state.liveRequestRows(superseded.itemId) ) } } @@ -98,7 +99,7 @@ export function decideTurnOpen( ], commit: (next) => { if (superseded) { - next.endTurn(superseded) + next.endTurn(superseded, journal ?? undefined) } if (pending) { next.inputs = next.inputs.filter((each) => each !== pending) @@ -140,14 +141,20 @@ export function decideTurnEnd( settle: { what: 'turn-end', resolve: (journal) => - providerTimelineSettlement(journal, { turnItemId: turn.itemId }, { turns: [turn], end }) + providerTimelineSettlement( + journal, + { turnItemId: turn.itemId }, + { turns: [turn], end }, + state.liveRequestRows(turn.itemId) + ) }, - commit: (next) => next.endTurn(turn) + commit: (next) => next.endTurn(turn, journal ?? undefined) } } /** External settlement ends text/prompts; calls wait for provider end, a newer turn or session end. */ export function decideTurnSettled( + input: ProviderTimelineDecisionInput, event: Extract ): ProviderTimelineDecision { const { turn } = event @@ -155,7 +162,14 @@ export function decideTurnSettled( ends: { turnItemId: turn.itemId, current: true }, settle: { what: 'turn-settled', - resolve: (journal) => providerTimelineSettlement(journal, { turnItemId: turn.itemId }) + // Live requests end by their own answer or withdrawal, which Stop sends first. + resolve: (journal) => + providerTimelineSettlement( + journal, + { turnItemId: turn.itemId }, + undefined, + input.state.liveRequestRows(turn.itemId) + ) }, commit: (next) => next.stopTurn(turn) } diff --git a/src/renderer/src/components/native-chat/NativeChatStructuredSession.tsx b/src/renderer/src/components/native-chat/NativeChatStructuredSession.tsx index 82151fa6f22..214bb156690 100644 --- a/src/renderer/src/components/native-chat/NativeChatStructuredSession.tsx +++ b/src/renderer/src/components/native-chat/NativeChatStructuredSession.tsx @@ -185,7 +185,7 @@ export function NativeChatStructuredSession(props: Omit cancelStructuredPrompt(controller, prompt, props.agent) + const cancelPrompt = () => cancelStructuredPrompt(controller, prompt) const rootInput = useNativeChatRootInputRouting({ tabId: props.tabId, rootRef, diff --git a/src/renderer/src/components/native-chat/native-chat-structured-stop-controls.ts b/src/renderer/src/components/native-chat/native-chat-structured-stop-controls.ts index 077c9e33fb2..f5d1376ae05 100644 --- a/src/renderer/src/components/native-chat/native-chat-structured-stop-controls.ts +++ b/src/renderer/src/components/native-chat/native-chat-structured-stop-controls.ts @@ -1,7 +1,6 @@ import { agentStopDisplayStatus } from '../../../../shared/agent-status/lifecycle/agent-stop-display-status' import type { useStructuredAgentSession } from './use-structured-agent-session' import type { NativeChatAfterStopSend } from './native-chat-composer-target' -import type { AgentType } from '../../../../shared/agent-status/contracts/agent-status-types' type StopController = Pick< ReturnType, @@ -44,13 +43,12 @@ export function nativeChatStructuredStopControls( type Session = ReturnType -/** Cancel the shown prompt at its revision; without a turn only Pi takes the cancel. */ +/** Cancel the shown prompt at its revision; the host routes a card with no running turn. */ export function cancelStructuredPrompt( controller: Pick, - prompt: Session['prompts'][number] | null, - agent: AgentType + prompt: Session['prompts'][number] | null ): void { - if (prompt && (controller.turnId || agent === 'pi')) { + if (prompt) { void controller.cancel(controller.turnId ?? undefined, { itemId: prompt.itemId, expectedRevision: prompt.revision diff --git a/src/renderer/src/components/native-chat/structured-agent-session-prompt-response.ts b/src/renderer/src/components/native-chat/structured-agent-session-prompt-response.ts index afef507eb4a..b84932d5625 100644 --- a/src/renderer/src/components/native-chat/structured-agent-session-prompt-response.ts +++ b/src/renderer/src/components/native-chat/structured-agent-session-prompt-response.ts @@ -57,6 +57,10 @@ export async function cancelStructuredAgentSessionPrompt( const promptTarget = prompt && { ...prompt } const promptSupported = promptTarget !== undefined && (await supportsStructuredAgentSessionPromptCancel(action.target)) + // Naming neither the card nor a turn would stop the whole chat. + if (promptTarget && !promptSupported && !turnId) { + return null + } return action.mutate('agentSession.cancel', 'agentSession.cancel', { ...(turnId ? { turnId } : {}), ...(promptSupported ? { prompt: promptTarget } : {}) diff --git a/src/renderer/src/components/native-chat/use-structured-agent-session-question-answers.test.tsx b/src/renderer/src/components/native-chat/use-structured-agent-session-question-answers.test.tsx index 2cf509f12b9..1a9cd9fb184 100644 --- a/src/renderer/src/components/native-chat/use-structured-agent-session-question-answers.test.tsx +++ b/src/renderer/src/components/native-chat/use-structured-agent-session-question-answers.test.tsx @@ -158,6 +158,25 @@ describe('desktop structured prompt answers', () => { expect(mocks.toast).not.toHaveBeenCalled() }) + it.each([true, false])( + 'cancels a card with no running turn by naming only it, or not at all (host takes cards: %s)', + async (supported) => { + mocks.promptCancelSupported.mockResolvedValue(supported) + const view = renderHook(() => + useStructuredAgentSession({ sessionId: 'session-1', target, agent: 'omp', isVisible: true }) + ) + const prompt = { itemId: approval.itemId, expectedRevision: approval.revision } + await act(async () => { + await view.result.current.cancel(undefined, prompt) + }) + const calls = mocks.call.mock.calls.filter(([, method]) => method === 'agentSession.cancel') + expect(calls.map(([, , params]) => params)).toEqual( + supported ? [expect.objectContaining({ prompt })] : [] + ) + expect(calls.some(([, , params]) => 'turnId' in params)).toBe(false) + } + ) + it('packs the answer into an option id for a host that predates structured answers', async () => { mocks.questionAnswersSupported.mockResolvedValue(false) const { result } = renderHook(() => diff --git a/src/shared/rpc-contract/structured-agent-session-agent-params.test.ts b/src/shared/rpc-contract/structured-agent-session-agent-params.test.ts index 4f2ef999f3c..2de9d171c99 100644 --- a/src/shared/rpc-contract/structured-agent-session-agent-params.test.ts +++ b/src/shared/rpc-contract/structured-agent-session-agent-params.test.ts @@ -1,6 +1,7 @@ import { describe, expect, it } from 'vitest' import { AttachParams, + CancelParams, CreateIntentParams, CreateSupportParams, ModelCatalogParams, @@ -113,4 +114,15 @@ describe('structured agent params', () => { expect(AttachParams.safeParse(attach).success).toBe(true) expect(AttachParams.safeParse({ ...attach, provider: 'grok' }).success).toBe(false) }) + + it('lets a card with no running turn cancel by itself, while background-task Stop still names its turn', () => { + const prompt = { itemId: 'request-1', expectedRevision: 2 } + expect(CancelParams.safeParse({ envelope: ENVELOPE, prompt }).success).toBe(true) + expect(CancelParams.safeParse({ envelope: ENVELOPE, turnId: 'turn-1', prompt }).success).toBe( + true + ) + expect(CancelParams.safeParse({ envelope: ENVELOPE, scope: 'background-tasks' }).success).toBe( + false + ) + }) }) diff --git a/src/shared/rpc-contract/structured-agent-session-params.ts b/src/shared/rpc-contract/structured-agent-session-params.ts index 8cd096ede62..805e8a4a6fd 100644 --- a/src/shared/rpc-contract/structured-agent-session-params.ts +++ b/src/shared/rpc-contract/structured-agent-session-params.ts @@ -175,8 +175,9 @@ export const CancelParams = z if (value.prompt !== undefined && value.scope === 'background-tasks') { ctx.addIssue({ code: 'custom', message: 'A prompt cannot use background-task scope' }) } - if (value.turnId === undefined && (value.prompt !== undefined || value.scope !== undefined)) { - ctx.addIssue({ code: 'custom', message: 'A prompt or background-task cancel names its turn' }) + // A card with no running turn names only itself; the host routes it. + if (value.turnId === undefined && value.scope !== undefined) { + ctx.addIssue({ code: 'custom', message: 'A background-task cancel names its turn' }) } })