Skip to content

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

feat(desktop): report crash dumps found on the next launch

zhangqingkun9762b6d552e8e5c
diff --git a/apps/desktop/electron/main/bootstrap/startup.ts b/apps/desktop/electron/main/bootstrap/startup.ts
index 81676a380..355a8e3e2 100644
--- a/apps/desktop/electron/main/bootstrap/startup.ts
+++ b/apps/desktop/electron/main/bootstrap/startup.ts
@@ -1,4 +1,4 @@
-import { app, BrowserWindow, Menu, safeStorage } from "electron";
+import { app, BrowserWindow, crashReporter, Menu, safeStorage } from "electron";
import {
APP_NAME,
APP_VERSION,
@@ -32,6 +32,11 @@ import type { HostProcess } from "../host-process";
import type { Logger } from "../logger";
import type { PluginRuntime } from "../plugin-runtime";
import { runSessionListProbe } from "../session-list-probe";
+import {
+ describeCrashDumps,
+ readCrashDumpMarker,
+ writeCrashDumpMarker,
+} from "../crash-report";
type IpcInvoker = (
channel: string,
@@ -116,6 +121,11 @@ export function registerApplicationStartup(deps: StartupDependencies): void {
// Electron only accepts scheme privileges before the app is ready, and this
// runs from the composition root, before the `whenReady` promise can settle.
registerPluginAssetScheme();
+ // Crashpad ships with Electron, so the reporter needs no native dependency.
+ // Dumps stay local (`uploadToServer: false`) in `app.getPath("crashDumps")`;
+ // nothing is uploaded. Started before `ready`, so no crash can happen ahead
+ // of the handler.
+ crashReporter.start({ uploadToServer: false, productName: APP_NAME });
void app.whenReady().then(async () => {
const {
hasSingleInstanceLock,
@@ -151,6 +161,38 @@ export function registerApplicationStartup(deps: StartupDependencies): void {
// create a window, a tray, or a child process on top of the running app.
if (!hasSingleInstanceLock) return;
applyDevelopmentBranding();
+
+ // A crash from a previous run left a minidump in `crashDumps`, and nothing
+ // else would ever mention it. Report one durable line per crash: compare
+ // dumps against the marker the previous launch wrote into this same
+ // best-effort JSON store, then advance it. Crashpad nests dumps under
+ // `crashDumps` subdirectories (e.g. `reports/`), so this walks that tree.
+ // Reporting is diagnostics: a failure warns and is dropped rather than
+ // holding up the first window.
+ try {
+ const crashDumpMarker = readCrashDumpMarker(dataDir)?.newestMtimeMs ?? null;
+ const crashDumps = describeCrashDumps(app.getPath("crashDumps"), crashDumpMarker);
+ if (crashDumps.newDumpCount > 0) {
+ logger.app("diagnostics", "error", "crash dumps found from a previous run", {
+ data: {
+ count: crashDumps.newDumpCount,
+ total: crashDumps.dumpCount,
+ directory: crashDumps.directory,
+ newestMtimeMs: crashDumps.newestMtimeMs,
+ },
+ });
+ }
+ if (
+ crashDumps.newestMtimeMs !== null &&
+ (crashDumpMarker === null || crashDumps.newestMtimeMs > crashDumpMarker)
+ ) {
+ writeCrashDumpMarker(dataDir, crashDumps.newestMtimeMs);
+ }
+ } catch (error) {
+ logger.app("diagnostics", "warn", "crash dump report failed", {
+ data: String(error),
+ });
+ }
// Serve declared theme assets before the renderer can ask for one; the
// scheme itself was reserved in `registerApplicationStartup`.
installPluginAssetProtocol((pluginId, assetPath) =>
diff --git a/apps/desktop/electron/main/crash-report.ts b/apps/desktop/electron/main/crash-report.ts
new file mode 100644
index 000000000..3c33a6475
--- /dev/null
+++ b/apps/desktop/electron/main/crash-report.ts
@@ -0,0 +1,117 @@
+/**
+ * Local crash-dump collection for the Electron main process.
+ *
+ * Electron ships Crashpad, so `crashReporter.start()` needs no native
+ * dependency. Dumps stay on this machine — nothing is uploaded — and this
+ * module only describes what is already on disk plus the marker of the last
+ * scan, so a crash from a previous run becomes one durable log line instead of
+ * staying invisible.
+ *
+ * Crashpad nests dumps under subdirectories of `app.getPath("crashDumps")`
+ * (for example `reports/`), so the scan walks a bounded depth instead of
+ * assuming a flat directory: a flat readdir finds zero dumps and the feature
+ * would be silently useless.
+ *
+ * Crashes of the host-core / sidecar children are out of scope here: main
+ * supervises and restarts those processes (see `runtime/lifecycle.ts`) and
+ * their stderr already lands in the `host` / `agent` log channels.
+ */
+import { mkdirSync, readFileSync, readdirSync, statSync, writeFileSync } from "node:fs";
+import type { Dirent } from "node:fs";
+import { join } from "node:path";
+
+/** Crashpad uses one nesting level; three leaves room without a full walk. */
+const MAX_DUMP_SCAN_DEPTH = 3;
+
+/** Marker file, beside the other best-effort main-process state JSON. */
+export const CRASH_DUMP_MARKER_FILE = "crash-dumps.json";
+
+export type CrashDumpSummary = {
+ /** Directory that was scanned. */
+ directory: string;
+ /** Every `*.dmp` file found at or below `directory`. */
+ dumpCount: number;
+ /** Dumps strictly newer than the caller's marker mtime. */
+ newDumpCount: number;
+ /** Newest mtime across every dump found, or null when there is none. */
+ newestMtimeMs: number | null;
+};
+
+function collectDumpPaths(directory: string, depth: number, found: string[]): void {
+ let entries: Dirent[];
+ try {
+ entries = readdirSync(directory, { withFileTypes: true });
+ } catch {
+ // Crashpad has not created the directory yet: no crash has been observed.
+ return;
+ }
+ for (const entry of entries) {
+ const path = join(directory, entry.name);
+ if (entry.isDirectory()) {
+ if (depth > 0) collectDumpPaths(path, depth - 1, found);
+ } else if (entry.isFile() && entry.name.toLowerCase().endsWith(".dmp")) {
+ found.push(path);
+ }
+ }
+}
+
+/**
+ * Describe the dumps below `directory`, and how many of them are newer than
+ * `sinceMtimeMs` (the previous launch's marker; null reports every dump).
+ * Filesystem races stay benign: a dump removed between list and stat is not a
+ * dump for this scan, and a directory that does not exist is an empty scan.
+ */
+export function describeCrashDumps(
+ directory: string,
+ sinceMtimeMs: number | null = null,
+): CrashDumpSummary {
+ const found: string[] = [];
+ collectDumpPaths(directory, MAX_DUMP_SCAN_DEPTH, found);
+ let newDumpCount = 0;
+ let newestMtimeMs: number | null = null;
+ for (const path of found) {
+ let mtimeMs: number;
+ try {
+ mtimeMs = statSync(path).mtimeMs;
+ } catch {
+ continue; // removed between readdir and stat; not a dump this scan
+ }
+ if (sinceMtimeMs === null || mtimeMs > sinceMtimeMs) newDumpCount += 1;
+ if (newestMtimeMs === null || mtimeMs > newestMtimeMs) newestMtimeMs = mtimeMs;
+ }
+ return { directory, dumpCount: found.length, newDumpCount, newestMtimeMs };
+}
+
+export type CrashDumpMarker = { newestMtimeMs: number };
+
+/** Read the previous scan's marker; missing or malformed reads as "unset". */
+export function readCrashDumpMarker(dataDir: string): CrashDumpMarker | null {
+ try {
+ const raw = JSON.parse(
+ readFileSync(join(dataDir, CRASH_DUMP_MARKER_FILE), "utf8"),
+ ) as { newestMtimeMs?: unknown };
+ const newestMtimeMs = Number(raw?.newestMtimeMs);
+ return Number.isFinite(newestMtimeMs) ? { newestMtimeMs } : null;
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * Persist the newest mtime a scan saw, so the next launch reports only dumps
+ * from crashes after this one. Best-effort, like the other main-process state
+ * files: failing to write the marker repeats a log line on the next launch,
+ * which is better than turning a diagnostic into a boot failure.
+ */
+export function writeCrashDumpMarker(dataDir: string, newestMtimeMs: number): void {
+ try {
+ mkdirSync(dataDir, { recursive: true });
+ writeFileSync(
+ join(dataDir, CRASH_DUMP_MARKER_FILE),
+ JSON.stringify({ newestMtimeMs }),
+ "utf8",
+ );
+ } catch {
+ // best-effort persistence
+ }
+}
diff --git a/apps/desktop/test/crash-report-surface.test.mjs b/apps/desktop/test/crash-report-surface.test.mjs
new file mode 100644
index 000000000..fc0a81c4a
--- /dev/null
+++ b/apps/desktop/test/crash-report-surface.test.mjs
@@ -0,0 +1,148 @@
+import assert from "node:assert/strict";
+import {
+ mkdirSync,
+ mkdtempSync,
+ rmSync,
+ utimesSync,
+ writeFileSync,
+} from "node:fs";
+import { tmpdir } from "node:os";
+import { dirname, join } from "node:path";
+import test from "node:test";
+import {
+ CRASH_DUMP_MARKER_FILE,
+ describeCrashDumps,
+ readCrashDumpMarker,
+ writeCrashDumpMarker,
+} from "../electron/main/crash-report.ts";
+import { readMainModule } from "./helpers/source-contracts.mjs";
+
+/**
+ * Crash collection has two halves: the pure scan/marker pair below, exercised
+ * against real files in a temp directory, and the main-process wiring that runs
+ * it at startup, held to the properties a behavior test cannot observe without
+ * Electron (local-only reporter, diagnostics log surface, marker store).
+ */
+const startupSource = await readMainModule("bootstrap/startup.ts");
+const mainIndexSource = await readMainModule("index.ts");
+
+const parentDir = mkdtempSync(join(tmpdir(), "pi-desktop-crash-report-"));
+test.after(() => {
+ rmSync(parentDir, { recursive: true, force: true });
+});
+
+/** Whole-second mtimes keep the assertions filesystem-precision independent. */
+const SECOND = 1_000;
+const BASE_MS = 1_700_000_000_000;
+
+function makeDump(path, mtimeMs) {
+ mkdirSync(dirname(path), { recursive: true });
+ writeFileSync(path, "minidump");
+ utimesSync(path, new Date(mtimeMs), new Date(mtimeMs));
+}
+
+function storedMarkerMtime(dataDir) {
+ return readCrashDumpMarker(dataDir)?.newestMtimeMs ?? null;
+}
+
+test("a crashDumps directory that does not exist yet reports nothing", () => {
+ const summary = describeCrashDumps(join(parentDir, "never-created"));
+ assert.deepEqual(summary, {
+ directory: join(parentDir, "never-created"),
+ dumpCount: 0,
+ newDumpCount: 0,
+ newestMtimeMs: null,
+ });
+});
+
+test("dumps are found under Crashpad's nested reports/ layout, and only .dmp files", () => {
+ const root = join(parentDir, "crashDumps");
+ makeDump(join(root, "reports", "older.dmp"), BASE_MS);
+ makeDump(join(root, "reports", "newer.DMP"), BASE_MS + 60 * SECOND);
+ makeDump(join(root, "crash.dmp"), BASE_MS + 30 * SECOND);
+ // Not dumps: metadata beside the minidump, a directory ending in .dmp, and an
+ // unrelated file.
+ makeDump(join(root, "reports", "older.meta"), BASE_MS);
+ mkdirSync(join(root, "decoy.dmp"), { recursive: true });
+ writeFileSync(join(root, "notes.txt"), "not a dump");
+
+ const summary = describeCrashDumps(root);
+ assert.equal(summary.dumpCount, 3);
+ assert.equal(summary.newDumpCount, 3);
+ assert.equal(summary.newestMtimeMs, BASE_MS + 60 * SECOND);
+});
+
+test("a crash is reported once: the marker suppresses the repeat on the next launch", () => {
+ const root = join(parentDir, "marker-scan");
+ const dataDir = join(parentDir, "marker-scan-data");
+ makeDump(join(root, "reports", "crashed-last-run.dmp"), BASE_MS);
+ makeDump(join(root, "reports", "crashed-before-that.dmp"), BASE_MS - 120 * SECOND);
+ assert.equal(readCrashDumpMarker(dataDir), null);
+
+ // First launch: both dumps are new, so startup reports them and records the
+ // newest mtime it saw.
+ const firstScan = describeCrashDumps(root, storedMarkerMtime(dataDir));
+ assert.equal(firstScan.dumpCount, 2);
+ assert.equal(firstScan.newDumpCount, 2);
+ writeCrashDumpMarker(dataDir, firstScan.newestMtimeMs);
+
+ // Second launch: the same dumps are still on disk, but none is new.
+ const secondScan = describeCrashDumps(root, storedMarkerMtime(dataDir));
+ assert.equal(secondScan.dumpCount, 2);
+ assert.equal(secondScan.newDumpCount, 0);
+
+ // A later crash is reported again, on the launch after it.
+ makeDump(join(root, "reports", "crashed-again.dmp"), BASE_MS + 360 * SECOND);
+ const afterNewCrash = describeCrashDumps(root, storedMarkerMtime(dataDir));
+ assert.equal(afterNewCrash.newDumpCount, 1);
+ assert.equal(afterNewCrash.newestMtimeMs, BASE_MS + 360 * SECOND);
+});
+
+test("the marker round-trips through the data-dir JSON store", () => {
+ const dataDir = join(parentDir, "data");
+ assert.equal(readCrashDumpMarker(dataDir), null);
+
+ writeCrashDumpMarker(dataDir, BASE_MS);
+ assert.deepEqual(readCrashDumpMarker(dataDir), { newestMtimeMs: BASE_MS });
+ assert.equal(CRASH_DUMP_MARKER_FILE, "crash-dumps.json");
+
+ writeFileSync(join(dataDir, CRASH_DUMP_MARKER_FILE), "{ not json");
+ assert.equal(readCrashDumpMarker(dataDir), null);
+ writeFileSync(join(dataDir, CRASH_DUMP_MARKER_FILE), JSON.stringify({ newestMtimeMs: "x" }));
+ assert.equal(readCrashDumpMarker(dataDir), null);
+});
+
+test("startup starts Crashpad local-only, before ready", () => {
+ assert.match(startupSource, /crashReporter\.start\(\{\s*uploadToServer: false,/);
+ assert.match(startupSource, /productName: APP_NAME/);
+ const startAt = startupSource.indexOf("crashReporter.start(");
+ assert.ok(startAt > 0, "startup must start the crash reporter");
+ assert.ok(
+ startAt < startupSource.indexOf("app.whenReady()"),
+ "the reporter must start before the app is ready",
+ );
+ // One installation point: the composition root does not start it again.
+ assert.doesNotMatch(mainIndexSource, /crashReporter\.start/);
+});
+
+test("startup reports new crash dumps under diagnostics and advances the marker", () => {
+ assert.match(
+ startupSource,
+ /describeCrashDumps\(app\.getPath\("crashDumps"\), crashDumpMarker\)/,
+ );
+ assert.match(startupSource, /readCrashDumpMarker\(dataDir\)/);
+ assert.match(
+ startupSource,
+ /logger\.app\(\s*"diagnostics",\s*"error",\s*"crash dumps found from a previous run"/,
+ );
+ // Only dumps newer than the marker are reported: one crash is one log line.
+ assert.match(startupSource, /if \(crashDumps\.newDumpCount > 0\) \{/);
+ assert.match(startupSource, /writeCrashDumpMarker\(dataDir, crashDumps\.newestMtimeMs\)/);
+ // With no dumps at all there is no mtime to record.
+ assert.match(startupSource, /crashDumps\.newestMtimeMs !== null/);
+ // A failure to report is a warning; it never blocks the first window.
+ assert.match(
+ startupSource,
+ /logger\.app\(\s*"diagnostics",\s*"warn",\s*"crash dump report failed"/,
+ );
+});