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): persist crash cards before draining queued turns
Linuxdazhaoe5c4c54785e7
diff --git a/apps/desktop/electron/main/index.ts b/apps/desktop/electron/main/index.tsindex 73c6bdaa0..b096f1073 100644--- a/apps/desktop/electron/main/index.ts+++ b/apps/desktop/electron/main/index.ts@@ -764,7 +764,8 @@ const planRuntime = createPlanRuntime({pendingExecutionFinishes,announceTurnEnded,emitAgentEvent: (envelope) => emitAgentEvent(envelope),- persistAgentEvent: (envelope) => persistAgentEvent(envelope),+ persistInterruptionMessage: (sessionId, turnId, message) =>+ eventPersistence.persistInterruptionMessage(sessionId, turnId, message),acquireSessionOperation,resolveAgentRuntimeLaunch,isQuitting: () => mainState.quitting,diff --git a/apps/desktop/electron/main/runtime/event-persistence.ts b/apps/desktop/electron/main/runtime/event-persistence.tsindex 77109f8e3..9232f206e 100644--- a/apps/desktop/electron/main/runtime/event-persistence.ts+++ b/apps/desktop/electron/main/runtime/event-persistence.ts@@ -64,6 +64,7 @@ export function createEventPersistence({}: EventPersistenceDependencies): {subagentTagged: (message: UiMessage, envelope: AgentEventEnvelope) => UiMessage;persistAgentEvent: (envelope: AgentEventEnvelope) => UiMessage | undefined;+ persistInterruptionMessage: (sessionId: string, turnId: string, message: UiMessage) => Promise<void>;beginTranscriptRewrite: (sessionId: string) => {commit: () => void;rollback: () => void;@@ -85,6 +86,28 @@ export function createEventPersistence({}}+ async function persistInterruptionMessage(sessionId: string, turnId: string, message: UiMessage): Promise<void> {+ inflightSnapshots.delete(sessionId);+ completionNoticeTurns.delete(turnId);+ const host = runtimeState.host;+ if (host?.isAvailable()) {+ try {+ // A queued prompt appends directly to the Host, so the crash card+ // needs its own acknowledgement before turn finalization releases it.+ await host.call("session.appendMessage", { sessionId, turnId, message });+ return;+ } catch (error) {+ logger.app("persistence", "warn", "interruption message append failed", {+ sessionId, data: String(error),+ });+ }+ }+ await persistenceOutbox.enqueue({+ key: `message:${sessionId}:${message.id}`,+ sessionId, turnId, message,+ }, () => runtimeState.host);+ }+function beginTranscriptRewrite(sessionId: string) {const lease = transcriptRewrite.beginTranscriptRewrite(sessionId);let settled = false;@@ -449,5 +472,5 @@ function persistAgentEvent(envelope: AgentEventEnvelope): UiMessage | undefinedreturn message;}}- return { subagentTagged, persistAgentEvent, beginTranscriptRewrite, flush };+ return { subagentTagged, persistAgentEvent, persistInterruptionMessage, beginTranscriptRewrite, flush };}diff --git a/apps/desktop/electron/main/runtime/plans.ts b/apps/desktop/electron/main/runtime/plans.tsindex a059e5c52..021cda6c8 100644--- a/apps/desktop/electron/main/runtime/plans.ts+++ b/apps/desktop/electron/main/runtime/plans.ts@@ -64,7 +64,7 @@ export type PlanRuntimeDependencies = {*/announceTurnEnded: (payload: TurnEndedPayload) => void;emitAgentEvent: (envelope: AgentEventEnvelope) => void;- persistAgentEvent: (envelope: AgentEventEnvelope) => void;+ persistInterruptionMessage: (sessionId: string, turnId: string, message: UiMessage) => Promise<void>;acquireSessionOperation: (sessionId: string) => Promise<() => void>;resolveAgentRuntimeLaunch: (...args: any[]) => Promise<any>;isQuitting: () => boolean;@@ -95,7 +95,7 @@ export function createPlanRuntime({pendingExecutionFinishes,announceTurnEnded,emitAgentEvent,- persistAgentEvent,+ persistInterruptionMessage,acquireSessionOperation,resolveAgentRuntimeLaunch,isQuitting,@@ -212,6 +212,7 @@ function finishTurn((!wasPlanSubmission && shouldCreateTaskNotification(id));const recoverInflight = options.recoverInflight === true;const interruptionError = options.interruptionError;+ const ownsLiveTurn = () => !isQuitting() && isActiveTurn(id, turnId);const runFinalization = async (): Promise<void> => {try {@@ -237,7 +238,7 @@ function finishTurn(notification: result.notification,});}- if (result.recovered) {+ if (result.recovered && (!interruptionError || ownsLiveTurn())) {// Settle the renderer's streaming row the same way a final// message_end would have, so it does not stay "streaming" forever.emitAgentEvent({@@ -255,32 +256,31 @@ function finishTurn(}}- if (interruptionError && !isQuitting() && isActiveTurn(id, turnId)) {+ if (interruptionError && ownsLiveTurn()) {const ts = Date.now();const identity = { sessionId: id, turnId, ts };- const messageEnd: AgentEventEnvelope = {- ...identity,- event: {- type: "message_end",- message: {- id: randomUUID(),- role: "assistant",- content: "",- createdAt: new Date(ts).toISOString(),- status: "error",- isError: true,- error: interruptionError,- },- },+ const message: UiMessage = {+ id: randomUUID(),+ role: "assistant",+ content: "",+ createdAt: new Date(ts).toISOString(),+ status: "error",+ isError: true,+ error: interruptionError,};- persistAgentEvent(messageEnd);- emitAgentEvent(messageEnd);- // The renderer needs its terminal error event. Agent Host gets the- // interrupted outcome from endTurn after the finalization claim clears.- sendToRenderer(IPC.event.agentMessage, {- ...identity,- event: { type: "error", error: interruptionError },- } satisfies AgentEventEnvelope);+ await persistInterruptionMessage(id, turnId, message).catch((error: unknown) => {+ logger.app("persistence", "warn", "interruption message enqueue failed", {+ sessionId: id, data: String(error),+ });+ });+ if (ownsLiveTurn()) {+ emitAgentEvent({ ...identity, event: { type: "message_end", message } });+ // Agent Host gets the interrupted outcome when finalization releases.+ sendToRenderer(IPC.event.agentMessage, {+ ...identity,+ event: { type: "error", error: interruptionError },+ } satisfies AgentEventEnvelope);+ }}if (runId && runtimeState.host) {diff --git a/apps/desktop/test/queued-turn-finalization.test.mjs b/apps/desktop/test/queued-turn-finalization.test.mjsindex 889e5b2f9..00a387deb 100644--- a/apps/desktop/test/queued-turn-finalization.test.mjs+++ b/apps/desktop/test/queued-turn-finalization.test.mjs@@ -13,6 +13,7 @@ register(pathToFileURL(join(here, "helpers/ts-import-hooks.mjs")));// Exercise the real plan runtime, the real turn coordination state and the real// Agent Host bridge, without booting Electron or making a provider request.const { createPlanRuntime } = await import("../electron/main/runtime/plans.ts");+const { createEventPersistence } = await import("../electron/main/runtime/event-persistence.ts");const { createSessionCoordination } = await import("../electron/main/runtime/session-coordination.ts");@@ -41,7 +42,8 @@ function fixture({ onTurnEnded } = {}) {const writes = [];const announcements = [];const rendererEvents = [];- const persistedEvents = [];+ const appends = [];+ const outboxWrites = [];let quitting = false;const coordination = createSessionCoordination({@@ -51,6 +53,7 @@ function fixture({ onTurnEnded } = {}) {});const host = {+ isAvailable: () => true,async call(method, params) {if (method === "session.get") {return { session: { id: params.id, permissionMode: "ask" } };@@ -67,6 +70,11 @@ function fixture({ onTurnEnded } = {}) {writes.push({ ...write, turnId: params.turnId });return write.promise;}+ if (method === "session.appendMessage") {+ const write = deferred();+ appends.push({ ...write, ...params });+ return write.promise;+ }if (method === "session.queuePrioritize") {return {};}@@ -109,8 +117,21 @@ function fixture({ onTurnEnded } = {}) {},});+ const runtimeState = { host, agentHostBridge: bridge };+ const persistence = createEventPersistence({+ runtimeState,+ completionNoticeTurns: new Set(),+ logger: { app() {} },+ persistenceOutbox: {+ enqueue(entry) {+ const write = deferred();+ outboxWrites.push({ ...write, entry });+ return write.promise;+ },+ },+ });const planRuntime = createPlanRuntime({- runtimeState: { host, agentHostBridge: bridge },+ runtimeState,planState: { approvedExecutionDrain: null },logger: { app() {} },sendToRenderer(channel, envelope) {@@ -132,7 +153,7 @@ function fixture({ onTurnEnded } = {}) {emitAgentEvent(envelope) {rendererEvents.push(envelope);},- persistAgentEvent: (envelope) => persistedEvents.push(envelope),+ persistInterruptionMessage: persistence.persistInterruptionMessage,acquireSessionOperation: coordination.acquireSessionOperation,resolveAgentRuntimeLaunch: async () => {throw new Error("not used by this fixture");@@ -190,7 +211,8 @@ function fixture({ onTurnEnded } = {}) {prompts,announcements,rendererEvents,- persistedEvents,+ appends,+ outboxWrites,writes,finish,finishTurn: planRuntime.finishTurn,@@ -218,6 +240,13 @@ for (const errorCode of ["AGENT_SIDECAR_CRASHED", "AGENT_SIDECAR_OOM"]) {createdAt: "2026-11-25T00:00:00Z", status: "aborted",},});+ await setImmediate();+ assert.equal(f.appends.length, 1);+ assert.equal(f.appends[0].turnId, FIRST_TURN);+ assert.equal(f.appends[0].message.error.code, errorCode);+ assert.deepEqual(f.rendererEvents.map(({ event }) => event.type), ["message_end"]);+ assert.deepEqual(f.prompts, []);+ f.appends[0].resolve({ ok: true });await pending;await setImmediate();assert.deepEqual(f.rendererEvents.map(({ event }) => event.type), [@@ -225,7 +254,8 @@ for (const errorCode of ["AGENT_SIDECAR_CRASHED", "AGENT_SIDECAR_OOM"]) {]);assert.equal(f.rendererEvents[0].event.message.id, "partial");assert.equal(f.rendererEvents[1].event.message.error.code, errorCode);- assert.deepEqual(f.persistedEvents, [f.rendererEvents[1]]);+ assert.deepEqual(f.appends[0].message, f.rendererEvents[1].event.message);+ assert.deepEqual(f.outboxWrites, []);assert.deepEqual(f.rendererEvents[2].event.error, error);assert(f.rendererEvents.every(({ turnId }) => turnId === FIRST_TURN));const interrupted = f.bridge.agentHost.getTurn(FIRST_TURN);@@ -235,7 +265,7 @@ for (const errorCode of ["AGENT_SIDECAR_CRASHED", "AGENT_SIDECAR_OOM"]) {});}-test("a crashed turn does not publish a live error after its session moved on", async () => {+test("a crashed turn does not publish recovered rows after its session moved on", async () => {const f = fixture();const error = { code: "AGENT_SIDECAR_CRASHED", message: "Agent sidecar exited unexpectedly" };const pending = f.finishTurn(SESSION, "aborted", error.code, {@@ -243,13 +273,56 @@ test("a crashed turn does not publish a live error after its session moved on",});await setImmediate();f.activeTurns.set(SESSION, "successor");+ f.writes[0].resolve({ ok: true, recovered: { id: "partial" } });+ await pending;+ assert.deepEqual(f.rendererEvents, []);+ assert.deepEqual(f.appends, []);+ assert.equal(f.activeTurns.get(SESSION), "successor");+});++test("a crash-card append finishing after ownership changes does not stop the successor", async () => {+ const f = fixture();+ const error = { code: "AGENT_SIDECAR_CRASHED", message: "Agent sidecar exited unexpectedly" };+ const pending = f.finishTurn(SESSION, "aborted", error.code, {+ turnId: FIRST_TURN, interruptionError: error,+ });+ await setImmediate();f.writes[0].resolve({ ok: true });+ await setImmediate();+ assert.equal(f.appends[0].turnId, FIRST_TURN);+ f.activeTurns.set(SESSION, "successor");+ f.appends[0].resolve({ ok: true });await pending;assert.deepEqual(f.rendererEvents, []);- assert.deepEqual(f.persistedEvents, []);assert.equal(f.activeTurns.get(SESSION), "successor");});+test("a failed crash-card append is spooled with its original turn before the queue resumes", async () => {+ const f = fixture();+ await f.bridge.queue.push({ sessionId: SESSION, content: "follow-up" });+ const error = { code: "AGENT_SIDECAR_CRASHED", message: "Agent sidecar exited unexpectedly" };+ const pending = f.finishTurn(SESSION, "aborted", error.code, {+ turnId: FIRST_TURN, interruptionError: error,+ });+ await setImmediate();+ f.writes[0].resolve({ ok: true });+ await setImmediate();+ f.appends[0].reject(new Error("host disconnected"));+ await setImmediate();+ assert.equal(f.outboxWrites.length, 1);+ assert.deepEqual(f.outboxWrites[0].entry, {+ key: `message:${SESSION}:${f.appends[0].message.id}`,+ sessionId: SESSION,+ turnId: FIRST_TURN,+ message: f.appends[0].message,+ });+ assert.deepEqual(f.prompts, []);+ f.outboxWrites[0].resolve();+ await pending;+ await setImmediate();+ assert.deepEqual(f.prompts.map(({ content }) => content), ["follow-up"]);+});+for (const status of ["completed", "error", "aborted"]) {test(`queued prompts resume once, in FIFO order, after ${status} turn finalization`, async () => {const f = fixture();diff --git a/docs/spec/03-runtime/07-process-model.md b/docs/spec/03-runtime/07-process-model.mdindex 240b94c42..6eab6402f 100644--- a/docs/spec/03-runtime/07-process-model.md+++ b/docs/spec/03-runtime/07-process-model.md@@ -269,7 +269,9 @@ classified error as an assistant transcript row and publishes a terminalrenderer event for each turn that still owns its session. Foreground andbackground sessions clear their running state and settle live tool rows.Agent Host closes the turn as interrupted with the same error code before-queued work can resume.+queued work can resume. Turn finalization waits for the Host to acknowledge+the crash row. If the Host cannot accept the row, the persistence outbox+spools it before finalization releases the queue.Minimizing the main window is a resident-shell action, not an applicationshutdown. On Windows/Linux, explicit application minimize actions use thediff --git a/docs/spec/06-delivery/e2e/conversation.md b/docs/spec/06-delivery/e2e/conversation.mdindex d7dea9b1a..daeebb612 100644--- a/docs/spec/06-delivery/e2e/conversation.md+++ b/docs/spec/06-delivery/e2e/conversation.md@@ -677,8 +677,8 @@ folder/mixed-selection behavior. No system clipboard contents are changed.The streaming row settles to `aborted` in place with its text. The sessiontimer, running badge, and tool spinner stop, and a localized crash errorappears. The recovered reply and one crash card remain after a reload, and- no `.inflight.json` remains. A follow-up prompt can run on the restarted- sidecar. 4) The partial+ no `.inflight.json` remains. A queued follow-up runs on the restarted+ sidecar and appears after the crash card on reload. 4) The partialreply is visible immediately after Stop and after reopening; the transcriptfile was not rewritten (its earlier lines are byte-identical) and thecheckpoint file is gone once the aborted final row landed. 5) The completed