Skip to content

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

fix(host-runtime): drain checkpoint writes across turn settlement

FuYukiH25bca249dc09
diff --git a/apps/desktop/test/inflight-checkpoint-lifecycle.test.mjs b/apps/desktop/test/inflight-checkpoint-lifecycle.test.mjs
new file mode 100644
index 000000000..8ec94c955
--- /dev/null
+++ b/apps/desktop/test/inflight-checkpoint-lifecycle.test.mjs
@@ -0,0 +1,148 @@
+import assert from "node:assert/strict";
+import { setImmediate as nextTurn } from "node:timers/promises";
+import test from "node:test";
+import { InflightCheckpointer } from "../../../packages/host-runtime/src/inflight-checkpoint.ts";
+
+const snapshot = (id, content = id, sessionId = "session") => ({
+ sessionId, turnId: id,
+ message: { id, role: "assistant", content, createdAt: "2026-10-27T00:00:00Z" },
+});
+
+for (const settled of [false, true]) {
+ test(`flushAll awaits a started save${settled ? " after its session is settled" : " with no trailing snapshot"}`, async (t) => {
+ const gate = Promise.withResolvers();
+ const started = Promise.withResolvers();
+ let saved = false;
+ const writer = new InflightCheckpointer(async () => {
+ started.resolve();
+ await gate.promise;
+ saved = true;
+ });
+ t.after(async () => { gate.resolve(); await writer.flushAll(); writer.dispose(); });
+ writer.observe(snapshot("reply"));
+ await started.promise;
+ if (settled) writer.settle("session");
+ let flushed = false;
+ const flushing = writer.flushAll().then(() => { flushed = true; });
+ await nextTurn();
+ assert.equal(flushed, false, "host shutdown must not outrun the checkpoint RPC");
+ gate.resolve();
+ await flushing;
+ assert.equal(saved, true);
+ assert.deepEqual(writer.pendingSessions(), []);
+ });
+}
+
+test("settling a turn cannot start a newer save before the old write finishes", async (t) => {
+ const gate = Promise.withResolvers();
+ const oldStarted = Promise.withResolvers();
+ const order = [];
+ let concurrent = 0;
+ let maximum = 0;
+ const writer = new InflightCheckpointer(async ({ message }) => {
+ concurrent++;
+ maximum = Math.max(maximum, concurrent);
+ if (message.id === "old") { oldStarted.resolve(); await gate.promise; }
+ order.push(message.id);
+ concurrent--;
+ });
+ t.after(async () => { gate.resolve(); await writer.flushAll(); writer.dispose(); });
+ writer.observe(snapshot("old"));
+ await oldStarted.promise;
+ writer.settle("session");
+ writer.observe(snapshot("new"));
+ const flushing = writer.flushAll();
+ await nextTurn();
+ assert.equal(maximum, 1, "a settled generation still owns its unfinished write");
+ gate.resolve();
+ await flushing;
+ assert.deepEqual([...order], ["old", "new"]);
+ assert.equal(maximum, 1);
+});
+
+test("flushAll drains a newer snapshot queued behind an existing save", async (t) => {
+ const gate = Promise.withResolvers();
+ const started = Promise.withResolvers();
+ const saved = [];
+ const writer = new InflightCheckpointer(async ({ message }) => {
+ if (saved.length === 0) { started.resolve(); await gate.promise; }
+ saved.push(message.content);
+ }, 60_000);
+ t.after(async () => { gate.resolve(); await writer.flushAll(); writer.dispose(); });
+ writer.observe(snapshot("reply", "first"));
+ await started.promise;
+ writer.observe(snapshot("reply", "latest"));
+ const flushing = writer.flushAll();
+ gate.resolve();
+ await flushing;
+ assert.deepEqual([...saved], ["first", "latest"]);
+});
+
+test("a drain does not chase snapshots accepted after its barrier", async (t) => {
+ const first = Promise.withResolvers();
+ const second = Promise.withResolvers();
+ const firstStarted = Promise.withResolvers();
+ const secondStarted = Promise.withResolvers();
+ const saved = [];
+ const writer = new InflightCheckpointer(async ({ message }) => {
+ if (message.content === "first") { firstStarted.resolve(); await first.promise; }
+ if (message.content === "target") { secondStarted.resolve(); await second.promise; }
+ saved.push(message.content);
+ }, 60_000);
+ t.after(async () => { first.resolve(); second.resolve(); await writer.flushAll(); writer.dispose(); });
+ writer.observe(snapshot("reply", "first"));
+ await firstStarted.promise;
+ writer.observe(snapshot("reply", "target"));
+ const flushing = writer.flushAll();
+ first.resolve();
+ await secondStarted.promise;
+ writer.observe(snapshot("reply", "later"));
+ second.resolve();
+ await flushing;
+ assert.deepEqual([...saved], ["first", "target"]);
+ assert.deepEqual(writer.pendingSessions(), ["session"]);
+});
+
+test("late settlement of an older message preserves a newer write's throttle", async (t) => {
+ t.mock.timers.enable({ apis: ["Date", "setTimeout"] });
+ const gate = Promise.withResolvers();
+ const started = Promise.withResolvers();
+ const saved = [];
+ const writer = new InflightCheckpointer(async ({ message }) => {
+ saved.push(message.content);
+ if (message.content === "first") { started.resolve(); await gate.promise; }
+ }, 1000);
+ t.after(async () => { gate.resolve(); await writer.flushAll(); writer.dispose(); });
+ writer.observe(snapshot("new", "first"));
+ await started.promise;
+ writer.settleIf("session", "old");
+ writer.observe(snapshot("new", "latest"));
+ gate.resolve();
+ await nextTurn();
+ assert.deepEqual([...saved], ["first"]);
+ t.mock.timers.tick(1000);
+ await nextTurn();
+ assert.deepEqual([...saved], ["first", "latest"]);
+});
+
+test("flushing a final message does not force writes for the next reply", async (t) => {
+ t.mock.timers.enable({ apis: ["Date", "setTimeout"] });
+ const gate = Promise.withResolvers();
+ const started = Promise.withResolvers();
+ const saved = [];
+ const writer = new InflightCheckpointer(async ({ message }) => {
+ saved.push(message.id);
+ if (message.id === "old") { started.resolve(); await gate.promise; }
+ }, 1000);
+ t.after(async () => { gate.resolve(); await writer.flushAll(); writer.dispose(); });
+ writer.observe(snapshot("old"));
+ await started.promise;
+ const flushing = writer.flush("session");
+ writer.observe(snapshot("new"));
+ gate.resolve();
+ await flushing;
+ assert.deepEqual([...saved], ["old"]);
+ t.mock.timers.tick(1000);
+ await nextTurn();
+ assert.deepEqual([...saved], ["old", "new"]);
+});
diff --git a/docs/spec/03-runtime/04-data-storage.md b/docs/spec/03-runtime/04-data-storage.md
index b9b34e30a..94320b4a5 100644
--- a/docs/spec/03-runtime/04-data-storage.md
+++ b/docs/spec/03-runtime/04-data-storage.md
@@ -1549,6 +1549,11 @@ sweep promotes a leftover checkpoint whose final row never landed: as
`aborted` turn. `completed`/`error` endTurn does not delete an unindexed
checkpoint. A user Stop does not touch the checkpoint, because the runtime's
own aborted final row is still on its way and removes it on arrival.
+Checkpoint writes are serialized per session even across message settlement:
+forgetting a pending snapshot does not cancel or release an already issued RPC.
+Shutdown drains both pending snapshots and unfinished writes before disposing
+the host. A final-message flush stays scoped to that message; later replies keep
+the streaming throttle, and other sessions can save independently.
Electron handshake awaits the outbox drain before a cold `session.get`.
Renderer-side Stop never rewrites a transcript that has a
started reply (spec 01 §5.3); its only rewrite is the undo of an unanswered
diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.md
index 44c1a5e3a..0eab354b1 100644
--- a/docs/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/spec/06-delivery/04-e2e-test-plan.md
@@ -88,6 +88,23 @@
- **Specs:** `04-ux/08-component-spec.md` §turn-process; **Milestone:** Maintenance.
- **Status:** Unit and source-contract regression; visual Electron scenario Draft.
+### E2E-CHECKPOINT-drain-before-host-exit
+
+- **Entry:** `node scripts/e2e-checkpoint-lifecycle.mjs` after building shared
+ and host-runtime dependencies.
+- **Sequence:** Hold a streaming checkpoint RPC, start runtime disposal, release
+ the save and restart the host peer. Then hold an older turn's save, settle its
+ message, start a new reply, and save a second session while the first is held.
+- **Expected:** Host disposal waits for the checkpoint acknowledgement; the
+ restarted peer reads the saved progress. A new save in the same session waits
+ for the older write, so the newest reply remains on disk. The independent
+ session saves while the other is blocked.
+- **Coverage:** Production `HostProcess`, `TurnEventPipeline` and
+ `InflightCheckpointer`, real child processes and temporary disk files; a
+ controlled Node JSON-RPC peer replaces Rust host-core. Unit tests cover late
+ settlement, snapshots arriving during a drain, failure recovery and throttling.
+- **Specs:** `03-runtime/04-data-storage.md` §4.7, ADR 0153.
+
### E2E model discovery membership
- **Entry:** `node scripts/e2e-model-discovery-state.mjs` after building Host,
diff --git a/packages/host-runtime/src/inflight-checkpoint.ts b/packages/host-runtime/src/inflight-checkpoint.ts
index f2c61d9f4..63d65fe48 100644
--- a/packages/host-runtime/src/inflight-checkpoint.ts
+++ b/packages/host-runtime/src/inflight-checkpoint.ts
@@ -14,10 +14,10 @@ export type InflightCheckpoint = {
};
type SessionState = {
+ messageId: string;
lastSavedAt: number;
pending?: InflightCheckpoint;
timer?: ReturnType<typeof setTimeout>;
- inFlight?: Promise<void>;
};
/** Whether a streamed assistant message carries anything worth keeping. */
@@ -34,11 +34,13 @@ export function isCheckpointableMessage(message: UiMessage): boolean {
* `observe` is fed every `message_update`; the newest snapshot wins and is
* written at most once per interval, with a trailing write so the last update
* of a burst is not lost to the throttle. `settle` drops whatever is pending
- * once the final row is on its way: the host's own append supersedes the
- * checkpoint, and a late write is a wasted round trip at best.
+ * once the final row is on its way. Issued writes stay tracked until they
+ * finish, so shutdown and later turns cannot overtake them.
*/
export class InflightCheckpointer {
private readonly sessions = new Map<string, SessionState>();
+ /** Physical writes outlive settlement of the message that started them. */
+ private readonly writes = new Map<string, Promise<void>>();
private readonly save: (checkpoint: InflightCheckpoint) => Promise<unknown>;
private readonly intervalMs: number;
private readonly now: () => number;
@@ -58,19 +60,20 @@ export class InflightCheckpointer {
if (this.disposed || !isCheckpointableMessage(checkpoint.message)) return;
let state = this.sessions.get(checkpoint.sessionId);
if (!state) {
- state = { lastSavedAt: Number.NEGATIVE_INFINITY };
+ state = { messageId: checkpoint.message.id, lastSavedAt: Number.NEGATIVE_INFINITY };
this.sessions.set(checkpoint.sessionId, state);
}
+ state.messageId = checkpoint.message.id;
state.pending = checkpoint;
- if (state.timer || state.inFlight) return;
+ if (state.timer || this.writes.has(checkpoint.sessionId)) return;
const due = state.lastSavedAt + this.intervalMs - this.now();
if (due <= 0) {
- this.flush(checkpoint.sessionId);
+ void this.writePending(checkpoint.sessionId);
return;
}
state.timer = setTimeout(() => {
state!.timer = undefined;
- this.flush(checkpoint.sessionId);
+ void this.writePending(checkpoint.sessionId);
}, due);
state.timer.unref?.();
}
@@ -83,7 +86,7 @@ export class InflightCheckpointer {
settleIf(sessionId: string, messageId: string): void {
const state = this.sessions.get(sessionId);
if (!state) return;
- if (state.pending && state.pending.message.id !== messageId) return;
+ if (state.messageId !== messageId) return;
this.settle(sessionId);
}
@@ -95,19 +98,19 @@ export class InflightCheckpointer {
this.sessions.delete(sessionId);
}
- /** Sessions that still have an unsaved snapshot, for a shutdown flush. */
+ /** Sessions with a pending or still-writing snapshot, including settled turns. */
pendingSessions(): string[] {
- return [...this.sessions.entries()]
- .filter(([, state]) => state.pending)
- .map(([sessionId]) => sessionId);
+ return [...new Set([
+ ...this.writes.keys(),
+ ...[...this.sessions.entries()]
+ .filter(([, state]) => state.pending)
+ .map(([sessionId]) => sessionId),
+ ])];
}
- /** Write every pending snapshot now, ignoring the interval. */
+ /** Drain the work present at this barrier; callers quiesce producers before shutdown. */
async flushAll(): Promise<void> {
- const flushes = this.pendingSessions().map((sessionId) =>
- this.flush(sessionId),
- );
- await Promise.allSettled(flushes);
+ await Promise.allSettled(this.pendingSessions().map((sessionId) => this.flush(sessionId)));
}
dispose(): void {
@@ -118,13 +121,24 @@ export class InflightCheckpointer {
this.sessions.clear();
}
- /** Write the session's pending snapshot now, ignoring the interval. */
- flush(sessionId: string): Promise<void> {
+ /** Drain this message's writes without forcing a later reply past its throttle. */
+ async flush(sessionId: string): Promise<void> {
+ const state = this.sessions.get(sessionId);
+ const messageId = state?.messageId;
+ const pending = state?.pending;
+ const inFlight = this.writes.get(sessionId);
+ if (inFlight) await inFlight;
+ if (pending && this.sessions.get(sessionId) === state && state?.messageId === messageId) {
+ await this.writePending(sessionId);
+ }
+ }
+
+ /** Start one write; ordinary streaming keeps the interval between writes. */
+ private writePending(sessionId: string): Promise<void> {
+ const inFlight = this.writes.get(sessionId);
+ if (inFlight) return inFlight;
const state = this.sessions.get(sessionId);
if (!state) return Promise.resolve();
- // A write already running carries an older snapshot; the newer one goes
- // right after it so a shutdown flush ends on the latest text.
- if (state.inFlight) return state.inFlight.then(() => this.flush(sessionId));
if (!state.pending) return Promise.resolve();
if (state.timer) {
clearTimeout(state.timer);
@@ -136,12 +150,12 @@ export class InflightCheckpointer {
const run = this.save(checkpoint)
.catch(() => undefined)
.then(() => {
- // The state object may have been replaced by settle + observe.
- if (this.sessions.get(sessionId) !== state) return;
- state.inFlight = undefined;
- if (state.pending) this.observe(state.pending);
+ this.writes.delete(sessionId);
+ // Settlement may have replaced the logical state while this write ran.
+ const current = this.sessions.get(sessionId);
+ if (current?.pending) this.observe(current.pending);
});
- state.inFlight = run;
+ this.writes.set(sessionId, run);
return run;
}
}
diff --git a/packages/host-runtime/src/turn-events.test.ts b/packages/host-runtime/src/turn-events.test.ts
index 1f8efdd0c..c56aa861f 100644
--- a/packages/host-runtime/src/turn-events.test.ts
+++ b/packages/host-runtime/src/turn-events.test.ts
@@ -1,7 +1,45 @@
import { describe, expect, it } from "vitest";
+import { setImmediate as nextTurn } from "node:timers/promises";
import type { AgentEventEnvelope, UiMessage } from "@pi-desktop/shared";
import { TurnEventPipeline } from "./turn-events.js";
+it("keeps the host alive until a streaming checkpoint finishes during disposal", async () => {
+ const started = Promise.withResolvers<void>();
+ const release = Promise.withResolvers<void>();
+ let hostDisposed = false;
+ let saved: UiMessage | undefined;
+ const pipeline = new TurnEventPipeline({
+ getHost: () => ({ async call<T>(method: string, params: unknown): Promise<T> {
+ expect(method).toBe("session.saveInflightMessage");
+ started.resolve();
+ await release.promise;
+ expect(hostDisposed).toBe(false);
+ saved = (params as { message: UiMessage }).message;
+ return {} as T;
+ } }),
+ ownership: { activeTurnId: () => "turn", isStaleTerminalEvent: () => false, finishTurn: async () => undefined },
+ emit: () => undefined,
+ log: () => undefined,
+ });
+ const message: UiMessage = {
+ id: "reply", role: "assistant", content: "Migration step completed",
+ status: "streaming", createdAt: "2026-10-27T00:00:00Z",
+ };
+ pipeline.handle({ sessionId: "session", turnId: "turn", ts: 1,
+ event: { type: "message_update", message } });
+ await started.promise;
+ const disposing = pipeline.dispose().then(() => { hostDisposed = true; });
+ try {
+ await nextTurn();
+ expect(hostDisposed).toBe(false);
+ } finally {
+ release.resolve();
+ await disposing;
+ }
+ expect(saved).toMatchObject({ id: "reply", content: message.content });
+ expect(hostDisposed).toBe(true);
+});
+
for (const delegate of [false, true]) {
describe(`nested tool persistence (${delegate ? "delegate" : "root"})`, () => {
it("retains tool nesting without changing Task ownership", async () => {
diff --git a/scripts/e2e-checkpoint-lifecycle.mjs b/scripts/e2e-checkpoint-lifecycle.mjs
new file mode 100644
index 000000000..cb4cf69a8
--- /dev/null
+++ b/scripts/e2e-checkpoint-lifecycle.mjs
@@ -0,0 +1,76 @@
+/** Real host transport, event pipeline and disk writes against a controlled RPC peer. */
+import assert from "node:assert/strict";
+import { mkdtemp, rm } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { setImmediate as nextTurn } from "node:timers/promises";
+import { fileURLToPath } from "node:url";
+import { HostProcess } from "../packages/host-runtime/dist/host-process.js";
+import { TurnEventPipeline } from "../packages/host-runtime/dist/turn-events.js";
+import { InflightCheckpointer } from "../packages/host-runtime/dist/inflight-checkpoint.js";
+
+const root = await mkdtemp(join(tmpdir(), "pi-checkpoint-lifecycle-"));
+const hosts = [];
+const snapshot = (sessionId, id) => ({ sessionId, turnId: `turn-${id}`,
+ message: { id, role: "assistant", content: `Progress from ${id}`, createdAt: "2026-10-27T00:00:00Z" } });
+async function startHost() {
+ const host = new HostProcess({ binaryPath: process.execPath, dataDir: root,
+ env: { NODE_OPTIONS: `--require=${JSON.stringify(fileURLToPath(new URL("./e2e/checkpoint-host-fixture.cjs", import.meta.url)))}` },
+ onStderr: (text) => process.stderr.write(text),
+ });
+ hosts.push(host);
+ await host.handshake();
+ return host;
+}
+const call = (host, method, params) => host.call(method, params, 5000);
+
+try {
+ const host = await startHost();
+ const pipeline = new TurnEventPipeline({
+ getHost: () => host,
+ ownership: { activeTurnId: () => "turn-held", isStaleTerminalEvent: () => false, finishTurn: async () => undefined },
+ emit: () => undefined, log: () => undefined,
+ });
+ const checkpoint = snapshot("shutdown", "held");
+ pipeline.handle({ sessionId: checkpoint.sessionId, turnId: checkpoint.turnId, ts: 1,
+ event: { type: "message_update", message: checkpoint.message } });
+ await call(host, "fixture.waitStarted", { sessionId: "shutdown", id: "held" });
+ const quitting = pipeline.dispose().then(() => host.dispose());
+ await nextTurn();
+ assert.equal(host.isAvailable(), true, "disposal closed the host before its save reply");
+ await call(host, "fixture.release", { sessionId: "shutdown", id: "held" });
+ await quitting;
+
+ const restarted = await startHost();
+ const recovered = await call(restarted, "fixture.read", { sessionId: "shutdown" });
+ assert.deepEqual(recovered, checkpoint);
+
+ const writer = new InflightCheckpointer((value) =>
+ call(restarted, "session.saveInflightMessage", value));
+ try {
+ writer.observe(snapshot("handoff", "old"));
+ await call(restarted, "fixture.waitStarted", { sessionId: "handoff", id: "old" });
+ writer.settle("handoff");
+ writer.observe(snapshot("handoff", "new"));
+ writer.observe(snapshot("parallel", "free"));
+ await call(restarted, "fixture.waitSaved", { sessionId: "parallel", id: "free" });
+ const state = await call(restarted, "fixture.state");
+ assert.deepEqual(state.started.filter((item) => item.sessionId === "handoff").map((item) => item.id), ["old"]);
+ const flushing = writer.flushAll();
+ await call(restarted, "fixture.release", { sessionId: "handoff", id: "old" });
+ await flushing;
+ const latest = await call(restarted, "fixture.read", { sessionId: "handoff" });
+ assert.equal(latest.message.id, "new");
+ assert.deepEqual(writer.pendingSessions(), []);
+ } finally {
+ await call(restarted, "fixture.release", { sessionId: "handoff", id: "old" });
+ await writer.flushAll();
+ writer.dispose();
+ }
+ await restarted.dispose();
+ console.log(JSON.stringify({ passed: true, checkpointSurvivedRestart: true,
+ sameSessionWritesSerialized: true, otherSessionProgressedWhileHeld: true }));
+} finally {
+ await Promise.allSettled(hosts.map((host) => host.dispose()));
+ await rm(root, { recursive: true, force: true });
+}
diff --git a/scripts/e2e/checkpoint-host-fixture.cjs b/scripts/e2e/checkpoint-host-fixture.cjs
new file mode 100644
index 000000000..f454ff6a5
--- /dev/null
+++ b/scripts/e2e/checkpoint-host-fixture.cjs
@@ -0,0 +1,60 @@
+/** Controlled JSON-RPC peer for checkpoint lifecycle tests; data is temporary. */
+const { createInterface } = require("node:readline");
+const { readFile, rename, writeFile } = require("node:fs/promises");
+const { join } = require("node:path");
+
+const root = process.env.PI_DESKTOP_DATA_DIR;
+const started = [];
+const startWaiters = new Map();
+const saveWaiters = new Map();
+const held = new Map();
+const saved = new Set();
+const key = (sessionId, id) => `${sessionId}:${id}`;
+const checkpointPath = (sessionId) => join(root, `${sessionId}.inflight.json`);
+function waiter(map, id) {
+ if (!map.has(id)) map.set(id, Promise.withResolvers());
+ return map.get(id);
+}
+function send(response) { process.stdout.write(JSON.stringify(response) + "\n"); }
+
+async function handle({ id, method, params = {} }) {
+ try {
+ let result = {};
+ if (method === "session.saveInflightMessage") {
+ const identity = key(params.sessionId, params.message.id);
+ started.push({ sessionId: params.sessionId, id: params.message.id });
+ waiter(startWaiters, identity).resolve();
+ if (params.message.id === "held" || params.message.id === "old") {
+ await waiter(held, identity).promise;
+ }
+ const target = checkpointPath(params.sessionId);
+ const temporary = `${target}.${params.message.id}.tmp`;
+ await writeFile(temporary, JSON.stringify(params));
+ await rename(temporary, target);
+ saved.add(identity);
+ waiter(saveWaiters, identity).resolve();
+ } else if (method === "fixture.waitStarted") {
+ await waiter(startWaiters, key(params.sessionId, params.id)).promise;
+ } else if (method === "fixture.waitSaved") {
+ const identity = key(params.sessionId, params.id);
+ if (!saved.has(identity)) await waiter(saveWaiters, identity).promise;
+ } else if (method === "fixture.release") {
+ waiter(held, key(params.sessionId, params.id)).resolve();
+ } else if (method === "fixture.state") {
+ result = { started };
+ } else if (method === "fixture.read") {
+ result = JSON.parse(await readFile(checkpointPath(params.sessionId), "utf8"));
+ } else if (method !== "app.handshake") {
+ throw new Error(`unexpected fixture method: ${method}`);
+ }
+ send({ jsonrpc: "2.0", id, result });
+ } catch (error) {
+ send({ jsonrpc: "2.0", id, error: { code: -32603, message: error.message } });
+ }
+}
+
+// A --require preload receives stdin before Node's stdin script entry point.
+// EOF has the same shutdown meaning as the real host.
+const lines = createInterface({ input: process.stdin });
+lines.on("line", (line) => { if (line.trim()) void handle(JSON.parse(line)); });
+lines.on("close", () => process.exit(0));