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): own the crash-loop fallback per renderer
vastsae6d7c1e59ce3
diff --git a/apps/desktop/electron/main/bootstrap/renderer-crash-loop-window.ts b/apps/desktop/electron/main/bootstrap/renderer-crash-loop-window.tsnew file mode 100644index 000000000..e738cae22--- /dev/null+++ b/apps/desktop/electron/main/bootstrap/renderer-crash-loop-window.ts@@ -0,0 +1,69 @@+import { app, dialog, shell } from "electron";+import { mkdirSync } from "node:fs";+import { join } from "node:path";+import { catalogs, resolveLocale } from "@pi-desktop/i18n";+import type { Logger } from "../logger";+import {+ createRendererCrashLoopFallback,+ type RendererCrashLoopFallback,+} from "../renderer-crash-loop";++export const DISABLE_GPU_SWITCH = "--disable-gpu";++/**+ * Electron wiring for the #2595 crash-loop fallback. Both exits go through+ * the ordered `before-quit` shutdown with the quit already confirmed, so+ * host-core and running turns are settled before the process ends.+ */+export function createWindowRendererCrashLoopFallback({+ state,+ dataDir,+ logger,+}: Readonly<{+ state: { quitConfirmed: boolean };+ dataDir: string;+ logger: Pick<Logger, "app">;+}>): RendererCrashLoopFallback {+ const quit = () => {+ state.quitConfirmed = true;+ app.quit();+ };+ const showTerminalDialog = async () => {+ 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) {+ const logs = join(dataDir, "logs");+ mkdirSync(logs, { recursive: true });+ await shell.openPath(logs);+ }+ quit();+ };+ return createRendererCrashLoopFallback({+ // userData is the installation anchor: known before `ready`, where boot+ // reads the marker, and independent of the selected data location.+ markerDir: app.getPath("userData"),+ logger,+ relaunch: () => {+ const args = process.argv.slice(1);+ app.relaunch({ args: args.includes(DISABLE_GPU_SWITCH) ? args : [...args, DISABLE_GPU_SWITCH] });+ quit();+ },+ showTerminalDialog: () => {+ void showTerminalDialog().catch((error: unknown) => {+ logger.app("diagnostics", "error", "renderer crash-loop dialog failed; quitting", {+ event: "rendererCrashLoop",+ data: { action: "dialog", error: error instanceof Error ? error.message : String(error) },+ });+ quit();+ });+ },+ });+}diff --git a/apps/desktop/electron/main/bootstrap/window.ts b/apps/desktop/electron/main/bootstrap/window.tsindex 8c41e0cff..62c5d094b 100644--- a/apps/desktop/electron/main/bootstrap/window.ts+++ b/apps/desktop/electron/main/bootstrap/window.ts@@ -1,15 +1,9 @@-import { app, BrowserWindow, dialog, nativeTheme, screen, shell, type Tray } from "electron";+import { app, BrowserWindow, nativeTheme, screen, type Tray } from "electron";import { execFileSync } from "node:child_process";-import { existsSync, mkdirSync } from "node:fs";+import { existsSync } 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 { createWindowRendererCrashLoopFallback } from "./renderer-crash-loop-window";import {APP_NAME,builtinWindowBackground,@@ -63,7 +57,7 @@ import {macosWindowSurfaceOptions,mainWindowBackgroundOptions,} from "../window-background";-import { recoverRendererAfterGone } from "../renderer-recovery";+import { noteRendererLoaded, recoverRendererAfterGone } from "../renderer-recovery";import { installWindowStateSync } from "../window-state-sync";function windowsIconPath(): string | undefined {@@ -598,49 +592,12 @@ export async function createWindow({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();- };+ // reload futile: the breaker hands over to a one-time fallback (#2595).+ const crashLoopFallback = createWindowRendererCrashLoopFallback({ state: windowState, dataDir, logger });+ window.on("closed", crashLoopFallback.dispose);window.webContents.on("render-process-gone", (_event, details) => {windowState.notificationViewingSessionId = null;+ crashLoopFallback.rendererGone();recoverRendererAfterGone(details, {isCurrentWindow: windowState.mainWindow === window,quitting: windowState.quitting,@@ -648,7 +605,7 @@ export async function createWindow({windowDestroyed: window.isDestroyed(),webContentsDestroyed: window.webContents.isDestroyed(),reload: () => window.webContents.reload(),- onCrashLoopDetected: handleRendererCrashLoop,+ onCrashLoopDetected: crashLoopFallback.crashLoopDetected,log: (rendererDetails, reloaded) => {logger.app("diagnostics",@@ -731,9 +688,7 @@ export async function createWindow({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);+ crashLoopFallback.rendererLoaded();});const sendMaximized = () => {diff --git a/apps/desktop/electron/main/index.ts b/apps/desktop/electron/main/index.tsindex 387c5f0df..7a42e2cef 100644--- a/apps/desktop/electron/main/index.ts+++ b/apps/desktop/electron/main/index.ts@@ -1,5 +1,4 @@import { createBackgroundContinuationCoordinator } from "./runtime/background-continuations";-import { hasGpuFallbackMarker } from "./renderer-crash-loop";import {app,BrowserWindow,@@ -187,11 +186,6 @@ 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/installation.ts b/apps/desktop/electron/main/installation.tsindex 185f538bc..3b9904ee5 100644--- a/apps/desktop/electron/main/installation.ts+++ b/apps/desktop/electron/main/installation.ts@@ -2,6 +2,7 @@ import { app } from "electron";import { APP_ID, APP_NAME } from "@pi-desktop/shared";import { applyDevelopmentUserData, desktopDataDir } from "./data-paths";import { ignoreBrokenStdio } from "./logger";+import { hasGpuFallbackMarker } from "./renderer-crash-loop";import { installMainProcessErrorHandlers } from "./main-process-errors";// Complete identity and locking synchronously, before the ready promise or any writer.@@ -21,3 +22,6 @@ if (!hasSingleInstanceLock) app.quit();// Preserve the existing Chromium accessibility crash workaround before ready.app.commandLine.appendSwitch("disable-renderer-accessibility");+// A spent renderer crash-loop fallback (#2595) also covers manual launches;+// hardware acceleration can only be disabled before ready.+if (hasGpuFallbackMarker(app.getPath("userData"))) app.disableHardwareAcceleration();diff --git a/apps/desktop/electron/main/renderer-crash-loop.ts b/apps/desktop/electron/main/renderer-crash-loop.tsindex 1af98783d..95fa9a848 100644--- a/apps/desktop/electron/main/renderer-crash-loop.ts+++ b/apps/desktop/electron/main/renderer-crash-loop.ts@@ -1,50 +1,166 @@-import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import { existsSync, mkdirSync, rmSync, writeFileSync } from "node:fs";import { join } from "node:path";+import type { Logger } from "./logger";/**- * 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.+ * Crash-loop fallback (issue #2595): a renderer that crashes on every+ * startup turns automatic recovery into an endless reload loop — the window+ * never finishes loading, so the user sees a black screen and a flashing+ * taskbar icon. When the breaker in `renderer-recovery.ts` trips, the first+ * trip relaunches once without hardware acceleration, a common mitigation+ * for renderer crashes at startup. The cause on the affected machines is+ * not established; the marker only records that the attempt was 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.+ * The marker lives in the installation's `userData` directory, which is+ * known synchronously before `ready`: boot reads it there to disable+ * hardware acceleration (see `installation.ts`), so manual launches are+ * covered too. A fallback run that stays healthy for+ * `GPU_FALLBACK_STABLE_MS` without a renderer crash clears the marker, so a+ * later boot returns to hardware acceleration.*/-export function gpuFallbackMarkerPath(dataDir: string): string {- return join(dataDir, "renderer-crash-loop.json");+export const GPU_FALLBACK_STABLE_MS = 10 * 60_000;++export function gpuFallbackMarkerPath(markerDir: string): string {+ return join(markerDir, "renderer-crash-loop.json");+}++/**+ * Whether the one GPU-fallback relaunch is spent. Presence alone decides, so+ * an unreadable or corrupt marker still counts as spent; never throws.+ */+export function hasGpuFallbackMarker(markerDir: string): boolean {+ return existsSync(gpuFallbackMarkerPath(markerDir));+}++/** Persist the spent fallback. Throws when the marker cannot be written. */+export function writeGpuFallbackMarker(markerDir: string): void {+ mkdirSync(markerDir, { recursive: true });+ writeFileSync(+ gpuFallbackMarkerPath(markerDir),+ JSON.stringify({ gpuFallbackAt: new Date().toISOString() }),+ "utf8",+ );}-/** 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;- }+/** Remove the marker. Throws when an existing marker cannot be removed. */+export function clearGpuFallbackMarker(markerDir: string): void {+ rmSync(gpuFallbackMarkerPath(markerDir), { force: 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");+type TimerHandle = ReturnType<typeof setTimeout>;++export type RendererCrashLoopFallbackDependencies = Readonly<{+ markerDir: string;+ logger: Pick<Logger, "app">;+ /** Restart the app through the confirmed-quit path. */+ relaunch: () => void;+ /** Tell the user automatic recovery stopped; owns quit / open-logs. */+ showTerminalDialog: () => void;+ stableMs?: number;+ setTimer?: (callback: () => void, ms: number) => TimerHandle;+ clearTimer?: (handle: TimerHandle) => void;+}>;++export type RendererCrashLoopFallback = Readonly<{+ /** The window's renderer finished loading. */+ rendererLoaded: () => void;+ /** The window's renderer exited, for any reason. */+ rendererGone: () => void;+ /** The recovery breaker tripped for this window's renderer. */+ crashLoopDetected: () => void;+ /** The owning window closed. */+ dispose: () => void;+}>;++function errorMessage(error: unknown): string {+ return error instanceof Error ? error.message : String(error);}-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.- }+/**+ * One controller per main window. The stable-uptime timer belongs to the+ * renderer that is currently loaded: a crash, a newer load, terminal+ * escalation, or window disposal cancels it, so a marker is only cleared+ * after continuous healthy uptime of a single renderer.+ */+export function createRendererCrashLoopFallback(+ dependencies: RendererCrashLoopFallbackDependencies,+): RendererCrashLoopFallback {+ const { markerDir, logger } = dependencies;+ const stableMs = dependencies.stableMs ?? GPU_FALLBACK_STABLE_MS;+ const setTimer = dependencies.setTimer ?? ((callback, ms) => setTimeout(callback, ms));+ const clearTimer = dependencies.clearTimer ?? ((handle) => clearTimeout(handle));+ let stableTimer: TimerHandle | null = null;+ let settled = false;++ const log = (level: "info" | "warn" | "error", message: string, data: Record<string, unknown>) =>+ logger.app("diagnostics", level, message, { event: "rendererCrashLoop", data });++ const cancelStableTimer = () => {+ if (stableTimer === null) return;+ clearTimer(stableTimer);+ stableTimer = null;+ };++ const escalateToDialog = (data: Record<string, unknown>, message: string) => {+ settled = true;+ log(data.error === undefined ? "warn" : "error", message, { action: "dialog", ...data });+ dependencies.showTerminalDialog();+ };++ return {+ rendererLoaded() {+ cancelStableTimer();+ if (settled || !hasGpuFallbackMarker(markerDir)) return;+ stableTimer = setTimer(() => {+ stableTimer = null;+ try {+ clearGpuFallbackMarker(markerDir);+ log("info", "renderer stayed healthy without GPU acceleration; cleared fallback marker", {+ action: "clear-marker",+ });+ } catch (error) {+ log("warn", "could not clear renderer crash-loop fallback marker", {+ action: "clear-marker",+ error: errorMessage(error),+ });+ }+ }, stableMs);+ },+ rendererGone() {+ cancelStableTimer();+ },+ crashLoopDetected() {+ cancelStableTimer();+ if (settled) return;+ if (hasGpuFallbackMarker(markerDir)) {+ escalateToDialog(+ {},+ "renderer crash loop persists without GPU acceleration; stopping automatic reloads",+ );+ return;+ }+ try {+ writeGpuFallbackMarker(markerDir);+ } catch (error) {+ // Without a persisted marker the relaunch has no deduplication guard+ // and could loop across processes; stop here and tell the user.+ escalateToDialog(+ { error: errorMessage(error) },+ "could not persist renderer crash-loop fallback marker; stopping automatic reloads",+ );+ return;+ }+ settled = true;+ log("warn", "renderer crash loop detected; relaunching without GPU acceleration", {+ action: "relaunch-disable-gpu",+ });+ dependencies.relaunch();+ },+ dispose() {+ cancelStableTimer();+ settled = true;+ },+ };}diff --git a/apps/desktop/electron/main/renderer-recovery.ts b/apps/desktop/electron/main/renderer-recovery.tsindex 4870a64ea..b2dc86885 100644--- a/apps/desktop/electron/main/renderer-recovery.ts+++ b/apps/desktop/electron/main/renderer-recovery.ts@@ -25,9 +25,8 @@ 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+ * (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;@@ -48,9 +47,13 @@ export function _resetCooldownForTest(): void {crashLoopReported = false;}-/** A renderer finished loading: the crash streak restarts from zero. */+/**+ * A renderer finished loading: the crash streak restarts from zero, and a+ * breaker that tripped for an earlier renderer re-arms for this one.+ */export function noteRendererLoaded(): void {consecutiveCrashesWithoutLoad = 0;+ crashLoopReported = false;}/** Reload an unexpectedly exited renderer while its owning app window is live. */diff --git a/apps/desktop/test/renderer-crash-loop.test.mjs b/apps/desktop/test/renderer-crash-loop.test.mjsnew file mode 100644index 000000000..afa109e1d--- /dev/null+++ b/apps/desktop/test/renderer-crash-loop.test.mjs@@ -0,0 +1,189 @@+import assert from "node:assert/strict";+import { chmodSync, existsSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { afterEach, beforeEach, describe, it, mock } from "node:test";+import {+ createRendererCrashLoopFallback,+ gpuFallbackMarkerPath,+ hasGpuFallbackMarker,+} from "../electron/main/renderer-crash-loop.ts";+import {+ _resetCooldownForTest,+ noteRendererLoaded,+ recoverRendererAfterGone,+} from "../electron/main/renderer-recovery.ts";++/** Manual timer queue: nothing fires until the test advances the clock. */+function fakeTimers() {+ let now = 0;+ let nextId = 1;+ const pending = new Map();+ return {+ setTimer: (callback, ms) => {+ const id = nextId++;+ pending.set(id, { at: now + ms, callback });+ return id;+ },+ clearTimer: (id) => pending.delete(id),+ advance(ms) {+ now += ms;+ for (const [id, timer] of [...pending]) {+ if (timer.at > now) continue;+ pending.delete(id);+ timer.callback();+ }+ },+ get size() {+ return pending.size;+ },+ };+}++const STABLE_MS = 600_000;++/**+ * One app process: a fallback controller wired to the real recovery breaker+ * the way `bootstrap/window.ts` wires it. `relaunch` ends the process.+ */+function launch(markerDir, timers) {+ _resetCooldownForTest();+ const outcome = { relaunches: 0, dialogs: 0, reloads: 0, logs: [] };+ const fallback = createRendererCrashLoopFallback({+ markerDir,+ logger: { app: (_category, level, message, fields) => outcome.logs.push({ level, message, fields }) },+ relaunch: () => outcome.relaunches++,+ showTerminalDialog: () => outcome.dialogs++,+ stableMs: STABLE_MS,+ setTimer: timers.setTimer,+ clearTimer: timers.clearTimer,+ });+ const crash = () => {+ mock.timers.tick(3_000); // past the reload cooldown+ fallback.rendererGone();+ recoverRendererAfterGone(+ { reason: "crashed", exitCode: -2147483645 },+ {+ isCurrentWindow: true,+ quitting: false,+ windowCloseAccepted: false,+ windowDestroyed: false,+ webContentsDestroyed: false,+ reload: () => outcome.reloads++,+ log: () => {},+ onCrashLoopDetected: fallback.crashLoopDetected,+ },+ );+ };+ const load = () => {+ noteRendererLoaded();+ fallback.rendererLoaded();+ };+ return { outcome, fallback, crash, load };+}++describe("renderer crash-loop fallback (#2595)", () => {+ let markerDir;+ beforeEach(() => {+ markerDir = mkdtempSync(join(tmpdir(), "pi-crash-loop-"));+ mock.timers.enable({ apis: ["Date"], now: 10_000 });+ });+ afterEach(() => {+ _resetCooldownForTest();+ mock.timers.reset();+ chmodSync(markerDir, 0o755);+ rmSync(markerDir, { recursive: true, force: true });+ });++ it("relaunches once, then a second failing launch reaches the dialog", () => {+ const timers = fakeTimers();+ const first = launch(markerDir, timers);+ for (let i = 0; i < 8; i += 1) first.crash();+ assert.equal(first.outcome.relaunches, 1, "one guarded relaunch");+ assert.equal(first.outcome.dialogs, 0);+ assert.equal(first.outcome.reloads, 4, "reloads stop once the breaker trips");+ assert.ok(hasGpuFallbackMarker(markerDir), "the relaunch is persisted before it happens");++ const second = launch(markerDir, timers);+ for (let i = 0; i < 8; i += 1) second.crash();+ assert.equal(second.outcome.relaunches, 0, "the fallback is never spent twice");+ assert.equal(second.outcome.dialogs, 1, "the loop that survives it reaches the dialog once");+ assert.ok(hasGpuFallbackMarker(markerDir));+ });++ it("a stable fallback run clears the marker after continuous healthy uptime", () => {+ writeFileSync(gpuFallbackMarkerPath(markerDir), "{}");+ const timers = fakeTimers();+ const run = launch(markerDir, timers);+ run.load();+ timers.advance(STABLE_MS - 1);+ assert.ok(hasGpuFallbackMarker(markerDir), "not before the stable window elapses");+ timers.advance(1);+ assert.equal(hasGpuFallbackMarker(markerDir), false);+ });++ it("an earlier load's timer never clears the marker after a later crash", () => {+ writeFileSync(gpuFallbackMarkerPath(markerDir), "{}");+ const timers = fakeTimers();+ const run = launch(markerDir, timers);+ run.load();+ timers.advance(STABLE_MS / 2);+ for (let i = 0; i < 5; i += 1) run.crash();+ assert.equal(run.outcome.dialogs, 1, "terminal dialog is open");+ timers.advance(STABLE_MS * 2);+ assert.equal(timers.size, 0, "no timer outlives the crashed renderer");+ assert.ok(hasGpuFallbackMarker(markerDir), "marker survives while the dialog is open");+ });++ it("a reload restarts the healthy-uptime window instead of stacking timers", () => {+ writeFileSync(gpuFallbackMarkerPath(markerDir), "{}");+ const timers = fakeTimers();+ const run = launch(markerDir, timers);+ run.load();+ timers.advance(STABLE_MS - 1_000);+ run.load();+ assert.equal(timers.size, 1);+ timers.advance(1_000);+ assert.ok(hasGpuFallbackMarker(markerDir), "uptime counts from the latest load");+ timers.advance(STABLE_MS);+ assert.equal(hasGpuFallbackMarker(markerDir), false);+ });++ it("closing the window cancels the healthy-uptime timer", () => {+ writeFileSync(gpuFallbackMarkerPath(markerDir), "{}");+ const timers = fakeTimers();+ const run = launch(markerDir, timers);+ run.load();+ run.fallback.dispose();+ timers.advance(STABLE_MS * 2);+ assert.ok(hasGpuFallbackMarker(markerDir));+ });++ it("a normal boot without a marker arms no timer", () => {+ const timers = fakeTimers();+ launch(markerDir, timers).load();+ assert.equal(timers.size, 0);+ });++ it("a marker that cannot be persisted shows the dialog instead of relaunching", (t) => {+ if (process.platform === "win32" || process.getuid?.() === 0) {+ t.skip("directory permissions do not block writes here");+ return;+ }+ chmodSync(markerDir, 0o500);+ const timers = fakeTimers();+ const run = launch(markerDir, timers);+ for (let i = 0; i < 5; i += 1) run.crash();+ assert.equal(run.outcome.relaunches, 0, "no relaunch without a deduplication guard");+ assert.equal(run.outcome.dialogs, 1);+ const failure = run.outcome.logs.find((entry) => entry.level === "error");+ assert.ok(failure?.fields?.data?.error, "the write failure is logged");+ });++ it("a corrupt marker still counts as spent without being rewritten", () => {+ const path = gpuFallbackMarkerPath(markerDir);+ writeFileSync(path, "not json");+ assert.ok(hasGpuFallbackMarker(markerDir));+ assert.ok(existsSync(path));+ });+});diff --git a/apps/desktop/test/renderer-recovery.test.mjs b/apps/desktop/test/renderer-recovery.test.mjsindex 69c310654..65617a4a7 100644--- a/apps/desktop/test/renderer-recovery.test.mjs+++ b/apps/desktop/test/renderer-recovery.test.mjs@@ -158,6 +158,35 @@ describe("recoverRendererAfterGone", () => {assert.equal(trips, 0);});+ it("a load after a trip re-arms the breaker for the next renderer", () => {+ mock.timers.enable({ apis: ["Date", "setTimeout"] });+ mock.timers.tick(10_000);++ const details = { reason: "crashed", exitCode: 1 };+ let trips = 0;+ let reloads = 0;+ const crash = () => {+ const attempt = recovery({+ onCrashLoopDetected: () => {+ trips += 1;+ },+ reload: () => {+ reloads += 1;+ },+ });+ mock.timers.tick(3_000);+ recoverRendererAfterGone(details, attempt.dependencies);+ };++ for (let i = 0; i < 5; i += 1) crash();+ assert.equal(trips, 1);+ noteRendererLoaded();+ crash();+ assert.equal(reloads, 5, "a crash after a successful load reloads again");+ for (let i = 0; i < 4; i += 1) crash();+ assert.equal(trips, 2);+ });+it("clean exits never count toward the breaker", () => {mock.timers.enable({ apis: ["Date", "setTimeout"] });mock.timers.tick(10_000);diff --git a/docs/spec/03-runtime/07-process-model.md b/docs/spec/03-runtime/07-process-model.mdindex 58c560baf..ef4fb08b3 100644--- a/docs/spec/03-runtime/07-process-model.md+++ b/docs/spec/03-runtime/07-process-model.md@@ -107,7 +107,7 @@ errors remain readable instead of becoming replacement characters.| Crash | Policy ||---|---|-| 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 |+| 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. Five consecutive unexpected exits with no successful load in between stop the reloads: the first time, write `<userData>/renderer-crash-loop.json` and relaunch once without hardware acceleration through the confirmed-quit shutdown; when the marker already exists or cannot be written, show a localized dialog (open log folder / quit). While the marker exists, boot disables hardware acceleration before `ready`; a single renderer that stays loaded for 10 minutes clears it || 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; 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 |diff --git a/docs/spec/06-delivery/e2e/release-and-platform.md b/docs/spec/06-delivery/e2e/release-and-platform.mdindex 7b91c6554..8a2569cef 100644--- a/docs/spec/06-delivery/e2e/release-and-platform.md+++ b/docs/spec/06-delivery/e2e/release-and-platform.md@@ -1349,3 +1349,20 @@## E2E-ISSUE-1707Use synthetic Darwin x64/arm64 uname responses through production SSH bootstrap, serialize its code/details as IPC does, and resolve the renderer error. The platform explanation appears, no checksum or upload occurs. Linux and other bootstrap failures keep existing messages. Coverage: remote-host-ssh-bootstrap.test.mjs and remote-host-errors.test.mjs.++## E2E-RENDERER-crash-loop-fallback++- **Preconditions:** Built desktop, isolated data directory and Chromium+ profile, candidate host-core via `PI_DESKTOP_HOST_BIN`. No user instance.+- **Steps:** Run `node scripts/e2e-renderer-crash-loop.mjs`. Launch 1 makes+ every main-window load crash before `did-finish-load`. Launch 2 repeats on+ the same profile. Launch 3 boots normally and stays loaded. `app.relaunch`+ and `dialog.showMessageBox` are intercepted in Main.+- **Expected:** Launch 1 persists `<userData>/renderer-crash-loop.json`, logs+ `relaunch-disable-gpu`, and exits through the ordered shutdown. Launch 2+ boots without hardware acceleration, never relaunches, shows the terminal+ dialog once, and quits from it; the marker survives. Launch 3 clears the+ marker after continuous healthy uptime of one renderer.+- **Coverage:** `renderer-crash-loop.test.mjs`, `renderer-recovery.test.mjs`.+- **Qualification:** Forced renderer crashes reproduce the reload loop, not the+ #2595 Windows trigger, whose cause is unconfirmed.diff --git a/scripts/e2e-renderer-crash-loop.mjs b/scripts/e2e-renderer-crash-loop.mjsnew file mode 100644index 000000000..422ab1276--- /dev/null+++ b/scripts/e2e-renderer-crash-loop.mjs@@ -0,0 +1,150 @@+// E2E for the renderer crash-loop fallback (#2595): a renderer that dies on+// every load must not reload forever. Three isolated launches share one+// profile: (1) a crash loop relaunches once without GPU acceleration, (2) a+// loop that survives the fallback reaches the terminal dialog, (3) a stable+// fallback boot clears the marker. Relaunch and the dialog are intercepted in+// Main so no detached process or modal is left behind.+import assert from "node:assert/strict";+import { existsSync } from "node:fs";+import { mkdir, readFile } from "node:fs/promises";+import { createRequire } from "node:module";+import { join, resolve } from "node:path";++const require = createRequire(new URL("../apps/desktop/package.json", import.meta.url));+const { _electron } = require(process.env.PI_TEST_PLAYWRIGHT ?? "playwright");+const root = resolve(import.meta.dirname, "..");+const output = join(root, ".artifacts", `renderer-crash-loop-${Date.now()}`);+const dataDir = join(output, "data");+const profile = join(output, "profile");+const marker = join(profile, "renderer-crash-loop.json");+await mkdir(dataDir, { recursive: true });++const check = (name, value = true) => {+ assert.ok(value, name);+ console.log(`PASS ${name}`);+};+async function until(probe, label, timeout = 60_000) {+ const deadline = Date.now() + timeout;+ while (Date.now() < deadline) {+ const result = await probe();+ if (result) return result;+ await new Promise((done) => setTimeout(done, 100));+ }+ throw new Error(`Timed out: ${label}`);+}++/** `evaluate` can race Main startup; retry until Main answers. */+async function evaluate(app, fn, arg) {+ let lastError;+ for (let attempt = 0; attempt < 50; attempt += 1) {+ try {+ return await app.evaluate(fn, arg);+ } catch (error) {+ lastError = error;+ await new Promise((done) => setTimeout(done, 200));+ }+ }+ throw lastError;+}++async function shell(app) {+ const page = await until(async () => {+ for (const candidate of app.windows()) if (await candidate.locator(".app-shell").count()) return candidate;+ }, "desktop shell");+ await page.locator(".app-shell:not(.app-shell-boot)").waitFor();+ return page;+}++async function launch() {+ const env = { ...process.env, PI_DESKTOP_DATA_DIR: dataDir, ELECTRON_RENDERER_URL: "",+ PI_DESKTOP_HOST_BIN: process.env.PI_DESKTOP_HOST_BIN ?? join(root, "target/release/pi-desktop-host-core") };+ delete env.ELECTRON_RUN_AS_NODE;+ const app = await _electron.launch({+ executablePath: require("electron"),+ args: [join(root, "apps/desktop"), `--user-data-dir=${profile}`],+ env,+ timeout: 60_000,+ });+ const exited = new Promise((done) => app.process().once("exit", (code) => done(code)));+ // Intercept the two process-level escapes before any crash is induced.+ await evaluate(app, ({ app: electronApp, dialog }) => {+ globalThis.__crashLoopE2E = { relaunches: [], dialogs: [] };+ electronApp.relaunch = (options) => globalThis.__crashLoopE2E.relaunches.push(options?.args ?? []);+ dialog.showMessageBox = async (...args) => {+ const options = args.find((arg) => arg && typeof arg === "object" && "buttons" in arg);+ globalThis.__crashLoopE2E.dialogs.push({ title: options?.title, buttons: options?.buttons });+ return { response: 1, checkboxChecked: false };+ };+ });+ return { app, exited };+}++/** Make every renderer load of the main window crash before it finishes. */+async function crashEveryLoad(app) {+ const url = (await shell(app)).url();+ await evaluate(app, ({ BrowserWindow }, mainUrl) => {+ const window = BrowserWindow.getAllWindows().find((candidate) => candidate.webContents.getURL() === mainUrl);+ const crash = () => {+ if (!window.isDestroyed() && !window.webContents.isDestroyed()) window.webContents.forcefullyCrashRenderer();+ };+ window.webContents.on("did-start-loading", () => setTimeout(crash, 50));+ crash();+ }, url);+}++async function appLog(name) {+ const file = join(dataDir, "logs", "app", `${name}.log`);+ return existsSync(file) ? (await readFile(file, "utf8")).split("\n").filter(Boolean) : [];+}++let current;+try {+ // 1. First crash loop: one guarded relaunch through the confirmed quit.+ current = await launch();+ await crashEveryLoad(current.app);+ const firstExit = await current.exited;+ current = undefined;+ check("first crash loop exits the process", firstExit === 0);+ check("fallback marker persisted before relaunch", existsSync(marker));+ check("relaunch logged", (await appLog("diagnostics")).some((line) =>+ line.includes("renderer.crash.loop") && line.includes("relaunch-disable-gpu")));+ check("relaunch went through the ordered shutdown", (await appLog("lifecycle")).some((line) =>+ line.includes("app.shutdown")));++ // 2. The loop survives the fallback: no second relaunch, the dialog shows.+ current = await launch();+ const gpuDisabled = await evaluate(current.app, ({ app: electronApp }) =>+ electronApp.isHardwareAccelerationEnabled() === false);+ check("marker boot runs without hardware acceleration", gpuDisabled);+ await crashEveryLoad(current.app);+ const state = await until(+ () => current.app.evaluate(() => (globalThis.__crashLoopE2E.dialogs.length ? globalThis.__crashLoopE2E : null)),+ "terminal dialog",+ );+ check("no second relaunch", state.relaunches.length === 0);+ check("terminal dialog shown once", state.dialogs.length === 1 && state.dialogs[0].buttons.length === 2);+ const secondExit = await current.exited;+ current = undefined;+ check("quit from the dialog exits the process", secondExit === 0);+ check("marker survives a failing fallback launch", existsSync(marker));++ // 3. A stable fallback boot clears the marker after continuous uptime.+ current = await launch();+ const mainUrl = (await shell(current.app)).url();+ check("fallback boot loads the shell", existsSync(marker));+ // Shorten only the 10-minute healthy-uptime timer, then reload so the+ // current renderer arms it; every other timer keeps its real duration.+ await evaluate(current.app, ({ BrowserWindow }, url) => {+ const original = globalThis.setTimeout;+ globalThis.setTimeout = (callback, ms, ...rest) => original(callback, ms === 600_000 ? 2_000 : ms, ...rest);+ BrowserWindow.getAllWindows().find((candidate) => candidate.webContents.getURL() === url).webContents.reload();+ }, mainUrl);+ await until(() => !existsSync(marker), "marker cleared after stable uptime", 30_000);+ check("stable fallback boot clears the marker");+ await current.app.evaluate(() => { process.env.PI_DESKTOP_BOOT_PROBE = "1"; });+ await current.app.close();+ current = undefined;+ console.log(`renderer crash-loop E2E passed; artifacts: ${output}`);+} finally {+ if (current) await current.app.close().catch(() => undefined);+}