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(landing): harden plugin crashes and provider retries
vastsa9d39e7d6298e
diff --git a/apps/desktop/electron/main/plugin-runtime.ts b/apps/desktop/electron/main/plugin-runtime.tsindex 43e64bb87..b29694153 100644--- a/apps/desktop/electron/main/plugin-runtime.ts+++ b/apps/desktop/electron/main/plugin-runtime.ts@@ -391,8 +391,6 @@ export type PluginHostServices = {exitCode: number;/** Hex form for Windows hard-fault codes, when applicable. */exitCodeHex?: string;- /** 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;@@ -633,14 +631,6 @@ 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 };-/** Convert Electron's signed Windows status into the process's unsigned code. */function childExitUnsigned(code: number): number {if (!Number.isFinite(code)) return code;@@ -669,59 +659,6 @@ function childExitLabel(code: number): string {return `exit code ${unsigned}${hex ? ` (${hex})` : ""}`;}-function rememberPluginLogLine(- tail: PluginLogLine[],- level: string,- message: string,-): void {- if (!message.trim()) return;- tail.push({ level, message: message.slice(0, PLUGIN_LOG_TAIL_LINE_CHARS) });- if (tail.length > PLUGIN_LOG_TAIL_LINES) tail.shift();-}--/** Append arbitrary stream chunks while retaining complete logical lines. */-function appendPluginLogChunk(- tail: PluginLogLine[],- fragments: Map<string, string>,- level: string,- chunk: string,-): void {- const normalized = `${fragments.get(level) ?? ""}${chunk}`.replace(/\r\n?/g, "\n");- const lines = normalized.split("\n");- fragments.set(level, lines.pop() ?? "");- for (const line of lines) rememberPluginLogLine(tail, level, line);-}--/** Include a final unterminated line before a crash report snapshots the tail. */-function flushPluginLogTail(- tail: PluginLogLine[],- fragments: Map<string, string>,-): void {- for (const [level, fragment] of fragments) {- rememberPluginLogLine(tail, level, fragment);- }- fragments.clear();-}--/** 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. */@@ -780,10 +717,6 @@ type LoadedPlugin = {pending: Map<string, PendingCall>;nextCallId: number;disposing: boolean;- /** Newest host-process output lines, so a crash report can quote them. */- logTail: PluginLogLine[];- /** Unterminated stdout/stderr fragments waiting for their newline. */- logFragments: Map<string, string>;};type PluginApiError = Error & { code?: string };@@ -1803,8 +1736,6 @@ export class PluginRuntime {pending: new Map(),nextCallId: 1,disposing: false,- logTail: [],- logFragments: new Map(),};this.loaded.set(manifest.id, loaded);@@ -1812,9 +1743,6 @@ export class PluginRuntime {child.onExit((code) => this.handleChildExit(loaded, code));child.onLog?.((level, message) => {if (!message) return;- // Stream data events are arbitrary chunks, not logical lines. Keep the- // audit shape unchanged, but only put complete lines in the crash tail.- appendPluginLogChunk(loaded.logTail, loaded.logFragments, level, message);this.services.audit?.({pluginId: manifest.id,api: "plugin.stdio",@@ -2827,15 +2755,11 @@ export class PluginRuntime {if (loaded.disposing) return;if (this.loaded.get(loaded.manifest.id) !== loaded) return;const pluginId = loaded.manifest.id;- // 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.- flushPluginLogTail(loaded.logTail, loaded.logFragments);- const detail = childExitDetail(code, loaded.logTail);- const lastOutput = lastLogLine(loaded.logTail);+ // The exit code is the diagnosis for a crash report: a Windows hard fault+ // (0xC0000005 and friends) and a plugin's own process.exit(1) are different+ // bugs. Do not copy plugin stdout/stderr into user-visible errors or crash+ // audit records because plugin output may contain workspace data or secrets.+ const detail = childExitLabel(code);const exitCode = childExitUnsigned(code);const exitCodeHex = childExitHex(code);this.rejectPending(@@ -2855,7 +2779,6 @@ export class PluginRuntime {errorCode: "PLUGIN_CRASHED",exitCode,...(exitCodeHex ? { exitCodeHex } : {}),- ...(lastOutput ? { message: lastOutput } : {}),ts: Date.now(),});this.services.showToast(`Plugin stopped unexpectedly: ${loaded.manifest.name}`, "error");@@ -2864,7 +2787,6 @@ export class PluginRuntime {name: loaded.manifest.name,exitCode,...(exitCodeHex ? { exitCodeHex } : {}),- ...(lastOutput ? { lastOutput } : {}),});this.superviseCrash(loaded, code);}diff --git a/apps/desktop/electron/main/services/plugin-services.ts b/apps/desktop/electron/main/services/plugin-services.tsindex 4cfdadf2f..376dad792 100644--- a/apps/desktop/electron/main/services/plugin-services.ts+++ b/apps/desktop/electron/main/services/plugin-services.ts@@ -411,14 +411,13 @@ 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, exitCodeHex, lastOutput }) => {+ onPluginCrash: ({ pluginId, exitCode, exitCodeHex }) => {logger.app("plugin", "error", "plugin host process crashed", {pluginId,code: "PLUGIN_CRASHED",data: {exitCode,...(exitCodeHex ? { exitCodeHex } : {}),- ...(lastOutput ? { lastOutput } : {}),},});// No toast here: the runtime already raised one through `showToast` on thediff --git a/apps/desktop/test/plugin-services.test.mjs b/apps/desktop/test/plugin-services.test.mjsindex 02a206354..2a47798ed 100644--- a/apps/desktop/test/plugin-services.test.mjs+++ b/apps/desktop/test/plugin-services.test.mjs@@ -33,12 +33,6 @@ 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(),};}@@ -344,9 +338,6 @@ 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.- // 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 older line\\nfixture service worker died");@@ -365,14 +356,15 @@ test("a crashed host process is restarted with backoff and the restart is counteconst failed = await waitFor(() =>runtime.getServiceStates().find((s) => s.state === "failed"),);- // The exit code is the diagnosis: without it a report says only "it died".+ // The exit code is the safe diagnosis: plugin output is not copied into+ // user-visible errors or crash audit records.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");+ assert.equal("message" in crash, false);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 b876d7279..010f2ee41 100644--- a/docs/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/spec/06-delivery/04-e2e-test-plan.md@@ -14067,16 +14067,16 @@ the latest destination. These assertions measure work counts, not device FPS.log channel. Repeat with a hard fault (a Windows `0xC0000005`-class exit) ifone 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+ and `exit code 3221225477 (0xC0000005)` for the fault), while the fixture's+ stderr line is absent from the load error and crash audit record. A clean quitreports 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`+ process, kills it with a fixture exit code and asserts the code plus the+ absence of raw stderr in the crash 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 pluginpage's error text.diff --git a/docs/spec/07-plugins/05-plugin-lifecycle.md b/docs/spec/07-plugins/05-plugin-lifecycle.mdindex 1b3262dab..e447388a0 100644--- a/docs/spec/07-plugins/05-plugin-lifecycle.md+++ b/docs/spec/07-plugins/05-plugin-lifecycle.md@@ -104,15 +104,13 @@ unexpectedly" 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.+process's exit code because 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. The exit code reaches the load error, the+`failed` service state, the `plugin.crash` audit record and the `plugin` log+channel. Plugin stdout/stderr is not copied into the crash report because it+may contain workspace data or secrets. 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 must@@ -202,7 +200,7 @@ Fields:- ts- errorCode?- attempt? / delayMs? (service restarts)-- exitCode? (crash), exitCodeHex? (Windows hard fault), message? (the plugin's newest output line)+- exitCode? (crash), exitCodeHex? (Windows hard fault)## 9. Uninstall strategydiff --git a/docs/spec/08-meta/decisions-log.md b/docs/spec/08-meta/decisions-log.mdindex 35f4f1a49..6886755f6 100644--- a/docs/spec/08-meta/decisions-log.md+++ b/docs/spec/08-meta/decisions-log.md@@ -6471,7 +6471,7 @@ that was sitting at the bottom — including after the turn had finished.state, 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)+## 2026-09-21 — A plugin crash reports its exit code without copying raw output (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@@ -6481,10 +6481,8 @@ that was sitting at the bottom — including after the turn had finished.fault (`0xC0000005` and friends, delivered as a negative signed int, printedalongside its unsigned hex form) and a plugin's own `process.exit(1)` aredifferent 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`.+- Plugin stdout/stderr is not copied into the load error, crash audit record, or+ crash log payload because it may contain workspace data or secrets. Nothing+ new is persisted and no permission or API surface changes; the existing+ `plugin.stdio` audit stream is otherwise unchanged.- 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 67ee5ce66..767aaba18 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@@ -8358,10 +8358,10 @@ the latest destination. These assertions measure work counts, not device FPS.隔离的桌面配置;不访问市场或网络。- **步骤:** 加载插件并让宿主进程死亡。读取加载错误、`failed` 服务状态、`plugin.crash` 审计记录与 `plugin` 日志通道。若有条件,再用一次硬故障(Windows `0xC0000005` 一类退出)重复;最后在插件宿主存活时退出应用。-- **预期:** 上述每一处都给出退出码(`exit code 7`;硬故障为 `exit code 3221225477 (0xC0000005)`),且插件最新一行输出随加载错误与- 审计记录一同出现。干净退出完全不上报崩溃:退出是关闭而不是崩溃。+- **预期:** 上述每一处都给出退出码(`exit code 7`;硬故障为 `exit code 3221225477 (0xC0000005)`),而夹具的 stderr 行不会出现在+ 加载错误或崩溃审计记录中。干净退出完全不上报崩溃:退出是关闭而不是崩溃。- **规格:** 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` 与关闭用例覆盖"退出不是崩溃"那一半。+ 退出码及原始 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 fec1759a4..78cc96dd1 100644--- a/docs/zh-CN/spec/07-plugins/05-plugin-lifecycle.md+++ b/docs/zh-CN/spec/07-plugins/05-plugin-lifecycle.md@@ -104,10 +104,9 @@ discovered是一条错误日志、一个"意外停止"提示,以及主管把重启排进一个正在关闭的应用。干净退出时这些都不允许发生。-**崩溃上报必须带上诊断。** 崩溃路径会报出宿主进程的**退出码**与它**最新的一行输出**——这是用户唯一能在报障里引用的证据:-Windows 上的硬故障(`0xC0000005` 一类,Electron 以负的有符号整数交付)与插件自己调用 `process.exit(1)` 是两类完全不同的-问题,而因抛错而死的插件通常已经把原因打印出来了。退出码会出现在加载错误、`failed` 服务状态、`plugin.crash` 审计记录与-`plugin` 日志通道里;最新一行输出(只保留最近三行,每行有长度上限)随错误与审计记录一起走。不新增任何持久化,也不涉及+**崩溃上报必须带上诊断。** 崩溃路径会报出宿主进程的**退出码**:Windows 上的硬故障(`0xC0000005` 一类,Electron 以负的有+符号整数交付)与插件自己调用 `process.exit(1)` 是两类完全不同的问题。退出码会出现在加载错误、`failed` 服务状态、`plugin.crash`+审计记录与 `plugin` 日志通道里。插件 stdout/stderr 可能包含工作区数据或敏感信息,因此不会复制进崩溃上报。不新增任何持久化,也不涉及新的权限或 API 面。整个过程是有界的——每个插件的 `onUnload` 有 1.5s,整体拆除有 3s,超时后直接@@ -197,7 +196,7 @@ rollback all registrations from this plugin- TS- 错误代码?- 尝试? / 延迟女士? (服务重新启动)-- exitCode?(崩溃)、exitCodeHex?(Windows 硬故障)、message?(插件最新一行输出)+- exitCode?(崩溃)、exitCodeHex?(Windows 硬故障)## 9. 卸载策略diff --git a/docs/zh-CN/spec/08-meta/decisions-log.md b/docs/zh-CN/spec/08-meta/decisions-log.mdindex 6fabf46c5..0244a9617 100644--- a/docs/zh-CN/spec/08-meta/decisions-log.md+++ b/docs/zh-CN/spec/08-meta/decisions-log.md@@ -4600,13 +4600,12 @@ that amendment are retired by ADR 0268; the upstream work-panel lifecycle stays.或权限。见 `04-ux/08-component-spec.md` 与E2E-CHAT-opaque-floating-decision-and-retry-surfaces。-## 2026-09-21 —— 插件崩溃上报带上退出码与最后一行输出(D607,issue #747)+## 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` 进入审计流。+- 插件 stdout/stderr 不复制进加载错误、崩溃审计记录或崩溃日志负载,因为其中可能包含工作区数据或敏感信息。不新增任何持久化,权限与 API 面不变;+ 既有的 `plugin.stdio` 审计流保持不变。- 见 `07-plugins/05-plugin-lifecycle.md` §3.1。diff --git a/packages/agent-runtime/src/runtime.ts b/packages/agent-runtime/src/runtime.tsindex a8aaa2729..60f6a8014 100644--- a/packages/agent-runtime/src/runtime.ts+++ b/packages/agent-runtime/src/runtime.ts@@ -5511,7 +5511,10 @@ Delegation rules:if (messages.at(-1)?.role !== "assistant") {throw new Error("Cannot retry a provider stream without its failed assistant message");}- messages.pop();+ // A failed stream can be represented by more than one trailing assistant+ // message after a tool round. Remove the whole failed suffix before+ // continuing; pi-agent-core rejects any assistant-terminated transcript.+ while (messages.at(-1)?.role === "assistant") messages.pop();this.setAgentMessages(messages);this.providerRetryInProgress = true;