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): classify crash dumps and keep them in the data directory
vastsa8f0ee175bf04
diff --git a/apps/desktop/electron/main/bootstrap/startup.ts b/apps/desktop/electron/main/bootstrap/startup.tsindex 355a8e3e2..ef50c461c 100644--- a/apps/desktop/electron/main/bootstrap/startup.ts+++ b/apps/desktop/electron/main/bootstrap/startup.ts@@ -33,9 +33,8 @@ import type { Logger } from "../logger";import type { PluginRuntime } from "../plugin-runtime";import { runSessionListProbe } from "../session-list-probe";import {- describeCrashDumps,- readCrashDumpMarker,- writeCrashDumpMarker,+ ensureCrashDumpsDirectory,+ reportPreviousCrashDumps,} from "../crash-report";type IpcInvoker = (@@ -122,10 +121,21 @@ export function registerApplicationStartup(deps: StartupDependencies): void {// 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 });+ // Dumps stay local (`uploadToServer: false`) under the installation data+ // directory so a `PI_DESKTOP_DATA_DIR` profile does not share them. Started+ // before `ready`, so no crash can happen ahead of the handler. A failure+ // here is a warning: it never blocks boot.+ try {+ app.setPath("crashDumps", ensureCrashDumpsDirectory(deps.dataDir));+ crashReporter.start({ uploadToServer: false, productName: APP_NAME });+ } catch (error) {+ deps.logger.app("diagnostics", "warn", "crash reporter failed to start", {+ event: "crashReporterStartFailed",+ data: String(error),+ });+ }++void app.whenReady().then(async () => {const {hasSingleInstanceLock,@@ -162,37 +172,17 @@ export function registerApplicationStartup(deps: StartupDependencies): void {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),- });- }+ // A Chromium-process crash from a previous run left a minidump, and nothing+ // else would ever mention it. Report one durable line per new dump set,+ // classified by process type, then advance the marker. Reporting is+ // diagnostics: a failure warns and is dropped rather than holding up the+ // first window.+ reportPreviousCrashDumps({+ dataDir,+ crashDumpsDirectory: app.getPath("crashDumps"),+ logger,+ });+// 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.tsindex 3c33a6475..77a1e322b 100644--- a/apps/desktop/electron/main/crash-report.ts+++ b/apps/desktop/electron/main/crash-report.ts@@ -4,46 +4,92 @@* 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+ * scan, so a Chromium-process crash becomes one durable log line instead of* staying invisible.*+ * Crashpad collects dumps from every Chromium process it was started for+ * (main, renderer, GPU, utility), not only a main-process abort. A renderer+ * crash the app already recovered still leaves a dump; the next-launch line+ * therefore classifies dumps by Crashpad's `ptype` annotation and logs+ * recovered child crashes at warn rather than claiming the previous run died.+ ** 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.+ * would be silently useless. The dumps directory itself is relocated under+ * the installation data directory so a `PI_DESKTOP_DATA_DIR` profile does+ * not share dumps with another installation.** 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 { randomUUID } from "node:crypto";+import {+ closeSync,+ mkdirSync,+ openSync,+ readFileSync,+ readSync,+ readdirSync,+ renameSync,+ rmSync,+ statSync,+ writeFileSync,+} from "node:fs";+import type { Dirent } from "node:fs";import { join } from "node:path";+import type { Logger } from "./logger";/** 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";+/** Installation-local Crashpad root, under the data directory. */+export const CRASH_DUMPS_DIR_NAME = "crash-dumps";++export type CrashDumpProcessType =+ | "main"+ | "renderer"+ | "gpu"+ | "utility"+ | "unknown";+export type CrashDumpSummary = {/** Directory that was scanned. */directory: string;- /** Every `*.dmp` file found at or below `directory`. */+ /** Every `*.dmp` file that could be stated 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;+ /** Process types of dumps strictly newer than the marker. */+ newByProcessType: Partial<Record<CrashDumpProcessType, number>>;};+function isEnoent(error: unknown): boolean {+ return (+ typeof error === "object" &&+ error !== null &&+ "code" in error &&+ (error as { code: unknown }).code === "ENOENT"+ );+}+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;+ } catch (error) {+ // Crashpad has not created this directory yet: skip just this branch.+ // Any other failure (EACCES, ENOTDIR, EIO) is a real scan error.+ if (isEnoent(error)) return;+ throw error;}for (const entry of entries) {const path = join(directory, entry.name);@@ -55,11 +101,110 @@ function collectDumpPaths(directory: string, depth: number, found: string[]): vo}}+/**+ * Crashpad annotations are `MinidumpUTF8String` objects: a little-endian+ * `uint32` length, the bytes, then a NUL. Electron sets `ptype` to Chromium's+ * process name (`browser`, `renderer`, `gpu-process`, `utility`, …). Key and+ * value are separate objects, usually packed next to each other with up to+ * four bytes of padding. This is a bounded scan, not a minidump parser: a+ * miss reports `unknown` rather than guessing.+ */+function readMinidumpUtf8(+ contents: Buffer,+ offset: number,+): { value: string; bytes: number } | null {+ if (offset < 0 || offset + 5 > contents.length) return null;+ const length = contents.readUInt32LE(offset);+ if (length < 1 || length > 32) return null;+ const start = offset + 4;+ const nul = start + length;+ if (nul >= contents.length || contents[nul] !== 0) return null;+ const value = contents.toString("latin1", start, start + length);+ if (!/^[a-z][a-z0-9_-]{0,31}$/.test(value)) return null;+ return { value, bytes: 4 + length + 1 };+}++function encodeMinidumpUtf8Key(key: string): Buffer {+ const encoded = Buffer.alloc(4 + key.length + 1);+ encoded.writeUInt32LE(key.length, 0);+ encoded.write(key, 4, "latin1");+ encoded[4 + key.length] = 0;+ return encoded;+}++function readCrashpadAnnotation(contents: Buffer, key: string): string | null {+ const keyEncoded = encodeMinidumpUtf8Key(key);+ let from = 0;+ while (from <= contents.length - keyEncoded.length) {+ const idx = contents.indexOf(keyEncoded, from);+ if (idx < 0) return null;+ const afterKey = idx + keyEncoded.length;+ for (const pad of [0, 1, 2, 3, 4]) {+ const parsed = readMinidumpUtf8(contents, afterKey + pad);+ if (parsed) return parsed.value;+ }+ from = idx + 1;+ }+ return null;+}++function classifyProcessType(raw: string | null): CrashDumpProcessType {+ if (raw === "browser" || raw === "main") return "main";+ if (raw === "renderer") return "renderer";+ if (raw === "gpu" || raw === "gpu-process") return "gpu";+ if (+ raw === "utility" ||+ raw === "plugin" ||+ raw === "ppapi" ||+ raw === "zygote" ||+ raw === "sandbox"+ ) {+ return "utility";+ }+ return "unknown";+}++/** Head+tail is enough: CrashpadInfo is a stream, not guaranteed to be first. */+const ANNOTATION_SCAN_SLICE = 512 * 1024;++function readDumpForAnnotations(path: string): Buffer {+ const size = statSync(path).size;+ if (size <= ANNOTATION_SCAN_SLICE * 2) return readFileSync(path);+ const fd = openSync(path, "r");+ try {+ const head = Buffer.alloc(ANNOTATION_SCAN_SLICE);+ const tail = Buffer.alloc(ANNOTATION_SCAN_SLICE);+ readSync(fd, head, 0, ANNOTATION_SCAN_SLICE, 0);+ readSync(fd, tail, 0, ANNOTATION_SCAN_SLICE, size - ANNOTATION_SCAN_SLICE);+ return Buffer.concat([head, Buffer.alloc(4), tail]);+ } finally {+ closeSync(fd);+ }+}++function processTypeOfDump(path: string): CrashDumpProcessType {+ try {+ return classifyProcessType(readCrashpadAnnotation(readDumpForAnnotations(path), "ptype"));+ } catch {+ // Unreadable dump: still counted, but not guessed as main.+ return "unknown";+ }+}+++function incrementType(+ counts: Partial<Record<CrashDumpProcessType, number>>,+ type: CrashDumpProcessType,+): void {+ counts[type] = (counts[type] ?? 0) + 1;+}+/*** 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.+ * Permission and type errors propagate so a broken tree is observable.*/export function describeCrashDumps(directory: string,@@ -67,19 +212,26 @@ export function describeCrashDumps(): CrashDumpSummary {const found: string[] = [];collectDumpPaths(directory, MAX_DUMP_SCAN_DEPTH, found);+ let dumpCount = 0;let newDumpCount = 0;let newestMtimeMs: number | null = null;+ const newByProcessType: Partial<Record<CrashDumpProcessType, number>> = {};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+ } catch (error) {+ if (isEnoent(error)) continue; // removed between readdir and stat+ throw error;}- if (sinceMtimeMs === null || mtimeMs > sinceMtimeMs) newDumpCount += 1;+ dumpCount += 1;if (newestMtimeMs === null || mtimeMs > newestMtimeMs) newestMtimeMs = mtimeMs;+ if (sinceMtimeMs === null || mtimeMs > sinceMtimeMs) {+ newDumpCount += 1;+ incrementType(newByProcessType, processTypeOfDump(path));+ }}- return { directory, dumpCount: found.length, newDumpCount, newestMtimeMs };+ return { directory, dumpCount, newDumpCount, newestMtimeMs, newByProcessType };}export type CrashDumpMarker = { newestMtimeMs: number };@@ -101,17 +253,80 @@ export function readCrashDumpMarker(dataDir: string): CrashDumpMarker | 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.+ * which is better than turning a diagnostic into a boot failure. The write is+ * temp-plus-rename so a crash mid-write cannot truncate a previously good+ * marker into malformed JSON.*/export function writeCrashDumpMarker(dataDir: string, newestMtimeMs: number): void {try {mkdirSync(dataDir, { recursive: true });- writeFileSync(- join(dataDir, CRASH_DUMP_MARKER_FILE),- JSON.stringify({ newestMtimeMs }),- "utf8",- );+ const destination = join(dataDir, CRASH_DUMP_MARKER_FILE);+ const temporary = `${destination}.${randomUUID()}.tmp`;+ try {+ writeFileSync(temporary, JSON.stringify({ newestMtimeMs }), {+ encoding: "utf8",+ mode: 0o600,+ });+ renameSync(temporary, destination);+ } finally {+ rmSync(temporary, { force: true });+ }} catch {// best-effort persistence}}++export function crashDumpsDirectory(dataDir: string): string {+ return join(dataDir, CRASH_DUMPS_DIR_NAME);+}++/** Create the installation-local Crashpad root and return it. */+export function ensureCrashDumpsDirectory(dataDir: string): string {+ const directory = crashDumpsDirectory(dataDir);+ mkdirSync(directory, { recursive: true });+ return directory;+}++/**+ * One diagnostics line per new dump set, then advance the marker. A failure+ * here is a warning: it never blocks the first window.+ */+export function reportPreviousCrashDumps(input: {+ dataDir: string;+ crashDumpsDirectory: string;+ logger: Pick<Logger, "app">;+}): void {+ try {+ const crashDumpMarker = readCrashDumpMarker(input.dataDir)?.newestMtimeMs ?? null;+ const crashDumps = describeCrashDumps(input.crashDumpsDirectory, crashDumpMarker);+ if (crashDumps.newDumpCount > 0) {+ const level = (crashDumps.newByProcessType.main ?? 0) > 0 ? "error" : "warn";+ input.logger.app(+ "diagnostics",+ level,+ "crash dumps found from a previous process crash",+ {+ event: "crashDumpsFound",+ data: {+ count: crashDumps.newDumpCount,+ total: crashDumps.dumpCount,+ byProcessType: crashDumps.newByProcessType,+ directory: crashDumps.directory,+ newestMtimeMs: crashDumps.newestMtimeMs,+ },+ },+ );+ }+ if (+ crashDumps.newestMtimeMs !== null &&+ (crashDumpMarker === null || crashDumps.newestMtimeMs > crashDumpMarker)+ ) {+ writeCrashDumpMarker(input.dataDir, crashDumps.newestMtimeMs);+ }+ } catch (error) {+ input.logger.app("diagnostics", "warn", "crash dump report failed", {+ event: "crashDumpReportFailed",+ data: String(error),+ });+ }+}diff --git a/apps/desktop/test/crash-report-surface.test.mjs b/apps/desktop/test/crash-report-surface.test.mjsindex fc0a81c4a..de250ceb5 100644--- a/apps/desktop/test/crash-report-surface.test.mjs+++ b/apps/desktop/test/crash-report-surface.test.mjs@@ -2,7 +2,9 @@ import assert from "node:assert/strict";import {mkdirSync,mkdtempSync,+ readdirSync,rmSync,+ statSync,utimesSync,writeFileSync,} from "node:fs";@@ -11,17 +13,21 @@ import { dirname, join } from "node:path";import test from "node:test";import {CRASH_DUMP_MARKER_FILE,+ CRASH_DUMPS_DIR_NAME,describeCrashDumps,+ ensureCrashDumpsDirectory,readCrashDumpMarker,+ reportPreviousCrashDumps,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).+ * Crash collection has two halves: the scan/marker/report path below,+ * exercised against real files in a temp directory, and the main-process+ * wiring that starts Crashpad, held to the properties a behavior test cannot+ * observe without Electron (local-only reporter, dumps under dataDir, start+ * before ready).*/const startupSource = await readMainModule("bootstrap/startup.ts");const mainIndexSource = await readMainModule("index.ts");@@ -35,24 +41,65 @@ test.after(() => {const SECOND = 1_000;const BASE_MS = 1_700_000_000_000;-function makeDump(path, mtimeMs) {+function encodeMinidumpUtf8(s) {+ const buf = Buffer.alloc(4 + s.length + 1);+ buf.writeUInt32LE(s.length, 0);+ buf.write(s, 4, "ascii");+ buf[4 + s.length] = 0;+ return buf;+}++function crashpadDump(ptype, padBytes = 0) {+ return Buffer.concat([+ Buffer.from("MDMP"),+ encodeMinidumpUtf8("ptype"),+ Buffer.alloc(padBytes),+ encodeMinidumpUtf8(ptype),+ ]);+}++function makeDump(path, mtimeMs, contents) {mkdirSync(dirname(path), { recursive: true });- writeFileSync(path, "minidump");+ const body =+ contents === undefined+ ? Buffer.from("minidump")+ : Buffer.isBuffer(contents)+ ? contents+ : crashpadDump(contents);+ writeFileSync(path, body);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"),+function loggerSpy() {+ const records = [];+ return {+ records,+ logger: {+ app(category, level, message, fields) {+ records.push({ category, level, message, fields });+ },+ },+ };+}++function emptySummary(directory) {+ return {+ directory,dumpCount: 0,newDumpCount: 0,newestMtimeMs: null,- });+ newByProcessType: {},+ };+}++test("a crashDumps directory that does not exist yet reports nothing", () => {+ const summary = describeCrashDumps(join(parentDir, "never-created"));+ assert.deepEqual(summary, emptySummary(join(parentDir, "never-created")));});test("dumps are found under Crashpad's nested reports/ layout, and only .dmp files", () => {@@ -70,6 +117,7 @@ test("dumps are found under Crashpad's nested reports/ layout, and only .dmp filassert.equal(summary.dumpCount, 3);assert.equal(summary.newDumpCount, 3);assert.equal(summary.newestMtimeMs, BASE_MS + 60 * SECOND);+ assert.deepEqual(summary.newByProcessType, { unknown: 3 });});test("a crash is reported once: the marker suppresses the repeat on the next launch", () => {@@ -90,6 +138,7 @@ test("a crash is reported once: the marker suppresses the repeat on the next lauconst secondScan = describeCrashDumps(root, storedMarkerMtime(dataDir));assert.equal(secondScan.dumpCount, 2);assert.equal(secondScan.newDumpCount, 0);+ assert.deepEqual(secondScan.newByProcessType, {});// A later crash is reported again, on the launch after it.makeDump(join(root, "reports", "crashed-again.dmp"), BASE_MS + 360 * SECOND);@@ -98,13 +147,20 @@ test("a crash is reported once: the marker suppresses the repeat on the next lauassert.equal(afterNewCrash.newestMtimeMs, BASE_MS + 360 * SECOND);});-test("the marker round-trips through the data-dir JSON store", () => {+test("the marker round-trips through the data-dir JSON store without leftover temps", () => {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");+ assert.deepEqual(+ readdirSync(dataDir).filter((name) => name.startsWith("crash-dumps")),+ [CRASH_DUMP_MARKER_FILE],+ );+ if (process.platform !== "win32") {+ assert.equal(statSync(join(dataDir, CRASH_DUMP_MARKER_FILE)).mode & 0o777, 0o600);+ }writeFileSync(join(dataDir, CRASH_DUMP_MARKER_FILE), "{ not json");assert.equal(readCrashDumpMarker(dataDir), null);@@ -112,11 +168,157 @@ test("the marker round-trips through the data-dir JSON store", () => {assert.equal(readCrashDumpMarker(dataDir), null);});-test("startup starts Crashpad local-only, before ready", () => {+test("ptype annotations classify Chromium process dumps", () => {+ const root = join(parentDir, "ptype");+ makeDump(join(root, "reports", "main.dmp"), BASE_MS, "browser");+ makeDump(join(root, "reports", "renderer.dmp"), BASE_MS + SECOND, "renderer");+ makeDump(join(root, "reports", "gpu.dmp"), BASE_MS + 2 * SECOND, "gpu-process");+ makeDump(join(root, "reports", "utility.dmp"), BASE_MS + 3 * SECOND, "utility");+ makeDump(join(root, "reports", "plain.dmp"), BASE_MS + 4 * SECOND);+ // A substring must not count as the key.+ mkdirSync(join(root, "reports"), { recursive: true });+ writeFileSync(+ join(root, "reports", "decoy-key.dmp"),+ Buffer.from("MDMP\0notptype\0renderer\0", "latin1"),+ );+ utimesSync(+ join(root, "reports", "decoy-key.dmp"),+ new Date(BASE_MS + 5 * SECOND),+ new Date(BASE_MS + 5 * SECOND),+ );++ const summary = describeCrashDumps(root);+ assert.equal(summary.dumpCount, 6);+ assert.deepEqual(summary.newByProcessType, {+ main: 1,+ renderer: 1,+ gpu: 1,+ utility: 1,+ unknown: 2,+ });+});+++test("Crashpad length-prefixed ptype survives padding; a C-string decoy does not classify", () => {+ const root = join(parentDir, "ptype-format");+ makeDump(join(root, "padded.dmp"), BASE_MS, crashpadDump("browser", 2));+ makeDump(+ join(root, "cstring.dmp"),+ BASE_MS + SECOND,+ Buffer.from("MDMP\0ptype\0browser\0", "latin1"),+ );+ const summary = describeCrashDumps(root);+ assert.deepEqual(summary.newByProcessType, { main: 1, unknown: 1 });+});++test("an unclassified dump is a warning, and a failed scan does not advance the marker", () => {+ const unknownRoot = join(parentDir, "unknown-only");+ const unknownData = join(parentDir, "unknown-only-data");+ makeDump(join(unknownRoot, "plain.dmp"), BASE_MS);+ const unknown = loggerSpy();+ reportPreviousCrashDumps({+ dataDir: unknownData,+ crashDumpsDirectory: unknownRoot,+ logger: unknown.logger,+ });+ assert.equal(unknown.records[0].level, "warn");+ assert.equal(unknown.records[0].fields.event, "crashDumpsFound");+ assert.equal(unknown.records[0].category, "diagnostics");++ const failedData = join(parentDir, "failed-marker-data");+ mkdirSync(failedData, { recursive: true });+ const notADir = join(parentDir, "failed-marker-not-dir");+ writeFileSync(notADir, "file");+ const failed = loggerSpy();+ reportPreviousCrashDumps({+ dataDir: failedData,+ crashDumpsDirectory: notADir,+ logger: failed.logger,+ });+ assert.equal(failed.records[0].fields.event, "crashDumpReportFailed");+ assert.equal(readCrashDumpMarker(failedData), null);++});++test("a recovered renderer dump is a warning; a main dump is an error", () => {+ const rendererRoot = join(parentDir, "report-renderer");+ const rendererData = join(parentDir, "report-renderer-data");+ makeDump(join(rendererRoot, "reports", "renderer.dmp"), BASE_MS, "renderer");+ const renderer = loggerSpy();+ reportPreviousCrashDumps({+ dataDir: rendererData,+ crashDumpsDirectory: rendererRoot,+ logger: renderer.logger,+ });+ assert.equal(renderer.records.length, 1);+ assert.equal(renderer.records[0].level, "warn");+ assert.equal(renderer.records[0].fields.event, "crashDumpsFound");+ assert.deepEqual(renderer.records[0].fields.data.byProcessType, { renderer: 1 });+ assert.equal(storedMarkerMtime(rendererData), BASE_MS);++ // Same dumps on the next launch: no repeat.+ const second = loggerSpy();+ reportPreviousCrashDumps({+ dataDir: rendererData,+ crashDumpsDirectory: rendererRoot,+ logger: second.logger,+ });+ assert.equal(second.records.length, 0);++ const mainRoot = join(parentDir, "report-main");+ const mainData = join(parentDir, "report-main-data");+ makeDump(join(mainRoot, "reports", "main.dmp"), BASE_MS, "browser");+ makeDump(join(mainRoot, "reports", "renderer.dmp"), BASE_MS + SECOND, "renderer");+ const main = loggerSpy();+ reportPreviousCrashDumps({+ dataDir: mainData,+ crashDumpsDirectory: mainRoot,+ logger: main.logger,+ });+ assert.equal(main.records[0].level, "error");+ assert.equal(+ main.records[0].message,+ "crash dumps found from a previous process crash",+ );+ assert.deepEqual(main.records[0].fields.data.byProcessType, { main: 1, renderer: 1 });+});++test("a scan that is not a missing directory is reported, and never thrown", () => {+ const notADir = join(parentDir, "not-a-crash-dir");+ writeFileSync(notADir, "this is a file");+ assert.throws(() => describeCrashDumps(notADir));++ const spy = loggerSpy();+ reportPreviousCrashDumps({+ dataDir: join(parentDir, "not-a-crash-data"),+ crashDumpsDirectory: notADir,+ logger: spy.logger,+ });+ assert.equal(spy.records.length, 1);+ assert.equal(spy.records[0].level, "warn");+ assert.equal(spy.records[0].fields.event, "crashDumpReportFailed");+});++test("ensureCrashDumpsDirectory is the installation-local Crashpad root", () => {+ const dataDir = join(parentDir, "install-data");+ const directory = ensureCrashDumpsDirectory(dataDir);+ assert.equal(directory, join(dataDir, CRASH_DUMPS_DIR_NAME));+ assert.equal(statSync(directory).isDirectory(), true);+});++test("startup starts Crashpad local-only, under dataDir, before ready", () => {assert.match(startupSource, /crashReporter\.start\(\{\s*uploadToServer: false,/);assert.match(startupSource, /productName: APP_NAME/);+ assert.match(+ startupSource,+ /app\.setPath\(\s*"crashDumps",\s*ensureCrashDumpsDirectory\(deps\.dataDir\)\s*\)/,+ );+ assert.match(startupSource, /try \{\s*app\.setPath\(\s*"crashDumps"/);+ assert.match(startupSource, /event: "crashReporterStartFailed"/);+ const setAt = startupSource.indexOf('app.setPath("crashDumps"');const startAt = startupSource.indexOf("crashReporter.start(");- assert.ok(startAt > 0, "startup must start the crash reporter");+ assert.ok(setAt > 0, "startup must relocate the crash dumps directory");+ assert.ok(setAt < startAt, "the dumps path must be set before the reporter starts");assert.ok(startAt < startupSource.indexOf("app.whenReady()"),"the reporter must start before the app is ready",@@ -125,24 +327,12 @@ test("startup starts Crashpad local-only, before ready", () => {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.+test("startup reports new crash dumps after the single-instance lock", () => {assert.match(startupSource,- /logger\.app\(\s*"diagnostics",\s*"warn",\s*"crash dump report failed"/,+ /reportPreviousCrashDumps\(\{\s*dataDir,\s*crashDumpsDirectory:\s*app\.getPath\(\s*"crashDumps"\s*\),\s*logger,/,);+ const lockAt = startupSource.indexOf("if (!hasSingleInstanceLock) return;");+ const reportAt = startupSource.indexOf("reportPreviousCrashDumps(");+ assert.ok(lockAt > 0 && reportAt > lockAt, "only the lock holder reports dumps");});diff --git a/docs/privacy-policy.md b/docs/privacy-policy.mdindex d9e31f880..aaca383ff 100644--- a/docs/privacy-policy.md+++ b/docs/privacy-policy.md@@ -1,6 +1,6 @@# Privacy Policy-**Effective date: 2026-09-10**+**Effective date: 2026-09-20**This Privacy Policy describes how PI-Desktop handles information when you usethe PI-Desktop desktop application. PI-Desktop is a local-first, open-source@@ -22,7 +22,7 @@ processing.- Projects, sessions, settings, transcripts, and application logs are storedlocally by default.- PI-Desktop does not currently operate a remote telemetry pipeline or cloud- crash-analytics service.+ crash-analytics service. Crash minidumps stay on this machine.- Your prompts, files, tool results, and other content may be sent to the modelprovider, gateway, local model server, plugin, or MCP server that you chooseor invoke.@@ -43,6 +43,8 @@ computer:encrypted local secret store and are not shown in the UI;- plugin code, plugin settings, plugin-owned data, and plugin logs;- application, host, agent, and audit logs;+- local Crashpad minidumps of Chromium processes (main, renderer, GPU,+ utility) under the data directory, never uploaded;- temporary files, caches, review snapshots, and other operational data; and- a bounded in-memory clipboard history containing explicit clipboard writesand user-initiated paste events. It may retain up to 500 entries or 256 MB for@@ -157,6 +159,8 @@ backup, and operating-system behavior.files.- Application, host, and agent logs are size-capped and rotated. Audit recordsare retained locally and normally pruned after 90 days.+- Crashpad minidumps remain in the data directory until you delete them; they+ are never uploaded.- Temporary session scratch data is removed with the session, and disposablecaches may be recreated or removed during maintenance.- Provider credentials remain until you remove the provider or credential,diff --git a/docs/spec/03-runtime/04-data-storage.md b/docs/spec/03-runtime/04-data-storage.mdindex b3b5dc255..0b3258fb4 100644--- a/docs/spec/03-runtime/04-data-storage.md+++ b/docs/spec/03-runtime/04-data-storage.md@@ -69,6 +69,8 @@ to an absolute path before it reaches host-core as a child-process variable.├── plugins/ # code + data + registry.json (unchanged, spec 07-11)├── logs/ # NDJSON app/<category>, host/<category>, agent/<category> logs├── cache/ # disposable caches+ ├── crash-dumps/ # local Crashpad minidumps (never uploaded; D602)+ ├── crash-dumps.json # last-reported dump mtime (best-effort marker)├── review-changes/<sessionId>/<snapshotId>/│ ├── before # bounded pre-tool bytes, when reversible│ └── meta.json # path, hashes, diff state, and ownership@@ -80,6 +82,8 @@ to an absolute path before it reaches host-core as a child-process variable.```One database file keeps cross-entity writes transactional (e.g. session ++turn + artifact in one commit). The DB stores **no large payloads**: message+turn + artifact in one commit). The DB stores **no large payloads**: messagecontent lives in `sessions/`, attachments and tool outputs beyond the limitsof [16-tool-result-limits](16-tool-result-limits.md) live on disk, referenceddiff --git a/docs/spec/03-runtime/07-process-model.md b/docs/spec/03-runtime/07-process-model.mdindex b629e8c18..97759e26e 100644--- a/docs/spec/03-runtime/07-process-model.md+++ b/docs/spec/03-runtime/07-process-model.md@@ -84,6 +84,16 @@ errors remain readable instead of becoming replacement characters.| 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 || Electron main crash | full app exit |+Crashpad is started local-only (`uploadToServer: false`) before `ready`, and+dumps are stored under `<data_dir>/crash-dumps` (D602) so a+`PI_DESKTOP_DATA_DIR` profile does not share dumps with another installation.+The next launch that holds the single-instance lock writes one diagnostics+line for dumps newer than `crash-dumps.json`. Crashpad records+Chromium-process crashes (main, renderer, GPU, utility); a renderer crash the+app already recovered still leaves a dump and is logged at warn. Host-core and+sidecar crashes stay on the supervisor path in this section and the `host` /+`agent` log channels.+Broken stdout/stderr (`EPIPE`/`EIO`) is not a main-process crash. Main ignoresthose writes so a Linux AppImage or GUI launch without a live TTY keepssupervising host/sidecar instead of showing Electron's uncaught exceptiondiff --git a/docs/spec/03-runtime/09-logging-and-observability.md b/docs/spec/03-runtime/09-logging-and-observability.mdindex 54d3299c0..13cd81fe6 100644--- a/docs/spec/03-runtime/09-logging-and-observability.md+++ b/docs/spec/03-runtime/09-logging-and-observability.md@@ -75,7 +75,13 @@ The application categories are:(ADR 0272). The record carries the host name, the address it resolved to, thatclass and that route — never the URL, its path, query or credentials — because acatalog source URL is user-supplied and the refused host and address are the- whole diagnostic value (issue #419).+ whole diagnostic value (issue #419). After a Chromium-process crash, the next+ launch writes one `crashDumpsFound` record (`error` if any new dump is the+ browser/main process, `warn` otherwise) with `count`, `total`,+ `byProcessType`, `directory`, and `newestMtimeMs`. A recovered renderer crash+ is therefore not reported as the previous app run aborting. A scan failure is+ one `crashDumpReportFailed` warn and never blocks the first window (D602).+- `runtime` — host/sidecar lifecycle, uncategorized child output, andmain-process `uncaughtException` / `unhandledRejection` records@@ -202,9 +208,12 @@ There is no remote telemetry pipeline or cloud crash analytics in the MVP.- app/host/agent category logs: rotate each category file at 5 MB and keep tworotated files beside it (`<category>.1.log`, `<category>.2.log`);- audit log (SQLite): retained with the database and pruned according to the- host retention policy; and+ host retention policy;+- Crashpad minidumps in `<data_dir>/crash-dumps` are not rotated by the+ logger; they remain until the user deletes them; and- rotation and logging failures must never fail the caller.+Session transcripts are user data and are not deleted by log rotation.## 10. Acceptancediff --git a/docs/spec/08-meta/decisions-log.md b/docs/spec/08-meta/decisions-log.mdindex 08cad88cd..ede070476 100644--- a/docs/spec/08-meta/decisions-log.md+++ b/docs/spec/08-meta/decisions-log.md@@ -303,6 +303,8 @@ Gold source: local Codex electron captures; latest row wins where rows conflict.| D278 | Subagent model selection | **Task.model overrides definition pin; only models with `availableForSubagents` appear in the delegation catalog; on-demand RPC resolves models not pre-resolved at launch** | The parent agent needs per-task model choice without exposing the full provider configuration. An opt-in flag keeps the delegation catalog bounded and intentional, and on-demand resolution avoids stale bindings for models added after sidecar launch. See §3/02 §5f, §3/11 §7, and E2E-166. || D365 | Named quiet intervals on the live activity row | **Amend D338 / ADR 0175: `AgentActivity` adds `preparing`, `compacting`, and `recovering`; `starting` shows its own label; `waiting-subagents` carries a live running snapshot (`name`, `lastPhase`, `lastToolName`) that updates on child tool/thinking changes, not on every token. The row stays one compact inline status and does not restore an activity-group capsule.** | Compaction, silent-turn recovery, the post-tool gap, and startup all looked like a stuck generic wait, and a parent wait hid what its delegates were doing (ADR 0198, E2E-008c / E2E-094) || D599 | A development build is its own installation | **Narrow D236 / amend ADR 0094: a development build (unpackaged, or `PI_DESKTOP_DEV=1`) takes `PI-Desktop Dev` as its Electron `userData` — and with it the single-instance lock, renderer `localStorage`, the plugin panel partitions, and browser pane cookies — and reads `~/.pi-desktop-dev`. An explicit `--user-data-dir` still wins, which is how the E2E harnesses point a build at a throwaway profile. A packaged installation keeps `PI-Desktop` and `~/.pi-desktop`, so no existing profile is relocated. `PI_DESKTOP_DATA_DIR` still overrides either profile and is made absolute before it reaches host-core as a child-process environment variable; Electron main publishes the resolved directory back to that variable so the plugin runtime reads one root. No IPC, protocol, schema, or packaged-installation path change. See `03-runtime/07-process-model.md` and E2E-150.** | A packaged app that was already running held the lock, so `pnpm dev` quit on arrival; a development host that won the race instead put a second host-core over the same single-writer `pi.sqlite`, the outbox, and the log tree. |+| D602 | Crash dumps stay in the data directory | **Electron's Crashpad reporter starts local-only (`uploadToServer: false`) before `ready`. Dumps live under `<data_dir>/crash-dumps`, not the default Electron `userData` crashDumps path, so a `PI_DESKTOP_DATA_DIR` profile does not share dumps. The next lock-holding launch writes one `diagnostics` line for dumps newer than `crash-dumps.json`, classified by Crashpad `ptype`: `error` if any new dump is the browser/main process, `warn` for recovered renderer/GPU/utility crashes. Host-core and sidecar crashes stay on the supervisor path. No upload, no IPC, no schema change.** | A crash left a minidump nobody read. Crashpad also records recovered renderer crashes, so a next-launch `error` that said the previous run died was a lie; and dumps outside the data directory escaped `PI_DESKTOP_DATA_DIR` isolation. |+## M0. Model catalog decisions@@ -6437,3 +6439,21 @@ that was sitting at the bottom — including after the turn had finished.- No IPC channel, host protocol, storage schema, persisted setting, or i18n keychanged: every sentence keeps its key and only its placement moved. See`04-ux/06-settings-ia.md` and `04-ux/07-ui-design-system.md`.++## 2026-09-20 — Crash dumps stay in the data directory (D602)++- Crashpad starts local-only (`uploadToServer: false`) before `ready`. Dumps+ live under `<data_dir>/crash-dumps`, not Electron's default `userData`+ crashDumps path, so a `PI_DESKTOP_DATA_DIR` profile does not share dumps+ with another installation. The marker `crash-dumps.json` records the newest+ mtime already reported.+- The next lock-holding launch writes one `diagnostics` line for dumps newer+ than that marker, classified by Crashpad's `ptype` annotation: `error` if+ any new dump is the browser/main process, `warn` for a recovered renderer,+ GPU, or utility crash. A scan failure is one `crashDumpReportFailed` warn+ and never blocks the first window.+- Host-core and sidecar crashes stay on the supervisor path and the `host` /+ `agent` log channels. Nothing is uploaded. See+ `03-runtime/07-process-model.md` §4, `03-runtime/09-logging-and-observability.md`,+ and `03-runtime/04-data-storage.md`.+