Skip to content

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

fix(host-runtime): serialize abort with session admission

Mu6761192cc0a7
diff --git a/docs/spec/03-runtime/02-agent-runtime.md b/docs/spec/03-runtime/02-agent-runtime.md
index 1ca248a76..43d25ef15 100644
--- a/docs/spec/03-runtime/02-agent-runtime.md
+++ b/docs/spec/03-runtime/02-agent-runtime.md
@@ -74,6 +74,15 @@ 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.
+On a headless Host, prompt and approved-plan admission share a per-session
+operation queue with immediate abort and its durable settlement. An abort
+received during launch resolution, turn creation, transcript append, or sidecar
+history restoration waits for that admission before canceling its runtime.
+The abort intent for an already-active turn is recorded before waiting, so a
+racing terminal event cannot report completion instead. A delayed abort keeps
+its original turn identity and cannot cancel a later turn. Other sessions can
+continue admitting work independently.
+
### 4.0 Active-turn steering
`steer` validates the current turn identity before changing any state, then
diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.md
index 5adefab0a..0d88ec682 100644
--- a/docs/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/spec/06-delivery/04-e2e-test-plan.md
@@ -2171,6 +2171,13 @@ identify the platform validation still needed.
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.
+ On a headless Host, hold durable-turn creation, user-row append, and sidecar
+ history restoration in turn, then request abort during each hold. Release the
+ hold and confirm abort settles the runtime before acknowledging cancellation;
+ a follow-up input completes under a new durable turn. Repeat with an approved
+ plan still being admitted, and ensure its execution settles as interrupted.
+ An old turn's delayed abort must leave a newer turn alone, and admission in
+ another session must not wait for this session's cancellation.
- **Specs linked**: `03-runtime/02-agent-runtime.md`,
`03-runtime/03-tools-and-permissions.md`, `03-runtime/06-host-rpc-protocol.md`,
ADR `tool-abort-abandons-host-call`
@@ -2184,7 +2191,12 @@ identify the platform validation still needed.
`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
+ `packages/host-runtime/src/runtime-service.test.ts` covers headless admission,
+ approved-plan startup, stale aborts, and independent sessions. After building
+ host-runtime and the sidecar bundle, `node scripts/e2e-headless-startup-abort.mjs`
+ exercises the production RuntimeService, stdio transport, sidecar, and local
+ provider through startup cancellation and a successful follow-up.
+ Rendered Electron interaction remains
a manual validation run.
#### E2E-171: Streaming reply survives quit, crash, and stop
diff --git a/packages/host-runtime/src/runtime-service.test.ts b/packages/host-runtime/src/runtime-service.test.ts
index 46f62c14a..c4a2d76c7 100644
--- a/packages/host-runtime/src/runtime-service.test.ts
+++ b/packages/host-runtime/src/runtime-service.test.ts
@@ -2,12 +2,14 @@ import { describe, expect, it } from "vitest";
import type { AgentEventEnvelope, UiMessage } from "@pi-desktop/shared";
import type { LaunchResolver } from "./launch-resolver.js";
+import { PlanExecutionDispatcher } from "./plan-dispatch.js";
import { RuntimeService, type RuntimeHostLink, type RuntimeSidecarLink, type TurnEndedInfo } from "./runtime-service.js";
type Call = { method: string; params: Record<string, unknown> };
class FakeHost implements RuntimeHostLink {
calls: Call[] = [];
+ beforeCall?: (method: string) => Promise<void>;
notify: ((method: string, params: unknown) => void) | null = null;
available = true;
private turnCounter = 0;
@@ -17,6 +19,7 @@ class FakeHost implements RuntimeHostLink {
async call<T = unknown>(method: string, params: Record<string, unknown> = {}): Promise<T> {
this.calls.push({ method, params });
+ if (this.beforeCall) await this.beforeCall(method);
switch (method) {
case "settings.get":
return {} as T;
@@ -37,6 +40,8 @@ class FakeHost implements RuntimeHostLink {
case "session.saveInflightMessage":
return { ok: true } as T;
case "plans.abort":
+ case "plans.claimExecution":
+ case "plans.finishExecution":
return {} as T;
default:
throw new Error(`unexpected host call ${method}`);
@@ -58,6 +63,7 @@ class FakeHost implements RuntimeHostLink {
class FakeSidecar implements RuntimeSidecarLink {
calls: Call[] = [];
+ beforeCall?: (method: string) => Promise<void>;
notify: ((method: string, params: unknown) => void) | null = null;
exit: ((info: { intentional: boolean; code: number | null; signal: NodeJS.Signals | null }) => void) | null = null;
roots = new Map<string, string | undefined>();
@@ -70,8 +76,10 @@ class FakeSidecar implements RuntimeSidecarLink {
async call<T = unknown>(method: string, params: Record<string, unknown> = {}): Promise<T> {
this.calls.push({ method, params });
+ if (this.beforeCall) await this.beforeCall(method);
switch (method) {
case "agent.prompt":
+ case "agent.executeApprovedPlan":
if (this.rejectPrompt) throw Object.assign(new Error("model not configured"), { data: { errorCode: "MODEL_NOT_CONFIGURED" } });
this.running = true;
return { accepted: true, turnId: params.turnId } as T;
@@ -84,6 +92,7 @@ class FakeSidecar implements RuntimeSidecarLink {
if (this.compactError) throw this.compactError;
return { accepted: true } as T;
case "agent.abort":
+ this.running = false;
return { ok: true } as T;
case "agent.stop":
return { requested: this.running } as T;
@@ -206,6 +215,139 @@ async function settle(): Promise<void> {
for (let index = 0; index < 5; index += 1) await new Promise((resolve) => setImmediate(resolve));
}
+function holdNextCall(link: FakeHost | FakeSidecar, method: string) {
+ let entered!: () => void;
+ let release!: () => void;
+ const reached = new Promise<void>((resolve) => { entered = resolve; });
+ const released = new Promise<void>((resolve) => { release = resolve; });
+ link.beforeCall = async (calledMethod) => {
+ if (calledMethod !== method) return;
+ link.beforeCall = undefined;
+ entered();
+ await released;
+ };
+ return { reached, release };
+}
+
+describe("RuntimeService startup cancellation", () => {
+ for (const targeted of [false, true]) {
+ it.each([
+ ["host", "settings.get"],
+ ["host", "session.beginTurn"],
+ ["host", "session.appendMessage"],
+ ["sidecar", "agent.prompt"],
+ ] as const)(`settles a ${targeted ? "named" : "session"} abort after %s %s admission`, async (link, method) => {
+ const fixture = build();
+ const { host, sidecar, service, ended } = fixture;
+ const gate = holdNextCall(fixture[link], method);
+ const starting = service.prompt({ sessionId: "s1", content: "hello", effectivePermissionMode: "ask", principal: owner });
+ await gate.reached;
+ const stopping = service.abort("s1", targeted ? "turn-1" : undefined);
+ try {
+ await settle();
+ } finally {
+ gate.release();
+ }
+ await Promise.all([starting, stopping]);
+ expect(sidecar.running).toBe(false);
+ expect(service.isBusy("s1")).toBe(false);
+ expect(ended).toEqual([expect.objectContaining({ turnId: "turn-1", reason: "aborted" })]);
+ expect(host.calls.filter((call) => call.method === "session.endTurn")).toHaveLength(1);
+
+ // The abort acknowledgement is the boundary after which a new input may
+ // start; it must not inherit the canceled admission or its terminal event.
+ await expect(service.prompt({ sessionId: "s1", content: "follow-up", effectivePermissionMode: "ask", principal: owner }))
+ .resolves.toEqual({ turnId: "turn-2" });
+ expect(sidecar.running).toBe(true);
+ await service.dispose();
+ });
+ }
+
+ it("preserves an admission failure and releases the session for the next input", async () => {
+ const { host, sidecar, service, ended } = build();
+ host.failAppend = true;
+ const gate = holdNextCall(host, "session.appendMessage");
+ const starting = service.prompt({ sessionId: "s1", content: "hello", effectivePermissionMode: "ask", principal: owner });
+ const failedStart = expect(starting).rejects.toThrow("disk full");
+ await gate.reached;
+ const stopping = service.abort("s1");
+ await settle();
+ gate.release();
+ await Promise.all([failedStart, stopping]);
+ expect(sidecar.calls.some((call) => call.method === "agent.prompt")).toBe(false);
+ expect(service.isBusy("s1")).toBe(false);
+ expect(ended).toHaveLength(1);
+ host.failAppend = false;
+ await expect(service.prompt({ sessionId: "s1", content: "retry", effectivePermissionMode: "ask", principal: owner }))
+ .resolves.toEqual({ turnId: "turn-2" });
+ await service.dispose();
+ });
+
+ it.each([
+ ["host", "plans.claimExecution"],
+ ["sidecar", "agent.executeApprovedPlan"],
+ ] as const)("cancels an approved plan still being admitted at %s %s", async (link, method) => {
+ const fixture = build();
+ const { host, sidecar, service, ended } = fixture;
+ const dispatcher = new PlanExecutionDispatcher({
+ getHost: () => host, getSidecar: () => sidecar, launch, runtime: service, log: () => {},
+ });
+ const gate = holdNextCall(fixture[link], method);
+ const starting = dispatcher.dispatchApprovedPlan({
+ id: "execution-1", proposalId: "proposal-1", sessionId: "s1", state: "queued",
+ title: "Approved work", plan: "Work", question: "Proceed?", targetPermissionMode: "ask",
+ artifact: { relativePath: ".pi/plan/approved.md", sha256: "a".repeat(64), sizeBytes: 4 },
+ });
+ await gate.reached;
+ const stopping = service.abort("s1");
+ await settle();
+ gate.release();
+ await Promise.all([starting, stopping]);
+ await settle();
+ expect(sidecar.running).toBe(false);
+ expect(ended).toEqual([expect.objectContaining({ turnId: "turn-1", reason: "aborted" })]);
+ expect(host.calls.filter((call) => call.method === "plans.finishExecution")).toEqual([
+ { method: "plans.finishExecution", params: { executionId: "execution-1", status: "interrupted", errorCode: "TURN_ABORTED" } },
+ ]);
+ dispatcher.dispose();
+ await service.dispose();
+ });
+
+ it("locks an active turn's abort reason before a racing terminal event", async () => {
+ const { sidecar, service, ended } = build();
+ const { turnId } = await service.prompt({ sessionId: "s1", content: "hello", effectivePermissionMode: "ask", principal: owner });
+ const stopping = service.abort("s1", turnId);
+ sidecar.notify?.("agent.event", { sessionId: "s1", turnId, ts: 1, event: { type: "agent_end", messageIds: [] } });
+ await stopping;
+ await settle();
+ expect(ended).toEqual([expect.objectContaining({ turnId, reason: "aborted" })]);
+ await service.dispose();
+ });
+
+ it("keeps a pending abort ahead of the next input without blocking other sessions", async () => {
+ const { host, sidecar, service } = build();
+ await service.prompt({ sessionId: "s1", content: "first", effectivePermissionMode: "ask", principal: owner });
+ const gate = holdNextCall(sidecar, "agent.abort");
+ const stopping = service.abort("s1", "turn-1");
+ await gate.reached;
+ const next = service.prompt({ sessionId: "s1", content: "next", effectivePermissionMode: "ask", principal: owner });
+ const staleStop = service.abort("s1", "turn-1");
+ try {
+ await expect(service.prompt({ sessionId: "s2", content: "independent", effectivePermissionMode: "ask", principal: owner }))
+ .resolves.toEqual({ turnId: "turn-2" });
+ } finally {
+ gate.release();
+ }
+ await stopping;
+ await expect(next).resolves.toEqual({ turnId: "turn-3" });
+ await staleStop;
+ expect(service.activeTurnId("s1")).toBe("turn-3");
+ expect(service.activeTurnId("s2")).toBe("turn-2");
+ expect(host.calls.filter((call) => call.method === "session.endTurn")).toHaveLength(1);
+ await service.dispose();
+ });
+});
+
describe("RuntimeService prompt lifecycle", () => {
it("opens a durable turn, persists the user row, then starts the runtime under that turn id", async () => {
const { host, sidecar, service, events } = build();
diff --git a/packages/host-runtime/src/runtime-service.ts b/packages/host-runtime/src/runtime-service.ts
index 0142038aa..3bd8907a0 100644
--- a/packages/host-runtime/src/runtime-service.ts
+++ b/packages/host-runtime/src/runtime-service.ts
@@ -424,21 +424,28 @@ export class RuntimeService implements RuntimePort {
}
async abort(sessionId: string, turnId?: string): Promise<void> {
- const sidecar = this.requireSidecar();
- const abortedTurnId = this.activeTurns.get(sessionId);
- if (turnId && abortedTurnId !== turnId) return;
- this.options.log("info", "prompt aborted", { sessionId });
- // Lock the abort reason before the first await: the cancel RPC can take a
- // while, and a terminal event arriving in that window must not settle the
- // turn as completed.
- this.lockAbortReason(sessionId, abortedTurnId);
- try {
- await sidecar.call("agent.abort", { sessionId, ...(turnId ? { turnId } : {}) });
- } finally {
- if (abortedTurnId) {
- await this.finishTurn(sessionId, "aborted", "TURN_ABORTED", { turnId: abortedTurnId });
+ const id = sessionId.trim();
+ const requestedTurnId = turnId ?? this.activeTurns.get(id);
+ // Preserve an already-running turn's abort reason before waiting for the
+ // session operation, and never let its delayed abort target a later turn.
+ this.lockAbortReason(id, requestedTurnId);
+ await this.withSessionOperation(id, async () => {
+ // Admission owns this operation until the sidecar accepts the turn.
+ // Reading ownership and canceling before that boundary can miss the
+ // runtime, then allow the pending prompt to start after abort returns.
+ const abortedTurnId = this.activeTurns.get(id);
+ if (requestedTurnId && abortedTurnId !== requestedTurnId) return;
+ const sidecar = this.requireSidecar();
+ this.options.log("info", "prompt aborted", { sessionId: id });
+ this.lockAbortReason(id, abortedTurnId);
+ try {
+ await sidecar.call("agent.abort", { sessionId: id, ...(abortedTurnId ? { turnId: abortedTurnId } : {}) });
+ } finally {
+ if (abortedTurnId) {
+ await this.finishTurn(id, "aborted", "TURN_ABORTED", { turnId: abortedTurnId });
+ }
}
- }
+ });
}
async respondInput(resolution: AskToolResolution): Promise<void> {
diff --git a/scripts/e2e-headless-startup-abort.mjs b/scripts/e2e-headless-startup-abort.mjs
new file mode 100644
index 000000000..23a6fa2ee
--- /dev/null
+++ b/scripts/e2e-headless-startup-abort.mjs
@@ -0,0 +1,157 @@
+import assert from "node:assert/strict";
+import { once } from "node:events";
+import { mkdtemp, rm } from "node:fs/promises";
+import { createServer } from "node:http";
+import { tmpdir } from "node:os";
+import { basename, dirname, join, resolve } from "node:path";
+import test from "node:test";
+import { fileURLToPath } from "node:url";
+import { AgentSidecar } from "../packages/host-runtime/dist/agent-sidecar.js";
+import { RuntimeService } from "../packages/host-runtime/dist/runtime-service.js";
+import { isolatedEnv } from "./e2e/hosted-search-sidecar.mjs";
+
+// Build host-runtime and the production sidecar bundle first. Only host-core
+// and the provider HTTP endpoint are fixtures; admission, cancellation,
+// transport, the Agent loop and turn finalization use the production code.
+const bundle = fileURLToPath(new URL("../packages/agent-runtime/dist-bundle/sidecar.js", import.meta.url));
+const principal = { subject: "fixture", roles: ["owner"], pairedDevice: true };
+
+for (const phase of ["begin", "append", "restore"]) {
+ test(`headless startup abort during ${phase} settles before a follow-up`, { timeout: 30_000 }, async (t) => {
+ const scratch = await mkdtemp(join(tmpdir(), "pi-headless-startup-"));
+ const entered = Promise.withResolvers();
+ const release = Promise.withResolvers();
+ const nextEnded = Promise.withResolvers();
+ const history = [];
+ const ended = [];
+ const durableEnds = [];
+ const providerBodies = [];
+ let held = false;
+ let turnCounter = 0;
+ let stderr = "";
+ let service;
+ let sidecar;
+
+ const server = createServer(async (request, response) => {
+ const chunks = [];
+ for await (const chunk of request) chunks.push(chunk);
+ const body = JSON.parse(Buffer.concat(chunks).toString("utf8"));
+ providerBodies.push(body);
+ const lastUser = body.messages.filter((message) => message.role === "user").at(-1);
+ const followUp = JSON.stringify(lastUser?.content).includes("Follow-up task");
+ const frame = (delta, finishReason) => `data: ${JSON.stringify({
+ id: "fixture-completion", object: "chat.completion.chunk", created: 1, model: "fixture-model",
+ choices: [{ index: 0, delta, finish_reason: finishReason }],
+ })}\n\n`;
+ response.writeHead(200, { "content-type": "text/event-stream" });
+ response.write(frame({ role: "assistant", content: followUp ? "Follow-up completed" : "Working" }, null));
+ if (followUp) response.end(frame({}, "stop") + "data: [DONE]\n\n");
+ // The first response stays open until the real runtime cancels it.
+ });
+ t.after(async () => {
+ release.resolve();
+ await service?.dispose();
+ await sidecar?.dispose();
+ server.closeAllConnections();
+ await new Promise((done) => server.close(done));
+ const directory = resolve(scratch);
+ assert.equal(dirname(directory), resolve(tmpdir()));
+ assert.ok(basename(directory).startsWith("pi-headless-startup-"));
+ await rm(directory, { recursive: true, force: true });
+ });
+ server.listen(0, "127.0.0.1");
+ await once(server, "listening");
+
+ const host = {
+ async call(method, params = {}) {
+ const shouldHold = phase === "begin" ? method === "session.beginTurn"
+ : phase === "append" ? method === "session.appendMessage"
+ : method === "session.get" && params.messageLimit === undefined;
+ if (!held && shouldHold) {
+ held = true;
+ entered.resolve();
+ await release.promise;
+ }
+ switch (method) {
+ case "settings.get": return {};
+ case "session.get": return { session: {
+ id: params.id, mode: "agent", permissionMode: "ask", messages: history,
+ providerId: "fixture", modelId: "fixture-model",
+ } };
+ case "session.beginTurn": return { turnId: `turn-${++turnCounter}` };
+ case "session.appendMessage": {
+ const index = history.findIndex((message) => message.id === params.message.id);
+ if (index < 0) history.push(params.message);
+ else history[index] = params.message;
+ return { ok: true };
+ }
+ case "session.endTurn": durableEnds.push(params); return { ok: true };
+ case "session.saveInflightMessage": return { ok: true };
+ case "plans.abort": return { ok: true };
+ case "tools.fileBatchCapabilities": return { version: 1, supported: false };
+ default: throw new Error(`Unexpected fixture Host call: ${method}`);
+ }
+ },
+ isAvailable: () => true,
+ onNotification: () => () => {},
+ onExit: () => () => {},
+ };
+ sidecar = new AgentSidecar({
+ launch: { command: process.execPath, args: [bundle], env: await isolatedEnv(scratch), cwd: scratch },
+ onStderr: (chunk) => { stderr += chunk; },
+ });
+ sidecar.setHost(host);
+ service = new RuntimeService({
+ getHost: () => host,
+ getSidecar: () => sidecar,
+ launch: { async resolve(sessionId) {
+ return {
+ providerId: "fixture", modelId: "fixture-model", projectPath: scratch,
+ sidecarParams: {
+ sessionId, mode: "agent", thinkingLevel: "off", scratchDir: scratch,
+ commandShell: { id: "bash", label: "Bash", dialect: "posix", available: true, isDefault: true },
+ provider: {
+ id: "fixture", name: "Fixture", modelId: "fixture-model", apiKey: "fixture-only",
+ baseUrl: `http://127.0.0.1:${server.address().port}/v1`, apiStyle: "chat_completions",
+ supportsReasoning: false, supportedThinkingLevels: ["off"],
+ },
+ },
+ };
+ } },
+ log: () => {},
+ });
+ service.attachHost(host);
+ service.attachSidecar(sidecar);
+ service.onTurnEnded((info) => {
+ ended.push(info);
+ if (info.turnId === "turn-2") nextEnded.resolve(info);
+ });
+ await sidecar.call("sidecar.health");
+ const sessionId = `startup-${phase}`;
+ const starting = service.prompt({ sessionId, content: "First task", effectivePermissionMode: "ask", principal });
+ await entered.promise;
+ let abortReturned = false;
+ const stopping = service.abort(sessionId, phase === "restore" ? "turn-1" : undefined)
+ .then(() => { abortReturned = true; });
+ // A real status round trip lets an incorrectly early cancellation settle
+ // while the admission gate is still closed, without a timing-based sleep.
+ await service.getStatus(sessionId);
+ const returnedBeforeAdmission = abortReturned;
+ release.resolve();
+ await Promise.all([starting, stopping]);
+ assert.equal(returnedBeforeAdmission, false, "abort acknowledged before the runtime could be canceled");
+ assert.equal((await service.getStatus(sessionId)).isRunning, false, "the aborted startup still runs");
+ assert.deepEqual(ended.map(({ turnId, reason }) => ({ turnId, reason })), [{ turnId: "turn-1", reason: "aborted" }]);
+ assert.equal(durableEnds.length, 1);
+ assert.equal(durableEnds[0].status, "aborted");
+
+ await service.prompt({ sessionId, content: "Follow-up task", effectivePermissionMode: "ask", principal });
+ assert.equal((await nextEnded.promise).reason, "completed");
+ assert.equal(service.isBusy(sessionId), false);
+ assert.ok(history.some((message) => message.role === "assistant" && message.content === "Follow-up completed"));
+ const lastUser = providerBodies.at(-1).messages.filter((message) => message.role === "user").at(-1);
+ assert.ok(JSON.stringify(lastUser.content).includes("Follow-up task"));
+ assert.equal(durableEnds.length, 2, "each durable turn must settle once");
+ assert.doesNotMatch(stderr, /unhandled promise rejection|TypeError:|ReferenceError:/);
+ });
+}