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): break renderer crash loops with a GPU-fallback relaunch
liuzixiangbe3effd8cf2a
diff --git a/apps/desktop/electron/main/bootstrap/window.ts b/apps/desktop/electron/main/bootstrap/window.tsindex ee293303e..8c41e0cff 100644--- a/apps/desktop/electron/main/bootstrap/window.ts+++ b/apps/desktop/electron/main/bootstrap/window.ts@@ -1,8 +1,15 @@-import { app, BrowserWindow, nativeTheme, screen, type Tray } from "electron";+import { app, BrowserWindow, dialog, nativeTheme, screen, shell, type Tray } from "electron";import { execFileSync } from "node:child_process";-import { existsSync } from "node:fs";+import { existsSync, mkdirSync } from "node:fs";import { join } from "node:path";+import { catalogs, resolveLocale } from "@pi-desktop/i18n";import { getModuleDirectory } from "../module-path";+import {+ clearGpuFallbackMarker,+ hasGpuFallbackMarker,+ writeGpuFallbackMarker,+} from "../renderer-crash-loop";+import { noteRendererLoaded } from "../renderer-recovery";import {APP_NAME,builtinWindowBackground,@@ -590,6 +597,48 @@ export async function createWindow({windowState.notificationViewingSessionId = null;if (windowState.mainWindow === window) resetMenuRendererReady(window);});+ // A renderer that crashes before it ever finishes loading makes every+ // reload futile: trip the breaker, spend this install's one GPU-fallback+ // relaunch, and only talk to the user if even that did not help (#2595).+ const showRendererCrashLoopDialog = async (): Promise<void> => {+ const labels = catalogs[resolveLocale(app.getLocale())];+ const { response } = await dialog.showMessageBox({+ type: "error",+ title: labels.rendererCrash.title,+ message: labels.rendererCrash.body,+ buttons: [labels.rendererCrash.openLogs, labels.tray.quit],+ defaultId: 0,+ cancelId: 1,+ noLink: true,+ });+ if (response !== 0) {+ app.quit();+ return;+ }+ const logs = join(dataDir, "logs");+ mkdirSync(logs, { recursive: true });+ await shell.openPath(logs);+ };+ const handleRendererCrashLoop = (): void => {+ if (!hasGpuFallbackMarker(dataDir)) {+ writeGpuFallbackMarker(dataDir);+ logger.app("diagnostics", "warn", "renderer crash loop detected; relaunching without GPU acceleration", {+ event: "rendererCrashLoop",+ data: { action: "relaunch-disable-gpu" },+ });+ const args = process.argv.slice(1);+ app.relaunch({+ args: args.includes("--disable-gpu") ? args : [...args, "--disable-gpu"],+ });+ app.exit(0);+ return;+ }+ logger.app("diagnostics", "warn", "renderer crash loop persists without GPU acceleration; stopping automatic reloads", {+ event: "rendererCrashLoop",+ data: { action: "dialog" },+ });+ void showRendererCrashLoopDialog();+ };window.webContents.on("render-process-gone", (_event, details) => {windowState.notificationViewingSessionId = null;recoverRendererAfterGone(details, {@@ -599,6 +648,7 @@ export async function createWindow({windowDestroyed: window.isDestroyed(),webContentsDestroyed: window.webContents.isDestroyed(),reload: () => window.webContents.reload(),+ onCrashLoopDetected: handleRendererCrashLoop,log: (rendererDetails, reloaded) => {logger.app("diagnostics",@@ -679,6 +729,12 @@ export async function createWindow({scheduleWorkPanelReservation();});window.webContents.on("did-finish-load", sendFullScreen);+ window.webContents.on("did-finish-load", () => {+ noteRendererLoaded();+ // A session that stays up cleared the crash streak; give the machine its+ // normal GPU path back on a later boot once the run looks stable.+ setTimeout(() => clearGpuFallbackMarker(dataDir), 10 * 60_000);+ });const sendMaximized = () => {if (window.isDestroyed() || window.webContents.isDestroyed()) return;diff --git a/apps/desktop/electron/main/index.ts b/apps/desktop/electron/main/index.tsindex 7a42e2cef..387c5f0df 100644--- a/apps/desktop/electron/main/index.ts+++ b/apps/desktop/electron/main/index.ts@@ -1,4 +1,5 @@import { createBackgroundContinuationCoordinator } from "./runtime/background-continuations";+import { hasGpuFallbackMarker } from "./renderer-crash-loop";import {app,BrowserWindow,@@ -186,6 +187,11 @@ const dataDir = storage.preferences.roots.data;// it as a parameter, and a profile split across two directories is the// divergence D236 closes.process.env.PI_DESKTOP_DATA_DIR = dataDir;+// A spent GPU-fallback marker (#2595) also guards manual launches: crash+// loops start before any window exists, and this must run before ready.+if (hasGpuFallbackMarker(dataDir)) {+ app.disableHardwareAcceleration();+}// Agent extensions (D387/D388, ADR 0214): plugins contribute the modules,// the sidecar loads them; this bridge carries commands, diagnostics, anddiff --git a/apps/desktop/electron/main/renderer-crash-loop.ts b/apps/desktop/electron/main/renderer-crash-loop.tsnew file mode 100644index 000000000..1af98783d--- /dev/null+++ b/apps/desktop/electron/main/renderer-crash-loop.ts@@ -0,0 +1,50 @@+import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import { join } from "node:path";++/**+ * Crash-loop breaker marker (issue #2595): a renderer that crashes+ * deterministically at startup turns the automatic recovery reload into an+ * infinite loop — the window never finishes loading, so the user sees a+ * black screen and a flashing taskbar icon forever. The first trip+ * relaunches once with `--disable-gpu` (the classic GPU-corruption+ * mitigation; a plain reinstall never clears the cached GPU state in+ * userData). The marker records that the fallback was already spent, so a+ * loop that survives it surfaces a dialog instead of relaunching forever.+ *+ * Boot reads the marker to start without hardware acceleration, so manual+ * launches are safe too; a run that stays loaded clears it again, so a+ * machine whose driver was fixed (or whose corruption was transient) goes+ * back to normal on a later boot.+ */++export function gpuFallbackMarkerPath(dataDir: string): string {+ return join(dataDir, "renderer-crash-loop.json");+}++/** Whether this install already spent its one GPU-fallback relaunch. */+export function hasGpuFallbackMarker(dataDir: string): boolean {+ const path = gpuFallbackMarkerPath(dataDir);+ if (!existsSync(path)) return false;+ try {+ const parsed = JSON.parse(readFileSync(path, "utf8")) as { gpuFallbackAt?: unknown };+ return typeof parsed.gpuFallbackAt === "string";+ } catch {+ // A corrupt marker still means "the fallback was spent"; rewrite it.+ writeGpuFallbackMarker(dataDir);+ return true;+ }+}++export function writeGpuFallbackMarker(dataDir: string): void {+ const path = gpuFallbackMarkerPath(dataDir);+ mkdirSync(join(dataDir), { recursive: true });+ writeFileSync(path, JSON.stringify({ gpuFallbackAt: new Date().toISOString() }), "utf8");+}++export function clearGpuFallbackMarker(dataDir: string): void {+ try {+ rmSync(gpuFallbackMarkerPath(dataDir), { force: true });+ } catch {+ // Best effort; a stale marker only costs one dialog instead of a relaunch.+ }+}diff --git a/apps/desktop/electron/main/renderer-recovery.ts b/apps/desktop/electron/main/renderer-recovery.tsindex b0b1a9dc5..4870a64ea 100644--- a/apps/desktop/electron/main/renderer-recovery.ts+++ b/apps/desktop/electron/main/renderer-recovery.ts@@ -11,6 +11,8 @@ export type RendererRecoveryDependencies = Readonly<{webContentsDestroyed: boolean;reload: () => void;log: (details: RendererGoneDetails, reloaded: boolean) => void;+ /** Fired once when consecutive startup crashes trip the breaker (#2595). */+ onCrashLoopDetected?: () => void;}>;/**@@ -20,15 +22,35 @@ export type RendererRecoveryDependencies = Readonly<{*/const CRASH_COOLDOWN_MS = 2_000;+/**+ * Consecutive crashes without a single successful load before recovery+ * gives up on reloading: a renderer that dies deterministically at startup+ * (GPU driver or cache corruption, issue #2595) makes every reload futile,+ * and the 2s cooldown alone just turns the crash into a visible infinite+ * loop. The caller decides what a trip means (GPU-fallback relaunch, then+ * a dialog); the counter resets on every successful load.+ */+const CRASH_LOOP_THRESHOLD = 5;+/** Tracks the last reload timestamp per recovery call site. */let lastReloadTimestamp = 0;+let consecutiveCrashesWithoutLoad = 0;+let crashLoopReported = false;+/*** Reset internal cooldown state. Exposed exclusively for deterministic tests;* production code must never call this.*/export function _resetCooldownForTest(): void {lastReloadTimestamp = 0;+ consecutiveCrashesWithoutLoad = 0;+ crashLoopReported = false;+}++/** A renderer finished loading: the crash streak restarts from zero. */+export function noteRendererLoaded(): void {+ consecutiveCrashesWithoutLoad = 0;}/** Reload an unexpectedly exited renderer while its owning app window is live. */@@ -44,8 +66,22 @@ export function recoverRendererAfterGone(!dependencies.windowDestroyed &&!dependencies.webContentsDestroyed;- dependencies.log(details, shouldReload);- if (!shouldReload) return false;+ if (!shouldReload) {+ dependencies.log(details, false);+ return false;+ }++ consecutiveCrashesWithoutLoad += 1;+ const tripped =+ consecutiveCrashesWithoutLoad >= CRASH_LOOP_THRESHOLD && !crashLoopReported;+ if (tripped) crashLoopReported = true;+ // Once the breaker has tripped, keep logging every crash but stop+ // reloading: the caller's escalation owns recovery from here.+ const reloaded = !crashLoopReported;++ dependencies.log(details, reloaded);+ if (tripped) dependencies.onCrashLoopDetected?.();+ if (!reloaded) return false;const now = Date.now();const elapsed = now - lastReloadTimestamp;diff --git a/apps/desktop/test/renderer-recovery.test.mjs b/apps/desktop/test/renderer-recovery.test.mjsindex 58a2cf7f8..69c310654 100644--- a/apps/desktop/test/renderer-recovery.test.mjs+++ b/apps/desktop/test/renderer-recovery.test.mjs@@ -1,6 +1,10 @@import assert from "node:assert/strict";import { afterEach, describe, it, mock } from "node:test";-import { recoverRendererAfterGone, _resetCooldownForTest } from "../electron/main/renderer-recovery.ts";+import {+ recoverRendererAfterGone,+ noteRendererLoaded,+ _resetCooldownForTest,+} from "../electron/main/renderer-recovery.ts";function recovery(overrides = {}) {const calls = { reload: 0, logs: [] };@@ -106,4 +110,71 @@ describe("recoverRendererAfterGone", () => {assert.equal(recoverRendererAfterGone(details, second.dependencies), true);assert.equal(second.calls.reload, 1, "should reload immediately after cooldown");});++ it("consecutive startup crashes without a load trip the breaker once (#2595)", () => {+ mock.timers.enable({ apis: ["Date", "setTimeout"] });+ mock.timers.tick(10_000);++ const details = { reason: "crashed", exitCode: 1 };+ let trips = 0;+ const reloads = [];++ for (let i = 1; i <= 7; i += 1) {+ const attempt = recovery({+ onCrashLoopDetected: () => {+ trips += 1;+ },+ reload: () => reloads.push(i),+ });+ mock.timers.tick(3_000); // clear cooldown between attempts+ recoverRendererAfterGone(details, attempt.dependencies);+ }++ // Crashes 1-4 keep reloading; crash 5 trips the breaker and stops the+ // loop; 6-7 are logged but inert.+ assert.deepEqual(reloads, [1, 2, 3, 4]);+ assert.equal(trips, 1, "the escalation fires exactly once");+ });++ it("a successful load resets the crash streak, so scattered crashes never trip it", () => {+ mock.timers.enable({ apis: ["Date", "setTimeout"] });+ mock.timers.tick(10_000);++ const details = { reason: "crashed", exitCode: 1 };+ let trips = 0;++ for (let cycle = 0; cycle < 6; cycle += 1) {+ const attempt = recovery({+ onCrashLoopDetected: () => {+ trips += 1;+ },+ });+ mock.timers.tick(3_000);+ recoverRendererAfterGone(details, attempt.dependencies);+ // The renderer came back up between crashes.+ noteRendererLoaded();+ }++ assert.equal(trips, 0);+ });++ it("clean exits never count toward the breaker", () => {+ mock.timers.enable({ apis: ["Date", "setTimeout"] });+ mock.timers.tick(10_000);++ let trips = 0;+ for (let i = 0; i < 8; i += 1) {+ const attempt = recovery({+ onCrashLoopDetected: () => {+ trips += 1;+ },+ });+ mock.timers.tick(3_000);+ assert.equal(+ recoverRendererAfterGone({ reason: "clean-exit", exitCode: 0 }, attempt.dependencies),+ false,+ );+ }+ assert.equal(trips, 0);+ });});diff --git a/packages/i18n/src/locales/de/index.ts b/packages/i18n/src/locales/de/index.tsindex 417981a9a..ce075fef9 100644--- a/packages/i18n/src/locales/de/index.ts+++ b/packages/i18n/src/locales/de/index.ts@@ -3305,7 +3305,12 @@ sklm: {"continue": "Weiter","dismiss": "Verwerfen"}- }+ },+ rendererCrash: {+ title: "PI-Desktop konnte nicht starten",+ body: "Die Oberfläche stürzte beim Start wiederholt ab, daher wurden die automatischen Versuche gestoppt. Der Protokollordner enthält Details; falls das Problem bestehen bleibt, teile uns die Protokolle bitte mit.",+ openLogs: "Protokollordner öffnen",+ },} satisfies EnglishCatalog;export default de;diff --git a/packages/i18n/src/locales/en/index.ts b/packages/i18n/src/locales/en/index.tsindex ef1ac0a40..38e5ded6a 100644--- a/packages/i18n/src/locales/en/index.ts+++ b/packages/i18n/src/locales/en/index.ts@@ -3448,6 +3448,11 @@ importConfirm: "Imported extensions run inside the agent process with the same adismiss: "Dismiss",},},+ rendererCrash: {+ title: "PI-Desktop could not start",+ body: "The interface kept crashing on startup, so automatic retries were stopped. The log folder has the details; if this keeps happening, please share the logs with us.",+ openLogs: "Open log folder",+ },} as const;type DeepStringify<T> = {diff --git a/packages/i18n/src/locales/es/index.ts b/packages/i18n/src/locales/es/index.tsindex bb637eccb..80bb37732 100644--- a/packages/i18n/src/locales/es/index.ts+++ b/packages/i18n/src/locales/es/index.ts@@ -3303,7 +3303,12 @@ sklm: {"continue": "Continuar","dismiss": "Descartar"}- }+ },+ rendererCrash: {+ title: "PI-Desktop no pudo iniciarse",+ body: "La interfaz fallaba repetidamente al iniciarse, así que se detuvieron los reintentos automáticos. La carpeta de registros contiene los detalles; si el problema continúa, compártenos los registros.",+ openLogs: "Abrir carpeta de registros",+ },} satisfies EnglishCatalog;export default es;diff --git a/packages/i18n/src/locales/fr/index.ts b/packages/i18n/src/locales/fr/index.tsindex 5e35f7b6c..fc389d707 100644--- a/packages/i18n/src/locales/fr/index.ts+++ b/packages/i18n/src/locales/fr/index.ts@@ -3303,7 +3303,12 @@ sklm: {"continue": "Continuer","dismiss": "Ignorer"}- }+ },+ rendererCrash: {+ title: "PI-Desktop n'a pas pu démarrer",+ body: "L'interface plantait de façon répétée au démarrage : les tentatives automatiques ont été arrêtées. Le dossier des journaux contient les détails ; si le problème persiste, partagez-les avec nous.",+ openLogs: "Ouvrir le dossier des journaux",+ },} satisfies EnglishCatalog;export default fr;diff --git a/packages/i18n/src/locales/ko/index.ts b/packages/i18n/src/locales/ko/index.tsindex 572896ff0..19c1f8003 100644--- a/packages/i18n/src/locales/ko/index.ts+++ b/packages/i18n/src/locales/ko/index.ts@@ -3346,6 +3346,11 @@ importConfirm: "가져온 확장은 에이전트 프로세스 안에서 에이dismiss: "닫기",},},+ rendererCrash: {+ title: "PI-Desktop를 시작할 수 없습니다",+ body: "인터페이스가 시작 시 반복해서 충돌하여 자동 재시도를 중지했습니다. 자세한 내용은 로그 폴더에 있습니다. 문제가 계속되면 로그를 공유해 주세요.",+ openLogs: "로그 폴더 열기",+ },} satisfies EnglishCatalog;export default ko;diff --git a/packages/i18n/src/locales/pt-BR/index.ts b/packages/i18n/src/locales/pt-BR/index.tsindex 88ef2c335..19793894f 100644--- a/packages/i18n/src/locales/pt-BR/index.ts+++ b/packages/i18n/src/locales/pt-BR/index.ts@@ -3273,7 +3273,12 @@ export const ptBR = {continue: "Continuar",dismiss: "Dispensar"}- }+ },+ rendererCrash: {+ title: "O PI-Desktop não pôde ser iniciado",+ body: "A interface continuava falhando na inicialização, então as tentativas automáticas foram interrompidas. A pasta de registros tem os detalhes; se o problema persistir, compartilhe os registros conosco.",+ openLogs: "Abrir pasta de registros",+ },} satisfies EnglishCatalog;export default ptBR;diff --git a/packages/i18n/src/locales/tr/index.ts b/packages/i18n/src/locales/tr/index.tsindex ec98ffa74..ab8b17d2e 100644--- a/packages/i18n/src/locales/tr/index.ts+++ b/packages/i18n/src/locales/tr/index.ts@@ -3339,6 +3339,11 @@ importConfirm: "İçe aktarılan uzantılar ajan sürecinde, ajanın kendi araçdismiss: "Kapat",},},+ rendererCrash: {+ title: "PI-Desktop başlatılamadı",+ body: "Arayüz işlemi başlangıçta sürekli çöktüğü için otomatik yeniden denemeler durduruldu. Ayrıntılar günlük klasöründe; sorun sürerse lütfen günlükleri bizimle paylaşın.",+ openLogs: "Günlük klasörünü aç",+ },} satisfies EnglishCatalog;export default tr;diff --git a/packages/i18n/src/locales/zh-CN/index.ts b/packages/i18n/src/locales/zh-CN/index.tsindex 3325ba8d4..34cca1afb 100644--- a/packages/i18n/src/locales/zh-CN/index.ts+++ b/packages/i18n/src/locales/zh-CN/index.ts@@ -3378,6 +3378,11 @@ sklm: {dismiss: "关闭",},},+ rendererCrash: {+ title: "PI-Desktop 无法启动",+ body: "界面进程在启动时反复崩溃,已停止自动重试。日志文件夹中有详细信息;若问题持续,请将日志反馈给我们。",+ openLogs: "打开日志文件夹",+ },} satisfies EnglishCatalog;export default zhCN;diff --git a/packages/i18n/src/locales/zh-TW/index.ts b/packages/i18n/src/locales/zh-TW/index.tsindex 2a12b8e10..797658bbf 100644--- a/packages/i18n/src/locales/zh-TW/index.ts+++ b/packages/i18n/src/locales/zh-TW/index.ts@@ -3328,6 +3328,11 @@ sklm: {dismiss: "關閉",},},+ rendererCrash: {+ title: "PI-Desktop 無法啟動",+ body: "介面程序在啟動時反覆崩潰,已停止自動重試。記錄資料夾中有詳細資訊;若問題持續,請將記錄回報給我們。",+ openLogs: "開啟記錄資料夾",+ },} satisfies EnglishCatalog;export default zhTW;