diff --git a/docs/buzz-help.md b/docs/buzz-help.md index 1243f9254c..4d60833ab0 100644 --- a/docs/buzz-help.md +++ b/docs/buzz-help.md @@ -1094,7 +1094,7 @@ available rather than silently discarding it. agent’s activity or stop an individual request. Expand recorded work for its activity controls. Stop availability depends on the agent type. - For native Claude and Codex, Stop also cancels pending plugin tool calls + For native Claude, Codex and Goose, Stop also cancels pending plugin tool calls that use the host signal. It cannot undo a write already sent. - Agent-to-agent messages stay in the conversation as collapsed history after work finishes or you reopen a thread. Expand them to read dispatches, handoffs, diff --git a/docs/plugin-architecture.md b/docs/plugin-architecture.md index a838debacb..cf05158fd9 100644 --- a/docs/plugin-architecture.md +++ b/docs/plugin-architecture.md @@ -897,8 +897,11 @@ lowercase and cannot be a Buzz tool's. The tool is removed when its plugin's scope ends, so safe mode removes installed plugins' tools. `call(client, context, args)` can read `client.signal`, a host-owned -`AbortSignal` captured for that call. Native Claude and Codex cancel it on -Stop. Keep that exact signal across waits. Pass it to work that supports +`AbortSignal` captured for that call. Native Claude, Codex and Goose cancel it on +Stop. Goose captures the current ACP work burst: steers share its signal, and +Stop, eligible final-message settlement, normal completion, failure or session close abort +it. Calls before a Goose session starts work or while idle receive an aborted +signal; agent retirement also aborts captured calls. Keep that exact signal across waits. Pass it to work that supports cancellation, then call `signal.throwIfAborted()` before an external write. A new turn does not restore a canceled call. The supplied client also checks cancellation before it publishes. Stop cannot undo a write already sent. diff --git a/src/bundled/goose/goose.test.ts b/src/bundled/goose/goose.test.ts index 31a7f358db..99dd7a4468 100644 --- a/src/bundled/goose/goose.test.ts +++ b/src/bundled/goose/goose.test.ts @@ -326,11 +326,11 @@ describe("GooseProcess", () => { const session = await open(); session.conversation = "channel/root"; const response = await process.mcp(session.id, "tools/list"); - expect(tools).toHaveBeenCalledWith("channel/root", { - id: 1, - method: "tools/list", - params: {}, - }); + expect(tools).toHaveBeenCalledWith( + "channel/root", + { id: 1, method: "tools/list", params: {} }, + expect.objectContaining({ aborted: true }), + ); // goose matches the reply to its request by the id it sent. expect(response).toEqual({ jsonrpc: "2.0", diff --git a/src/bundled/goose/runtime.test.ts b/src/bundled/goose/runtime.test.ts index 300b730be5..7606f0f3c6 100644 --- a/src/bundled/goose/runtime.test.ts +++ b/src/bundled/goose/runtime.test.ts @@ -1,4 +1,5 @@ import { describe, expect, it, vi } from "vitest"; +import type { AddedTool } from "../../buzz-mcp/session-tools"; import type { BuzzClient, Memories } from "../../buzz-mcp/client"; import { callTool, memoryVersion } from "../../buzz-mcp/tools"; import { createAgentMemories } from "../../features/agents/memory"; @@ -66,6 +67,7 @@ function setup( options: Readonly<{ /** Channels that are the owner's own Solo chats; the owner is the viewer. */ solo?: Set; + added?: readonly AddedTool[]; hold?: boolean; reply?: string; thread?: readonly EventData[]; @@ -189,7 +191,7 @@ function setup( () => relay, core, storage, - undefined, + () => options.added ?? [], options.repositories, ); const published: { kind: number; content: string; tags: string[][] }[] = []; @@ -855,6 +857,158 @@ describe("GooseRuntime", () => { expect(process?.cancelled).toEqual([process?.turns[0]?.sessionId]); }); + it("lists added tools and cancels a held write across Stop without reviving it in the next turn", async () => { + let signal: AbortSignal | undefined; + let enter!: () => void; + let release!: () => void; + const entered = new Promise((resolve) => { + enter = resolve; + }); + const held = new Promise((resolve) => { + release = resolve; + }); + const write = vi.fn(); + const tool: AddedTool = { + name: "fixture_save", + description: "Fixture write", + inputSchema: { type: "object" }, + call: async (client) => { + signal = client.signal; + if (!signal) throw new Error("Cancellation required"); + signal.throwIfAborted(); + enter(); + await held; + signal.throwIfAborted(); + write(); + return "saved"; + }, + }; + const f = setup({ hold: true, scope: "channel", added: [tool] }); + const interruptible = vi.fn>(); + await f.deliver(message("1", "save"), { interruptible }); + await vi.waitFor(() => expect(f.goose()?.turns).toHaveLength(1)); + const process = f.goose(); + const sessionId = process?.turns[0]?.sessionId; + if (!process || !sessionId) throw new Error("Turn missing"); + expect(await process.mcp(sessionId, "tools/list")).toMatchObject({ + result: { + tools: expect.arrayContaining([ + expect.objectContaining({ name: tool.name }), + ]), + }, + }); + const pending = process.mcp(sessionId, "tools/call", { + name: tool.name, + arguments: {}, + }); + try { + await entered; + expect(signal?.aborted).toBe(false); + await interruptible.mock.calls[0]?.[0](); + expect(signal?.aborted).toBe(true); + await f.deliver(message("2", "next")); + await vi.waitFor(() => expect(process.turns).toHaveLength(2)); + expect(signal?.aborted).toBe(true); + } finally { + release(); + } + expect(await pending).toMatchObject({ result: { isError: true } }); + expect(write).not.toHaveBeenCalled(); + const old = signal; + expect( + await process.mcp(sessionId, "tools/call", { + name: tool.name, + arguments: {}, + }), + ).not.toMatchObject({ result: { isError: true } }); + expect(signal).not.toBe(old); + expect(signal?.aborted).toBe(false); + expect(write).toHaveBeenCalledTimes(1); + process.turns[1]?.finish(); + await vi.waitFor(() => expect(signal?.aborted).toBe(true)); + expect( + await process.mcp(sessionId, "tools/call", { + name: tool.name, + arguments: {}, + }), + ).toMatchObject({ result: { isError: true } }); + expect(write).toHaveBeenCalledTimes(1); + }); + + it("keeps steered work live, then cancels its plugin calls on a successful final send or retirement", async () => { + const signals: AbortSignal[] = []; + const f = setup({ + hold: true, + scope: "channel", + added: [ + { + name: "fixture_signal", + description: "Capture cancellation", + inputSchema: { type: "object" }, + call: async (client) => { + if (!client.signal) throw new Error("Cancellation required"); + client.signal.throwIfAborted(); + signals.push(client.signal); + return "live"; + }, + }, + ], + }); + try { + await f.deliver(message("1", "first")); + await vi.waitFor(() => expect(f.goose()?.turns).toHaveLength(1)); + const process = f.goose(); + const id = process?.turns[0]?.sessionId; + if (!process || !id) throw new Error("Missing turn"); + const capture = () => + process.mcp(id, "tools/call", { name: "fixture_signal" }); + await capture(); + await f.deliver(message("2", "steer")); + await vi.waitFor(() => expect(process.turns[0]?.steered).toHaveLength(1)); + expect(signals[0]?.aborted).toBe(false); + expect( + await process.mcp(id, "tools/call", { + name: "send", + arguments: { text: "Finished", audience: "everyone", final: true }, + _meta: { "agent-tool-call-request-id": "final-call" }, + }), + ).not.toMatchObject({ result: { isError: true } }); + // A burst with steered messages is not finished by a single final send. + expect(signals[0]?.aborted).toBe(false); + process.turns[0]?.finish(); + await vi.waitFor(() => expect(signals[0]?.aborted).toBe(true)); + await f.deliver(message("3", "new work")); + await vi.waitFor(() => expect(process.turns).toHaveLength(2)); + await capture(); + expect(signals[1]?.aborted).toBe(false); + expect( + await process.mcp(id, "tools/call", { + name: "send", + arguments: { text: "Done", audience: "everyone", final: true }, + _meta: { "agent-tool-call-request-id": "final-call" }, + }), + ).not.toMatchObject({ result: { isError: true } }); + expect(signals[1]?.aborted).toBe(true); + // The final tool result still reaches Goose before ACP cancel is sent. + expect(process.cancelled).toHaveLength(0); + process.update(id, { + sessionUpdate: "tool_call_update", + toolCallId: "final-call", + status: "completed", + }); + await vi.waitFor(() => expect(process.cancelled).toHaveLength(1)); + await f.deliver(message("4", "retire")); + await vi.waitFor(() => expect(process.turns).toHaveLength(3)); + await capture(); + expect(signals[2]?.aborted).toBe(false); + const retired = f.runtime.retire(self); + expect(signals[2]?.aborted).toBe(true); + await retired; + } finally { + f.runtime.dispose(); + } + }); + it("returns no read that the owner's Stop overtook", async () => { let release!: () => void; let entered!: () => void; diff --git a/src/bundled/goose/runtime.ts b/src/bundled/goose/runtime.ts index 2ffcdebc74..8b27b80e94 100644 --- a/src/bundled/goose/runtime.ts +++ b/src/bundled/goose/runtime.ts @@ -824,14 +824,19 @@ export class GooseRuntime { }; // Every session of the agent shares them, so they read the settings, the // handle and the conversation's place as they are when called. - const tools: ToolServer = async (conversation, message) => { + const tools: ToolServer = async (conversation, message, workSignal) => { const handle = entry.handle; // A call in a conversation answers only while its turn runs unstopped. const current = conversation && entry.sessions.current(conversation); + const signal = AbortSignal.any([ + entry.lifetime.signal, + workSignal ?? AbortSignal.abort(new Error("The turn has ended")), + ]); const client = handle && appClient(handle, { - signal: entry.lifetime.signal, + signal, + callSignal: signal, ...(current && { check: () => { if (!current()) throw new Error("The Goose turn has ended"); diff --git a/src/bundled/goose/sessions.test.ts b/src/bundled/goose/sessions.test.ts index 0392957536..c990ec044e 100644 --- a/src/bundled/goose/sessions.test.ts +++ b/src/bundled/goose/sessions.test.ts @@ -207,11 +207,11 @@ describe("AgentSessions", () => { ]); await goose?.mcp("session-2", "tools/list"); expect(ada).not.toHaveBeenCalled(); - expect(bo).toHaveBeenCalledWith("chan/root", { - id: expect.anything(), - method: "tools/list", - params: {}, - }); + expect(bo).toHaveBeenCalledWith( + "chan/root", + { id: expect.anything(), method: "tools/list", params: {} }, + expect.objectContaining({ aborted: true }), + ); await goose?.mcp("session-1", "tools/list"); expect(ada).toHaveBeenCalledOnce(); expect(bo).toHaveBeenCalledOnce(); diff --git a/src/features/agent-harness/acp/client.test.ts b/src/features/agent-harness/acp/client.test.ts index a8b891bd7d..c7b654cb8a 100644 --- a/src/features/agent-harness/acp/client.test.ts +++ b/src/features/agent-harness/acp/client.test.ts @@ -553,6 +553,96 @@ describe("a session without hooks", () => { await second; }); + it("cancels captured work on Stop, final settlement, failure and close, independently per session", async () => { + const harness = fakeHarness({ hold: true }); + const acp = await start(harness); + const session = await acp.open({ cwd: "/work", systemPrompt: "" }); + const other = await acp.open({ cwd: "/work", systemPrompt: "" }); + expect(session.signal.aborted).toBe(true); + const first = session.send("first"); + const parallel = other.send("other"); + await flush(); + const old = session.signal; + const isolated = other.signal; + session.interrupt(); + expect(old.aborted).toBe(true); + expect(isolated.aborted).toBe(false); + const second = session.send("second"); + expect(session.signal.aborted).toBe(true); + harness.turns[0]?.finish(); + await flush(); + const fresh = session.signal; + expect(fresh).not.toBe(old); + expect(fresh.aborted).toBe(false); + expect(old.aborted).toBe(true); + session.finished("final-call"); + expect(fresh.aborted).toBe(true); + expect(session.working).toBe(true); + await second; + harness.turns[2]?.finish(); + await first; + await acp.close(other); + expect(isolated.aborted).toBe(true); + await parallel; + const failed = session.send("failure"); + await flush(); + const failing = session.signal; + session.fail("failure"); + expect(failing.aborted).toBe(true); + await expect(failed).resolves.toMatchObject({ ok: false }); + }); + + it("aborts work when a prompt fails, without waiting for a process close", async () => { + const harness = fakeHarness({ + promptError: { code: -32000, message: "failed" }, + }); + const acp = await start(harness); + const session = await acp.open({ cwd: "/work", systemPrompt: "" }); + const done = session.send("first"); + const signal = session.signal; + expect(signal.aborted).toBe(false); + await expect(done).resolves.toMatchObject({ ok: false }); + expect(signal.aborted).toBe(true); + expect(session.open).toBe(true); + }); + + it("forwards an aborted signal before session/new and while idle, and aborts active calls on process exit", async () => { + const fake = fakeGoose({ hold: true }); + const signals: AbortSignal[] = []; + const handler: ToolServer = async (_conversation, message, signal) => { + if (!signal) throw new Error("Missing cancellation"); + signals.push(signal); + return { jsonrpc: "2.0", id: message.id, result: {} }; + }; + const acp = await AcpProcess.start(fake.spawn, GOOSE, { + cwd: "/work", + serve: async (dispatch) => { + await dispatch({ id: 1, method: "tools/list" }); + return fake.serve(dispatch); + }, + }); + const session = await acp.open({ + cwd: "/work", + systemPrompt: "", + tools: handler, + }); + expect(signals).toHaveLength(1); + expect(signals[0]?.aborted).toBe(true); + const process = fake.geese[0]; + if (!process) throw new Error("Missing process"); + await process.mcp(session.id, "tools/list"); + expect(signals.every((signal) => signal.aborted)).toBe(true); + const done = session.send("first"); + await vi.waitFor(() => expect(process.turns).toHaveLength(1)); + await process.mcp(session.id, "tools/call", { name: "fixture" }); + const active = signals.at(-1); + expect(active?.aborted).toBe(false); + process.exit(1, "failed"); + await acp.exited; + expect(active?.aborted).toBe(true); + await expect(done).resolves.toMatchObject({ ok: false }); + }); + it("keeps the harness's error code on a failed turn", async () => { const harness = fakeHarness({ promptError: { code: -32000, message: "Authentication required" }, diff --git a/src/features/agent-harness/acp/process.ts b/src/features/agent-harness/acp/process.ts index fb4b50fe04..fcf6fd6b1f 100644 --- a/src/features/agent-harness/acp/process.ts +++ b/src/features/agent-harness/acp/process.ts @@ -525,11 +525,11 @@ export class AcpProcess { ): Promise { const { id, method = "", params } = (message ?? {}) as Wire; if (id === undefined || id === null) return undefined; - const response = (await tools(session?.conversation, { - id, - method, - params, - })) as Wire; + const response = (await tools( + session?.conversation, + { id, method, params }, + session?.signal ?? AbortSignal.abort(new Error("The turn has ended")), + )) as Wire; const call = (params ?? {}) as { name?: unknown; arguments?: { final?: unknown }; diff --git a/src/features/agent-harness/acp/session.ts b/src/features/agent-harness/acp/session.ts index 707a16c1f1..85d0949a71 100644 --- a/src/features/agent-harness/acp/session.ts +++ b/src/features/agent-harness/acp/session.ts @@ -105,6 +105,8 @@ export class AcpSession { private idlers: (() => void)[] = []; /** How often its work has been stopped or has ended. */ private generation = 0; + /** Cancellation belongs to this burst of work, never the next one. */ + private work: AbortController | undefined; constructor( private readonly acp: AcpProcess, @@ -152,6 +154,7 @@ export class AcpSession { ): Promise { if (this.closed) return Promise.resolve({ ok: false, error: "The session was closed" }); + if (this.quiet()) this.work = new AbortController(); this.pending++; let waiter!: Waiter; const settled = new Promise((resolve) => { @@ -195,6 +198,17 @@ export class AcpSession { this.generation === generation && !this.stopped && !this.quiet(); } + /** The exact work's cancellation, already aborted before any work starts. */ + get signal(): AbortSignal { + return ( + this.work?.signal ?? AbortSignal.abort(new Error("The turn has ended")) + ); + } + + private abortWork() { + this.work?.abort(new Error("The turn has ended")); + } + /** A final message succeeded: the work counts as done at once, and the * turn of tool call `call` ends, unless another message is still waiting * for its answer. */ @@ -211,6 +225,7 @@ export class AcpSession { interrupt() { if (!this.working || this.closed) return; this.generation++; + this.abortWork(); this.queue.length = 0; this.steered = Promise.resolve(); this.stopped = { @@ -384,6 +399,8 @@ export class AcpSession { this.ending = undefined; // Stopped work has ended, and messages sent since run as new work. if (this.stopped) this.endStopped(); + if (!this.work || this.work.signal.aborted) + this.work = new AbortController(); const { text, model, @@ -573,6 +590,7 @@ export class AcpSession { ); } private settle(settled: Settled) { + this.abortWork(); this.pending = 0; this.active.clear(); this.displaced.clear(); @@ -601,6 +619,7 @@ export class AcpSession { } private wake() { if (!this.quiet()) return; + this.abortWork(); this.generation++; for (const resolve of this.idlers.splice(0)) resolve(); } diff --git a/src/features/agent-harness/acp/types.ts b/src/features/agent-harness/acp/types.ts index 3b349f5a6a..a1f6a2fb43 100644 --- a/src/features/agent-harness/acp/types.ts +++ b/src/features/agent-harness/acp/types.ts @@ -57,6 +57,8 @@ export type ActivityReceipt = Readonly<{ export type ToolServer = ( conversation: string | undefined, message: Readonly<{ id: string | number; method: string; params?: unknown }>, + /** Captured work lifetime; aborted while idle or before the session opens. */ + signal?: AbortSignal, ) => Promise; /** The provider, model and thinking level a session's turns run on; empty is