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): settle live turns after sidecar crashes
Linuxdazhao7362961a54e8
diff --git a/apps/desktop/electron/main/index.ts b/apps/desktop/electron/main/index.tsindex 7a42e2cef..73c6bdaa0 100644--- a/apps/desktop/electron/main/index.ts+++ b/apps/desktop/electron/main/index.ts@@ -764,6 +764,7 @@ const planRuntime = createPlanRuntime({pendingExecutionFinishes,announceTurnEnded,emitAgentEvent: (envelope) => emitAgentEvent(envelope),+ persistAgentEvent: (envelope) => persistAgentEvent(envelope),acquireSessionOperation,resolveAgentRuntimeLaunch,isQuitting: () => mainState.quitting,diff --git a/apps/desktop/electron/main/runtime/plans.ts b/apps/desktop/electron/main/runtime/plans.tsindex 33caf36ea..a059e5c52 100644--- a/apps/desktop/electron/main/runtime/plans.ts+++ b/apps/desktop/electron/main/runtime/plans.ts@@ -1,4 +1,5 @@-import { ErrorCodes, IPC, type AgentEventEnvelope, type AppNotification, type MessageUsage, type PlanExecution, type PlanExecutionFinishStatus, type UiMessage } from "@pi-desktop/shared";+import { randomUUID } from "node:crypto";+import { ErrorCodes, IPC, type AgentEventEnvelope, type AppError, type AppNotification, type MessageUsage, type PlanExecution, type PlanExecutionFinishStatus, type UiMessage } from "@pi-desktop/shared";import { executionFromResponse, executionListFromResponse, planExecutionFromUnknown } from "@pi-desktop/host-runtime";import type { RuntimeState } from "./context";import type {@@ -17,6 +18,7 @@ export type FinishTurnOptions = {turnId: string;createNotification?: boolean;recoverInflight?: boolean;+ interruptionError?: AppError;};/**@@ -62,6 +64,7 @@ export type PlanRuntimeDependencies = {*/announceTurnEnded: (payload: TurnEndedPayload) => void;emitAgentEvent: (envelope: AgentEventEnvelope) => void;+ persistAgentEvent: (envelope: AgentEventEnvelope) => void;acquireSessionOperation: (sessionId: string) => Promise<() => void>;resolveAgentRuntimeLaunch: (...args: any[]) => Promise<any>;isQuitting: () => boolean;@@ -92,6 +95,7 @@ export function createPlanRuntime({pendingExecutionFinishes,announceTurnEnded,emitAgentEvent,+ persistAgentEvent,acquireSessionOperation,resolveAgentRuntimeLaunch,isQuitting,@@ -128,14 +132,22 @@ function hostTurnStatus(}/**- * The error a settled failing turn carries into Agent Host. The terminal event- * owns the real message; this path only runs when that event never landed, so the- * code the settlement recorded is the best available description.+ * The error carried by Agent Host settlement when a runtime terminal event+ * could not deliver it.*/function hostTurnError(reason: TurnEndReason,errorCode: string | undefined,+ interruptionError: AppError | undefined,): { code: string; message: string; retriable: boolean; traceId: string } | undefined {+ if (interruptionError) {+ return {+ code: interruptionError.code,+ message: interruptionError.message,+ retriable: interruptionError.retriable ?? false,+ traceId: interruptionError.traceId ?? "",+ };+ }if (reason !== "error") return undefined;const code = errorCode ?? "TURN_ERROR";return { code, message: code, retriable: false, traceId: "" };@@ -199,6 +211,7 @@ function finishTurn(options.createNotification ??(!wasPlanSubmission && shouldCreateTaskNotification(id));const recoverInflight = options.recoverInflight === true;+ const interruptionError = options.interruptionError;const runFinalization = async (): Promise<void> => {try {@@ -242,6 +255,34 @@ function finishTurn(}}+ if (interruptionError && !isQuitting() && isActiveTurn(id, turnId)) {+ 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,+ },+ },+ };+ 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);+ }+if (runId && runtimeState.host) {await runtimeState.host.call("scheduled.finishRun", { runId, status: reason, errorCode })@@ -317,7 +358,7 @@ function finishTurn(id,turnId,hostTurnStatus(reason),- hostTurnError(reason, errorCode),+ hostTurnError(reason, errorCode, interruptionError),);runtimeState.agentHostBridge?.agentHost.kick(id);}diff --git a/apps/desktop/electron/main/runtime/sidecar.ts b/apps/desktop/electron/main/runtime/sidecar.tsindex 4807f397a..e60b58467 100644--- a/apps/desktop/electron/main/runtime/sidecar.ts+++ b/apps/desktop/electron/main/runtime/sidecar.ts@@ -171,6 +171,8 @@ export function createSidecarRuntime({errorCode: string,): Promise<void> => {const executionId = approvedExecutionIdsBySession.get(sessionId);+ agentExtensions.cancelPrompts(sessionId);+ plugins.cancelSessionTools(sessionId, "Agent sidecar exited unexpectedly");if (runtimeState.host) {await runtimeState.host.call("plans.abort", { sessionId }).catch(() => undefined);}@@ -195,6 +197,7 @@ export function createSidecarRuntime({await finishTurn(sessionId, "aborted", errorCode, {recoverInflight: true,turnId: crashedTurnId,+ interruptionError: { code: errorCode, message: "Agent sidecar exited unexpectedly" },});if (executionId) {await finishApprovedExecution(diff --git a/apps/desktop/src/lib/session-transcript.ts b/apps/desktop/src/lib/session-transcript.tsindex 72a6b70aa..3385b14a4 100644--- a/apps/desktop/src/lib/session-transcript.ts+++ b/apps/desktop/src/lib/session-transcript.ts@@ -104,6 +104,28 @@ export function projectMessageEnd(: upsertLiveSessionMessage(next, event.message);}+export function settleTranscriptAfterError(+ messages: UiMessage[],+ aborted: boolean,+): UiMessage[] {+ return messages+ .filter((message) => !(+ message.role === "assistant" &&+ message.status === "aborted" &&+ !message.content.trim() &&+ !(message.thinking || "").trim()+ ))+ .map((message) => {+ if (message.role === "tool" && message.toolStatus === "running") {+ return { ...message, toolStatus: "error", status: "error", isError: true };+ }+ if (message.role === "assistant" && message.status === "streaming") {+ return { ...message, status: aborted ? "aborted" : "error" };+ }+ return message;+ });+}+/*** Collapse repeated transcript rows by their canonical message id.*diff --git a/apps/desktop/src/stores/runtime/session-runtime.ts b/apps/desktop/src/stores/runtime/session-runtime.tsindex c1a0267a5..06399f3e1 100644--- a/apps/desktop/src/stores/runtime/session-runtime.ts+++ b/apps/desktop/src/stores/runtime/session-runtime.ts@@ -12,6 +12,7 @@ import {mergeLiveSessionMessages,projectMessageEnd,removeLiveSessionMessage,+ settleTranscriptAfterError,upsertLiveSessionMessage,} from "../../lib/session-transcript";import { getSessionMessageSnapshot, getSessionToolMessagePositions } from "../../lib/session-transcript-updates";@@ -359,6 +360,8 @@ export function createSessionRuntime({ get, set }: StoreAccess): SessionRuntime: upsertLiveSessionMessage(current, completed);break;}+ case "error":+ return settleTranscriptAfterError(current, event.error.code === "TURN_ABORTED");default:return current;}@@ -381,6 +384,9 @@ export function createSessionRuntime({ get, set }: StoreAccess): SessionRuntimenext,sessionHistoryCache.get(sessionId) ?? state.sessionHistory[sessionId],);+ if (envelope.event.type === "error" && state.retainedTranscripts[sessionId]) {+ set((current) => recordPaneTranscript(current, sessionId, next));+ }}function queueWorkspaceAlignment<T>(task: () => Promise<T>): Promise<T> {diff --git a/apps/desktop/src/stores/slices/events-slice.ts b/apps/desktop/src/stores/slices/events-slice.tsindex 1a8b56579..35c9d557e 100644--- a/apps/desktop/src/stores/slices/events-slice.ts+++ b/apps/desktop/src/stores/slices/events-slice.ts@@ -4,6 +4,7 @@ import {dedupeSessionMessages,projectMessageEnd,reconcilePersistedUserMessage,+ settleTranscriptAfterError,upsertLiveSessionMessage,} from "../../lib/session-transcript";import {@@ -706,34 +707,7 @@ export function createEventsSlice({const hasErrorMessage =last?.role === "assistant" &&(last.status === "error" || last.isError === true);- const messages: UiMessage[] = state.messages- .filter(- (message) =>- !(- message.role === "assistant" &&- message.status === "aborted" &&- !message.content.trim() &&- !(message.thinking || "").trim()- ),- )- .map((message) =>- message.role === "tool" && message.toolStatus === "running"- ? {- ...message,- toolStatus: "error" as const,- status: "error" as const,- isError: true,- }- : message.role === "assistant" &&- message.status === "streaming"- ? {- ...message,- status: aborted- ? ("aborted" as const)- : ("error" as const),- }- : message,- );+ const messages = settleTranscriptAfterError(state.messages, aborted);return {isRunning: false,error: null,diff --git a/apps/desktop/test/queued-turn-finalization.test.mjs b/apps/desktop/test/queued-turn-finalization.test.mjsindex b445e8037..889e5b2f9 100644--- a/apps/desktop/test/queued-turn-finalization.test.mjs+++ b/apps/desktop/test/queued-turn-finalization.test.mjs@@ -40,6 +40,8 @@ function fixture({ onTurnEnded } = {}) {const prompts = [];const writes = [];const announcements = [];+ const rendererEvents = [];+ const persistedEvents = [];let quitting = false;const coordination = createSessionCoordination({@@ -111,7 +113,9 @@ function fixture({ onTurnEnded } = {}) {runtimeState: { host, agentHostBridge: bridge },planState: { approvedExecutionDrain: null },logger: { app() {} },- sendToRenderer() {},+ sendToRenderer(channel, envelope) {+ if (channel === IPC.event.agentMessage) rendererEvents.push(envelope);+ },coordination,scheduledRunsBySession: new Map(),activeToolCalls: new Map(),@@ -125,7 +129,10 @@ function fixture({ onTurnEnded } = {}) {inFlightExecutionFinishes: new Set(),pendingExecutionFinishes: new Map(),announceTurnEnded: (payload) => announcements.push(payload),- emitAgentEvent() {},+ emitAgentEvent(envelope) {+ rendererEvents.push(envelope);+ },+ persistAgentEvent: (envelope) => persistedEvents.push(envelope),acquireSessionOperation: coordination.acquireSessionOperation,resolveAgentRuntimeLaunch: async () => {throw new Error("not used by this fixture");@@ -182,6 +189,8 @@ function fixture({ onTurnEnded } = {}) {persistedQueue,prompts,announcements,+ rendererEvents,+ persistedEvents,writes,finish,finishTurn: planRuntime.finishTurn,@@ -191,6 +200,56 @@ function fixture({ onTurnEnded } = {}) {};}+for (const errorCode of ["AGENT_SIDECAR_CRASHED", "AGENT_SIDECAR_OOM"]) {+ test(`a crashed turn publishes its recovered reply and one ${errorCode} card before releasing the queue`, async () => {+ const f = fixture();+ await f.bridge.queue.push({ sessionId: SESSION, content: "follow-up" });+ const error = { code: errorCode, message: "Agent sidecar exited unexpectedly" };+ const options = { turnId: FIRST_TURN, recoverInflight: true, interruptionError: error };+ const pending = f.finishTurn(SESSION, "aborted", errorCode, options);+ assert.equal(f.finishTurn(SESSION, "aborted", errorCode, options), pending);+ await setImmediate();+ assert.deepEqual(f.rendererEvents, []);+ assert.deepEqual(f.prompts, []);+ f.writes[0].resolve({+ ok: true,+ recovered: {+ id: "partial", role: "assistant", content: "Partial reply",+ createdAt: "2026-11-25T00:00:00Z", status: "aborted",+ },+ });+ await pending;+ await setImmediate();+ assert.deepEqual(f.rendererEvents.map(({ event }) => event.type), [+ "message_end", "message_end", "error",+ ]);+ 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.rendererEvents[2].event.error, error);+ assert(f.rendererEvents.every(({ turnId }) => turnId === FIRST_TURN));+ const interrupted = f.bridge.agentHost.getTurn(FIRST_TURN);+ assert.equal(interrupted.status, "interrupted");+ assert.equal(interrupted.error?.code, errorCode);+ assert.deepEqual(f.prompts.map(({ content }) => content), ["follow-up"]);+ });+}++test("a crashed turn does not publish a live error 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, {+ turnId: FIRST_TURN, recoverInflight: true, interruptionError: error,+ });+ await setImmediate();+ f.activeTurns.set(SESSION, "successor");+ f.writes[0].resolve({ ok: true });+ await pending;+ assert.deepEqual(f.rendererEvents, []);+ assert.deepEqual(f.persistedEvents, []);+ assert.equal(f.activeTurns.get(SESSION), "successor");+});+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/apps/desktop/test/session-runtime-updates.test.mjs b/apps/desktop/test/session-runtime-updates.test.mjsindex ad6b65565..7e90ce61a 100644--- a/apps/desktop/test/session-runtime-updates.test.mjs+++ b/apps/desktop/test/session-runtime-updates.test.mjs@@ -24,6 +24,11 @@ function harness(messages, background = []) {retainedSessionIds: ["active", "background"],retainedTranscripts: { active: messages, background },runningSessions: { active: true, background: true },+ agentStatuses: { active: { currentTurnId: "other-turn" }, background: { currentTurnId: "crashed-turn" } },+ pendingPermissions: {},+ pendingAsks: {},+ askDrafts: {},+ latestTurnResults: {},sessionHistory: {},};const access = {@@ -40,7 +45,13 @@ function harness(messages, background = []) {runtime = createSessionRuntime(access);runtime.cacheSessionTranscript("active", messages);runtime.cacheSessionTranscript("background", background);- Object.assign(state, createEventsSlice({ ...access, runtime }));+ Object.assign(state, createEventsSlice({+ ...access, runtime,+ withoutRecordKey: (record, key) => Object.fromEntries(+ Object.entries(record).filter(([entry]) => entry !== key),+ ),+ flushPendingSessionConfiguration: async () => {},+ }));return { ...access, runtime, writes: () => writes };}@@ -117,6 +128,36 @@ test("background deltas update only their cache and leave active and retained arassert.equal(getSessionMessageSnapshot(cached).owner, getSessionMessageSnapshot(background).owner);}));+test("a background crash settles its retained tool row and keeps the recovered reply and error card", () => {+ const active = [message("other")];+ const h = harness(active, [+ message("partial", { status: "streaming" }),+ message("tool", { role: "tool", status: "streaming", toolStatus: "running" }),+ ]);+ const error = { code: "AGENT_SIDECAR_CRASHED", message: "Agent sidecar exited unexpectedly" };+ const send = (event) => h.get().handleAgentEvent({+ sessionId: "background", turnId: "crashed-turn", ts: 1, event,+ });+ send({ type: "message_end", message: message("partial", { status: "aborted" }) });+ send({ type: "message_end", message: message("error", { content: "", status: "error", error }) });+ send({ type: "error", error });++ const state = h.get();+ const retained = state.retainedTranscripts.background;+ assert.equal(state.runningSessions.background, false);+ assert.equal(state.agentStatuses.background, undefined);+ assert.equal(state.runningSessions.active, true);+ assert.equal(state.messages, active);+ assert.deepEqual(retained.map(({ id, status }) => ({ id, status })), [+ { id: "partial", status: "aborted" },+ { id: "tool", status: "error" },+ { id: "error", status: "error" },+ ]);+ assert.equal(retained[1].toolStatus, "error");+ assert.equal(retained[2].error.code, error.code);+ assert.equal(h.runtime.sessionTranscriptCache.get("background"), retained);+});+test("active and background duplicate inputs apply deltas to the last value at the first position", () => withFrames((flush) => {const duplicates = () => [message("live", { content: "old" }), message("middle"), message("live", { content: "latest" })];const h = harness(duplicates(), duplicates());diff --git a/docs/spec/03-runtime/07-process-model.md b/docs/spec/03-runtime/07-process-model.mdindex 58c560baf..240b94c42 100644--- a/docs/spec/03-runtime/07-process-model.md+++ b/docs/spec/03-runtime/07-process-model.md@@ -263,6 +263,14 @@ checkpoint of every running session is flushed and `session.endTurn` is askedto `recoverInflight`, so the streamed text becomes the turn's `aborted` rowinstead of vanishing with the process.+On an unexpected sidecar exit, Electron Main cancels the affected sessions'+extension prompts and plugin tools. After checkpoint recovery it records the+classified error as an assistant transcript row and publishes a terminal+renderer event for each turn that still owns its session. Foreground and+background 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.+Minimizing the main window is a resident-shell action, not an applicationshutdown. On Windows/Linux, explicit application minimize actions use thenative taskbar transition and keep the process alive; clicking the Windowsdiff --git a/docs/spec/06-delivery/e2e/conversation.md b/docs/spec/06-delivery/e2e/conversation.mdindex 12e31f1a4..d7dea9b1a 100644--- a/docs/spec/06-delivery/e2e/conversation.md+++ b/docs/spec/06-delivery/e2e/conversation.md@@ -666,15 +666,19 @@ folder/mixed-selection behavior. No system clipboard contents are changed.ten seconds before its first tool call.- **Steps**: 1) Send a prompt and let the reply stream for ~5 s. 2) Quit theapp (Cmd+Q / tray Quit) mid-stream, relaunch, and open the session. 3) Repeat- the send, then kill the agent sidecar process mid-stream and observe the- transcript. 4) Repeat the send, press Stop mid-stream, then reopen the+ the send, then kill the agent sidecar process mid-stream or during a tool+ call. Repeat with the session in the background and reselect it. 4) Repeat+ the send, press Stop mid-stream, then reopen thesession from the sidebar and inspect `sessions/<id>.jsonl` and`sessions/<id>.inflight.json`. 5) Repeat the send and let it finish normally.- **Expected**: 2) The session shows the user prompt followed by the streamedtext up to at most 1.5 s before the quit, as an `aborted` assistant row underan `aborted` turn; nothing earlier in the session is missing or truncated. 3)- The streaming row settles to `aborted` in place with its text, the same row- is present after a reload, and no `.inflight.json` remains. 4) The partial+ The streaming row settles to `aborted` in place with its text. The session+ timer, running badge, and tool spinner stop, and a localized crash error+ appears. 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 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