mirror of
https://github.com/stablyai/orca.git
synced 2026-11-19 04:23:57 +00:00
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
This commit is contained in:
@@ -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 })
|
||||
|
||||
@@ -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 }
|
||||
|
||||
@@ -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')
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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) => {
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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<ReturnType<typeof openHostRig>> | 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<ReturnType<typeof fixture>>['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' } } })
|
||||
})
|
||||
|
||||
@@ -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}`)
|
||||
|
||||
@@ -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' } }
|
||||
])
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -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', () => {
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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 () => {
|
||||
|
||||
@@ -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]
|
||||
])
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
@@ -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
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
+26
@@ -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)
|
||||
|
||||
@@ -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 })
|
||||
|
||||
@@ -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':
|
||||
|
||||
@@ -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 }
|
||||
|
||||
@@ -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 }
|
||||
|
||||
@@ -72,10 +72,14 @@ export type ProviderTimelineSettlementEnding = {
|
||||
export function providerTimelineSettlement(
|
||||
journal: StructuredAgentSessionTransitionJournal,
|
||||
scope: ProviderTimelineSettlementScope,
|
||||
ending?: ProviderTimelineSettlementEnding
|
||||
ending?: ProviderTimelineSettlementEnding,
|
||||
keep?: ReadonlySet<string>
|
||||
): 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))) {
|
||||
|
||||
@@ -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<string> {
|
||||
const rows = new Set<string>()
|
||||
for (const entry of this.items.values()) {
|
||||
if (entry.outlivesTurn && entry.row && entry.turnItemId === turnItemId) {
|
||||
rows.add(entry.row.itemId)
|
||||
}
|
||||
}
|
||||
return rows
|
||||
}
|
||||
|
||||
endSession(): void {
|
||||
|
||||
@@ -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<ProviderTimelineDecidedEvent, { type: 'turn.settled' }>
|
||||
): 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)
|
||||
}
|
||||
|
||||
@@ -185,7 +185,7 @@ export function NativeChatStructuredSession(props: Omit<NativeChatStructuredView
|
||||
const install = useNativeChatInstallSlot(props, agentLabel, installLayout)
|
||||
const canMention = composerShown && install.unavailableHint === undefined
|
||||
const approval = prompt?.body.kind === 'approval' ? chatApprovalFromJournal(prompt.body) : null
|
||||
const cancelPrompt = () => cancelStructuredPrompt(controller, prompt, props.agent)
|
||||
const cancelPrompt = () => cancelStructuredPrompt(controller, prompt)
|
||||
const rootInput = useNativeChatRootInputRouting({
|
||||
tabId: props.tabId,
|
||||
rootRef,
|
||||
|
||||
@@ -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<typeof useStructuredAgentSession>,
|
||||
@@ -44,13 +43,12 @@ export function nativeChatStructuredStopControls(
|
||||
|
||||
type Session = ReturnType<typeof useStructuredAgentSession>
|
||||
|
||||
/** 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<Session, 'cancel' | 'turnId'>,
|
||||
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
|
||||
|
||||
@@ -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 } : {})
|
||||
|
||||
+19
@@ -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(() =>
|
||||
|
||||
@@ -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
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -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' })
|
||||
}
|
||||
})
|
||||
|
||||
|
||||
Reference in New Issue
Block a user