Skip to content

Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins

fix(agent-runtime): wait for delegate retirement during parent abort

Linuxdazhao06d4e73b7e0c
diff --git a/docs/spec/03-runtime/02-agent-runtime.md b/docs/spec/03-runtime/02-agent-runtime.md
index 43d25ef15..3bfab39d1 100644
--- a/docs/spec/03-runtime/02-agent-runtime.md
+++ b/docs/spec/03-runtime/02-agent-runtime.md
@@ -73,6 +73,10 @@ runtime returns `{ requested: false }`; immediate `abort()` remains the
separate cancellation path. `abort()` resolves only after the named active
operation has completed its cancellation cleanup, so the same runtime can
accept a follow-up prompt as soon as the abort request returns.
+Cancellation remains busy until both the parent operation and all running
+delegates have retired. Concurrent aborts join that same cleanup. A parent's
+terminal event cannot make a new prompt admissible while a child is still
+retiring. Graceful turn-boundary stop remains a separate operation.
On a headless Host, prompt and approved-plan admission share a per-session
operation queue with immediate abort and its durable settlement. An abort
diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.md
index 0d7e3406f..8b9777038 100644
--- a/docs/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/spec/06-delivery/04-e2e-test-plan.md
@@ -13327,6 +13327,13 @@ This test plan spec is accepted when:
#### E2E-155: Subagent lifetime is parent-judged; runtime delivers reports
+- Abort the parent while it is waiting for a provider response and while it is
+ idle waiting for two delegates. Hold delegate teardown at the provider edge;
+ retire the parent and one child first. Abort must remain pending, status must
+ remain busy and a new prompt must be rejected until the last child retires.
+ Concurrent abort requests share cleanup. A follow-up prompt is accepted after
+ abort resolves, with no old-turn continuation or tool execution.
+
- **Preconditions**: A project-bound Agent session with a Bash-capable
`explorer` definition and a mocked provider stream.
- **Steps**: 1) Start a delegate and let the parent stop calling tools while
diff --git a/packages/agent-runtime/src/parent-stop-retirement.test.ts b/packages/agent-runtime/src/parent-stop-retirement.test.ts
new file mode 100644
index 000000000..3b2fb0a25
--- /dev/null
+++ b/packages/agent-runtime/src/parent-stop-retirement.test.ts
@@ -0,0 +1,148 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import {
+ createAssistantMessageEventStream,
+ type AssistantMessage,
+ type Models,
+} from "@earendil-works/pi-ai";
+import type { AgentEventEnvelope, SubagentDefinition } from "@pi-desktop/shared";
+import { DesktopAgentRuntime, type RuntimeProviderConfig } from "./runtime.js";
+
+// Keep both parent and delegate pi loops real; replace only provider transport.
+const transport = vi.hoisted(() => vi.fn<Models["streamSimple"]>());
+vi.mock("./provider-binding.js", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("./provider-binding.js")>();
+ return {
+ ...actual,
+ createProviderModels: (...args: Parameters<typeof actual.createProviderModels>) => {
+ const models = actual.createProviderModels(...args);
+ models.streamSimple = transport;
+ return models;
+ },
+ };
+});
+
+function deferred<T>() {
+ let resolve!: (value: T) => void;
+ let reject!: (error: unknown) => void;
+ const promise = new Promise<T>((done, fail) => { resolve = done; reject = fail; });
+ return { promise, resolve, reject };
+}
+
+const provider: RuntimeProviderConfig = {
+ id: "fixture", name: "Fixture", apiKey: "", authKind: "none",
+ baseUrl: "http://127.0.0.1:1/v1", modelId: "fixture", supportsReasoning: false,
+ supportedThinkingLevels: ["off"],
+};
+const definition = (name: string, permission?: SubagentDefinition["permission"]): SubagentDefinition => ({
+ name, permission, description: "Focused delegate", tools: ["Read", "Write"],
+ prompt: "Perform the task and report.", source: "builtin",
+});
+function message(content: AssistantMessage["content"], stopReason: AssistantMessage["stopReason"] = "stop"): AssistantMessage {
+ return {
+ role: "assistant", api: "openai-completions", provider: "fixture", model: "fixture",
+ timestamp: Date.now(), stopReason, content,
+ usage: { input: 10, output: 5, cacheRead: 0, cacheWrite: 0, totalTokens: 15,
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } },
+ };
+}
+function response(content: AssistantMessage["content"], stopReason: "stop" | "toolUse" = "stop") {
+ const stream = createAssistantMessageEventStream();
+ const result = message(content, stopReason);
+ queueMicrotask(() => {
+ stream.push({ type: "start", partial: result });
+ stream.push({ type: "done", reason: stopReason, message: result });
+ stream.end(result);
+ });
+ return stream;
+}
+const finalResponse = () => response([{ type: "text", text: "Finished the requested work." }]);
+const runtimes: DesktopAgentRuntime[] = [];
+function fixture(call = vi.fn(async (_method: string, _params?: any): Promise<any> => ({ ok: true, content: {} }))) {
+ const events: AgentEventEnvelope[] = [];
+ const runtime = new DesktopAgentRuntime({
+ host: { call, onNotification: () => () => {} } as never,
+ sessionId: "delegate-boundaries", mode: "agent", thinkingLevel: "off", provider,
+ commandShell: { id: "bash", label: "Bash", dialect: "posix", available: true, isDefault: true },
+ subagents: [definition("inherited")],
+ onEvent: (event) => events.push(event),
+ });
+ runtimes.push(runtime);
+ return { runtime, internal: runtime as any };
+}
+beforeEach(() => { transport.mockReset().mockImplementation(finalResponse); });
+afterEach(async () => {
+ for (const runtime of runtimes.splice(0)) await runtime.dispose();
+});
+
+// Event-loop deadline, not the resolver's outcome, is the cancellation oracle.
+async function promptly<T>(promise: Promise<T>): Promise<T> {
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ try {
+ return await Promise.race([promise, new Promise<never>((_, reject) => {
+ timer = setTimeout(() => reject(new Error("operation did not retire before authorization")), 1000);
+ })]);
+ } finally {
+ clearTimeout(timer);
+ }
+}
+
+describe("Parent Stop waits for every delegate", () => {
+ it.each(["waiting-model", "waiting-subagents"] as const)(
+ "aborts every child and waits for their retirement while the parent is %s",
+ async (phase) => {
+ const streams = new Map<string, { signal?: AbortSignal; finish: () => void }>();
+ const { runtime, internal } = fixture();
+ let parentRequests = 0;
+ transport.mockImplementation((_model, context, options) => {
+ const isParent = context.messages.some((message) => message.role === "user" && JSON.stringify(message.content).includes("Start both workers."));
+ if (isParent) {
+ if (++parentRequests === 1) return response(["A", "B"].map((id) => ({
+ type: "toolCall" as const, id: `task-${id}`, name: "Task",
+ arguments: { agent: "inherited", task: `Worker ${id}` },
+ })), "toolUse");
+ if (phase === "waiting-subagents") return finalResponse();
+ }
+ const stream = createAssistantMessageEventStream();
+ const key = isParent
+ ? "parent" : JSON.stringify(context.messages.at(-1)?.content);
+ const finish = () => {
+ const aborted = message([], "aborted");
+ stream.push({ type: "error", reason: "aborted", error: aborted });
+ stream.end(aborted);
+ };
+ streams.set(key, { signal: options?.signal, finish });
+ return stream;
+ });
+ const running = runtime.prompt("Start both workers.");
+ let stopping: Promise<void> | undefined;
+ try {
+ await vi.waitFor(() => {
+ expect(parentRequests).toBe(2);
+ expect(streams.size).toBe(phase === "waiting-model" ? 3 : 2);
+ });
+ let acknowledged = false;
+ const cancellation = runtime.abort();
+ expect(runtime.abort()).toBe(cancellation);
+ stopping = cancellation.then(() => { acknowledged = true; });
+ expect([...streams.values()].every((stream) => stream.signal?.aborted)).toBe(true);
+ streams.get("parent")?.finish();
+ const children = [...streams.entries()].filter(([key]) => key !== "parent").map(([, stream]) => stream);
+ children[0].finish();
+ await vi.waitFor(() => expect(internal.runningDelegations()).toHaveLength(1));
+ expect(runtime.getStatus().isRunning).toBe(true);
+ expect(acknowledged).toBe(false);
+ await expect(runtime.prompt("Too soon.")).rejects.toMatchObject({ errorCode: "AGENT_BUSY" });
+ children[1].finish();
+ await promptly(Promise.all([running, stopping]));
+ expect(runtime.getStatus().isRunning).toBe(false);
+ expect(internal.runningDelegations()).toHaveLength(0);
+ expect(parentRequests).toBe(2);
+ transport.mockImplementation(finalResponse);
+ await promptly(runtime.prompt("Safe follow-up."));
+ } finally {
+ for (const stream of streams.values()) stream.finish();
+ await promptly(Promise.allSettled([running, stopping ?? runtime.abort()]));
+ }
+ },
+ );
+});
diff --git a/packages/agent-runtime/src/runtime.test.ts b/packages/agent-runtime/src/runtime.test.ts
index 0541a93a3..5ecad6e58 100644
--- a/packages/agent-runtime/src/runtime.test.ts
+++ b/packages/agent-runtime/src/runtime.test.ts
@@ -13256,7 +13256,7 @@ describe("DesktopAgentRuntime delegation wait settlement safety", () => {
}
});
- it("lets user Stop interrupt auto-resume even if a delegate ignores abort", async () => {
+ it("interrupts auto-resume but keeps Stop pending until an uncooperative delegate retires", async () => {
const runtime = createRuntime({ subagents: [explorer] });
subagentRuns.calls.length = 0;
subagentRuns.instances.length = 0;
@@ -13271,9 +13271,16 @@ describe("DesktopAgentRuntime delegation wait settlement safety", () => {
const resume = (runtime as any).resumeAfterDelegations();
await Promise.resolve();
- await runtime.abort();
+ let acknowledged = false;
+ const stopping = runtime.abort().then(() => { acknowledged = true; });
await resume;
+ expect(acknowledged).toBe(false);
+ expect(runtime.getStatus().isRunning).toBe(true);
+ subagentRuns.resolveRun!({ agentName: "explorer", status: "aborted", report: "", turns: 0, toolCalls: 0 });
+ await stopping;
+ expect(runtime.getStatus().isRunning).toBe(false);
} finally {
+ (subagentRuns.resolveRun as ((result: unknown) => void) | undefined)?.({ agentName: "explorer", status: "aborted", report: "", turns: 0, toolCalls: 0 });
subagentRuns.ignoreAbort = false;
subagentRuns.deferred = false;
await runtime.dispose();
diff --git a/packages/agent-runtime/src/runtime.ts b/packages/agent-runtime/src/runtime.ts
index 6c57f354d..05e6049ae 100644
--- a/packages/agent-runtime/src/runtime.ts
+++ b/packages/agent-runtime/src/runtime.ts
@@ -1787,6 +1787,7 @@ export class DesktopAgentRuntime {
private model: Model<Api>;
private turnId?: string;
private disposed = false;
+ private aborting?: Promise<void>;
readonly sessionId: string;
private mode: Mode;
private provider: RuntimeProviderConfig;
@@ -9416,11 +9417,16 @@ Do not invent objections or turn speculative risks into blockers. Stop when the
}
}
- async abort(): Promise<void> {
+ abort(): Promise<void> {
+ return this.aborting ??= this.abortTurn().finally(() => { this.aborting = undefined; });
+ }
+
+ private async abortTurn(): Promise<void> {
const turnId = this.turnId;
const settlement = turnId
? this.activeTurnSettlements.get(turnId)
: undefined;
+ const delegates = this.runningDelegations().map((record) => record.completion);
this.acceptingSteering = false;
this.gracefulStopRequested = false;
this.runCancelled = true;
@@ -9441,7 +9447,7 @@ Do not invent objections or turn speculative risks into blockers. Stop when the
// the whole session until it finished on its own (#1767). Drive the tools
// from here as well, so a stop always releases them.
for (const abortTool of [...this.activeToolAborts]) abortTool();
- await settlement;
+ await Promise.allSettled([...(settlement ? [settlement] : []), ...delegates]);
}
private trackTurnOperation<T>(
@@ -9485,6 +9491,7 @@ Do not invent objections or turn speculative risks into blockers. Stop when the
return {
sessionId: this.sessionId,
isRunning:
+ this.aborting !== undefined ||
this.agent.state.isStreaming ||
this.compactionInProgress ||
this.agentActivity !== undefined ||