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): name the plugin host exit code in a crash report
zhangqingkun976c0ad421910f2
diff --git a/apps/desktop/electron/main/plugin-runtime.ts b/apps/desktop/electron/main/plugin-runtime.tsindex a84f30d7e..38945c3ad 100644--- a/apps/desktop/electron/main/plugin-runtime.ts+++ b/apps/desktop/electron/main/plugin-runtime.ts@@ -384,7 +384,13 @@ export type PluginHostServices = {*/pluginShortcuts?: PluginShortcutRegistry;/** Fired when a plugin host process dies on its own (crash, OOM, hard exit). */- onPluginCrash?: (info: { pluginId: string; name: string; exitCode: number }) => void;+ onPluginCrash?: (info: {+ pluginId: string;+ name: string;+ exitCode: number;+ /** The plugin's own last output line, when it printed one before dying. */+ lastOutput?: string;+ }) => void;/** Fired when a resident service changes supervision state. */onServiceChange?: (status: PluginServiceStatus) => void;/** Fired after a development plugin was reloaded from disk, or failed to. */@@ -624,6 +630,47 @@ const SERVICE_RESTART_MAX_DELAY_MS = 30_000;const MAX_SERVICE_RESTARTS = 5;/** A host process that stays up this long is healthy; the backoff resets. */const SERVICE_HEALTHY_MS = 60_000;+/** Trailing plugin-output lines kept for a crash report, newest last. */+const PLUGIN_LOG_TAIL_LINES = 3;+/** Per-line cap, so a plugin that printed a megabyte cannot fill the record. */+const PLUGIN_LOG_TAIL_LINE_CHARS = 400;++/** One line a plugin host process wrote to its own stdout/stderr. */+type PluginLogLine = { level: string; message: string };++/**+ * `exit code N`, plus the unsigned hex form in the range a Windows process+ * reports for a hard fault. Electron hands `code` through as a signed int, so+ * `-1073741819` is the same value as `0xC0000005`; printing both keeps the+ * number usable without interpreting what it means.+ */+function childExitLabel(code: number): string {+ if (!Number.isFinite(code)) return "exit code unknown";+ const unsigned = code < 0 ? code + 0x1_0000_0000 : code;+ const hex =+ unsigned >= 0x8000_0000 ? ` (0x${unsigned.toString(16).toUpperCase()})` : "";+ return `exit code ${unsigned}${hex}`;+}++/** The newest plugin-output line, flattened for a one-line report. */+function lastLogLine(+ tail: readonly PluginLogLine[] | undefined,+): string | undefined {+ const newest = tail?.[tail.length - 1];+ if (!newest?.message) return undefined;+ const text = newest.message.replace(/\s+/g, " ").trim();+ return text ? `${newest.level}: ${text}` : undefined;+}++/** The exit code plus the plugin's last words, when it left any. */+function childExitDetail(+ code: number,+ tail: readonly PluginLogLine[] | undefined,+): string {+ const label = childExitLabel(code);+ const lastOutput = lastLogLine(tail);+ return lastOutput ? `${label}; last output: ${lastOutput}` : label;+}/** Bus payloads are messages, not file transfers. */const MAX_BUS_PAYLOAD_BYTES = 64 * 1024;/** A plugin may hold at most this many live subscriptions. */@@ -682,6 +729,8 @@ type LoadedPlugin = {pending: Map<string, PendingCall>;nextCallId: number;disposing: boolean;+ /** Newest host-process output lines, so a crash report can quote them. */+ logTail: PluginLogLine[];};type PluginApiError = Error & { code?: string };@@ -1701,6 +1750,7 @@ export class PluginRuntime {pending: new Map(),nextCallId: 1,disposing: false,+ logTail: [],};this.loaded.set(manifest.id, loaded);@@ -1708,6 +1758,14 @@ export class PluginRuntime {child.onExit((code) => this.handleChildExit(loaded, code));child.onLog?.((level, message) => {if (!message) return;+ // Keep the newest lines on the record itself: a crash report has to carry+ // whatever the plugin printed before it died, and the audit thread alone+ // cannot be quoted in the error a user pastes into an issue.+ loaded.logTail.push({+ level,+ message: message.slice(0, PLUGIN_LOG_TAIL_LINE_CHARS),+ });+ if (loaded.logTail.length > PLUGIN_LOG_TAIL_LINES) loaded.logTail.shift();this.services.audit?.({pluginId: manifest.id,api: "plugin.stdio",@@ -2720,7 +2778,21 @@ export class PluginRuntime {if (loaded.disposing) return;if (this.loaded.get(loaded.manifest.id) !== loaded) return;const pluginId = loaded.manifest.id;- this.rejectPending(loaded, apiError("PLUGIN_CRASHED", `plugin host process exited: ${pluginId}`));+ // The exit code is the whole diagnosis for a crash report: a Windows hard+ // fault (0xC0000005 and friends) and a plugin's own `process.exit(1)` are+ // different bugs, and only this number tells them apart. The plugin's last+ // output line rides along because a plugin that died on a thrown error+ // usually printed the reason first, and the report a user can paste is the+ // one place that evidence has to survive.+ const detail = childExitDetail(code, loaded.logTail);+ const lastOutput = lastLogLine(loaded.logTail);+ this.rejectPending(+ loaded,+ apiError(+ "PLUGIN_CRASHED",+ `plugin host process exited: ${pluginId} (${detail})`,+ ),+ );this.clearContributions(pluginId);this.loaded.delete(pluginId);void this.services.closePanel(pluginId);@@ -2730,11 +2802,17 @@ export class PluginRuntime {ok: false,errorCode: "PLUGIN_CRASHED",exitCode: code,+ ...(lastOutput ? { message: lastOutput } : {}),ts: Date.now(),});this.services.showToast(`Plugin stopped unexpectedly: ${loaded.manifest.name}`, "error");- this.services.onPluginCrash?.({ pluginId, name: loaded.manifest.name, exitCode: code });- this.superviseCrash(loaded);+ this.services.onPluginCrash?.({+ pluginId,+ name: loaded.manifest.name,+ exitCode: code,+ ...(lastOutput ? { lastOutput } : {}),+ });+ this.superviseCrash(loaded, code);}/**@@ -2742,14 +2820,14 @@ export class PluginRuntime {* with exponential backoff, and after `MAX_SERVICE_RESTARTS` leave the plugin* down rather than spin forever — the failed state is what the user sees.*/- private superviseCrash(loaded: LoadedPlugin): void {+ private superviseCrash(loaded: LoadedPlugin, code: number): void {const pluginId = loaded.manifest.id;const declared = this.declaredServices(loaded);if (!declared.length) return;const record = this.restarts.get(pluginId) ?? { attempts: 0 };if (record.healthy) clearTimeout(record.healthy);record.healthy = undefined;- this.markServices(loaded, "failed", record.attempts, "plugin host process exited");+ this.markServices(loaded, "failed", record.attempts, `plugin host process exited (${childExitLabel(code)})`);const restartable =loaded.permissions.has("background.service") &&diff --git a/apps/desktop/electron/main/services/plugin-services.ts b/apps/desktop/electron/main/services/plugin-services.tsindex cfada9d69..195e98f12 100644--- a/apps/desktop/electron/main/services/plugin-services.ts+++ b/apps/desktop/electron/main/services/plugin-services.ts@@ -411,11 +411,11 @@ export function createPluginServices({},// A plugin host process dying is contained: contributions are already// deregistered by the runtime, we only have to tell the user and the UI.- onPluginCrash: ({ pluginId, exitCode }) => {+ onPluginCrash: ({ pluginId, exitCode, lastOutput }) => {logger.app("plugin", "error", "plugin host process crashed", {pluginId,code: "PLUGIN_CRASHED",- data: { exitCode },+ data: { exitCode, ...(lastOutput ? { lastOutput } : {}) },});// No toast here: the runtime already raised one through `showToast` on the// same code path, and a second identical message reads as two failures.diff --git a/apps/desktop/test/plugin-services.test.mjs b/apps/desktop/test/plugin-services.test.mjsindex c43dffc72..c2a12a634 100644--- a/apps/desktop/test/plugin-services.test.mjs+++ b/apps/desktop/test/plugin-services.test.mjs@@ -33,6 +33,12 @@ function forkPluginProcess({ entry }) {},onMessage: (handler) => child.on("message", handler),onExit: (handler) => child.on("exit", (code) => handler(code ?? 0)),+ // Mirrors the real spawner: the plugin's own stdout/stderr is what a crash+ // report has to be able to quote.+ onLog: (handler) => {+ child.stdout?.on("data", (chunk) => handler("info", String(chunk).trimEnd()));+ child.stderr?.on("data", (chunk) => handler("error", String(chunk).trimEnd()));+ },kill: () => child.kill(),};}@@ -321,7 +327,15 @@ test("a crashed host process is restarted with backoff and the restart is counteid: "worker",start: async () => {// Die once, right after the broker was told the service is up.- if (countStart() === 1) setTimeout(() => process.exit(7), 30);+ // Die once, right after the broker was told the service is up.+ // The line on stderr is the fixture's own "last words", which the+ // crash report has to carry (issue #747).+ if (countStart() === 1) {+ setTimeout(() => {+ process.stderr.write("fixture service worker died\\n");+ process.exit(7);+ }, 30);+ }},});},@@ -334,7 +348,14 @@ test("a crashed host process is restarted with backoff and the restart is counteconst failed = await waitFor(() =>runtime.getServiceStates().find((s) => s.state === "failed"),);- assert.equal(failed.message, "plugin host process exited");+ // The exit code is the diagnosis: without it a report says only "it died".+ assert.equal(failed.message, "plugin host process exited (exit code 7)");++ const crash = await waitFor(() =>+ audits.find((a) => a.api === "plugin.crash"),+ );+ assert.equal(crash.exitCode, 7);+ assert.equal(crash.message, "error: fixture service worker died");const scheduled = await waitFor(() =>audits.find((a) => a.api === "plugin.service.restart.scheduled"),diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.mdindex 97391bece..1f9a9f6b7 100644--- a/docs/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/spec/06-delivery/04-e2e-test-plan.md@@ -7957,6 +7957,8 @@ identify the platform validation still needed.| C — Conversation & stream (delegate context budget) | E2E-SUBAGENT-context-overflow-compacts-before-failing, E2E-SUBAGENT-context-overflow-reports-actionable-failure, E2E-SUBAGENT-resume-seeds-within-context-budget || Quality (delegate context budget) | E2E-SUBAGENT-context-overflow-compacts-before-failing, E2E-SUBAGENT-context-overflow-reports-actionable-failure, E2E-SUBAGENT-resume-seeds-within-context-budget || M6+ (delegate context budget) | E2E-SUBAGENT-context-overflow-compacts-before-failing, E2E-SUBAGENT-context-overflow-reports-actionable-failure, E2E-SUBAGENT-resume-seeds-within-context-budget |+| G — Plugin host lifecycle (crash report) | E2E-PLUGIN-crash-report-names-the-exit-code |+| Quality (crash report) | E2E-PLUGIN-crash-report-names-the-exit-code |The `US-UI-*` visual scenarios (§UI shell visual scenarios) trace to theCodex parity decisions in [decisions-log §D](../08-meta/decisions-log.md)@@ -14020,6 +14022,31 @@ the latest destination. These assertions measure work counts, not device FPS.default.- **Status:** Contract-covered; no end-to-end driver waits out a real 70s call.+### E2E-PLUGIN-crash-report-names-the-exit-code++- **Preconditions:** A loaded plugin whose host process dies on its own —+ `process.exit(7)` after writing one line to stderr is the fixture — with a+ resident service so the supervisor path is exercised too. Isolated desktop+ profile; no marketplace or network access.+- **Steps:** Load the plugin and let the host process die. Read the load error,+ the `failed` service state, the `plugin.crash` audit record and the `plugin`+ log channel. Repeat with a hard fault (a Windows `0xC0000005`-class exit) if+ one is available, and then quit the app while a plugin host is alive.+- **Expected:** Every one of those surfaces names the exit code (`exit code 7`,+ and `exit code 3221225477 (0xC0000005)` for the fault), and the newest plugin+ output line travels with the load error and the audit record. A clean quit+ reports no crash at all: quitting is a shutdown, not a crash.+- **Specs:** `07-plugins/05-plugin-lifecycle.md` §3.1 / §8,+ `08-meta/decisions-log.md` D607.+- **Acceptance:** G (plugin host lifecycle), Quality (diagnosability).+- **Milestone:** Post-MVP regression coverage.+- **Automation:** `apps/desktop/test/plugin-services.test.mjs` forks a real host+ process, kills it with a fixture exit code and asserts the code and the stderr+ line on the service state and the audit record; `plugin-isolation.test.mjs`+ and the shutdown cases cover the "quit is not a crash" half.+- **Status:** Automated at the runtime level; no UI driver reads the plugin+ page's error text.+### E2E-DIALOG-long-text-boundaries- **Preconditions:** Built renderer assets and an isolated Electron componentdiff --git a/docs/spec/07-plugins/05-plugin-lifecycle.md b/docs/spec/07-plugins/05-plugin-lifecycle.mdindex 52da0fe4c..6af97d00a 100644--- a/docs/spec/07-plugins/05-plugin-lifecycle.md+++ b/docs/spec/07-plugins/05-plugin-lifecycle.md@@ -103,6 +103,17 @@ marked is reported as a crash, which means an error log, a "stoppedunexpectedly" toast, and a supervisor scheduling restarts into an app that isclosing. None of that may happen on a clean quit.+**A crash report carries the diagnosis.** The crash path reports the host+process's exit code and its newest output line, because that is the only+evidence a user can quote in a bug report: on Windows a hard fault+(`0xC0000005` and friends, which Electron hands over as a negative signed int)+and a plugin's own `process.exit(1)` are different bugs, and a plugin that died+on a thrown error usually printed the reason first. The exit code reaches the+load error, the `failed` service state, the `plugin.crash` audit record and the+`plugin` log channel; the newest output line (the last three are kept, each+bounded) rides with the error and the audit record. Nothing new is persisted,+and no new permission or API surface is involved.+The sequence is bounded — `onUnload` gets 1.5s per plugin and teardown 3s intotal, after which the children are killed outright. A plugin's cleanup mustnever be the reason the app appears to hang on quit.@@ -190,7 +201,8 @@ Fields:- source (`installed` | `dev` | `marketplace`)- ts- errorCode?-- attempt? / delayMs? (service restarts)+ - attempt? / delayMs? (service restarts)+ - exitCode? (crash), message? (the plugin's newest output line)## 9. Uninstall strategydiff --git a/docs/spec/08-meta/decisions-log.md b/docs/spec/08-meta/decisions-log.mdindex 586981d85..35f4f1a49 100644--- a/docs/spec/08-meta/decisions-log.md+++ b/docs/spec/08-meta/decisions-log.md@@ -6470,3 +6470,21 @@ that was sitting at the bottom — including after the turn had finished.- Renderer CSS and the theme surface regression change only. There is no scrollstate, protocol, persistence, theme schema, or permission change. See`04-ux/08-component-spec.md` and E2E-CHAT-opaque-floating-decision-and-retry-surfaces.++## 2026-09-21 — A plugin crash reports its exit code and its last words (D607, issue #747)++- The host-process crash path reported only the plugin id, so a report read+ `plugin host process exited: <id>` and carried nothing else — the reporter in+ issue #747 had exactly that sentence and no way to say more. The exit code it+ already had is now part of the message, the `failed` service state, the+ `plugin.crash` audit record and the `plugin` log channel; on Windows a hard+ fault (`0xC0000005` and friends, delivered as a negative signed int, printed+ alongside its unsigned hex form) and a plugin's own `process.exit(1)` are+ different bugs and this is the only field that tells them apart.+- The plugin's newest output line rides with it. The runtime keeps the last+ three stdout/stderr lines per plugin, each bounded, and quotes the newest in+ the load error and the audit record (`message`), because a plugin that died on+ a thrown error usually printed the reason first. Nothing new is persisted and+ no permission or API surface changes; the audit thread already recorded every+ line as `plugin.stdio`.+- See `07-plugins/05-plugin-lifecycle.md` §3.1.diff --git a/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md b/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.mdindex 5ef8346c6..94a4a91e0 100644--- a/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md@@ -5269,6 +5269,8 @@ IPC 请求无法关闭。| C — 对话和直播(委托上下文预算) | E2E-SUBAGENT-context-overflow-compacts-before-failing、E2E-SUBAGENT-context-overflow-reports-actionable-failure、E2E-SUBAGENT-resume-seeds-within-context-budget || 品质(委托上下文预算) | E2E-SUBAGENT-context-overflow-compacts-before-failing、E2E-SUBAGENT-context-overflow-reports-actionable-failure、E2E-SUBAGENT-resume-seeds-within-context-budget || M6+(委托上下文预算) | E2E-SUBAGENT-context-overflow-compacts-before-failing、E2E-SUBAGENT-context-overflow-reports-actionable-failure、E2E-SUBAGENT-resume-seeds-within-context-budget |+| G — 插件宿主生命周期(崩溃上报) | E2E-PLUGIN-crash-report-names-the-exit-code |+| 品质(崩溃上报) | E2E-PLUGIN-crash-report-names-the-exit-code |`US-UI-*` 视觉场景(§UI shell 视觉场景)追踪到[决策日志 §D](/zh-CN/spec/08-meta/decisions-log) 中的法典平价决策@@ -8333,3 +8335,17 @@ the latest destination. These assertions measure work counts, not device FPS.- **Milestone**: Maintenance.- **Status**: Covered by the existing HTTP client integration fixture and afocused component-render validation; no live IDA process required.++### E2E-PLUGIN-crash-report-names-the-exit-code++- **先决条件:** 已加载的插件宿主进程自行死亡——夹具为写一行 stderr 后 `process.exit(7)`——并带一个常驻服务,使监督器路径也被覆盖。+ 隔离的桌面配置;不访问市场或网络。+- **步骤:** 加载插件并让宿主进程死亡。读取加载错误、`failed` 服务状态、`plugin.crash` 审计记录与 `plugin` 日志通道。若有条件,+ 再用一次硬故障(Windows `0xC0000005` 一类退出)重复;最后在插件宿主存活时退出应用。+- **预期:** 上述每一处都给出退出码(`exit code 7`;硬故障为 `exit code 3221225477 (0xC0000005)`),且插件最新一行输出随加载错误与+ 审计记录一同出现。干净退出完全不上报崩溃:退出是关闭而不是崩溃。+- **规格:** 07-plugins/05-plugin-lifecycle §3.1 / §8、08-meta/decisions-log D607。+- **验收:** G(插件宿主生命周期)、品质(可诊断性)。**里程碑:** Post-MVP 回归覆盖。+- **自动化:** `apps/desktop/test/plugin-services.test.mjs` 真实 fork 宿主进程、以夹具退出码杀死它,并断言服务状态与审计记录上的+ 退出码与 stderr 行;`plugin-isolation.test.mjs` 与关闭用例覆盖"退出不是崩溃"那一半。+- **状态:** 运行时层已自动化;无 UI 驱动读取插件页的错误文本。diff --git a/docs/zh-CN/spec/07-plugins/05-plugin-lifecycle.md b/docs/zh-CN/spec/07-plugins/05-plugin-lifecycle.mdindex 672d74e8e..8973c52bd 100644--- a/docs/zh-CN/spec/07-plugins/05-plugin-lifecycle.md+++ b/docs/zh-CN/spec/07-plugins/05-plugin-lifecycle.md@@ -104,6 +104,12 @@ discovered是一条错误日志、一个"意外停止"提示,以及主管把重启排进一个正在关闭的应用。干净退出时这些都不允许发生。+**崩溃上报必须带上诊断。** 崩溃路径会报出宿主进程的**退出码**与它**最新的一行输出**——这是用户唯一能在报障里引用的证据:+Windows 上的硬故障(`0xC0000005` 一类,Electron 以负的有符号整数交付)与插件自己调用 `process.exit(1)` 是两类完全不同的+问题,而因抛错而死的插件通常已经把原因打印出来了。退出码会出现在加载错误、`failed` 服务状态、`plugin.crash` 审计记录与+`plugin` 日志通道里;最新一行输出(只保留最近三行,每行有长度上限)随错误与审计记录一起走。不新增任何持久化,也不涉及+新的权限或 API 面。+整个过程是有界的——每个插件的 `onUnload` 有 1.5s,整体拆除有 3s,超时后直接杀掉子进程。插件的清理绝不能成为应用退出时看起来卡住的原因。@@ -191,6 +197,7 @@ rollback all registrations from this plugin- TS- 错误代码?- 尝试? / 延迟女士? (服务重新启动)+- exitCode?(崩溃)、message?(插件最新一行输出)## 9. 卸载策略diff --git a/docs/zh-CN/spec/08-meta/decisions-log.md b/docs/zh-CN/spec/08-meta/decisions-log.mdindex ef92c7d46..6fabf46c5 100644--- a/docs/zh-CN/spec/08-meta/decisions-log.md+++ b/docs/zh-CN/spec/08-meta/decisions-log.md@@ -4599,3 +4599,14 @@ that amendment are retired by ADR 0268; the upstream work-panel lifecycle stays.- 仅改动渲染器 CSS 与主题表面回归测试;不改变滚动状态、协议、持久化、主题 schema或权限。见 `04-ux/08-component-spec.md` 与E2E-CHAT-opaque-floating-decision-and-retry-surfaces。++## 2026-09-21 —— 插件崩溃上报带上退出码与最后一行输出(D607,issue #747)++- 宿主进程崩溃路径此前只报插件 id,于是报障里只有 `plugin host process exited: <id>` 一句话——issue #747 的报告者手里+ 就是这么一句。现在运行时代码本来就已经拿到的**退出码**会出现在消息、`failed` 服务状态、`plugin.crash` 审计记录与+ `plugin` 日志通道里;Windows 上的硬故障(`0xC0000005` 一类,以负的有符号整数交付,同时打印其无符号十六进制形式)与+ 插件自己调用 `process.exit(1)` 是两类不同的问题,而这个字段是唯一能区分它们的。+- 插件**最新一行输出**随之一同上报:运行时按插件保留最近三行 stdout/stderr(每行有长度上限),并把最新一行引用进+ 加载错误与审计记录(`message`)——因抛错而死的插件通常先打印了原因。不新增任何持久化,权限与 API 面不变;+ 每行原本已作为 `plugin.stdio` 进入审计流。+- 见 `07-plugins/05-plugin-lifecycle.md` §3.1。