Skip to content

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

fix(desktop): name a sidecar crash in the durable turn it kills (#1077)

joyawang37723d2e22df
diff --git a/apps/desktop/electron/main/runtime/sidecar.ts b/apps/desktop/electron/main/runtime/sidecar.ts
index d12348d66..4f2d5e47c 100644
--- a/apps/desktop/electron/main/runtime/sidecar.ts
+++ b/apps/desktop/electron/main/runtime/sidecar.ts
@@ -1,9 +1,11 @@
import { IPC, type AgentEventEnvelope, type UiMessage } from "@pi-desktop/shared";
import {
findSubagentProviderSource,
- loadInstructionChain,
modelConfigWithBinding,
+ loadInstructionChain,
subagentProviderLookupError,
+ classifySidecarCrash,
+ sidecarCrashErrorCode,
} from "@pi-desktop/agent-runtime";
import { loadBuiltinSkillBody } from "../builtin-skills";
import { createImageGenerationTool } from "../services/image-generation-service";
@@ -118,8 +120,10 @@ export function createSidecarRuntime({
* not be left behind. The finalizer refuses the settlement for a turn that no
* longer owns the session and drops exactly those records.
*/
- const releaseCrashedTurn = (sessionId: string, crashedTurnId: string) =>
- finishTurn(sessionId, "aborted", "PLAN_APPROVAL_INTERRUPTED", {
+ // The sidecar is dead, so this release path can never be reached while the
+ // crashed sidecar's tail is unknown: callers pass the classified code down.
+ const releaseCrashedTurn = (sessionId: string, crashedTurnId: string, errorCode: string) =>
+ finishTurn(sessionId, "aborted", errorCode, {
turnId: crashedTurnId,
});
@@ -131,6 +135,10 @@ export function createSidecarRuntime({
const settleCrashedSession = async (
sessionId: string,
crashedTurnId: string,
+ // Classified by the caller from the dead sidecar's stderr tail: the
+ // durable turn row names the real failure instead of an unrelated
+ // plan-approval code (issue #1077).
+ errorCode: string,
): Promise<void> => {
const executionId = approvedExecutionIdsBySession.get(sessionId);
if (runtimeState.host) {
@@ -139,7 +147,7 @@ export function createSidecarRuntime({
// A newer turn may own the session by now; this cleanup is the old one's.
// It must still not leave the crashed turn's records behind.
if (activeTurns.get(sessionId) !== crashedTurnId) {
- await releaseCrashedTurn(sessionId, crashedTurnId);
+ await releaseCrashedTurn(sessionId, crashedTurnId, errorCode);
return;
}
// No final row is coming from a dead sidecar: keep whatever the reply had
@@ -150,11 +158,11 @@ export function createSidecarRuntime({
// so it is reached only for the turn that still owns the session, and it is
// called synchronously right after this check: no await in between.
if (activeTurns.get(sessionId) !== crashedTurnId) {
- await releaseCrashedTurn(sessionId, crashedTurnId);
+ await releaseCrashedTurn(sessionId, crashedTurnId, errorCode);
return;
}
inflightCheckpointer.settle(sessionId);
- await finishTurn(sessionId, "aborted", "PLAN_APPROVAL_INTERRUPTED", {
+ await finishTurn(sessionId, "aborted", errorCode, {
recoverInflight: true,
turnId: crashedTurnId,
});
@@ -262,6 +270,11 @@ export function createSidecarRuntime({
},
});
}
+ // Classify the exit once, from the child's own stderr tail, and carry the
+ // verdict into every settlement and log line below: a heap-exhaustion death
+ // must not read as an unrelated plan-approval interruption (issue #1077).
+ const crash = classifySidecarCrash(stderrTail);
+ const crashErrorCode = sidecarCrashErrorCode(crash.kind);
// A sidecar crash closes live approval waiters before the replacement
// sidecar starts. This prevents an old renderer response from waking a
// dead runtime and records the durable turn as interrupted.
@@ -271,7 +284,7 @@ export function createSidecarRuntime({
// late cleanup must not settle or abort that newer turn.
const crashedTurnId = activeTurns.get(sessionId);
if (!crashedTurnId) continue;
- void settleCrashedSession(sessionId, crashedTurnId).catch((error: unknown) => {
+ void settleCrashedSession(sessionId, crashedTurnId, crashErrorCode).catch((error: unknown) => {
// The crash handler cannot await this and the sidecar is already gone:
// log the failure instead of leaving the rejection unhandled.
logger.app("runtime", "warn", "crashed-turn settlement failed", {
@@ -288,7 +301,13 @@ export function createSidecarRuntime({
);
}
logger.app("runtime", "error", "agent sidecar exited unexpectedly", {
- data: { exitCode: code, signal, stderrTail },
+ data: {
+ exitCode: code,
+ signal,
+ stderrTail,
+ crashKind: crash.kind,
+ ...(crash.marker ? { crashMarker: crash.marker } : {}),
+ },
});
sendToRenderer(IPC.event.hostStatus, {
ok: false,
diff --git a/apps/desktop/test/rpc-lifecycle-contract.test.mjs b/apps/desktop/test/rpc-lifecycle-contract.test.mjs
index 6aaa5d2af..70388cce5 100644
--- a/apps/desktop/test/rpc-lifecycle-contract.test.mjs
+++ b/apps/desktop/test/rpc-lifecycle-contract.test.mjs
@@ -297,7 +297,23 @@ test("sidecar crash reports carry the last stderr lines", () => {
);
assert.match(mainSource, /agent sidecar exited unexpectedly/);
assert.ok(
- mainSource.includes("data: { exitCode: code, signal, stderrTail }"),
+ mainSource.includes("stderrTail,"),
"crash log carries the tail",
);
+ // The crash kind is classified once from the tail and reaches both the
+ // settlement code and the log line, so an OOM death never reads as an
+ assert.match(runtimeSidecarSource, /classifySidecarCrash\(stderrTail\)/);
+ assert.match(runtimeSidecarSource, /sidecarCrashErrorCode\(crash\.kind\)/);
+ assert.match(runtimeSidecarSource, /crashKind: crash\.kind/);
+ assert.ok(
+ runtimeSidecarSource.includes(
+ "settleCrashedSession(sessionId, crashedTurnId, crashErrorCode)",
+ ),
+ "the owning turn settles with the classified code",
+ );
+ assert.doesNotMatch(runtimeSidecarSource, /finishTurn\([^)]*"PLAN_APPROVAL_INTERRUPTED"/);
+ assert.match(
+ runtimeSidecarSource,
+ /finishTurn\(sessionId, "aborted", errorCode, \{/,
+ );
});
diff --git a/docs/spec/03-runtime/07-process-model.md b/docs/spec/03-runtime/07-process-model.md
index 0039381f4..a2a1d5d62 100644
--- a/docs/spec/03-runtime/07-process-model.md
+++ b/docs/spec/03-runtime/07-process-model.md
@@ -94,7 +94,7 @@ errors remain readable instead of becoming replacement characters.
|---|---|
| Renderer crash | reload the current window after an unexpected renderer exit, unless the window is closing or the app is quitting; keep host/agent processes; same-host reload restores only live pending Plan/Goal approvals and their deadlines, not terminal cards |
| Rust host crash | mark app degraded, interrupt pending/queued/running approval work, keep pending sessions in their contract mode (Plan or Goal) and already-approved sessions in Agent, attempt restart host, and fail active sessions closed |
-| Node agent crash | abort active turns and live approval waiters/queue entries, keep pending sessions in their contract mode, preserve already-approved Agent mode in Rust, restart sidecar, and never replay an execution |
+| Node agent crash | abort active turns and live approval waiters/queue entries, keep pending sessions in their contract mode, preserve already-approved Agent mode in Rust, restart sidecar, and never replay an execution; the sidecar's stderr tail is classified at exit — a V8 heap-exhaustion banner settles the owning turn as `AGENT_SIDECAR_OOM`, any other unexpected exit as `AGENT_SIDECAR_CRASHED` (issue #1077) |
| Electron main crash | full app exit |
Crashpad is started local-only (`uploadToServer: false`) before `ready`, and
diff --git a/docs/spec/03-runtime/08-error-codes.md b/docs/spec/03-runtime/08-error-codes.md
index aacc76919..7d939ae5e 100644
--- a/docs/spec/03-runtime/08-error-codes.md
+++ b/docs/spec/03-runtime/08-error-codes.md
@@ -96,6 +96,8 @@ does not turn temporary thread pressure into a host process exit.
| `AGENT_NOT_FOUND` | no | session missing |
| `TURN_NOT_FOUND` | no | turn id invalid |
| `TURN_ABORTED` | no | turn aborted by user/system |
+| `AGENT_SIDECAR_CRASHED` | no | the Node agent sidecar process died mid-turn; the owning turn settles as aborted with this code instead of an unrelated plan-approval code (issue #1077) |
+| `AGENT_SIDECAR_OOM` | no | the sidecar died after its JavaScript heap hit the configured cap, diagnosed from the V8 fatal-error banner in its stderr tail; the same turn fails the same way until the input shrinks (issue #1077) |
| `MODEL_NOT_CONFIGURED` | no | no usable model selected, or provider rejects the selected model as unknown |
| `PROVIDER_ERROR` | yes | upstream provider failure; a retryable one (5xx gateway) gets up to ten same-turn retries, while a malformed 400/422 request or a request option the adapter itself refuses (a custom `fetch` for the Google adapters, issue #1072) is terminal |
| `PROVIDER_UNAUTHORIZED` | no | bad/missing provider credentials |
diff --git a/docs/zh-CN/spec/03-runtime/07-process-model.md b/docs/zh-CN/spec/03-runtime/07-process-model.md
index aaeed5435..bb2835bd1 100644
--- a/docs/zh-CN/spec/03-runtime/07-process-model.md
+++ b/docs/zh-CN/spec/03-runtime/07-process-model.md
@@ -72,7 +72,7 @@ queued/running `plan_approvals` 执行状态已中断并中止它们
|---|---|
| Renderer 崩溃 | 重新加载窗口,保留 host/agent 进程;同一主机重新加载仅恢复实时待处理的 Plan/Goal 批准及其截止日期,而不是终端卡 |
| Rust 主机崩溃 | 将应用程序标记为降级、中断 pending/queued/running 审批工作、将待处理会话保留在其合同模式(Plan 或 Goal)中并将已批准的会话保留在 Agent 中、尝试重新启动主机并关闭活动会话失败 |
-| Node 代理崩溃 | 中止活动轮次和实时批准 waiters/queue 条目,在合同模式下保留待处理会话,在 Rust 中保留已批准的 Agent 模式,重新启动 sidecar,并且从不重播执行 |
+| Node 代理崩溃 | 中止活动轮次和实时批准 waiters/queue 条目,在合同模式下保留待处理会话,在 Rust 中保留已批准的 Agent 模式,重新启动 sidecar,并且从不重播执行;sidecar 退出时对其 stderr 尾部做分类——V8 堆耗尽横幅使所属回合以 `AGENT_SIDECAR_OOM` 收尾,其他意外退出以 `AGENT_SIDECAR_CRASHED` 收尾(issue #1077) |
| Electron 主要崩溃 | 完整的应用程序退出 |
Crashpad 在 `ready` 之前以本地模式启动(`uploadToServer: false`),转储放在
diff --git a/docs/zh-CN/spec/03-runtime/08-error-codes.md b/docs/zh-CN/spec/03-runtime/08-error-codes.md
index 407ca0516..03b5864e0 100644
--- a/docs/zh-CN/spec/03-runtime/08-error-codes.md
+++ b/docs/zh-CN/spec/03-runtime/08-error-codes.md
@@ -97,6 +97,8 @@ stdio 与 Tokio 的动态阻塞池隔离,因此后一种情况
| `AGENT_NOT_FOUND` | 不 | 会话丢失 |
| `TURN_NOT_FOUND` | 不 | 使 id 无效 |
| `TURN_ABORTED` | 不 | 回合被 user/system 中止 |
+| `AGENT_SIDECAR_CRASHED` | 不 | Node agent sidecar 进程在回合中途死亡;所属回合以中止收尾并使用此代码,而不是无关的 Plan 审批代码(issue #1077) |
+| `AGENT_SIDECAR_OOM` | 不 | sidecar 在 JavaScript 堆触及配置上限后死亡,依据其 stderr 尾部的 V8 致命错误横幅判定;在输入缩小之前,同一回合会以同样方式失败(issue #1077) |
| `MODEL_NOT_CONFIGURED` | 不 | 未选择可用模型,或提供商因未知而拒绝所选模型 |
| `PROVIDER_ERROR` | 是的 | 上游提供商故障;可重试的故障(5xx 网关)最多获得四次同回合重试,而格式错误的 400/422 请求,以及适配器自身拒绝的请求选项(Google 适配器遇到自定义 `fetch`,issue #1072)都是终止的 |
| `PROVIDER_UNAUTHORIZED` | 不 | bad/missing 提供商凭证 |
diff --git a/packages/agent-runtime/src/index.ts b/packages/agent-runtime/src/index.ts
index 2834f0aa6..792a88a03 100644
--- a/packages/agent-runtime/src/index.ts
+++ b/packages/agent-runtime/src/index.ts
@@ -15,6 +15,8 @@ export * from "./project-instructions.js";
export * from "./project-instructions-prompt.js";
export * from "./project-memory-prompt.js";
export * from "./subagent.js";
+export { classifySidecarCrash, sidecarCrashErrorCode } from "./sidecar-crash.js";
+export type { SidecarCrash, SidecarCrashKind } from "./sidecar-crash.js";
export * from "./subagent-definitions.js";
export * from "./session-title-summarize.js";
export * from "./stream-coalescer.js";
diff --git a/packages/agent-runtime/src/sidecar-crash.test.ts b/packages/agent-runtime/src/sidecar-crash.test.ts
new file mode 100644
index 000000000..64bef18a8
--- /dev/null
+++ b/packages/agent-runtime/src/sidecar-crash.test.ts
@@ -0,0 +1,53 @@
+import { describe, expect, it } from "vitest";
+
+import { classifySidecarCrash, sidecarCrashErrorCode } from "./sidecar-crash.js";
+import { ErrorCodes } from "@pi-desktop/shared";
+
+const OOM_TAIL = [
+ "<--- Last few GCs --->",
+ "[43001:0x100008b0000] 2435727 ms: Mark-Compact (reduce) 2046.4 (2056.4) -> 2046.4 (2056.4) MB, ... last resort; GC in old space requested",
+ "",
+ "<--- JS stacktrace --->",
+ "",
+ "FATAL ERROR: Reached heap limit Allocation failed - JavaScript heap out of memory",
+].join("\n");
+
+describe("classifySidecarCrash", () => {
+ it("classifies a V8 heap-exhaustion tail as oom", () => {
+ const crash = classifySidecarCrash(OOM_TAIL);
+ expect(crash.kind).toBe("oom");
+ expect(crash.marker).toBeTruthy();
+ expect(sidecarCrashErrorCode(crash.kind)).toBe("AGENT_SIDECAR_OOM");
+ });
+
+ it("recognizes the compact heap-out-of-memory banner without the GC block", () => {
+ const crash = classifySidecarCrash(
+ "FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - JavaScript heap out of memory",
+ );
+ expect(crash.kind).toBe("oom");
+ expect(sidecarCrashErrorCode(crash.kind)).toBe("AGENT_SIDECAR_OOM");
+ });
+
+ it("an unrecognized native failure stays an honest generic crash", () => {
+ for (const tail of [
+ "",
+ "Segmentation fault",
+ "some unrelated warning\nanother line",
+ ]) {
+ const crash = classifySidecarCrash(tail);
+ expect(crash.kind).toBe("crashed");
+ expect(crash.marker).toBeUndefined();
+ expect(sidecarCrashErrorCode(crash.kind)).toBe("AGENT_SIDECAR_CRASHED");
+ }
+ });
+
+ it("non-string tails (undefined from an old exit payload) are not oom", () => {
+ expect(classifySidecarCrash(undefined).kind).toBe("crashed");
+ expect(classifySidecarCrash(null).kind).toBe("crashed");
+ });
+
+ it("both classified codes are registered shared error codes", () => {
+ expect(ErrorCodes.AGENT_SIDECAR_OOM).toBe("AGENT_SIDECAR_OOM");
+ expect(ErrorCodes.AGENT_SIDECAR_CRASHED).toBe("AGENT_SIDECAR_CRASHED");
+ });
+});
diff --git a/packages/agent-runtime/src/sidecar-crash.ts b/packages/agent-runtime/src/sidecar-crash.ts
new file mode 100644
index 000000000..565b9a2c1
--- /dev/null
+++ b/packages/agent-runtime/src/sidecar-crash.ts
@@ -0,0 +1,49 @@
+/**
+ * Classify an agent-sidecar crash from the stderr tail the child left behind.
+ *
+ * A sidecar that dies mid-turn settles its owning turn through
+ * `settleCrashedSession`. That settlement used one fixed Plan-family code for
+ * every exit, which hid the crash inside unrelated approval vocabulary and
+ * gave users no hint that their context was the problem. The classifier turns
+ * the child's own dying words — the V8 fatal-error banner in its stderr tail —
+ * into the honest terminal code (issue #1077).
+ */
+import { ErrorCodes } from "@pi-desktop/shared";
+
+/** Codes the classifier can return; both are registered in `ErrorCodes`. */
+export type SidecarCrashKind = "oom" | "crashed";
+
+/** V8 prints these lines before exiting on heap exhaustion. */
+const OOM_MARKERS = [
+ "Last few GCs ---",
+ "heap out of memory",
+ "Reached heap limit",
+ "CALL_AND_RETRY_LAST Allocation failed",
+] as const;
+
+export type SidecarCrash = {
+ kind: SidecarCrashKind;
+ /** The matching OOM marker, when `kind` is `"oom"`. */
+ marker?: string;
+};
+
+export function sidecarCrashErrorCode(kind: SidecarCrashKind): string {
+ // The code lives in the shared registry, so an unregistered code is a
+ // compile error here rather than a silent transcript mismatch.
+ return kind === "oom"
+ ? ErrorCodes.AGENT_SIDECAR_OOM
+ : ErrorCodes.AGENT_SIDECAR_CRASHED;
+}
+
+/**
+ * Read the crash kind from a sidecar's captured stderr tail. Returns
+ * `"crashed"` for anything that does not carry a recognizable OOM banner, so
+ * an unknown native failure still settles under an honest generic code.
+ */
+export function classifySidecarCrash(stderrTail: unknown): SidecarCrash {
+ const text = typeof stderrTail === "string" ? stderrTail : "";
+ for (const marker of OOM_MARKERS) {
+ if (text.includes(marker)) return { kind: "oom", marker };
+ }
+ return { kind: "crashed" };
+}
diff --git a/packages/host-runtime/src/runtime-service.test.ts b/packages/host-runtime/src/runtime-service.test.ts
index 2c61ff7c8..46f62c14a 100644
--- a/packages/host-runtime/src/runtime-service.test.ts
+++ b/packages/host-runtime/src/runtime-service.test.ts
@@ -339,16 +339,18 @@ describe("RuntimeService prompt lifecycle", () => {
});
});
- it("settles every running turn as aborted when the sidecar dies", async () => {
+ it("settles every running turn as aborted with the honest crash code when the sidecar dies", async () => {
const { host, sidecar, service, ended } = build();
await service.prompt({ sessionId: "s1", content: "hello", effectivePermissionMode: "ask", principal: owner });
sidecar.exit?.({ intentional: false, code: 1, signal: null });
await settle();
expect(host.calls.find((call) => call.method === "session.endTurn")?.params).toMatchObject({
status: "aborted",
+ errorCode: "AGENT_SIDECAR_CRASHED",
recoverInflight: true,
});
expect(ended[0]?.reason).toBe("aborted");
+ expect(ended[0]?.errorCode).toBe("AGENT_SIDECAR_CRASHED");
expect(service.isBusy("s1")).toBe(false);
});
diff --git a/packages/host-runtime/src/runtime-service.ts b/packages/host-runtime/src/runtime-service.ts
index 25d98c89d..6e9e43fed 100644
--- a/packages/host-runtime/src/runtime-service.ts
+++ b/packages/host-runtime/src/runtime-service.ts
@@ -643,7 +643,10 @@ export class RuntimeService implements RuntimePort {
await this.events.flushCheckpoint(sessionId);
if (this.activeTurns.get(sessionId) !== crashedTurnId) return;
this.events.settleCheckpoint(sessionId);
- await this.finishTurn(sessionId, "aborted", "PLAN_APPROVAL_INTERRUPTED", {
+ // The sidecar handle's exit info carries no stderr tail, so this path
+ // cannot classify a heap exhaustion; it still names the failure honestly
+ // instead of borrowing plan-approval vocabulary (issue #1077).
+ await this.finishTurn(sessionId, "aborted", "AGENT_SIDECAR_CRASHED", {
turnId: crashedTurnId,
recoverInflight: true,
});
diff --git a/packages/shared/src/errors.ts b/packages/shared/src/errors.ts
index 02a097b3f..271545863 100644
--- a/packages/shared/src/errors.ts
+++ b/packages/shared/src/errors.ts
@@ -79,6 +79,21 @@ export const ErrorCodes = {
CONTEXT_COMPACTION_FAILED: "CONTEXT_COMPACTION_FAILED",
STREAM_FAILED: "STREAM_FAILED",
EMPTY_MODEL_RESPONSE: "EMPTY_MODEL_RESPONSE",
+ /**
+ * The Node agent sidecar process died mid-turn (native crash, kill, or an
+ * unclassified abort). Main and the headless runtime settle the owning turn
+ * with this code so a crash is visible in the durable transcript instead of
+ * reading as a plan-approval interruption.
+ */
+ AGENT_SIDECAR_CRASHED: "AGENT_SIDECAR_CRASHED",
+ /**
+ * The Node agent sidecar died after its JavaScript heap hit the configured
+ * cap (`--max-old-space-size`): the turn's context, tool output, or stream
+ * grew past what the runtime process can hold. Diagnosed from the child's
+ * stderr tail (`Reached heap limit` / `heap out of memory`); retrying the
+ * same turn fails the same way until the input shrinks.
+ */
+ AGENT_SIDECAR_OOM: "AGENT_SIDECAR_OOM",
PROMPT_ENHANCEMENT_EMPTY: "PROMPT_ENHANCEMENT_EMPTY",
SPEECH_NOT_CONFIGURED: "SPEECH_NOT_CONFIGURED",
SPEECH_PROTOCOL_UNSUPPORTED: "SPEECH_PROTOCOL_UNSUPPORTED",