Skip to content

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

fix(agent-runtime): avoid blocking read-only Stop on abort RPCs

FuYukiH5244493c8fe1
diff --git a/docs/spec/03-runtime/03-tools-and-permissions.md b/docs/spec/03-runtime/03-tools-and-permissions.md
index b0297088b..42fe8271c 100644
--- a/docs/spec/03-runtime/03-tools-and-permissions.md
+++ b/docs/spec/03-runtime/03-tools-and-permissions.md
@@ -159,7 +159,9 @@ instead of starting after Stop. `Bash` and `GenerateImages` use the existing
process cancellation path; the runtime waits up to 10s for the host to return
output collected before termination. Local `Read`, `Glob`, and `Grep` calls may
end the runtime's wait immediately and return `TOOL_ABORTED`; their results are
-discarded. A blocking filesystem worker may continue until it returns, but
+discarded. This local stop does not wait for the `tools.abort` acknowledgement;
+late success or failure of either Host request cannot affect a subsequent turn.
+A blocking filesystem worker may continue until it returns, but
these tools do not mutate the workspace. For a mutating, MCP, or plugin call
that has already started, the runtime waits for the host result before it
settles the turn, so Stop cannot hide a write or extension action that is still
diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.md
index 0eab354b1..3880debb0 100644
--- a/docs/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/spec/06-delivery/04-e2e-test-plan.md
@@ -2127,6 +2127,7 @@ identify the platform validation still needed.
for partial output, then stop during the stream. 4) Immediately send a new
prompt after Stop returns, without waiting for an idle delay. 5) Start a
read-only Grep that does not return, press Stop, then start another prompt.
+ Hold its `tools.abort` acknowledgement as well and repeat for Read and Glob.
6) Start a Write that is waiting for permission, press Stop, then try to
approve the stale request. 7) Observe the transcript, composer, and workspace.
- **Expected**: The first Stop is honored even if prompt admission is still in
@@ -2134,7 +2135,9 @@ identify the platform validation still needed.
streaming send stops with its partial response preserved and no draft
restoration or duplicate user turn. The read-only tool returns
`TOOL_ABORTED`, its late result is discarded, and the follow-up starts
- without `AGENT_BUSY`. Stopping the pending Write cancels its permission;
+ without `AGENT_BUSY`, even while the cancellation acknowledgement is pending.
+ Late results or cancellation failures cannot change the follow-up turn.
+ Stopping the pending Write cancels its permission;
approving the stale request fails and creates no file. A mutating operation
that already started is not reported stopped before its Host result arrives.
- **Specs linked**: `03-runtime/02-agent-runtime.md`,
@@ -2144,7 +2147,13 @@ identify the platform validation still needed.
- **Milestone**: M2
- **Status**: Runtime and Host cancellation contracts automated by
`packages/agent-runtime/src/runtime.test.ts` and the pending-Write regression
- in `crates/host-core/src/rpc/mod.rs`; rendered Electron interaction remains
+ in `crates/host-core/src/rpc/mod.rs`. `read-only-stop.test.ts` covers held
+ acknowledgements and late failures through real Agent loops.
+ After building shared and running `node packages/agent-runtime/scripts/bundle.mjs`,
+ `node scripts/e2e-read-only-stop.mjs` runs the production sidecar bundle and
+ a localhost provider, holding execution and cancellation responses at the Host
+ edge. It verifies follow-up prompts and the Write settlement boundary;
+ rendered Electron interaction remains
a manual validation run.
#### E2E-171: Streaming reply survives quit, crash, and stop
diff --git a/packages/agent-runtime/src/read-only-stop.test.ts b/packages/agent-runtime/src/read-only-stop.test.ts
new file mode 100644
index 000000000..d7e9c3087
--- /dev/null
+++ b/packages/agent-runtime/src/read-only-stop.test.ts
@@ -0,0 +1,115 @@
+import { setImmediate as nextTurn } from "node:timers/promises";
+import { afterEach, expect, it, vi } from "vitest";
+import type { AgentEventEnvelope } from "@pi-desktop/shared";
+import { DesktopAgentRuntime } from "./runtime.js";
+
+type ToolName = "Read" | "Glob" | "Grep" | "Write";
+type ToolResult = { ok: boolean; content: unknown };
+
+function deferred<T>() {
+ let resolve!: (value: T | PromiseLike<T>) => void;
+ let reject!: (reason?: unknown) => void;
+ const promise = new Promise<T>((yes, no) => { resolve = yes; reject = no; });
+ return { promise, resolve, reject };
+}
+
+function fixture(toolName: ToolName) {
+ const execution = deferred<ToolResult>();
+ const cancellation = deferred<unknown>();
+ const started = deferred<void>();
+ const abortRequested = deferred<void>();
+ const events: AgentEventEnvelope[] = [];
+ const args = toolName === "Grep" ? { query: "needle" }
+ : toolName === "Glob" ? { pattern: "**/*.ts" }
+ : toolName === "Write" ? { path: "fixture.txt", content: "replacement" }
+ : { path: "fixture.txt" };
+ let requests = 0;
+ vi.stubGlobal("fetch", vi.fn(async () => {
+ requests++;
+ if (requests > 2) throw new Error("Unexpected provider retry");
+ const first = requests === 1;
+ const delta = first ? { role: "assistant", tool_calls: [{
+ index: 0, id: "fixture-call", type: "function",
+ function: { name: toolName, arguments: JSON.stringify(args) },
+ }] } : { role: "assistant", content: "Second turn completed" };
+ const chunk = (value: unknown, finish: string | null) =>
+ `data: ${JSON.stringify({ id: "completion", object: "chat.completion.chunk", created: 1,
+ model: "fixture-model", choices: [{ index: 0, delta: value, finish_reason: finish }] })}\n\n`;
+ return new Response(chunk(delta, null) + chunk({}, first ? "tool_calls" : "stop") + "data: [DONE]\n\n", {
+ headers: { "content-type": "text/event-stream" },
+ });
+ }));
+ const runtime = new DesktopAgentRuntime({
+ sessionId: "stop-fixture", mode: "agent", thinkingLevel: "off",
+ provider: { id: "fixture", name: "Fixture", modelId: "fixture-model",
+ baseUrl: "http://provider.invalid/v1", apiKey: "fixture-only", apiStyle: "chat_completions",
+ supportsReasoning: false, supportedThinkingLevels: ["off"] },
+ commandShell: { id: "bash", label: "Bash", dialect: "posix", available: true, isDefault: true },
+ host: { async call<T>(method: string): Promise<T> {
+ if (method === "tools.execute") { started.resolve(); return await execution.promise as T; }
+ if (method === "tools.abort") { abortRequested.resolve(); return await cancellation.promise as T; }
+ if (method === "session.appendMessage" || method === "project.instructions.resolve") return undefined as T;
+ throw new Error(`Unexpected host method: ${method}`);
+ } },
+ onEvent: (event) => events.push(event),
+ });
+ return { runtime, execution, cancellation, started, abortRequested, events, requests: () => requests };
+}
+
+afterEach(() => vi.unstubAllGlobals());
+
+it.each(["Read", "Glob", "Grep"] as const)("stops %s and accepts another prompt while the abort acknowledgement is held", async (name) => {
+ const f = fixture(name);
+ const first = f.runtime.prompt("Inspect the fixture").then(() => undefined, () => undefined);
+ let aborting: Promise<void> | undefined;
+ try {
+ await Promise.race([f.started.promise, first.then(() => { throw new Error("Tool did not start"); })]);
+ let stopped = false;
+ aborting = f.runtime.abort().then(() => { stopped = true; });
+ await f.abortRequested.promise;
+ await nextTurn();
+ expect(stopped, "a read-only local stop must not await the blocked host").toBe(true);
+ await first;
+ expect(f.runtime.getStatus().isRunning).toBe(false);
+
+ await f.runtime.prompt("Continue with a new task");
+ expect(f.requests()).toBe(2);
+ expect(f.runtime.getStatus().isRunning).toBe(false);
+ const eventCount = f.events.length;
+ f.cancellation.reject(new Error("late abort transport failure"));
+ f.execution.reject(new Error("late read failure"));
+ await nextTurn();
+ expect(f.events).toHaveLength(eventCount);
+ expect(f.requests()).toBe(2);
+ } finally {
+ f.cancellation.resolve({ ok: true });
+ f.execution.resolve({ ok: false, content: "cancelled" });
+ await Promise.allSettled([first, aborting]);
+ await f.runtime.dispose();
+ }
+});
+
+it("keeps a Write turn owned until both execution and host cancellation settle", async () => {
+ const f = fixture("Write");
+ const first = f.runtime.prompt("Update the fixture").then(() => undefined, () => undefined);
+ let aborting: Promise<void> | undefined;
+ try {
+ await Promise.race([f.started.promise, first.then(() => { throw new Error("Write did not start"); })]);
+ let stopped = false;
+ aborting = f.runtime.abort().then(() => { stopped = true; });
+ await f.abortRequested.promise;
+ await nextTurn();
+ expect(stopped).toBe(false);
+ f.execution.resolve({ ok: true, content: "written" });
+ await nextTurn();
+ expect(stopped, "mutation cancellation still requires host settlement").toBe(false);
+ f.cancellation.resolve({ ok: true });
+ await aborting;
+ expect(stopped).toBe(true);
+ } finally {
+ f.execution.resolve({ ok: false, content: "cancelled" });
+ f.cancellation.resolve({ ok: true });
+ await Promise.allSettled([first, aborting]);
+ await f.runtime.dispose();
+ }
+});
diff --git a/packages/agent-runtime/src/runtime.ts b/packages/agent-runtime/src/runtime.ts
index de99a6a3c..b224f2b0f 100644
--- a/packages/agent-runtime/src/runtime.ts
+++ b/packages/agent-runtime/src/runtime.ts
@@ -3736,8 +3736,13 @@ Do not invent objections or turn speculative risks into blockers. Stop when the
// it armed is released here instead.
if (abortGraceTimer) clearTimeout(abortGraceTimer);
}
- if (abortPromise) await abortPromise;
- if (abortError) throw abortError;
+ // A local read-only stop cannot depend on the same Host answering a
+ // second RPC. Its abort request already observes late rejections.
+ // Other tools retain Host settlement ownership for their side effects.
+ if (!canAbandonWait) {
+ if (abortPromise) await abortPromise;
+ if (abortError) throw abortError;
+ }
if (stopped) {
throw Object.assign(
new Error(`tool execution aborted while ${toolName} was running`),
diff --git a/scripts/e2e-read-only-stop.mjs b/scripts/e2e-read-only-stop.mjs
new file mode 100644
index 000000000..46ba9bdfa
--- /dev/null
+++ b/scripts/e2e-read-only-stop.mjs
@@ -0,0 +1,119 @@
+/** Real sidecar + provider HTTP adapter; hold only the host execution/cancel edge. */
+// Build the production sidecar first; --bundle selects an existing baseline artifact.
+import assert from "node:assert/strict";
+import { createServer } from "node:http";
+import { mkdir, mkdtemp, rm } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join, resolve } from "node:path";
+import { fileURLToPath } from "node:url";
+import { parseArgs } from "node:util";
+import { OfflineSidecar, fixtureHost } from "./e2e/hosted-search-sidecar.mjs";
+
+const root = fileURLToPath(new URL("../", import.meta.url));
+const { values } = parseArgs({ options: { bundle: { type: "string" } } });
+const bundle = values.bundle ? resolve(values.bundle) : join(root, "packages/agent-runtime/dist-bundle/sidecar.js");
+const temporary = await mkdtemp(join(tmpdir(), "pi-read-only-stop-"));
+const results = [];
+
+async function scenario(toolName) {
+ const dir = join(temporary, toolName);
+ await mkdir(dir, { recursive: true });
+ const execution = Promise.withResolvers();
+ const cancellation = Promise.withResolvers();
+ let started = false, abortRequested = false, executionReplied = false, abortReplied = false;
+ let requests = 0;
+ const requestBodies = [];
+ const args = toolName === "Grep" ? { query: "needle" }
+ : toolName === "Glob" ? { pattern: "**/*.ts" }
+ : toolName === "Write" ? { path: "fixture.txt", content: "replacement" } : { path: "fixture.txt" };
+ const server = createServer(async (request, response) => {
+ const chunks = [];
+ for await (const chunk of request) chunks.push(chunk);
+ requestBodies.push(Buffer.concat(chunks).toString("utf8"));
+ requests++;
+ if (request.url !== "/v1/chat/completions" || requests > 2) {
+ response.writeHead(400).end("Unexpected provider request");
+ return;
+ }
+ const first = requests === 1;
+ const delta = first ? { role: "assistant", tool_calls: [{
+ index: 0, id: "fixture-call", type: "function", function: { name: toolName, arguments: JSON.stringify(args) },
+ }] } : { role: "assistant", content: "Follow-up completed" };
+ const chunk = (value, finish) => `data: ${JSON.stringify({ id: "completion", object: "chat.completion.chunk",
+ created: 1, model: "fixture-model", choices: [{ index: 0, delta: value, finish_reason: finish }] })}\n\n`;
+ response.writeHead(200, { "content-type": "text/event-stream" });
+ response.end(chunk(delta, null) + chunk({}, first ? "tool_calls" : "stop") + "data: [DONE]\n\n");
+ });
+ await new Promise((done) => server.listen(0, "127.0.0.1", done));
+ const fallback = fixtureHost();
+ const host = async (method, params) => {
+ if (method === "tools.execute") {
+ assert.equal(params.toolName, toolName);
+ started = true;
+ const result = await execution.promise;
+ executionReplied = true;
+ return result;
+ }
+ if (method === "tools.abort") {
+ assert.equal(params.toolName, toolName);
+ abortRequested = true;
+ const result = await cancellation.promise;
+ abortReplied = true;
+ return result;
+ }
+ if (method === "plans.abort") return { ok: true };
+ return fallback(method, params);
+ };
+ let sidecar;
+ try {
+ sidecar = await OfflineSidecar.start(bundle, dir, host, 10_000);
+ const params = { sessionId: `stop-${toolName}`, mode: "agent", thinkingLevel: "off",
+ infiniteProviderRetry: false, scratchDir: dir, pluginTools: [], pluginSkills: [], trustedExtensions: [],
+ commandShell: { id: "bash", label: "Bash", dialect: "posix", available: true, isDefault: true },
+ provider: { id: "fixture", name: "Fixture", modelId: "fixture-model",
+ baseUrl: `http://127.0.0.1:${server.address().port}/v1`, apiKey: "fixture-only", apiStyle: "chat_completions",
+ supportsReasoning: false, supportedThinkingLevels: ["off"] } };
+ const turnId = `${toolName}-first`;
+ await sidecar.call("agent.prompt", { ...params, turnId, userMessageId: `${turnId}-user`, content: "Use the fixture tool" });
+ await sidecar.waitFor(() => started, "tool execution started");
+ const aborting = sidecar.call("agent.abort", { sessionId: params.sessionId, turnId });
+ await sidecar.waitFor(() => abortRequested, "host cancellation requested");
+ if (toolName === "Write") {
+ assert.equal((await sidecar.call("agent.getStatus", { sessionId: params.sessionId })).status.isRunning, true);
+ execution.resolve({ ok: true, content: "written" });
+ await sidecar.waitFor(() => executionReplied, "write result returned");
+ assert.equal((await sidecar.call("agent.getStatus", { sessionId: params.sessionId })).status.isRunning, true);
+ cancellation.resolve({ ok: true });
+ }
+ await aborting;
+ if (toolName !== "Write") assert.equal(abortReplied, false, "local stop waited for a host acknowledgement");
+ assert.equal((await sidecar.call("agent.getStatus", { sessionId: params.sessionId })).status.isRunning, false);
+ await sidecar.prompt(params, "Continue with a new task");
+ assert.equal(requests, 2);
+ const followUp = JSON.parse(requestBodies[1]).messages.filter((message) => message.role === "user").at(-1);
+ assert.ok(JSON.stringify(followUp.content).includes("Continue with a new task"), "the new prompt did not reach the provider");
+ assert.ok([...sidecar.messages.values()].some((message) => message.content === "Follow-up completed"));
+ const before = (await sidecar.call("agent.getStatus", { sessionId: params.sessionId })).status;
+ execution.resolve({ ok: true, content: "late read result" });
+ cancellation.resolve({ ok: true });
+ await sidecar.waitFor(() => executionReplied && abortReplied, "late host responses returned");
+ const after = (await sidecar.call("agent.getStatus", { sessionId: params.sessionId })).status;
+ assert.equal(after.currentTurnId, before.currentTurnId);
+ assert.equal(after.isRunning, false);
+ sidecar.check();
+ results.push({ toolName, passed: true, followUpAccepted: true });
+ } finally {
+ execution.resolve({ ok: false, content: "cancelled" });
+ cancellation.resolve({ ok: true });
+ await sidecar?.stop();
+ server.closeAllConnections();
+ await new Promise((done) => server.close(done));
+ }
+}
+
+try {
+ for (const tool of ["Read", "Glob", "Grep", "Write"]) await scenario(tool);
+ console.log(JSON.stringify({ passed: true, results }));
+} finally {
+ await rm(temporary, { recursive: true, force: true });
+}