Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins
TypeScript ai-agentcoding-agentdesktop-appelectronglobali18nlocal-firstmcppipi-agentpi-desktoppluginsreactrusttypescript
fix(desktop): finish regenerate archival before host shutdown
AR307fb48a3fb6d0a
diff --git a/Summary.md b/Summary.mdnew file mode 100644index 000000000..f4bf3b03f--- /dev/null+++ b/Summary.md@@ -0,0 +1,13 @@+# PI-Desktop++PI-Desktop is a local-first coding agent application. React renders the UI,+Electron coordinates host services, Rust owns persistence and native tools,+and the Node runtime executes the agent through pi libraries.++## 2026-10-07: Terminal persistence during quit++Quit stops sidecar event production and drains tracked terminal persistence+before disposing Rust host-core. Regenerated branches remain readable after+an immediate quit and restart. An unresponsive archive retains the bounded+quit behavior and logs a warning. Verification covers success, storage failure+and timeout plus an isolated Electron regenerate/quit/restart flow.diff --git a/apps/desktop/electron/main/bootstrap/shutdown.ts b/apps/desktop/electron/main/bootstrap/shutdown.tsindex 09838771c..930ed98ad 100644--- a/apps/desktop/electron/main/bootstrap/shutdown.ts+++ b/apps/desktop/electron/main/bootstrap/shutdown.ts@@ -38,6 +38,7 @@ export type ShutdownDependencies = {activeTurns: Map<string, string>;persistenceOutbox: PersistenceOutbox;inflightCheckpointer: InflightCheckpointer;+ flushEventPersistence: () => Promise<void>;pluginPanels: Pick<PluginPanelHost, "closeAll">;plugins: Pick<PluginRuntime, "disposeAll">;userMcp: Pick<UserMcpRuntime, "disposeAll">;@@ -62,6 +63,7 @@ export function registerShutdownHandlers({activeTurns,persistenceOutbox,inflightCheckpointer,+ flushEventPersistence,pluginPanels,plugins,userMcp,@@ -168,6 +170,27 @@ export function registerShutdownHandlers({pluginViews.dispose(),]);await pluginSurfacesShutdown;+ // Stop event production before draining the terminal writes. A finished+ // turn can already have left activeTurns while its branch archive is+ // still awaiting the host; closing host-core first loses that archive.+ const sidecarShutdown = getSidecar()?.dispose();+ await Promise.allSettled([sidecarShutdown]);+ await inflightCheckpointer.flushAll();+ let persistenceTimer: ReturnType<typeof setTimeout> | undefined;+ try {+ const settled = await Promise.race([+ flushEventPersistence().then(() => true),+ new Promise<boolean>((resolve) => {+ persistenceTimer = setTimeout(() => resolve(false), QUIT_TURN_SETTLE_BUDGET_MS);+ }),+ ]);+ if (!settled) {+ logger.app("lifecycle", "warn", "quit before event persistence settled");+ }+ } finally {+ if (persistenceTimer) clearTimeout(persistenceTimer);+ }+ await persistenceOutbox.flush(getHost);const hostShutdown = getHost()?.dispose();const mcpShutdown = getMcpControl()?.stop();updater.dispose();@@ -179,7 +202,6 @@ export function registerShutdownHandlers({mcpOAuth?.disposeAll();browserHost.dispose();inflightCheckpointer.dispose();- const sidecarShutdown = getSidecar()?.dispose();try {await hostShutdown;diff --git a/apps/desktop/electron/main/index.ts b/apps/desktop/electron/main/index.tsindex c66cdec99..420a72024 100644--- a/apps/desktop/electron/main/index.ts+++ b/apps/desktop/electron/main/index.ts@@ -1034,6 +1034,7 @@ registerShutdownHandlers({activeTurns,persistenceOutbox,inflightCheckpointer,+ flushEventPersistence: eventPersistence.flush,pluginPanels,plugins,userMcp,diff --git a/apps/desktop/electron/main/runtime/event-persistence.ts b/apps/desktop/electron/main/runtime/event-persistence.tsindex 1be3e5d4b..c7afa6469 100644--- a/apps/desktop/electron/main/runtime/event-persistence.ts+++ b/apps/desktop/electron/main/runtime/event-persistence.ts@@ -54,8 +54,22 @@ export function createEventPersistence({}: EventPersistenceDependencies): {subagentTagged: (message: UiMessage, envelope: AgentEventEnvelope) => UiMessage;persistAgentEvent: (envelope: AgentEventEnvelope) => UiMessage | undefined;+ flush: () => Promise<void>;} {const inflightSnapshots = new Map<string, UiMessage>();+ const pendingWrites = new Set<Promise<void>>();+ function trackWrite(write: Promise<void>): void {+ pendingWrites.add(write);+ void write.then(+ () => pendingWrites.delete(write),+ () => pendingWrites.delete(write),+ );+ }+ async function flush(): Promise<void> {+ while (pendingWrites.size > 0) {+ await Promise.allSettled([...pendingWrites]);+ }+ }function subagentTagged(message: UiMessage, envelope: AgentEventEnvelope): UiMessage {return tagMessageToolLineage(message, envelope);}@@ -162,7 +176,7 @@ function persistAgentEvent(envelope: AgentEventEnvelope): UiMessage | undefinedevent.error.code,{ turnId: envelope.turnId ?? "" },);- void turnFinalization+ trackWrite(turnFinalization.then(() =>executionId? finishApprovedExecution(executionId, "interrupted", event.error.code)@@ -173,7 +187,7 @@ function persistAgentEvent(envelope: AgentEventEnvelope): UiMessage | undefinedsessionId: envelope.sessionId,data: String(error),});- });+ }));return;}if (event.type === "agent_end") {@@ -186,7 +200,7 @@ function persistAgentEvent(envelope: AgentEventEnvelope): UiMessage | undefined// The finalizer's promise can reject — its body attempts the durable end and// its release handler no longer swallows a throwing body — so the chain is// observed even when no approved execution follows this turn.- void turnFinalization+ trackWrite(turnFinalization.then(() =>executionId ? finishApprovedExecution(executionId, "completed") : undefined,)@@ -195,10 +209,10 @@ function persistAgentEvent(envelope: AgentEventEnvelope): UiMessage | undefinedsessionId: envelope.sessionId,data: String(error),});- });+ }));// Persist the completed branch as the active regenerate revision when the// latest user turn carries revision metadata (ChatGPT-style history).- void (async () => {+ trackWrite((async () => {try {if (!runtimeState.host) return;// The turn's final assistant message may still be in the outbox. Archive@@ -236,7 +250,7 @@ function persistAgentEvent(envelope: AgentEventEnvelope): UiMessage | undefineddata: String(error),});}- })();+ })());return;}if (event.type === "message_end" && event.message.role === "user" && !envelope.parentToolCallId) {@@ -368,5 +382,5 @@ function persistAgentEvent(envelope: AgentEventEnvelope): UiMessage | undefinedreturn message;}}- return { subagentTagged, persistAgentEvent };+ return { subagentTagged, persistAgentEvent, flush };}diff --git a/apps/desktop/test/shutdown-regenerate-persistence.test.mjs b/apps/desktop/test/shutdown-regenerate-persistence.test.mjsnew file mode 100644index 000000000..17932555b--- /dev/null+++ b/apps/desktop/test/shutdown-regenerate-persistence.test.mjs@@ -0,0 +1,132 @@+import assert from "node:assert/strict";+import { mkdtemp } from "node:fs/promises";+import { register, registerHooks } from "node:module";+import { tmpdir } from "node:os";+import { join } from "node:path";+import test from "node:test";++// Only Electron is replaced; event persistence, the disk outbox and the quit+// handler use their production wiring. No user profile is opened by this test.+registerHooks({+ resolve(specifier, context, next) {+ if (specifier === "electron") return { url: "test:electron", shortCircuit: true };+ return next(specifier, context);+ },+ load(url, context, next) {+ if (url === "test:electron") return {+ format: "module", shortCircuit: true,+ source: `import { EventEmitter } from "node:events";+ export const app = new EventEmitter();+ app.quit = () => {};+ export const globalShortcut = { unregister() {} };`,+ };+ return next(url, context);+ },+});+register(new URL("./helpers/ts-import-hooks.mjs", import.meta.url));++const { app } = await import("electron");+const { createEventPersistence } = await import("../electron/main/runtime/event-persistence.ts");+const { PersistenceOutbox } = await import("../electron/main/persistence-outbox.ts");+const { registerShutdownHandlers } = await import("../electron/main/bootstrap/shutdown.ts");++for (const outcome of ["complete", "error", "unresponsive"]) {+test(`quit settles a regenerated branch when the host is ${outcome}`, async (t) => {+ const dataDir = await mkdtemp(join(tmpdir(), "pi-quit-regenerate-"));+ const archiveStarted = Promise.withResolvers();+ const releaseArchive = Promise.withResolvers();+ const sidecarStopped = Promise.withResolvers();+ const messages = new Map();+ const archived = [];+ const warnings = [];+ const activeTurns = new Map([["session", "turn"]]);+ let hostDisposed = false;+ const host = {+ isAvailable: () => !hostDisposed,+ async call(method, params) {+ assert.equal(hostDisposed, false, "persistence requires a live host");+ if (method === "session.appendMessage") messages.set(params.message.id, params.message);+ if (method === "session.saveActiveRevision") {+ archiveStarted.resolve();+ await releaseArchive.promise;+ if (outcome === "error") throw new Error("archive storage unavailable");+ assert.equal(hostDisposed, false, "the archive must finish before host disposal");+ archived.push([...messages.values()]);+ }+ return {};+ },+ async dispose() { hostDisposed = true; },+ };+ const logger = { app: (_area, level, event) => {+ if (level === "warn") warnings.push(event);+ } };+ const outbox = new PersistenceOutbox(dataDir, () => undefined);+ const checkpoint = {+ observe() {}, flush: async () => {}, flushAll: async () => {},+ settleIf() {}, dispose() {},+ };+ const persistence = createEventPersistence({+ runtimeState: { host }, steeringReplies: new Set(), activeTurns,+ activeToolCalls: new Map(), activeToolCallKey: (s, c) => `${s}:${c}`,+ approvedExecutionIdsBySession: new Map(), approvedExecutionTurns: new Map(),+ pendingExecutionFinishes: new Map(), planSubmissionTurnIds: new Set(),+ planSubmissionTurnKey: (s, turn) => `${s}:${turn}`,+ inflightCheckpointer: checkpoint, persistenceOutbox: outbox,+ addActiveTurnUsage() {}, logger,+ finishTurn: async () => { activeTurns.clear(); },+ isStaleTerminalEvent: () => false,+ finishApprovedExecution: async () => {}, emitAgentEvent() {},+ });+ const state = {+ shutdownComplete: false, shutdownPromise: null, quitting: false,+ quitConfirmed: true, closeBehavior: "quit", tray: null,+ pluginLauncherAccelerator: null, toggleWindowAccelerator: null,+ };+ const dispose = () => undefined;+ registerShutdownHandlers({+ hasSingleInstanceLock: true, state,+ getHost: () => host,+ getSidecar: () => ({ dispose: async () => { sidecarStopped.resolve(); } }),+ getMcpControl: () => null, activeTurns, persistenceOutbox: outbox,+ inflightCheckpointer: checkpoint,+ flushEventPersistence: () => persistence.flush(),+ pluginPanels: { closeAll: async () => {} },+ plugins: { disposeAll: async () => {} }, userMcp: { disposeAll: dispose },+ browserHost: { dispose }, pluginViews: { dispose: async () => {} },+ updater: { dispose, isInstallingUpdate: () => false }, logger,+ confirmQuitDialog: async () => true, disposePowerSaveBlockers: dispose,+ });+ t.after(async () => {+ releaseArchive.resolve();+ await state.shutdownPromise;+ await persistence.flush();+ app.removeAllListeners();+ });+ const reply = {+ id: "answer", role: "assistant", content: "Completed regenerated answer",+ createdAt: new Date(0).toISOString(), status: "complete",+ };+ persistence.persistAgentEvent({ sessionId: "session", turnId: "turn", ts: 1,+ event: { type: "message_end", message: reply } });+ persistence.persistAgentEvent({ sessionId: "session", turnId: "turn", ts: 2,+ event: { type: "agent_end", messageIds: [reply.id] } });+ await archiveStarted.promise;+ if (outcome === "unresponsive") t.mock.timers.enable({ apis: ["setTimeout"] });+ app.emit("before-quit", { preventDefault() {} });+ await sidecarStopped.promise;+ assert.equal(hostDisposed, false, "quit must wait for the branch already being saved");+ if (outcome === "unresponsive") {+ await new Promise((resolve) => setImmediate(resolve));+ t.mock.timers.tick(2_000);+ await state.shutdownPromise;+ assert.equal(hostDisposed, true, "an unresponsive archive cannot prevent quitting");+ assert.deepEqual(warnings, ["quit before event persistence settled"]);+ return;+ }+ releaseArchive.resolve();+ await state.shutdownPromise;+ assert.deepEqual(archived, outcome === "complete" ? [[reply]] : []);+ assert.deepEqual(warnings, outcome === "complete" ? [] : ["save active regenerate branch failed"]);+ assert.equal(hostDisposed, true);+});+}diff --git a/docs/adr/0060-regenerate-branch-archive-under-the-rpc-lock.md b/docs/adr/0060-regenerate-branch-archive-under-the-rpc-lock.mdindex 28197a44f..621be2648 100644--- a/docs/adr/0060-regenerate-branch-archive-under-the-rpc-lock.md+++ b/docs/adr/0060-regenerate-branch-archive-under-the-rpc-lock.md@@ -58,6 +58,16 @@ an idempotent stamp destroyed a message.which the caller already logs as a skipped archive rather than treating asdata loss. Nothing a v9 client relies on changes.+## Quit-time lifecycle correction (2026-10-07)++An archive can outlive `activeTurns` and an empty append outbox. Previously,+quitting in that interval disposed host-core while `session.saveActiveRevision`+was pending. Electron now tracks terminal event writes, stops sidecar event+production, and drains those writes before host disposal. The drain is bounded+using the existing two-second quit budget and warns if the host remains+unresponsive. This preserves the single-RPC archival contract without adding a+second archive path or changing stored transcript formats.+## Alternatives considered- **Await the outbox and keep the four-call rewrite:** narrows the window butdiff --git a/docs/spec/03-runtime/07-process-model.md b/docs/spec/03-runtime/07-process-model.mdindex ac1346bf1..4ef568079 100644--- a/docs/spec/03-runtime/07-process-model.md+++ b/docs/spec/03-runtime/07-process-model.md@@ -229,7 +229,10 @@ retains the lifecycle boundary whenever the local log write succeeds.3. Interrupt pending/queued/running Plan and Goal work and reject late responses4. Unload plugins5. Stop Node agent sidecar-6. Flush/close Rust host DB+6. Drain terminal event writes (turn finalization and regenerate archival),+ checkpoints and the outbox while Rust host-core remains available, then+ flush/close its DB. Terminal writes use a bounded wait of 2 s; a timeout logs+ `quit before event persistence settled` and allows quit to proceed.7. Stop Rust host8. Dispose update polling9. Close windows / exitdiff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.mdindex a0b4988d8..b46f0a73b 100644--- a/docs/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/spec/06-delivery/04-e2e-test-plan.md@@ -16927,3 +16927,18 @@ host-created files. The full app's file-preview viewer is covered separately.image model selection and provider configuration remain available.- Coverage: recent-models.test.mjs, recent-model-flow.test.mjs,default-model-picker.test.mjs, and scripts/e2e-composer-model-selection.mjs.+++## Regenerate archival during quit++- Regenerate a completed answer and quit as soon as the terminal event arrives.+ Restart the isolated profile: both revisions and their final messages remain+ readable, and no `host-core disposed` archival failure appears in the logs.+- Hold the archive RPC while requesting quit. Host disposal waits for successful+ archival; storage errors are logged. An unresponsive archive warns and allows+ quit after the existing two-second bounded wait.+- Automated coverage: `shutdown-regenerate-persistence.test.mjs` and+ `node scripts/e2e-regenerate-quit.mjs` (built Desktop, sidecar and host required;+ Playwright can be supplied through `PI_TEST_PLAYWRIGHT`). Only the model server+ is simulated in the Electron flow. The fixture profile and screenshots stay+ under `.artifacts/` for inspection; no user profile or paid model is used.diff --git a/scripts/e2e-regenerate-quit.mjs b/scripts/e2e-regenerate-quit.mjsnew file mode 100644index 000000000..e86ecf978--- /dev/null+++ b/scripts/e2e-regenerate-quit.mjs@@ -0,0 +1,138 @@+import assert from "node:assert/strict";+import { createServer } from "node:http";+import { createRequire } from "node:module";+import { mkdir, readFile, writeFile } from "node:fs/promises";+import { join, resolve } from "node:path";+import { once } from "node:events";++const require = createRequire(new URL("../apps/desktop/package.json", import.meta.url));+const { _electron } = require(process.env.PI_TEST_PLAYWRIGHT ?? "playwright");+const root = resolve(import.meta.dirname, "..");+const output = join(root, ".artifacts", `regenerate-quit-${Date.now()}`);+const workspace = join(output, "workspace");+await mkdir(workspace, { recursive: true });+await writeFile(join(workspace, "build.log"), "Build completed successfully\n");+const checks = [];+let app, page, requestCount = 0, sawLog = false;+const server = createServer(async (req, res) => {+ if (req.url !== "/v1/chat/completions") { res.writeHead(404).end(); return; }+ const raw = []; for await (const chunk of req) raw.push(chunk);+ const body = JSON.parse(Buffer.concat(raw).toString());+ requestCount++;+ const lastUser = body.messages.findLastIndex((message) => message.role === "user");+ const results = body.messages.slice(lastUser).filter((message) => message.role === "tool");+ const tool = results.length === 0;+ if (!tool) sawLog ||= JSON.stringify(results).includes("Build completed successfully");+ const chunk = (delta, finish_reason = null) => res.write(`data: ${JSON.stringify({+ id: `controlled-${requestCount}`, object: "chat.completion.chunk", created: 1, model: body.model,+ choices: [{ index: 0, delta, finish_reason }],+ })}\n\n`);+ res.writeHead(200, { "content-type": "text/event-stream" });+ chunk({ role: "assistant" });+ if (tool) chunk({ tool_calls: [{ index: 0, id: `read-${requestCount}`, type: "function",+ function: { name: "Read", arguments: JSON.stringify({ path: join(workspace, "build.log") }) } }] });+ else chunk({ content: `REGRESSION_REPLY_${requestCount}` });+ chunk({}, tool ? "tool_calls" : "stop");+ res.end("data: [DONE]\n\n");+});+server.listen(0, "127.0.0.1"); await once(server, "listening");+const origin = `http://127.0.0.1:${server.address().port}`;+const check = (name, value = true) => { assert.ok(value, name); checks.push(name); console.log(`PASS ${name}`); };+async function until(probe, label, timeout = 30_000) {+ const deadline = Date.now() + timeout;+ while (Date.now() < deadline) {+ const result = await probe(); if (result) return result;+ await new Promise((done) => setTimeout(done, 50));+ }+ throw new Error(`Timed out: ${label}`);+}+const invoke = (name, ...args) => page.evaluate(async ({ name, args }) => {+ const result = await window.piDesktop.invoke(`pi-desktop/${name}`, ...args);+ if (!result.ok) throw new Error(JSON.stringify(result.error));+ return result.data;+}, { name, args });+async function launch() {+ const env = { ...process.env, PI_DESKTOP_DATA_DIR: join(output, "data"),+ ELECTRON_RENDERER_URL: "" };+ delete env.ELECTRON_RUN_AS_NODE;+ app = await _electron.launch({ executablePath: require("electron"),+ args: [join(root, "apps/desktop"), `--user-data-dir=${join(output, "profile")}`], env, timeout: 60_000 });+ page = await until(async () => {+ for (const candidate of app.windows()) if (await candidate.locator(".app-shell").count()) return candidate;+ }, "desktop shell", 60_000);+ await page.locator(".app-shell:not(.app-shell-boot)").waitFor();+}+async function close() {+ if (!app) return;+ await app.evaluate(() => { process.env.PI_DESKTOP_BOOT_PROBE = "1"; });+ await app.close(); app = undefined;+}+try {+ await launch();+ const { provider } = await invoke("providers/create", {+ name: "Controlled local provider", type: "openai_compatible",+ baseUrl: `${origin}/v1`, apiStyle: "chat_completions", authKind: "none",+ models: [{ id: "fixture-model", contextWindow: 128000, maxTokens: 4096, thinkingLevels: ["off"] }],+ defaultModelId: "fixture-model",+ });+ assert.ok(provider);+ await invoke("settings/set", { ...await invoke("settings/get"), language: "en", theme: "dark",+ onboardingDismissed: true, autoGenerateTitle: false, defaultProviderId: provider.id, defaultModelId: "fixture-model" });+ const { session } = await invoke("session/create", { title: "Regenerate quit regression", projectPath: workspace,+ mode: "agent", providerId: provider.id, modelId: "fixture-model", thinkingLevel: "off", permissionMode: "bypass" });+ await invoke("project/set", workspace);+ await page.reload(); await page.locator(".app-shell:not(.app-shell-boot)").waitFor();+ await page.evaluate((id) => window.__PI_DESKTOP__.selectSession(id), session.id);+ await page.evaluate((id) => {+ window.__firstReplyEnded = false;+ window.piDesktop.on("pi-desktop/agent/event/message", (envelope) => {+ if (envelope.sessionId === id && envelope.event.type === "agent_end" && !envelope.parentToolCallId) {+ window.__firstReplyEnded = true;+ }+ });+ }, session.id);+ await invoke("agent/prompt", { sessionId: session.id, content: "Read the build log and report that it was inspected." });+ await page.getByText("REGRESSION_REPLY_2", { exact: true }).waitFor({ timeout: 30_000 });+ await until(() => page.evaluate(() => window.__firstReplyEnded), "initial turn completion");+ check("native Read delivers the fixture log to the real sidecar", sawLog);+ await page.screenshot({ path: join(output, "log-read.png") });+ await app.evaluate(() => { process.env.PI_DESKTOP_BOOT_PROBE = "1"; });+ await page.evaluate((id) => {+ window.piDesktop.on("pi-desktop/agent/event/message", (envelope) => {+ if (envelope.sessionId === id && envelope.event.type === "agent_end" && !envelope.parentToolCallId) {+ void window.piDesktop.invoke("pi-desktop/app/quit");+ }+ });+ }, session.id);+ const processExit = once(app.process(), "exit");+ await page.getByText("REGRESSION_REPLY_2", { exact: true }).click({ button: "right" });+ await page.getByRole("menuitem", { name: /Regenerate/i }).click();+ await processExit; app = undefined;+ check("regenerate finishes and exits through the native quit path", requestCount === 4);+ await launch();+ await page.evaluate((id) => window.__PI_DESKTOP__.selectSession(id), session.id);+ await page.getByText("REGRESSION_REPLY_4", { exact: true }).waitFor();+ const detail = (await invoke("session/get", { id: session.id })).session;+ const user = detail.messages.find((message) => message.role === "user");+ const rootUserId = user.revisionRootId ?? user.id;+ const revisions = await invoke("session/listRevisions", { sessionId: session.id, rootUserId });+ check("restarted conversation retains both regenerate branches", revisions.revisions.length === 2);+ const original = await invoke("session/activateRevision", { sessionId: session.id, rootUserId, revisionIndex: 1, prefix: [] });+ check("original branch remains readable", original.messages.some((message) => message.content === "REGRESSION_REPLY_2"));+ const regenerated = await invoke("session/activateRevision", { sessionId: session.id, rootUserId, revisionIndex: 2, prefix: [] });+ check("regenerated branch remains readable", regenerated.messages.some((message) => message.content === "REGRESSION_REPLY_4"));+ await page.screenshot({ path: join(output, "regenerated-after-restart.png") });+ await close();+ const logs = await readFile(join(output, "data/logs/app/persistence.log"), "utf8").catch((error) => {+ if (error.code === "ENOENT") return "";+ throw error;+ });+ check("quit produces no disposed-host archive error", !logs.includes("host-core disposed") && !logs.includes("save.active.regenerate.branch.failed"));+ await writeFile(join(output, "result.json"), JSON.stringify({ checks, requestCount, output }, null, 2));+ console.log(JSON.stringify({ output, checks: checks.length }));+} catch (error) {+ if (page && !page.isClosed()) await page.screenshot({ path: join(output, "failure.png") }).catch(() => undefined);+ throw error;+} finally {+ await close(); server.closeAllConnections(); server.close();+}