Skip to content

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

fix(agent-runtime): wait for stopped turns to settle

vastsa476962bf783e
diff --git a/apps/desktop/electron/main/ipc/agent-ipc.ts b/apps/desktop/electron/main/ipc/agent-ipc.ts
index face8cce2..2c190e02b 100644
--- a/apps/desktop/electron/main/ipc/agent-ipc.ts
+++ b/apps/desktop/electron/main/ipc/agent-ipc.ts
@@ -648,7 +648,10 @@ export function registerAgentIpc({
// An open extension prompt resolves with its abort value (spec 16 §9).
agentExtensions.cancelPrompts(req.sessionId);
cancelSessionTools(req.sessionId, "Session turn was aborted");
- result = await sidecar.call("agent.abort", req);
+ result = await sidecar.call("agent.abort", {
+ ...req,
+ ...(abortedTurnId ? { turnId: abortedTurnId } : {}),
+ });
} finally {
// A turn that already stopped owning the session is refused inside the
// finalizer, so the identity captured above is the only one used here.
diff --git a/apps/desktop/test/session-message-input.test.mjs b/apps/desktop/test/session-message-input.test.mjs
index d063be8f8..2fab6e07f 100644
--- a/apps/desktop/test/session-message-input.test.mjs
+++ b/apps/desktop/test/session-message-input.test.mjs
@@ -137,8 +137,8 @@ test("abort waits for prompt admission before dispatching to the sidecar", async
getHost: () => host,
getSidecar: () => ({
setProjectInstructionRoot() {},
- async call(method) {
- sidecarCalls.push(method);
+ async call(method, params) {
+ sidecarCalls.push({ method, params });
if (method === "agent.prompt") {
await promptGate;
return { accepted: true, turnId: "turn-1" };
@@ -180,7 +180,11 @@ test("abort waits for prompt admission before dispatching to the sidecar", async
releasePrompt();
await prompt;
await abort;
- assert.deepEqual(sidecarCalls, ["agent.prompt", "agent.abort"]);
+ assert.deepEqual(sidecarCalls.map((call) => call.method), ["agent.prompt", "agent.abort"]);
+ assert.deepEqual(sidecarCalls[1], {
+ method: "agent.abort",
+ params: { sessionId: "target", turnId: "turn-1" },
+ });
assert.equal(activeTurns.get("target"), "turn-1");
assert.deepEqual(finishedTurns, [["target", "aborted", "TURN_ABORTED", { turnId: "turn-1" }]]);
assert.deepEqual(calls.slice(0, 2), ["settings.get", "session.get"]);
diff --git a/docs/spec/03-runtime/02-agent-runtime.md b/docs/spec/03-runtime/02-agent-runtime.md
index 067998318..faf09f5d3 100644
--- a/docs/spec/03-runtime/02-agent-runtime.md
+++ b/docs/spec/03-runtime/02-agent-runtime.md
@@ -70,7 +70,9 @@ loop evaluates it after `turn_end`, once the current assistant response and
tool batch have completed, and emits a normal `agent_end` before another model
request. It does not cancel an active provider stream or running tool. An idle
runtime returns `{ requested: false }`; immediate `abort()` remains the
-separate cancellation path.
+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.
### 4.0 Active-turn steering
diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.md
index 25a811967..22a6af49f 100644
--- a/docs/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/spec/06-delivery/04-e2e-test-plan.md
@@ -1693,12 +1693,15 @@ identify the platform validation still needed.
- **Steps**: 1) Send ordinary text and click Stop immediately, including while
the prompt is still being admitted. 2) Confirm the user row is undone and
the text returns to the composer after that first Stop. 3) Send again, wait
- for partial output, then stop during the stream. 4) Observe the transcript
- and composer.
+ for partial output, then stop during the stream. 4) Immediately send a new
+ prompt after Stop returns, without waiting for an idle delay. 5) Observe the
+ transcript and composer.
- **Expected**: The first Stop is honored even if prompt admission is still in
progress; the unanswered send is undone and its draft restored. The
streaming send stops with its partial response preserved and no draft
- restoration or duplicate user turn. The session remains usable.
+ restoration or duplicate user turn. Stop returns after the active runtime
+ operation has settled, and the follow-up starts without `AGENT_BUSY`. The
+ session remains usable.
- **Specs linked**: `03-runtime/02-agent-runtime.md`
- **Acceptance**: C (abort)
- **Milestone**: M2
diff --git a/packages/agent-runtime/src/runtime.test.ts b/packages/agent-runtime/src/runtime.test.ts
index 6fe4d6ca8..090d4c9dd 100644
--- a/packages/agent-runtime/src/runtime.test.ts
+++ b/packages/agent-runtime/src/runtime.test.ts
@@ -7146,11 +7146,20 @@ describe("DesktopAgentRuntime per-turn context protection", () => {
const agent = (runtime as any).agent;
agent.prompt = vi.fn();
vi.spyOn(runtime as any, "automaticCompactionNeeded").mockReturnValue(true);
+ let releaseCheckpoint!: () => void;
+ let checkpointStarted!: () => void;
+ const checkpointGate = new Promise<void>((resolve) => {
+ releaseCheckpoint = resolve;
+ });
+ const checkpointReady = new Promise<void>((resolve) => {
+ checkpointStarted = resolve;
+ });
// The summary request is in flight when the user presses Stop.
vi.spyOn(runtime as any, "buildCheckpoint").mockImplementation(
async (...args: unknown[]) => {
const signal = args[0] as AbortSignal;
- await runtime.abort();
+ checkpointStarted();
+ await checkpointGate;
return {
ok: false,
entries: [],
@@ -7161,9 +7170,14 @@ describe("DesktopAgentRuntime per-turn context protection", () => {
},
);
- await expect(runtime.prompt("stopped request", "user-stopped")).rejects.toMatchObject({
+ const prompt = runtime.prompt("stopped request", "user-stopped");
+ await checkpointReady;
+ const abort = runtime.abort();
+ releaseCheckpoint();
+ await expect(prompt).rejects.toMatchObject({
name: "AbortError",
});
+ await abort;
expect(agent.prompt).not.toHaveBeenCalled();
expect((runtime as any).fullEntries).toEqual([
@@ -7191,6 +7205,59 @@ describe("DesktopAgentRuntime per-turn context protection", () => {
await runtime.dispose();
});
+ it("waits for the aborted prompt to settle before accepting a follow-up", async () => {
+ const runtime = createRuntime();
+ const testRuntime = runtime as unknown as {
+ agent: {
+ prompt: () => Promise<void>;
+ abort: () => void;
+ };
+ handleAgentEvent: (event: { type: "agent_end" }) => Promise<void>;
+ };
+ const agent = testRuntime.agent;
+ let rejectFirstPrompt!: (error: Error) => void;
+ let firstPromptStarted!: () => void;
+ const firstPromptGate = new Promise<void>((_resolve, reject) => {
+ rejectFirstPrompt = reject;
+ });
+ const firstPromptReady = new Promise<void>((resolve) => {
+ firstPromptStarted = resolve;
+ });
+ let promptCount = 0;
+ agent.prompt = vi.fn(async () => {
+ promptCount += 1;
+ if (promptCount === 1) {
+ firstPromptStarted();
+ await firstPromptGate;
+ return;
+ }
+ await testRuntime.handleAgentEvent({ type: "agent_end" });
+ });
+ agent.abort = vi.fn();
+
+ const firstPrompt = runtime.prompt("first task", "user-first", "turn-first");
+ await firstPromptReady;
+ let abortSettled = false;
+ const abort = runtime.abort().then(() => {
+ abortSettled = true;
+ });
+ await Promise.resolve();
+ expect(abortSettled).toBe(false);
+
+ rejectFirstPrompt(Object.assign(new Error("The operation was aborted"), {
+ name: "AbortError",
+ }));
+ await expect(firstPrompt).rejects.toMatchObject({ name: "AbortError" });
+ await abort;
+ expect(abortSettled).toBe(true);
+
+ await expect(runtime.prompt("continue", "user-next", "turn-next")).resolves.toEqual({
+ turnId: "turn-next",
+ });
+ expect(agent.prompt).toHaveBeenCalledTimes(2);
+ await runtime.dispose();
+ });
+
it("closes an overflow recovery cut short by Stop as aborted", async () => {
const onEvent = vi.fn();
const runtime = createRuntime({ onEvent });
diff --git a/packages/agent-runtime/src/runtime.ts b/packages/agent-runtime/src/runtime.ts
index c1b02e77f..752044810 100644
--- a/packages/agent-runtime/src/runtime.ts
+++ b/packages/agent-runtime/src/runtime.ts
@@ -1932,6 +1932,8 @@ export class DesktopAgentRuntime {
private turnEpoch = 0;
private compactionAbort?: AbortController;
private compactionInProgress = false;
+ /** Runtime operations that own a durable turn until their async cleanup ends. */
+ private readonly activeTurnSettlements = new Map<string, Promise<void>>();
/** The in-flight checkpoint was cut short by Stop/dispose, not by a failure. */
private compactionAborted = false;
/** Set by the `new_context` tool, consumed at the next turn boundary. */
@@ -8493,7 +8495,15 @@ Do not invent objections or turn speculative risks into blockers. Stop when the
errorCode: "TURN_NOT_FOUND",
});
}
+ return this.trackTurnOperation(durableTurnId, () =>
+ this.executeApprovedPlanTurn(execution, durableTurnId),
+ );
+ }
+ private async executeApprovedPlanTurn(
+ execution: PlanExecution,
+ durableTurnId: string,
+ ): Promise<{ turnId: string }> {
// Keep every new user turn small. A capability loaded for the preceding
// turn can be searched again when the new task actually needs it.
this.subagentOverrideProviders = {};
@@ -8604,12 +8614,23 @@ Do not invent objections or turn speculative risks into blockers. Stop when the
): Promise<{ turnId: string }> {
if (this.disposed) throw new Error("runtime disposed");
this.assertNotRunning();
+ const turnId = durableTurnId?.trim() || randomUUID();
+ return this.trackTurnOperation(turnId, () =>
+ this.promptTurn(input, userMessageId, turnId),
+ );
+ }
+
+ private async promptTurn(
+ input: string | RuntimePrompt,
+ userMessageId: string | undefined,
+ durableTurnId: string,
+ ): Promise<{ turnId: string }> {
const selectedTools = this.selectedMcpTools(input);
const modelInput = typeof input !== "string" && input.sessionMessage
? { ...input, text: formatSessionMessage(input.text, input.sessionMessage), sessionMessage: undefined }
: input;
this.retainPendingSteering();
- const nextTurnId = durableTurnId?.trim() || randomUUID();
+ const nextTurnId = durableTurnId;
this.turnId = nextTurnId;
this.acceptingSteering = true;
this.gracefulStopRequested = false;
@@ -8876,6 +8897,10 @@ Do not invent objections or turn speculative risks into blockers. Stop when the
}
async abort(): Promise<void> {
+ const turnId = this.turnId;
+ const settlement = turnId
+ ? this.activeTurnSettlements.get(turnId)
+ : undefined;
this.acceptingSteering = false;
this.gracefulStopRequested = false;
this.runCancelled = true;
@@ -8888,6 +8913,34 @@ Do not invent objections or turn speculative risks into blockers. Stop when the
this.providerRetryAbort?.abort();
if (this.compactionInProgress) this.compactionAborted = true;
this.compactionAbort?.abort();
+ await settlement;
+ }
+
+ private trackTurnOperation<T>(
+ turnId: string,
+ operation: () => Promise<T>,
+ ): Promise<T> {
+ let settle!: () => void;
+ const settlement = new Promise<void>((resolve) => {
+ settle = resolve;
+ });
+ this.activeTurnSettlements.set(turnId, settlement);
+ let result: Promise<T>;
+ try {
+ result = operation();
+ } catch (error) {
+ if (this.activeTurnSettlements.get(turnId) === settlement) {
+ this.activeTurnSettlements.delete(turnId);
+ }
+ settle();
+ throw error;
+ }
+ return result.finally(() => {
+ if (this.activeTurnSettlements.get(turnId) === settlement) {
+ this.activeTurnSettlements.delete(turnId);
+ }
+ settle();
+ });
}
/** Ask pi-agent-core to stop after the current assistant/tool turn. */
diff --git a/scripts/e2e-subagent-stop.mjs b/scripts/e2e-subagent-stop.mjs
index 2764cc388..5c1c62b69 100644
--- a/scripts/e2e-subagent-stop.mjs
+++ b/scripts/e2e-subagent-stop.mjs
@@ -30,6 +30,12 @@ const server = createServer(async (req, res) => {
const label = input.includes("Fixture worker A") ? "A" : input.includes("Fixture worker B") ? "B" : null;
res.writeHead(200, { "content-type": "text/event-stream" });
const delta = (value, finish = null) => res.write(`data: ${JSON.stringify({ id: `fixture-${++sequence}`, object: "chat.completion.chunk", created: 1, model: body.model, choices: [{ index: 0, delta: value, finish_reason: finish }] })}\n\n`);
+ if (input.includes("Continue immediately after Stop")) {
+ delta({ role: "assistant", content: "Follow-up completed after Stop." });
+ delta({}, "stop");
+ res.end("data: [DONE]\n\n");
+ return;
+ }
if (label) {
workers.set(label, res);
res.on("close", () => { if (workers.get(label) === res) workers.delete(label); });
@@ -68,6 +74,24 @@ async function until(check, message = "condition") {
}
throw new Error(`Timed out: ${message}\n${output.slice(-2500)}`);
}
+async function terminateChildTree(processHandle) {
+ if (!processHandle || processHandle.exitCode !== null) return;
+ const exited = new Promise(resolve => processHandle.once("exit", resolve));
+ const signalTree = signal => {
+ try {
+ if (process.platform === "win32") processHandle.kill(signal);
+ else process.kill(-processHandle.pid, signal);
+ } catch {
+ processHandle.kill(signal);
+ }
+ };
+ signalTree("SIGTERM");
+ const timeout = setTimeout(() => {
+ if (processHandle.exitCode === null) signalTree("SIGKILL");
+ }, 5_000);
+ await exited;
+ clearTimeout(timeout);
+}
async function connect(port, type) {
const target = await until(async () => {
try { return (await (await fetch(`http://127.0.0.1:${port}/json/list`)).json()).find(target => target.type === type && (type !== "page" || target.url.includes("/out/renderer/index.html") && !target.url.includes("surface="))); }
@@ -100,7 +124,7 @@ async function connect(port, type) {
const ports = [await freePort(), await freePort()];
const env = { ...process.env, HOME: join(scratch, "home"), PI_DESKTOP_DATA_DIR: join(scratch, "data"), PI_DESKTOP_HOST_BIN: resolveHostBinary(), PI_DESKTOP_PLAN_UI_PROBE: "1", PI_DESKTOP_TEST_API_KEY: "local-fixture", PI_DESKTOP_TEST_BASE_URL: `http://127.0.0.1:${server.address().port}/v1`, PI_DESKTOP_TEST_MODEL: "deepseek-flash", ELECTRON_RENDERER_URL: "", PI_DESKTOP_START_MAXIMIZED: "0" };
delete env.ELECTRON_RUN_AS_NODE;
-const child = spawn(resolveElectronBinary(root).electronBinary, [`--remote-debugging-port=${ports[0]}`, `--inspect=${ports[1]}`, `--user-data-dir=${join(scratch, "profile")}`, "."], { cwd: join(root, "apps/desktop"), env, stdio: ["ignore", "pipe", "pipe"] });
+const child = spawn(resolveElectronBinary(root).electronBinary, [`--remote-debugging-port=${ports[0]}`, `--inspect=${ports[1]}`, `--user-data-dir=${join(scratch, "profile")}`, "."], { cwd: join(root, "apps/desktop"), env, stdio: ["ignore", "pipe", "pipe"], detached: process.platform !== "win32" });
let output = "";
child.stdout.on("data", chunk => { output += chunk; });
child.stderr.on("data", chunk => { output += chunk; });
@@ -164,6 +188,28 @@ try {
}, "terminal statuses persisted");
console.log("PASS Desktop card/detail stop, session stop-all, parent isolation, partial output, persistence and invalid selection");
await invoke("agentAbort", { sessionId: setup.sessionId });
+ const followUp = await invoke("agentPrompt", {
+ sessionId: setup.sessionId,
+ content: "Continue immediately after Stop.",
+ });
+ assert.equal(followUp.ok, true, "a follow-up prompt is accepted as soon as Stop returns");
+ await until(
+ () => requests.some(request => JSON.stringify(request.messages).includes("Continue immediately after Stop")),
+ "follow-up reaches the local provider without AGENT_BUSY",
+ );
+ let followUpState;
+ await until(async () => {
+ const session = await invoke("sessionGet", { id: setup.sessionId });
+ const status = await invoke("agentGetStatus", setup.sessionId);
+ const responsePersisted = session.data.session.messages.some(
+ message => message.role === "assistant" && String(message.content ?? "").includes("Follow-up completed after Stop."),
+ );
+ followUpState = { status: status.data.status, responsePersisted };
+ return status.data.status?.isRunning === false && responsePersisted;
+ }, "follow-up turn completes and persists").catch(error => {
+ throw new Error(`${error.message}\nLast follow-up state: ${JSON.stringify(followUpState)}`);
+ });
+ console.log("PASS same-session follow-up starts immediately after Stop returns");
if (show) {
const demo = await invoke("sessionCreate", { title: "子智能体停止演示 · 本地模拟模型", mode: "agent", providerId: setup.providerId, modelId: setup.modelId, projectPath: workspace });
const demoId = demo.data.session.id;
@@ -181,7 +227,7 @@ try {
}
} finally {
main?.ws.close(); page?.ws.close();
- child.kill("SIGTERM");
+ await terminateChildTree(child);
server.closeAllConnections();
await new Promise(resolve => server.close(resolve));
if (!show) await rm(scratch, { recursive: true, force: true });