Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

feat(diagnostics): capture the JS stack of a hung renderer (MUL-5345) (#6026)

Naiyuan Qing420ffe7dbc02
diff --git a/apps/desktop/src/main/diagnostics-control-registry.test.ts b/apps/desktop/src/main/diagnostics-control-registry.test.ts
new file mode 100644
index 0000000000..5e4e6beaaa
--- /dev/null
+++ b/apps/desktop/src/main/diagnostics-control-registry.test.ts
@@ -0,0 +1,103 @@
+/**
+ * Review finding (MUL-5345): a single global control value does not survive
+ * multiple windows. Every renderer publishes `false` before its config lands,
+ * so with one shared value a window opened while capture was on would either
+ * never warm (the global value never changed) or would cool every other
+ * window on its way up. Both are pinned here.
+ */
+import { describe, expect, it, vi } from "vitest";
+
+import { createDiagnosticsControlRegistry } from "./diagnostics-control-registry";
+
+function setup() {
+ const warm = vi.fn();
+ const cool = vi.fn();
+ const registry = createDiagnosticsControlRegistry<object>({ warm, cool });
+ // Stand-ins for webContents; identity is all the registry uses.
+ return { registry, warm, cool, mainWindow: {}, issueWindow: {} };
+}
+
+describe("per-renderer control", () => {
+ it("warms a newly opened window even though another window is already on", () => {
+ const { registry, warm, mainWindow, issueWindow } = setup();
+ registry.apply(mainWindow, { stackCaptureEnabled: true });
+ warm.mockClear();
+
+ // The new window boots, publishes its pre-config default, then the real
+ // value. A global flag would have swallowed this as "no change".
+ registry.apply(issueWindow, { stackCaptureEnabled: false });
+ registry.apply(issueWindow, { stackCaptureEnabled: true });
+
+ expect(warm).toHaveBeenCalledTimes(1);
+ expect(warm).toHaveBeenCalledWith(issueWindow);
+ expect(registry.isStackCaptureEnabled(issueWindow)).toBe(true);
+ });
+
+ it("does not let a new window's pre-config default revoke another window", () => {
+ const { registry, cool, mainWindow, issueWindow } = setup();
+ registry.apply(mainWindow, { stackCaptureEnabled: true });
+
+ registry.apply(issueWindow, { stackCaptureEnabled: false });
+
+ expect(cool).not.toHaveBeenCalledWith(mainWindow);
+ expect(registry.isStackCaptureEnabled(mainWindow)).toBe(true);
+ expect(registry.isStackCaptureEnabled(issueWindow)).toBe(false);
+ });
+
+ it("cools only the window that revoked", () => {
+ const { registry, cool, mainWindow, issueWindow } = setup();
+ registry.apply(mainWindow, { stackCaptureEnabled: true });
+ registry.apply(issueWindow, { stackCaptureEnabled: true });
+
+ registry.apply(mainWindow, { stackCaptureEnabled: false });
+
+ expect(cool).toHaveBeenCalledTimes(1);
+ expect(cool).toHaveBeenCalledWith(mainWindow);
+ expect(registry.isStackCaptureEnabled(issueWindow)).toBe(true);
+ });
+
+ it("does not re-warm a window that repeats the same value", () => {
+ const { registry, warm, mainWindow } = setup();
+ registry.apply(mainWindow, { stackCaptureEnabled: true });
+ registry.apply(mainWindow, { stackCaptureEnabled: true });
+
+ expect(warm).toHaveBeenCalledTimes(1);
+ });
+
+ it("does not cool a window that was never warm", () => {
+ const { registry, cool, mainWindow } = setup();
+ registry.apply(mainWindow, { stackCaptureEnabled: false });
+
+ expect(cool).not.toHaveBeenCalled();
+ });
+});
+
+describe("fail-closed", () => {
+ it("starts disabled for a renderer that has never reported", () => {
+ const { registry, mainWindow } = setup();
+ expect(registry.isStackCaptureEnabled(mainWindow)).toBe(false);
+ });
+
+ it.each([
+ ["a malformed payload", { stackCaptureEnabled: "true" }],
+ ["null", null],
+ ["undefined", undefined],
+ ["an empty object", {}],
+ ])("treats %s as off", (_label, payload) => {
+ const { registry, warm, mainWindow } = setup();
+ registry.apply(mainWindow, payload);
+
+ expect(warm).not.toHaveBeenCalled();
+ expect(registry.isStackCaptureEnabled(mainWindow)).toBe(false);
+ });
+
+ it("revokes when a warm renderer later sends garbage", () => {
+ const { registry, cool, mainWindow } = setup();
+ registry.apply(mainWindow, { stackCaptureEnabled: true });
+
+ registry.apply(mainWindow, "nonsense");
+
+ expect(cool).toHaveBeenCalledWith(mainWindow);
+ expect(registry.isStackCaptureEnabled(mainWindow)).toBe(false);
+ });
+});
diff --git a/apps/desktop/src/main/diagnostics-control-registry.ts b/apps/desktop/src/main/diagnostics-control-registry.ts
new file mode 100644
index 0000000000..fa7d64b146
--- /dev/null
+++ b/apps/desktop/src/main/diagnostics-control-registry.ts
@@ -0,0 +1,58 @@
+import {
+ parseDiagnosticsControl,
+ type DiagnosticsControl,
+} from "../shared/diagnostics-control";
+
+/**
+ * Which renderers are allowed to be interrogated, tracked per renderer.
+ *
+ * A single global flag looked right — the value is one server-side switch, so
+ * every renderer reports the same thing — but it does not survive multiple
+ * windows. Every renderer publishes `false` before its config arrives, so a
+ * window opened while capture was already on would either be skipped (the
+ * global value never changed, so nothing warmed it) or, worse, would revoke
+ * capture for every other window on the way up. Windows come and go
+ * independently, so the state has to be per renderer.
+ *
+ * Each renderer therefore owns its own entry: its report warms or cools its
+ * own channel and nothing else. They converge on the same value because they
+ * read the same config, but they get there on their own schedules.
+ */
+export interface DiagnosticsControlRegistry<T> {
+ /** Apply a raw control payload from one renderer. Fail-closed on garbage. */
+ apply: (target: T, rawControl: unknown) => void;
+ /** Whether this renderer may currently be interrogated. */
+ isStackCaptureEnabled: (target: T) => boolean;
+}
+
+export interface DiagnosticsControlHandlers<T> {
+ /** Open the debugger channel for this renderer. */
+ warm: (target: T) => void;
+ /** Close the debugger channel for this renderer. */
+ cool: (target: T) => void;
+}
+
+export function createDiagnosticsControlRegistry<T extends object>({
+ warm,
+ cool,
+}: DiagnosticsControlHandlers<T>): DiagnosticsControlRegistry<T> {
+ // Keyed by the renderer itself, so a closed window's entry disappears with
+ // it rather than pinning the object alive.
+ const controls = new WeakMap<T, DiagnosticsControl>();
+
+ const enabled = (target: T) =>
+ controls.get(target)?.stackCaptureEnabled === true;
+
+ return {
+ apply(target, rawControl) {
+ const next = parseDiagnosticsControl(rawControl);
+ const was = enabled(target);
+ controls.set(target, next);
+ if (next.stackCaptureEnabled === was) return;
+ if (next.stackCaptureEnabled) warm(target);
+ else cool(target);
+ },
+
+ isStackCaptureEnabled: enabled,
+ };
+}
diff --git a/apps/desktop/src/main/freeze-breadcrumb.test.ts b/apps/desktop/src/main/freeze-breadcrumb.test.ts
index e24f3cc5c4..05ef0dcac6 100644
--- a/apps/desktop/src/main/freeze-breadcrumb.test.ts
+++ b/apps/desktop/src/main/freeze-breadcrumb.test.ts
@@ -5,8 +5,10 @@ import { join } from "node:path";
import {
writeFreezeBreadcrumb,
- readAndClearFreezeBreadcrumb,
+ readFreezeBreadcrumb,
+ ackFreezeBreadcrumb,
clearFreezeBreadcrumb,
+ FREEZE_BREADCRUMB_TTL_MS,
type FreezeBreadcrumb,
} from "./freeze-breadcrumb";
@@ -29,26 +31,22 @@ const sample: FreezeBreadcrumb = {
version: "0.3.1",
};
+// `now` inside the TTL for `sample`, so the age check isn't what a case is
+// accidentally exercising.
+const fresh = sample.ts + 1_000;
+
describe("freeze breadcrumb round-trip", () => {
it("writes then reads back the breadcrumb", () => {
const file = tempFile();
writeFreezeBreadcrumb(file, sample);
- expect(readAndClearFreezeBreadcrumb(file)).toEqual(sample);
- });
-
- it("read clears the file so a failure reports exactly once", () => {
- const file = tempFile();
- writeFreezeBreadcrumb(file, sample);
- expect(readAndClearFreezeBreadcrumb(file)).toEqual(sample);
- expect(existsSync(file)).toBe(false);
- expect(readAndClearFreezeBreadcrumb(file)).toBeNull();
+ expect(readFreezeBreadcrumb(file, fresh)).toEqual(sample);
});
it("clearFreezeBreadcrumb removes a pending breadcrumb (hang recovered)", () => {
const file = tempFile();
writeFreezeBreadcrumb(file, sample);
clearFreezeBreadcrumb(file);
- expect(readAndClearFreezeBreadcrumb(file)).toBeNull();
+ expect(readFreezeBreadcrumb(file, fresh)).toBeNull();
});
it("only lets the window that wrote a breadcrumb clear it", () => {
@@ -59,7 +57,67 @@ describe("freeze breadcrumb round-trip", () => {
expect(existsSync(file)).toBe(true);
clearFreezeBreadcrumb(file, "issue:2");
- expect(readAndClearFreezeBreadcrumb(file)).toBeNull();
+ expect(readFreezeBreadcrumb(file, fresh)).toBeNull();
+ });
+});
+
+// The whole point of splitting read from delete: a deterministic freeze means
+// the user reopens the app and hits the same content again seconds later. If
+// reading consumed the breadcrumb, that second hang would take the still-queued
+// event with it and the failure would never be reported (MUL-4115).
+describe("freeze breadcrumb survives an undelivered report", () => {
+ it("reading does not consume the breadcrumb", () => {
+ const file = tempFile();
+ writeFreezeBreadcrumb(file, sample);
+
+ expect(readFreezeBreadcrumb(file, fresh)).toEqual(sample);
+ expect(existsSync(file)).toBe(true);
+ // A boot that died before acknowledging still finds it next time.
+ expect(readFreezeBreadcrumb(file, fresh)).toEqual(sample);
+ });
+
+ it("ack with the matching ts retires the breadcrumb", () => {
+ const file = tempFile();
+ writeFreezeBreadcrumb(file, sample);
+
+ ackFreezeBreadcrumb(file, sample.ts);
+
+ expect(existsSync(file)).toBe(false);
+ expect(readFreezeBreadcrumb(file, fresh)).toBeNull();
+ });
+
+ it("a late ack does not delete a newer failure recorded since the read", () => {
+ const file = tempFile();
+ writeFreezeBreadcrumb(file, sample);
+ readFreezeBreadcrumb(file, fresh);
+
+ // Second hang overwrites the single slot before the first report acks.
+ const newer: FreezeBreadcrumb = { ...sample, ts: sample.ts + 5_000 };
+ writeFreezeBreadcrumb(file, newer);
+ ackFreezeBreadcrumb(file, sample.ts);
+
+ expect(readFreezeBreadcrumb(file, newer.ts + 1_000)).toEqual(newer);
+ });
+
+ it("ack on a missing file is a no-op, never throws", () => {
+ expect(() => ackFreezeBreadcrumb(tempFile(), 1)).not.toThrow();
+ });
+
+ it("drops a breadcrumb past the TTL instead of retrying it forever", () => {
+ const file = tempFile();
+ writeFreezeBreadcrumb(file, sample);
+
+ const expired = sample.ts + FREEZE_BREADCRUMB_TTL_MS + 1;
+ expect(readFreezeBreadcrumb(file, expired)).toBeNull();
+ expect(existsSync(file)).toBe(false);
+ });
+
+ it("keeps a breadcrumb that is exactly at the TTL boundary", () => {
+ const file = tempFile();
+ writeFreezeBreadcrumb(file, sample);
+
+ const boundary = sample.ts + FREEZE_BREADCRUMB_TTL_MS;
+ expect(readFreezeBreadcrumb(file, boundary)).toEqual(sample);
});
});
@@ -68,31 +126,55 @@ describe("freeze breadcrumb round-trip", () => {
// must never throw into boot. CLAUDE.md "API Response Compatibility".
describe("freeze breadcrumb defends against malformed input", () => {
it("returns null when no file exists", () => {
- expect(readAndClearFreezeBreadcrumb(tempFile())).toBeNull();
+ expect(readFreezeBreadcrumb(tempFile(), fresh)).toBeNull();
});
it("returns null on corrupt JSON", () => {
const file = tempFile();
writeFileSync(file, "{ not valid json", "utf8");
- expect(readAndClearFreezeBreadcrumb(file)).toBeNull();
+ expect(readFreezeBreadcrumb(file, fresh)).toBeNull();
});
it("returns null when `kind` is missing", () => {
const file = tempFile();
writeFileSync(file, JSON.stringify({ ts: 1, version: "x" }), "utf8");
- expect(readAndClearFreezeBreadcrumb(file)).toBeNull();
+ expect(readFreezeBreadcrumb(file, fresh)).toBeNull();
});
it("returns null when `kind` is the wrong type", () => {
const file = tempFile();
writeFileSync(file, JSON.stringify({ kind: 42, context: {} }), "utf8");
- expect(readAndClearFreezeBreadcrumb(file)).toBeNull();
+ expect(readFreezeBreadcrumb(file, fresh)).toBeNull();
});
it("returns null on a JSON null payload", () => {
const file = tempFile();
writeFileSync(file, "null", "utf8");
- expect(readAndClearFreezeBreadcrumb(file)).toBeNull();
+ expect(readFreezeBreadcrumb(file, fresh)).toBeNull();
+ });
+
+ // A malformed payload can never be acknowledged (the renderer never gets a
+ // ts for it), so it must be discarded on read or it becomes permanent boot
+ // noise.
+ it("deletes a malformed payload rather than retrying it every boot", () => {
+ const file = tempFile();
+ writeFileSync(file, "{ not valid json", "utf8");
+
+ readFreezeBreadcrumb(file, fresh);
+
+ expect(existsSync(file)).toBe(false);
+ });
+
+ it("drops a breadcrumb with a non-numeric ts (unackable)", () => {
+ const file = tempFile();
+ writeFileSync(
+ file,
+ JSON.stringify({ kind: "unresponsive", context: {}, ts: "nope" }),
+ "utf8",
+ );
+
+ expect(readFreezeBreadcrumb(file, fresh)).toBeNull();
+ expect(existsSync(file)).toBe(false);
});
it("clearing a non-existent file is a no-op, never throws", () => {
diff --git a/apps/desktop/src/main/freeze-breadcrumb.ts b/apps/desktop/src/main/freeze-breadcrumb.ts
index e49ec01239..a27bb481f9 100644
--- a/apps/desktop/src/main/freeze-breadcrumb.ts
+++ b/apps/desktop/src/main/freeze-breadcrumb.ts
@@ -5,11 +5,26 @@ import type { FreezeBreadcrumb } from "../shared/freeze-breadcrumb";
// itself — the thread is blocked or gone. The main process (always alive) is
// the only watcher that can react, but during the hang it can't reach the
// renderer's posthog-js either. So it writes a breadcrumb to disk; the next
-// time a renderer boots, it reads + clears the file and reports the event.
-// This survives even a force-quit, which is the whole point.
+// time a renderer boots, it reads the file and reports the event.
+//
+// Read and delete are deliberately SEPARATE steps. Reading used to delete in
+// the same call, which loses the report in exactly the case we care about
+// most: a deterministic freeze, where the user reopens the app and hits the
+// same content again within seconds. The event is still sitting in a JS batch
+// timer that the second hang kills, the process is force-quit, and the file is
+// already gone (MUL-4115: three hangs, zero events). Now the renderer reports
+// first and acknowledges after, so a failed attempt is simply retried on the
+// next boot.
export type { FreezeBreadcrumb };
+/**
+ * How long an unacknowledged breadcrumb keeps being retried. Without a bound,
+ * a client that can never deliver (analytics disabled, permanently offline)
+ * would re-report the same ancient failure on every launch forever.
+ */
+export const FREEZE_BREADCRUMB_TTL_MS = 7 * 24 * 60 * 60 * 1000;
+
/**
* Best-effort write. A breadcrumb we can't persist is lost, never fatal.
*
@@ -31,7 +46,7 @@ export function writeFreezeBreadcrumb(filePath: string, breadcrumb: FreezeBreadc
* Delete a persisted breadcrumb. Called when the renderer recovers from a hang
* (a `responsive` event after `unresponsive`): the breadcrumb was written
* pre-emptively while the thread was stuck, but since it came back, the
- * in-thread long-task watchdog already reports it — keeping the breadcrumb
+ * in-thread long-frame watchdog already reports it — keeping the breadcrumb
* would double-count it AND mislabel a recovered window as `recovered: false`.
* Best-effort; a stale breadcrumb only costs one duplicate report.
*/
@@ -54,22 +69,25 @@ export function clearFreezeBreadcrumb(filePath: string, ownerId?: string): void
}
/**
- * Read the breadcrumb and delete it in the same call, so a failure is reported
- * exactly once. Returns null when there's no breadcrumb (the normal case) or
- * when the file is unreadable / corrupt.
+ * Read the pending breadcrumb WITHOUT deleting it. Returns null when there is
+ * none (the normal case).
+ *
+ * Payloads that can never become a useful report are deleted here rather than
+ * retried: corrupt JSON, and anything older than the TTL. Everything else
+ * survives until `ackFreezeBreadcrumb`.
*/
-export function readAndClearFreezeBreadcrumb(filePath: string): FreezeBreadcrumb | null {
+export function readFreezeBreadcrumb(
+ filePath: string,
+ now = Date.now(),
+): FreezeBreadcrumb | null {
let raw: string;
try {
raw = readFileSync(filePath, "utf8");
} catch {
return null;
}
- try {
- rmSync(filePath, { force: true });
- } catch {
- // If we can't delete it we'd re-report next launch; acceptable over throwing.
- }
+
+ let breadcrumb: FreezeBreadcrumb | null = null;
try {
const parsed: unknown = JSON.parse(raw);
if (
@@ -77,10 +95,56 @@ export function readAndClearFreezeBreadcrumb(filePath: string): FreezeBreadcrumb
typeof parsed === "object" &&
typeof (parsed as FreezeBreadcrumb).kind === "string"
) {
- return parsed as FreezeBreadcrumb;
+ breadcrumb = parsed as FreezeBreadcrumb;
+ }
+ } catch {
+ // Corrupt JSON — fall through to the discard below.
+ }
+
+ if (!breadcrumb) {
+ discard(filePath);
+ return null;
+ }
+ if (isExpired(breadcrumb, now)) {
+ discard(filePath);
+ return null;
+ }
+ return breadcrumb;
+}
+
+/**
+ * Delete the breadcrumb the renderer just reported. The timestamp must match
+ * the stored one exactly: a hang that happened between the read and the ack
+ * has already overwritten the slot, and that newer failure must survive to be
+ * reported on the next boot.
+ */
+export function ackFreezeBreadcrumb(filePath: string, ts: number): void {
+ try {
+ const parsed = JSON.parse(readFileSync(filePath, "utf8")) as unknown;
+ if (
+ !parsed ||
+ typeof parsed !== "object" ||
+ (parsed as FreezeBreadcrumb).ts !== ts
+ ) {
+ return;
}
+ rmSync(filePath, { force: true });
+ } catch {
+ // Already gone / unreadable — nothing to acknowledge.
+ }
+}
+
+function isExpired(breadcrumb: FreezeBreadcrumb, now: number): boolean {
+ if (typeof breadcrumb.ts !== "number" || !Number.isFinite(breadcrumb.ts)) {
+ return true;
+ }
+ return now - breadcrumb.ts > FREEZE_BREADCRUMB_TTL_MS;
+}
+
+function discard(filePath: string): void {
+ try {
+ rmSync(filePath, { force: true });
} catch {
- // Corrupt JSON — drop.
+ // If we can't delete it we'd re-read it next launch; acceptable over throwing.
}
- return null;
}
diff --git a/apps/desktop/src/main/index.ts b/apps/desktop/src/main/index.ts
index 396e9f60a5..b71805ef38 100644
--- a/apps/desktop/src/main/index.ts
+++ b/apps/desktop/src/main/index.ts
@@ -28,9 +28,17 @@ import {
import { createBestEffortDevLog } from "./dev-log";
import {
writeFreezeBreadcrumb,
- readAndClearFreezeBreadcrumb,
+ readFreezeBreadcrumb,
+ ackFreezeBreadcrumb,
clearFreezeBreadcrumb,
} from "./freeze-breadcrumb";
+import {
+ captureHangStack,
+ coolDebuggerChannel,
+ warmDebuggerChannel,
+} from "./renderer-stack-capture";
+import { DIAGNOSTICS_CONTROL_CHANNEL } from "../shared/diagnostics-control";
+import { createDiagnosticsControlRegistry } from "./diagnostics-control-registry";
import {
loadWindowState,
resolveWindowOptions,
@@ -141,6 +149,36 @@ const rendererRouteContexts = new WeakMap<
Electron.WebContents,
RendererRouteContext
>();
+
+// Hang stack capture is off until the backend says otherwise, and stays off in
+// dev. Reading a stack means holding a debugger channel open on a renderer, so
+// it has to be revocable without shipping a release — the flag arrives with
+// /api/config, which is also why this cannot be decided at window creation: no
+// renderer has fetched config yet at that point.
+//
+// State is per renderer, not global: every window publishes `false` before its
+// own config lands, so one global value would let a newly opened window revoke
+// capture for the others (see diagnostics-control-registry).
+const diagnosticsControl = createDiagnosticsControlRegistry<Electron.WebContents>({
+ warm: (webContents) => {
+ if (is.dev || webContents.isDestroyed()) return;
+ void warmDebuggerChannel(webContents.debugger);
+ },
+ cool: (webContents) => {
+ if (webContents.isDestroyed()) return;
+ void coolDebuggerChannel(webContents.debugger);
+ },
+});
+
+/** Read the hung renderer's JS stack, or null when capture is not permitted. */
+async function captureStackIfEnabled(
+ webContents: Electron.WebContents,
+): Promise<unknown> {
+ if (is.dev) return null;
+ if (!diagnosticsControl.isStackCaptureEnabled(webContents)) return null;
+ if (webContents.isDestroyed()) return null;
+ return captureHangStack(webContents.debugger);
+}
let runtimeConfigResult: RuntimeConfigResult = {
ok: false,
error: { message: "Runtime config has not loaded yet" },
@@ -451,6 +489,7 @@ function createWindow(): BrowserWindow {
// Only persist in production: a true hang/crash can't report itself, so we
// write a breadcrumb and the next renderer boot flushes it to PostHog. Dev
// is excluded to keep field telemetry clean.
+ captureStack: () => captureStackIfEnabled(window.webContents),
persistBreadcrumb: is.dev
? undefined
: (payload) =>
@@ -534,6 +573,7 @@ function createIssueWindow(context: IssueWindowContext): void {
const routeContext = rendererRouteContexts.get(window.webContents);
return routeContext ? { desktopRoute: routeContext } : {};
},
+ captureStack: () => captureStackIfEnabled(window.webContents),
persistBreadcrumb: is.dev
? undefined
: (payload) =>
@@ -714,7 +754,24 @@ if (!gotTheLock) {
// reported when it happened — the renderer was hung or gone). Read-and-
// clear so a failure reports exactly once.
ipcMain.on("freeze:get-last", (event) => {
- event.returnValue = readAndClearFreezeBreadcrumb(freezeBreadcrumbPath());
+ event.returnValue = readFreezeBreadcrumb(freezeBreadcrumbPath());
+ });
+
+ // The renderer got its breadcrumb event to posthog — retire that exact
+ // payload. A newer failure recorded since the read keeps its own ts and
+ // survives to be reported on the next boot.
+ ipcMain.on("freeze:ack", (event, ts: unknown) => {
+ if (!BrowserWindow.fromWebContents(event.sender)) return;
+ if (typeof ts !== "number" || !Number.isFinite(ts)) return;
+ ackFreezeBreadcrumb(freezeBreadcrumbPath(), ts);
+ });
+
+ // Server-driven kill switch for stack capture. Fail-closed: anything that
+ // is not an explicit `true` turns it off, and turning it off also drops
+ // the debugger channels we are holding.
+ ipcMain.on(DIAGNOSTICS_CONTROL_CHANNEL, (event, control: unknown) => {
+ if (!BrowserWindow.fromWebContents(event.sender)) return;
+ diagnosticsControl.apply(event.sender, control);
});
// Sync IPC: preload exposes the validated runtime config before renderer
diff --git a/apps/desktop/src/main/renderer-recovery.test.ts b/apps/desktop/src/main/renderer-recovery.test.ts
index b4dda9d412..5de27083b4 100644
--- a/apps/desktop/src/main/renderer-recovery.test.ts
+++ b/apps/desktop/src/main/renderer-recovery.test.ts
@@ -269,3 +269,89 @@ describe("freeze/crash breadcrumb state machine", () => {
expect(persistBreadcrumb).not.toHaveBeenCalled();
});
});
+
+// The stack is the only field that names the code that blocked the thread, and
+// it can only be read while the thread is still stuck — so it is captured
+// before the breadcrumb is written, and a capture that fails must still leave
+// a reportable hang behind.
+describe("hang stack capture", () => {
+ beforeEach(() => vi.clearAllMocks());
+ afterEach(() => vi.useRealTimers());
+
+ function installWithCapture(
+ fixture: ReturnType<typeof makeWindow>,
+ captureStack: () => Promise<unknown>,
+ ) {
+ const persistBreadcrumb = vi.fn();
+ installRendererRecoveryHandlers(fixture.window, {
+ isDev: false,
+ showReloadPrompt: vi.fn(async () => "dismiss" as const),
+ persistBreadcrumb,
+ captureStack,
+ unresponsivePromptDelayMs: 100,
+ });
+ return { persistBreadcrumb };
+ }
+
+ const stack = [
+ { functionName: "parseMarkdownChunked", url: "assets/index-abc.js", lineNumber: 412, columnNumber: 17 },
+ ];
+
+ it("folds the captured stack into the hang report", async () => {
+ vi.useFakeTimers();
+ const fixture = makeWindow();
+ const { persistBreadcrumb } = installWithCapture(fixture, async () => stack);
+
+ fixture.windowHandlers.get("unresponsive")?.();
+ await vi.advanceTimersByTimeAsync(100);
+
+ expect(persistBreadcrumb).toHaveBeenCalledWith(
+ expect.objectContaining({
+ kind: "unresponsive",
+ context: expect.objectContaining({ stack }),
+ }),
+ );
+ });
+
+ it("still reports the hang when no stack could be captured", async () => {
+ vi.useFakeTimers();
+ const fixture = makeWindow();
+ const { persistBreadcrumb } = installWithCapture(fixture, async () => null);
+
+ fixture.windowHandlers.get("unresponsive")?.();
+ await vi.advanceTimersByTimeAsync(100);
+
+ expect(persistBreadcrumb).toHaveBeenCalledTimes(1);
+ const payload = persistBreadcrumb.mock.calls[0]?.[0] as {
+ context: Record<string, unknown>;
+ };
+ expect(payload.context).not.toHaveProperty("stack");
+ });
+
+ it("still reports the hang when the capture throws", async () => {
+ vi.useFakeTimers();
+ const fixture = makeWindow();
+ const { persistBreadcrumb } = installWithCapture(fixture, async () => {
+ throw new Error("debugger detached");
+ });
+
+ fixture.windowHandlers.get("unresponsive")?.();
+ await vi.advanceTimersByTimeAsync(100);
+
+ expect(persistBreadcrumb).toHaveBeenCalledTimes(1);
+ });
+
+ it("does not capture when the window recovers before the prompt delay", async () => {
+ vi.useFakeTimers();
+ const fixture = makeWindow();
+ const captureStack = vi.fn(async () => stack);
+ installWithCapture(fixture, captureStack);
+
+ fixture.windowHandlers.get("unresponsive")?.();
+ await vi.advanceTimersByTimeAsync(50);
+ fixture.windowHandlers.get("responsive")?.();
+ await vi.advanceTimersByTimeAsync(100);
+
+ expect(captureStack).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/desktop/src/main/renderer-recovery.ts b/apps/desktop/src/main/renderer-recovery.ts
index 2ad34b8634..61e4fefbea 100644
--- a/apps/desktop/src/main/renderer-recovery.ts
+++ b/apps/desktop/src/main/renderer-recovery.ts
@@ -33,6 +33,14 @@ type RendererRecoveryOptions = {
* process never recovers.
*/
clearBreadcrumb?: () => void;
+ /**
+ * Read the JS call stack out of the hung renderer. This is the only signal
+ * that says WHICH code blocked the thread — the in-thread watchdog reports a
+ * duration and the breadcrumb reports a route, but neither can name the
+ * function. Resolves to null whenever a stack can't be obtained; the hang is
+ * still reported without it. Omit in dev.
+ */
+ captureStack?: () => Promise<unknown>;
log?: (tag: string, ...args: unknown[]) => void;
unresponsivePromptDelayMs?: number;
};
@@ -47,6 +55,7 @@ export function installRendererRecoveryHandlers(
getDiagnosticContext,
persistBreadcrumb,
clearBreadcrumb,
+ captureStack,
log = noopDevLog,
unresponsivePromptDelayMs = 1500,
}: RendererRecoveryOptions,
@@ -95,16 +104,25 @@ export function installRendererRecoveryHandlers(
if (isDev || unresponsivePromptTimer) return;
unresponsivePromptTimer = setTimeout(() => {
unresponsivePromptTimer = null;
- const payload: ReloadPromptPayload = {
- kind: "unresponsive",
- context: mergeDiagnosticContext({}),
- };
- persistBreadcrumb?.(payload);
- unresponsiveBreadcrumbWritten = true;
- maybePromptReload(payload);
+ void reportHang();
}, unresponsivePromptDelayMs);
});
+ // The stack has to be read while the thread is still stuck, so it is
+ // captured before the breadcrumb is written — but it is never allowed to
+ // delay the prompt indefinitely (captureStack is itself bounded) and a
+ // failure just means the hang is reported without a stack.
+ const reportHang = async () => {
+ const stack = captureStack ? await readStack(captureStack, log) : null;
+ const payload: ReloadPromptPayload = {
+ kind: "unresponsive",
+ context: mergeDiagnosticContext(stack ? { stack } : {}),
+ };
+ persistBreadcrumb?.(payload);
+ unresponsiveBreadcrumbWritten = true;
+ maybePromptReload(payload);
+ };
+
window.on("responsive", () => {
if (unresponsivePromptTimer) {
clearTimeout(unresponsivePromptTimer);
@@ -188,6 +206,18 @@ function rendererRecoveryDetail(payload: ReloadPromptPayload) {
].join("\n");
}
+async function readStack(
+ captureStack: () => Promise<unknown>,
+ log: (tag: string, ...args: unknown[]) => void,
+): Promise<unknown> {
+ try {
+ return (await captureStack()) ?? null;
+ } catch (error) {
+ log("stack-capture-failed", formatError(error));
+ return null;
+ }
+}
+
function readDiagnosticContext(
getDiagnosticContext: (() => Record<string, unknown>) | undefined,
) {
diff --git a/apps/desktop/src/main/renderer-stack-capture.test.ts b/apps/desktop/src/main/renderer-stack-capture.test.ts
new file mode 100644
index 0000000000..cabda6c911
--- /dev/null
+++ b/apps/desktop/src/main/renderer-stack-capture.test.ts
@@ -0,0 +1,274 @@
+import { describe, expect, it, vi } from "vitest";
+import { readFileSync } from "node:fs";
+import { join } from "node:path";
+
+import {
+ ALLOWED_CDP_METHODS,
+ captureHangStack,
+ coolDebuggerChannel,
+ sendDebuggerCommand,
+ warmDebuggerChannel,
+ type CdpDebugger,
+} from "./renderer-stack-capture";
+
+type MessageListener = (
+ event: unknown,
+ method: string,
+ params: Record<string, unknown>,
+) => void;
+
+function makeDebugger(
+ options: {
+ attached?: boolean;
+ /** Frames to deliver via `Debugger.paused`, or null to never respond. */
+ pausedFrames?: unknown[] | null;
+ failOn?: string;
+ } = {},
+) {
+ const listeners = new Set<MessageListener>();
+ const sent: string[] = [];
+ let attached = options.attached ?? true;
+
+ const attach = vi.fn(() => {
+ if (options.failOn === "attach") throw new Error("boom: attach");
+ attached = true;
+ });
+ const detach = vi.fn(() => {
+ if (options.failOn === "detach") throw new Error("boom: detach");
+ attached = false;
+ });
+
+ const dbg: CdpDebugger = {
+ isAttached: () => attached,
+ attach,
+ detach,
+ sendCommand: vi.fn(async (method: string) => {
+ sent.push(method);
+ if (options.failOn === method) throw new Error(`boom: ${method}`);
+ if (method === "Debugger.pause" && options.pausedFrames) {
+ // The renderer answers on the message channel, not the command result.
+ for (const listener of listeners) {
+ listener({}, "Debugger.paused", { callFrames: options.pausedFrames });
+ }
+ }
+ return {};
+ }),
+ on: (_event, listener) => listeners.add(listener as MessageListener),
+ off: (_event, listener) => listeners.delete(listener as MessageListener),
+ };
+
+ return {
+ dbg,
+ sent,
+ attach,
+ detach,
+ isAttached: () => attached,
+ listenerCount: () => listeners.size,
+ };
+}
+
+const frame = {
+ functionName: "parseMarkdownChunked",
+ url: "file:///Applications/Multica.app/Contents/Resources/app.asar/out/renderer/assets/index-abc.js",
+ location: { lineNumber: 412, columnNumber: 17 },
+ // Present on every real frame; must never reach the payload.
+ scopeChain: [{ type: "local", object: { objectId: "{secret}" } }],
+ this: { objectId: "{secret}" },
+};
+
+describe("CDP allowlist", () => {
+ it.each(ALLOWED_CDP_METHODS)("permits %s", async (method) => {
+ const { dbg, sent } = makeDebugger();
+ await sendDebuggerCommand(dbg, method);
+ expect(sent).toEqual([method]);
+ });
+
+ it.each([
+ "Runtime.evaluate",
+ "Runtime.getProperties",
+ "Runtime.callFunctionOn",
+ "HeapProfiler.takeHeapSnapshot",
+ "Debugger.setBreakpointByUrl",
+ "Debugger.getScriptSource",
+ ])("refuses %s and never reaches the renderer", async (method) => {
+ const { dbg, sent } = makeDebugger();
+ await expect(sendDebuggerCommand(dbg, method)).rejects.toThrow(/Forbidden CDP method/);
+ expect(sent).toEqual([]);
+ });
+
+ // Pins the single-callsite invariant: if a future edit calls sendCommand
+ // directly it bypasses the allowlist, and CI should say so.
+ it("routes every command through sendDebuggerCommand", () => {
+ const source = readFileSync(join(__dirname, "renderer-stack-capture.ts"), "utf8");
+ const directCalls = source.match(/\bdbg\.sendCommand\(/g) ?? [];
+ expect(directCalls).toHaveLength(1);
+ });
+});
+
+describe("captureHangStack", () => {
+ it("returns code locations from the paused renderer", async () => {
+ const { dbg } = makeDebugger({ pausedFrames: [frame] });
+
+ const stack = await captureHangStack(dbg);
+
+ expect(stack).toEqual([
+ {
+ functionName: "parseMarkdownChunked",
+ url: "assets/index-abc.js",
+ lineNumber: 412,
+ columnNumber: 17,
+ },
+ ]);
+ });
+
+ it("never carries scope handles that could be dereferenced into user data", async () => {
+ const { dbg } = makeDebugger({ pausedFrames: [frame] });
+
+ const stack = await captureHangStack(dbg);
+
+ expect(JSON.stringify(stack)).not.toContain("secret");
+ expect(stack?.[0]).not.toHaveProperty("scopeChain");
+ expect(stack?.[0]).not.toHaveProperty("this");
+ });
+
+ it("always resumes — a pause we can't clear would make the hang permanent", async () => {
+ const { dbg, sent } = makeDebugger({ pausedFrames: [frame] });
+
+ await captureHangStack(dbg);
+
+ expect(sent).toEqual(["Debugger.pause", "Debugger.resume"]);
+ });
+
+ it("resumes even when the renderer never answers the pause", async () => {
+ const { dbg, sent } = makeDebugger({ pausedFrames: null });
+
+ const stack = await captureHangStack(dbg, { timeoutMs: 10 });
+
+ expect(stack).toBeNull();
+ expect(sent).toContain("Debugger.resume");
+ });
+
+ it("resumes even when the pause command itself throws", async () => {
+ const { dbg, sent } = makeDebugger({ failOn: "Debugger.pause" });
+
+ const stack = await captureHangStack(dbg, { timeoutMs: 10 });
+
+ expect(stack).toBeNull();
+ expect(sent).toContain("Debugger.resume");
+ });
+
+ it("does not leak a message listener per capture", async () => {
+ const { dbg, listenerCount } = makeDebugger({ pausedFrames: [frame] });
+
+ await captureHangStack(dbg);
+ await captureHangStack(dbg);
+
+ expect(listenerCount()).toBe(0);
+ });
+
+ it("returns null when the channel was never warmed", async () => {
+ const { dbg, sent } = makeDebugger({ attached: false });
+
+ expect(await captureHangStack(dbg)).toBeNull();
+ expect(sent).toEqual([]);
+ });
+
+ it("keeps the top of the stack when it is deeper than the cap", async () => {
+ const deep = Array.from({ length: 50 }, (_, i) => ({
+ ...frame,
+ functionName: `fn${i}`,
+ }));
+ const { dbg } = makeDebugger({ pausedFrames: deep });
+
+ const stack = await captureHangStack(dbg, { maxFrames: 3 });
+
+ expect(stack?.map((f) => f.functionName)).toEqual(["fn0", "fn1", "fn2"]);
+ });
+});
+
+describe("warmDebuggerChannel", () => {
+ it("attaches and enables when the renderer is healthy", async () => {
+ const { dbg, sent } = makeDebugger({ attached: false });
+
+ expect(await warmDebuggerChannel(dbg)).toBe(true);
+ expect(sent).toEqual(["Debugger.enable"]);
+ });
+
+ it("reports failure instead of throwing when another client owns the debugger", async () => {
+ const { dbg } = makeDebugger({ failOn: "Debugger.enable" });
+
+ expect(await warmDebuggerChannel(dbg)).toBe(false);
+ });
+});
+
+// Review finding (MUL-5345): the kill switch has to actually revoke. A detach
+// that only runs on the happy path leaves a debugger attached to a renderer
+// after the flag is turned off, which is the state the switch exists to exit.
+describe("the channel always closes", () => {
+ it("detaches even when Debugger.disable throws", async () => {
+ const { dbg, detach, isAttached } = makeDebugger({ failOn: "Debugger.disable" });
+
+ await coolDebuggerChannel(dbg);
+
+ expect(detach).toHaveBeenCalledTimes(1);
+ expect(isAttached()).toBe(false);
+ });
+
+ it("detaches on the normal path too", async () => {
+ const { dbg, sent, detach, isAttached } = makeDebugger();
+
+ await coolDebuggerChannel(dbg);
+
+ expect(sent).toEqual(["Debugger.disable"]);
+ expect(detach).toHaveBeenCalledTimes(1);
+ expect(isAttached()).toBe(false);
+ });
+
+ it("does nothing when the channel was never open", async () => {
+ const { dbg, detach, sent } = makeDebugger({ attached: false });
+
+ await coolDebuggerChannel(dbg);
+
+ expect(sent).toEqual([]);
+ expect(detach).not.toHaveBeenCalled();
+ });
+
+ it("survives a detach that itself throws", async () => {
+ const { dbg } = makeDebugger({ failOn: "detach" });
+
+ await expect(coolDebuggerChannel(dbg)).resolves.toBeUndefined();
+ });
+
+ // Warming is the other half: an attach we made and could not enable must be
+ // rolled back, or we report failure while leaving a channel open that
+ // nothing is tracking.
+ it("rolls the attach back when Debugger.enable throws", async () => {
+ const { dbg, attach, detach, isAttached } = makeDebugger({
+ attached: false,
+ failOn: "Debugger.enable",
+ });
+
+ expect(await warmDebuggerChannel(dbg)).toBe(false);
+
+ expect(attach).toHaveBeenCalledTimes(1);
+ expect(detach).toHaveBeenCalledTimes(1);
+ expect(isAttached()).toBe(false);
+ });
+
+ it("leaves an already-attached channel alone when enable throws", async () => {
+ // Someone else owns the debugger (DevTools). We did not attach it, so we
+ // must not detach it out from under them.
+ const { dbg, detach } = makeDebugger({ attached: true, failOn: "Debugger.enable" });
+
+ expect(await warmDebuggerChannel(dbg)).toBe(false);
+
+ expect(detach).not.toHaveBeenCalled();
+ });
+
+ it("reports failure without throwing when attach itself throws", async () => {
+ const { dbg, detach } = makeDebugger({ attached: false, failOn: "attach" });
+
+ expect(await warmDebuggerChannel(dbg)).toBe(false);
+ expect(detach).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/desktop/src/main/renderer-stack-capture.ts b/apps/desktop/src/main/renderer-stack-capture.ts
new file mode 100644
index 0000000000..d169e4aa2b
--- /dev/null
+++ b/apps/desktop/src/main/renderer-stack-capture.ts
@@ -0,0 +1,193 @@
+// JS call stack capture for a hung renderer (MUL-5345).
+//
+// When the renderer stops responding, the main process is still alive but has
+// no way to ask the renderer anything — the thread that would answer is the
+// thread that is stuck. The one channel that still gets through is the Chrome
+// DevTools Protocol, and only if it was already open: attaching after the hang
+// starts does not get dispatched. So the channel is warmed at window creation
+// and `Debugger.pause` is sent when the hang is detected.
+//
+// Measured on Electron 39.8.7 / Chromium 142 (spike, MUL-5345):
+// * pause during a 12s synchronous block returned the stack in 2ms, top
+// frame correctly identified as the blocking function;
+// * keeping the channel warm for the whole session showed no benchmark cost
+// beyond run-to-run noise;
+// * DevTools and this channel coexist in both open orders — opening DevTools
+// does not evict us, and pause keeps working afterwards.
+//
+// PRIVACY — hard constraints:
+//
+// * CDP ALLOWLIST: only the four `Debugger` verbs below may ever be sent.
+// Every command goes through `sendDebuggerCommand`, which throws on
+// anything else. `Runtime.evaluate` / `Runtime.getProperties` /
+// `Runtime.callFunctionOn` (arbitrary reads), `HeapProfiler.*` (heap
+// contents), and `Debugger.setBreakpoint*` are forbidden.
+// * CODE LOCATIONS ONLY: a paused frame also carries `scopeChain` handles
+// that can be dereferenced into live user data. We copy four scalar fields
+// per frame and drop everything else, so no such handle is ever retained.
+// * URLs are reduced to their bundle-relative tail — the absolute path can
+// contain the OS username.
+// * BEST EFFORT: every failure resolves to null. A diagnostic must never be
+// the reason the app stays broken.
+
+import {
+ HANG_STACK_MAX_FRAMES,
+ sanitizeHangStackFrames,
+ type HangStackFrame,
+} from "../shared/hang-stack";
+
+export type { HangStackFrame };
+
+/** Minimal CDP debugger surface — matches Electron's `webContents.debugger`. */
+export interface CdpDebugger {
+ isAttached(): boolean;
+ attach(protocolVersion?: string): void;
+ detach(): void;
+ sendCommand(method: string, commandParams?: Record<string, unknown>): Promise<unknown>;
+ on(
+ event: "message",
+ listener: (event: unknown, method: string, params: Record<string, unknown>) => void,
+ ): unknown;
+ off(
+ event: "message",
+ listener: (event: unknown, method: string, params: Record<string, unknown>) => void,
+ ): unknown;
+}
+
+/** The only CDP commands this module is permitted to send. */
+export const ALLOWED_CDP_METHODS = [
+ "Debugger.enable",
+ "Debugger.disable",
+ "Debugger.pause",
+ "Debugger.resume",
+] as const;
+
+export interface CaptureHangStackOptions {
+ /** Give up waiting for `Debugger.paused` after this long. */
+ timeoutMs?: number;
+ /** Deepest frames are the least useful; keep the top of the stack. */
+ maxFrames?: number;
+}
+
+const DEFAULT_TIMEOUT_MS = 2000;
+
+/**
+ * Send a single CDP command, enforcing the allowlist. This is the ONLY path to
+ * `debugger.sendCommand` in this module — nothing here may call `sendCommand`
+ * directly. Rejects for any other method so a forbidden command fails loudly
+ * in tests rather than silently exfiltrating.
+ */
+export function sendDebuggerCommand(
+ dbg: CdpDebugger,
+ method: string,
+): Promise<unknown> {
+ if (!(ALLOWED_CDP_METHODS as readonly string[]).includes(method)) {
+ return Promise.reject(
+ new Error(
+ `Forbidden CDP method "${method}": hang stack capture may only send ${ALLOWED_CDP_METHODS.join(" / ")}`,
+ ),
+ );
+ }
+ return dbg.sendCommand(method);
+}
+
+/**
+ * Open the debugger channel for this renderer. Must run while the renderer is
+ * healthy — that is the entire point. Returns whether the channel is usable.
+ */
+export async function warmDebuggerChannel(dbg: CdpDebugger): Promise<boolean> {
+ let attachedHere = false;
+ try {
+ if (!dbg.isAttached()) {
+ dbg.attach("1.3");
+ attachedHere = true;
+ }
+ await sendDebuggerCommand(dbg, "Debugger.enable");
+ return true;
+ } catch {
+ // Another client owns the debugger, or the renderer is already gone.
+ // An attach we made and could not enable has to be rolled back: reporting
+ // failure while leaving the channel open would strand a debugger on a
+ // renderer nothing is tracking.
+ if (attachedHere) detachQuietly(dbg);
+ return false;
+ }
+}
+
+/**
+ * Close the debugger channel. Called when the kill switch turns capture off:
+ * the channel is what makes capture possible, so revoking the flag has to
+ * revoke the channel too rather than merely skipping the next capture.
+ */
+export async function coolDebuggerChannel(dbg: CdpDebugger): Promise<void> {
+ if (!dbg.isAttached()) return;
+ try {
+ await sendDebuggerCommand(dbg, "Debugger.disable");
+ } catch {
+ // Disable is a courtesy to the renderer; detach is the contract. A failed
+ // disable must not leave the channel attached, or revoking the kill switch
+ // would not actually revoke anything.
+ } finally {
+ detachQuietly(dbg);
+ }
+}
+
+function detachQuietly(dbg: CdpDebugger): void {
+ try {
+ dbg.detach();
+ } catch {
+ // Already detached / renderer gone.
+ }
+}
+
+/**
+ * Interrupt the hung renderer, read the JS call stack, and let it run again.
+ *
+ * Resume is unconditional: a pause we requested and failed to clear would turn
+ * a recoverable hang into a permanent one, which is far worse than having no
+ * stack. Returns null whenever a stack could not be obtained.
+ */
+export async function captureHangStack(
+ dbg: CdpDebugger,
+ options: CaptureHangStackOptions = {},
+): Promise<HangStackFrame[] | null> {
+ const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
+ const maxFrames = options.maxFrames ?? HANG_STACK_MAX_FRAMES;
+
+ if (!dbg.isAttached()) return null;
+
+ let onMessage:
+ | ((event: unknown, method: string, params: Record<string, unknown>) => void)
+ | null = null;
+ let timer: ReturnType<typeof setTimeout> | undefined;
+
+ try {
+ const paused = new Promise<HangStackFrame[] | null>((resolve) => {
+ onMessage = (_event, method, params) => {
+ if (method !== "Debugger.paused") return;
+ resolve(sanitizeHangStackFrames(params.callFrames, maxFrames));
+ };
+ dbg.on("message", onMessage);
+ timer = setTimeout(() => resolve(null), timeoutMs);
+ });
+
+ await sendDebuggerCommand(dbg, "Debugger.pause");
+ return await paused;
+ } catch {
+ return null;
+ } finally {
+ if (timer) clearTimeout(timer);
+ if (onMessage) {
+ try {
+ dbg.off("message", onMessage);
+ } catch {
+ // Listener cleanup is best-effort.
+ }
+ }
+ try {
+ await sendDebuggerCommand(dbg, "Debugger.resume");
+ } catch {
+ // The renderer may already be gone; nothing left to resume.
+ }
+ }
+}
diff --git a/apps/desktop/src/preload/index.d.ts b/apps/desktop/src/preload/index.d.ts
index 6d72562ec9..460ef55488 100644
--- a/apps/desktop/src/preload/index.d.ts
+++ b/apps/desktop/src/preload/index.d.ts
@@ -2,6 +2,7 @@ import { ElectronAPI } from "@electron-toolkit/preload";
import type { RuntimeConfigResult } from "../shared/runtime-config";
import type { NavigationGesture } from "../shared/navigation-gestures";
import type { RendererRouteContextInput } from "../shared/renderer-route-context";
+import type { DiagnosticsControl } from "../shared/diagnostics-control";
import type { FreezeBreadcrumb } from "../shared/freeze-breadcrumb";
import type {
DesktopWindowContext,
@@ -31,9 +32,13 @@ interface DesktopAPI {
runtimeConfig: RuntimeConfigResult;
/** Main tabbed window or a dedicated issue-only window. */
windowContext: DesktopWindowContext;
- /** Read + clear any freeze/crash breadcrumb from a previous session, so the
- * renderer can flush it to telemetry on boot. Null when nothing's pending. */
+ /** Read any freeze/crash breadcrumb from a previous session, so the renderer
+ * can flush it to telemetry on boot. Null when nothing's pending. Reading
+ * does not consume it — acknowledge with `ackFreeze`. */
getLastFreeze: () => FreezeBreadcrumb | null;
+ /** Retire the breadcrumb with this exact timestamp once its event has been
+ * handed to analytics. Unacknowledged breadcrumbs are retried next boot. */
+ ackFreeze: (ts: number) => void;
/** Report the resolved account identity so stale issue windows can close. */
reportAuthSession: (userId: string | null) => void;
/** Listen for auth token delivered via deep link. Returns an unsubscribe function. */
@@ -69,6 +74,8 @@ interface DesktopAPI {
onNavigationGesture: (callback: (gesture: NavigationGesture) => void) => () => void;
/** Report the renderer's memory-router path for recovery diagnostics. */
setRendererRouteContext: (context: RendererRouteContextInput) => void;
+ /** Publish server-driven diagnostics flags; main stays fail-closed until then. */
+ setDiagnosticsControl: (control: DiagnosticsControl) => void;
/** Open the OS folder picker and return the chosen absolute path.
* Used by the Project settings "Add local directory" flow. */
pickDirectory: (
diff --git a/apps/desktop/src/preload/index.ts b/apps/desktop/src/preload/index.ts
index 4c187d6c3d..85f68eefcf 100644
--- a/apps/desktop/src/preload/index.ts
+++ b/apps/desktop/src/preload/index.ts
@@ -10,6 +10,10 @@ import {
RENDERER_ROUTE_CONTEXT_CHANNEL,
type RendererRouteContextInput,
} from "../shared/renderer-route-context";
+import {
+ DIAGNOSTICS_CONTROL_CHANNEL,
+ type DiagnosticsControl,
+} from "../shared/diagnostics-control";
import {
isNavigationGesture,
NAVIGATION_GESTURE_CHANNEL,
@@ -120,9 +124,10 @@ const desktopAPI = {
/** Identifies whether this renderer owns the main tabbed window or a
* dedicated issue window, parsed from validated launch arguments. */
windowContext,
- /** Read + clear any freeze/crash breadcrumb left by a previous session, so
- * the renderer can flush it to telemetry on boot. Returns null when there's
- * nothing pending (the normal case). */
+ /** Read any freeze/crash breadcrumb left by a previous session, so the
+ * renderer can flush it to telemetry on boot. Returns null when there's
+ * nothing pending (the normal case). Reading does not consume it — call
+ * `ackFreeze` once the event is on the wire. */
getLastFreeze: (): FreezeBreadcrumb | null => {
try {
return ipcRenderer.sendSync("freeze:get-last") as FreezeBreadcrumb | null;
@@ -130,6 +135,9 @@ const desktopAPI = {
return null;
}
},
+ /** Retire the breadcrumb with this exact timestamp after its event has been
+ * handed to analytics. Anything left unacknowledged is retried next boot. */
+ ackFreeze: (ts: number) => ipcRenderer.send("freeze:ack", ts),
/** Report only the resolved user id (never a token) so main can close
* dedicated issue windows that belong to an old account. */
reportAuthSession: (userId: string | null) =>
@@ -198,6 +206,10 @@ const desktopAPI = {
/** Report the renderer's memory-router path for recovery diagnostics. */
setRendererRouteContext: (context: RendererRouteContextInput) =>
ipcRenderer.send(RENDERER_ROUTE_CONTEXT_CHANNEL, context),
+ /** Publish the server-driven diagnostics flags. The main process starts
+ * fail-closed and only enables hang stack capture once this says so. */
+ setDiagnosticsControl: (control: DiagnosticsControl) =>
+ ipcRenderer.send(DIAGNOSTICS_CONTROL_CHANNEL, control),
/** Open the OS folder picker and return the chosen absolute path. */
pickDirectory: (defaultPath?: string) =>
ipcRenderer.invoke("local-directory:pick", defaultPath),
diff --git a/apps/desktop/src/renderer/src/App.tsx b/apps/desktop/src/renderer/src/App.tsx
index a981ca5c5c..4be152db30 100644
--- a/apps/desktop/src/renderer/src/App.tsx
+++ b/apps/desktop/src/renderer/src/App.tsx
@@ -23,7 +23,8 @@ import { captureEvent } from "@multica/core/analytics";
import { RESOURCES } from "@multica/views/locales";
import { DesktopClientUsageReporter } from "./platform/client-usage-reporter";
import { DiagnosticRouteReporter } from "./platform/diagnostic-route-reporter";
-import { buildFreezeEventProps } from "./freeze-flush";
+import { flushFreezeBreadcrumb } from "./freeze-flush";
+import { DiagnosticsControlReporter } from "./platform/diagnostics-control-reporter";
// BCP-47 region tags for the <html lang> attribute, mirroring
// apps/web/app/layout.tsx HTML_LANG. index.html ships a static lang="en";
@@ -380,14 +381,15 @@ export default function App() {
// (the renderer is blocked or gone), so the main process persists it and we
// emit it here on the next boot. The in-thread, recoverable freeze tier is
// handled separately by the shared watchdog in CoreProvider.
- useEffect(() => {
- const last = window.desktopAPI.getLastFreeze();
- if (!last) return;
- captureEvent(
- last.kind === "render-process-gone" ? "client_crash" : "client_unresponsive",
- buildFreezeEventProps(last),
- );
- }, []);
+ useEffect(
+ () =>
+ flushFreezeBreadcrumb({
+ getLastFreeze: () => window.desktopAPI.getLastFreeze(),
+ ackFreeze: (ts) => window.desktopAPI.ackFreeze(ts),
+ capture: captureEvent,
+ }),
+ [],
+ );
// Stable identity reference so downstream effects (WS reconnect) don't
// tear down on every parent render.
@@ -450,6 +452,7 @@ export default function App() {
>
<DesktopAuthSessionBridge />
{windowContext.kind === "main" && <DiagnosticRouteReporter />}
+ <DiagnosticsControlReporter />
{windowContext.kind === "main" && (
<DesktopClientUsageReporter
apiUrl={runtimeConfigResult.config.apiUrl}
diff --git a/apps/desktop/src/renderer/src/freeze-flush.test.ts b/apps/desktop/src/renderer/src/freeze-flush.test.ts
index 738c5677ba..35698220fb 100644
--- a/apps/desktop/src/renderer/src/freeze-flush.test.ts
+++ b/apps/desktop/src/renderer/src/freeze-flush.test.ts
@@ -1,15 +1,21 @@
/**
- * MUL-5345 — a hang report has to say which page it happened on, and must not
- * say anything else about the user.
+ * Two regressions are pinned here, both found in review of MUL-5345.
*
- * The props used to be built by spreading the whole breadcrumb context, which
- * shipped the workspace slug, the tab id and the absolute window URL. Building
- * them by whitelist is what keeps that from coming back the next time the
- * context grows a field.
+ * 1. The breadcrumb was acked inside `onCaptured`, which fires on hand-off to
+ * the PostHog SDK — not on delivery. An app that froze again or was killed
+ * while the request was still in flight lost the report AND the file, which
+ * is precisely the MUL-4115 failure the ack protocol exists to prevent.
+ * 2. The whole breadcrumb context was spread into telemetry props, so the
+ * workspace slug, tab id and absolute window URL shipped with every report
+ * despite the stated "bucketed path only" constraint.
*/
-import { describe, expect, it } from "vitest";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-import { buildFreezeEventProps } from "./freeze-flush";
+import {
+ buildFreezeEventProps,
+ flushFreezeBreadcrumb,
+ FREEZE_ACK_GRACE_MS,
+} from "./freeze-flush";
import type { FreezeBreadcrumb } from "../../shared/freeze-breadcrumb";
const hang: FreezeBreadcrumb = {
@@ -22,11 +28,96 @@ const hang: FreezeBreadcrumb = {
path: "/:slug/issues",
reportedAt: "2026-07-27T00:00:00.000Z",
},
+ stack: [
+ { functionName: "parseMarkdownChunked", url: "assets/index-abc.js", lineNumber: 412, columnNumber: 17 },
+ { functionName: "setContent", url: "assets/index-abc.js", lineNumber: 90, columnNumber: 4 },
+ ],
},
};
-describe("buildFreezeEventProps", () => {
- it("reports the bucketed route at the top level, like the in-thread watchdog", () => {
+function setup(overrides: Partial<FreezeBreadcrumb> | null = {}) {
+ const ackFreeze = vi.fn();
+ const capture = vi.fn();
+ const breadcrumb = overrides === null ? null : { ...hang, ...overrides };
+ const cleanup = flushFreezeBreadcrumb({
+ getLastFreeze: () => breadcrumb,
+ ackFreeze,
+ capture,
+ });
+ const options = capture.mock.calls[0]?.[2] as
+ | { onCaptured?: () => void; sendInstantly?: boolean }
+ | undefined;
+ return { ackFreeze, capture, cleanup, options };
+}
+
+beforeEach(() => {
+ vi.useFakeTimers();
+});
+
+afterEach(() => {
+ vi.useRealTimers();
+ vi.clearAllMocks();
+});
+
+describe("ack is not delivery", () => {
+ it("does not retire the breadcrumb at hand-off", () => {
+ const { ackFreeze, options } = setup();
+
+ options?.onCaptured?.();
+
+ expect(ackFreeze).not.toHaveBeenCalled();
+ });
+
+ it("retires it once the grace window has passed", () => {
+ const { ackFreeze, options } = setup();
+ options?.onCaptured?.();
+
+ vi.advanceTimersByTime(FREEZE_ACK_GRACE_MS);
+
+ expect(ackFreeze).toHaveBeenCalledWith(hang.ts);
+ });
+
+ it("keeps the breadcrumb when the app dies inside the grace window", () => {
+ const { ackFreeze, options, cleanup } = setup();
+ options?.onCaptured?.();
+
+ vi.advanceTimersByTime(FREEZE_ACK_GRACE_MS - 1);
+ // Second hang / force quit before the report ever left.
+ cleanup();
+ vi.advanceTimersByTime(FREEZE_ACK_GRACE_MS);
+
+ expect(ackFreeze).not.toHaveBeenCalled();
+ });
+
+ it("never acks when the event was not captured at all (analytics disabled)", () => {
+ const { ackFreeze } = setup();
+
+ // onCaptured never fires on a build without an analytics key.
+ vi.advanceTimersByTime(FREEZE_ACK_GRACE_MS * 10);
+
+ expect(ackFreeze).not.toHaveBeenCalled();
+ });
+
+ it("sends instantly rather than waiting on the batch timer", () => {
+ const { options } = setup();
+ expect(options?.sendInstantly).toBe(true);
+ });
+
+ it("does nothing when there is no pending breadcrumb (the normal case)", () => {
+ const { capture, ackFreeze } = setup(null);
+
+ expect(capture).not.toHaveBeenCalled();
+ expect(ackFreeze).not.toHaveBeenCalled();
+ });
+
+ it("reports a crash under its own event name", () => {
+ const { capture } = setup({ kind: "render-process-gone" });
+ expect(capture.mock.calls[0]?.[0]).toBe("client_crash");
+ });
+});
+
+describe("telemetry props carry no raw identifiers", () => {
+ it("ships the bucketed route and the stack", () => {
expect(buildFreezeEventProps(hang)).toEqual({
source: "main-unresponsive",
recovered: false,
@@ -34,6 +125,13 @@ describe("buildFreezeEventProps", () => {
crashed_version: "0.4.11",
path: "/:slug/issues",
surface: "tab",
+ stack: hang.context.stack,
+ stack_depth: 2,
+ // Top frame flattened so a hang groups by the blocking function without
+ // unpacking the array.
+ stack_function: "parseMarkdownChunked",
+ stack_url: "assets/index-abc.js",
+ stack_line: 412,
});
});
@@ -63,6 +161,54 @@ describe("buildFreezeEventProps", () => {
expect(props).not.toHaveProperty("windowUrl");
});
+ // Review finding (MUL-5345): the flush side used to forward `context.stack`
+ // wholesale. That array crosses an on-disk breadcrumb which is barely
+ // validated on read, so an older build, a corrupt file or a future writer
+ // could put a live handle in it and this would ship it.
+ it("rebuilds stack frames instead of forwarding whatever the file held", () => {
+ const props = buildFreezeEventProps({
+ ...hang,
+ context: {
+ stack: [
+ {
+ functionName: "blockMainThread",
+ url: "file:///Users/someone/Applications/Multica.app/out/renderer/main.js",
+ location: { lineNumber: 12, columnNumber: 3 },
+ scopeChain: [{ type: "local", object: { objectId: "{secret-scope}" } }],
+ this: { objectId: "{secret-this}" },
+ returnValue: "raw-value",
+ },
+ ],
+ },
+ });
+
+ const serialized = JSON.stringify(props);
+ expect(serialized).not.toContain("secret");
+ expect(serialized).not.toContain("raw-value");
+ // The absolute install path carries the OS username; only the tail ships.
+ expect(serialized).not.toContain("someone");
+ expect(props.stack).toEqual([
+ {
+ functionName: "blockMainThread",
+ url: "renderer/main.js",
+ lineNumber: 12,
+ columnNumber: 3,
+ },
+ ]);
+ expect(props.stack_function).toBe("blockMainThread");
+ expect(props.stack_url).toBe("renderer/main.js");
+ expect(props.stack_line).toBe(12);
+ });
+
+ it("omits the stack fields when the file held nothing usable", () => {
+ for (const stack of [undefined, [], "not-an-array", [null]]) {
+ const props = buildFreezeEventProps({ ...hang, context: { stack } });
+ expect(props).not.toHaveProperty("stack");
+ expect(props).not.toHaveProperty("stack_depth");
+ expect(props).not.toHaveProperty("stack_function");
+ }
+ });
+
it("drops an unknown context key rather than forwarding it", () => {
const props = buildFreezeEventProps({
...hang,
@@ -97,7 +243,9 @@ describe("buildFreezeEventProps", () => {
});
it("survives a breadcrumb with no context at all", () => {
- expect(buildFreezeEventProps({ ...hang, context: {} })).toEqual({
+ const props = buildFreezeEventProps({ ...hang, context: {} });
+
+ expect(props).toEqual({
source: "main-unresponsive",
recovered: false,
breadcrumb_ts: hang.ts,
diff --git a/apps/desktop/src/renderer/src/freeze-flush.ts b/apps/desktop/src/renderer/src/freeze-flush.ts
index 77e0a5bc96..e9814fb2f2 100644
--- a/apps/desktop/src/renderer/src/freeze-flush.ts
+++ b/apps/desktop/src/renderer/src/freeze-flush.ts
@@ -1,15 +1,83 @@
+import type { CaptureEventOptions } from "@multica/core/analytics";
import type { FreezeBreadcrumb } from "../../shared/freeze-breadcrumb";
+import { sanitizeHangStackFrames } from "../../shared/hang-stack";
-// Turning a breadcrumb the previous session left behind into event properties.
+// Reporting a failure the previous session couldn't report itself.
//
-// The breadcrumb context is assembled in the main process and can grow a field
-// at any time, so props are built by explicit whitelist here rather than by
-// spreading it: an unknown key is dropped, not forwarded. That matters because
-// this context is the one place a raw identifier could reach telemetry.
+// Two things here are easy to get wrong, so both are pinned by tests:
+//
+// 1. ACK TIMING. `onCaptured` fires when posthog.capture() returns, which is a
+// hand-off to the SDK, NOT a delivery confirmation — posthog-js exposes no
+// delivery callback (`CaptureOptions` has `send_instantly` and `transport`,
+// and nothing else). Acking there would delete the breadcrumb while the
+// request is still in flight, so an app that freezes again or is killed a
+// moment later loses the report anyway — the exact MUL-4115 failure this
+// was meant to fix. We therefore ack after a grace window: if the process
+// dies inside it, the timer never fires, the file survives, and the next
+// boot retries. A duplicate report is the acceptable trade (they carry
+// `breadcrumb_ts`, so query-side dedupe is trivial); a lost one is not.
+//
+// 2. FIELD SELECTION. The breadcrumb context is assembled in the main process
+// and could grow a field at any time. Spreading it into telemetry props
+// means any such field ships automatically. Props are therefore built by
+// explicit whitelist below — unknown keys are dropped, not forwarded.
+
+/**
+ * How long to leave the breadcrumb on disk after hand-off. Long enough for an
+ * instant send to complete on a slow link; short enough that the duplicate
+ * window stays small.
+ */
+export const FREEZE_ACK_GRACE_MS = 10_000;
+
+type CaptureFn = (
+ name: string,
+ props: Record<string, unknown>,
+ options?: CaptureEventOptions,
+) => void;
+
+export interface FlushFreezeBreadcrumbDeps {
+ getLastFreeze: () => FreezeBreadcrumb | null;
+ ackFreeze: (ts: number) => void;
+ capture: CaptureFn;
+ graceMs?: number;
+}
+
+/**
+ * Report a pending freeze/crash breadcrumb, then retire it once the report has
+ * had time to leave. Returns a cleanup that cancels a pending ack — a
+ * cancelled ack leaves the breadcrumb for the next boot, which is the safe
+ * direction.
+ */
+export function flushFreezeBreadcrumb({
+ getLastFreeze,
+ ackFreeze,
+ capture,
+ graceMs = FREEZE_ACK_GRACE_MS,
+}: FlushFreezeBreadcrumbDeps): () => void {
+ const last = getLastFreeze();
+ if (!last) return () => undefined;
+
+ let ackTimer: ReturnType<typeof setTimeout> | null = null;
+ const crashed = last.kind === "render-process-gone";
+
+ capture(crashed ? "client_crash" : "client_unresponsive", buildFreezeEventProps(last), {
+ // The batch timer lives in the thread that already froze once and may be
+ // about to freeze again.
+ sendInstantly: true,
+ onCaptured: () => {
+ ackTimer = setTimeout(() => ackFreeze(last.ts), graceMs);
+ },
+ });
+
+ return () => {
+ if (ackTimer) clearTimeout(ackTimer);
+ };
+}
/**
- * Build the event properties for a pending freeze/crash breadcrumb, field by
- * field. Anything not named here does not ship.
+ * Build the event properties from a breadcrumb, field by field. Anything not
+ * named here does not ship — including a future key added to the context in
+ * the main process.
*/
export function buildFreezeEventProps(
breadcrumb: FreezeBreadcrumb,
@@ -23,6 +91,7 @@ export function buildFreezeEventProps(
breadcrumb_ts: breadcrumb.ts,
crashed_version: breadcrumb.version,
...routeProps(context.desktopRoute),
+ ...stackProps(context.stack),
...crashProps(context.details),
};
}
@@ -42,6 +111,33 @@ function routeProps(value: unknown): Record<string, unknown> {
};
}
+/**
+ * Frames are rebuilt here rather than forwarded.
+ *
+ * The capture side already whitelists, but its output travels through an
+ * on-disk breadcrumb that `readFreezeBreadcrumb` barely validates — it only
+ * has to survive version skew. So the array reaching this function could come
+ * from an older build, a corrupt file, or a future writer, and shipping it
+ * as-is would put whatever it contains (a `scopeChain` handle, an absolute
+ * install path) straight into telemetry. Re-sanitizing is cheap; trusting the
+ * file is not.
+ *
+ * The top frame is also flattened onto the event so a hang groups by the
+ * function that blocked the thread without unpacking the array.
+ */
+function stackProps(value: unknown): Record<string, unknown> {
+ const frames = sanitizeHangStackFrames(value);
+ if (!frames) return {};
+ const top = frames[0]!;
+ return {
+ stack: frames,
+ stack_depth: frames.length,
+ stack_function: top.functionName,
+ ...(top.url ? { stack_url: top.url } : {}),
+ stack_line: top.lineNumber,
+ };
+}
+
/** Electron's render-process-gone details: two scalars, nothing else. */
function crashProps(value: unknown): Record<string, unknown> {
if (!value || typeof value !== "object") return {};
diff --git a/apps/desktop/src/renderer/src/platform/diagnostics-control-reporter.test.tsx b/apps/desktop/src/renderer/src/platform/diagnostics-control-reporter.test.tsx
new file mode 100644
index 0000000000..b8f129e9fd
--- /dev/null
+++ b/apps/desktop/src/renderer/src/platform/diagnostics-control-reporter.test.tsx
@@ -0,0 +1,88 @@
+/**
+ * The main process cannot read `/api/config` itself, so this component is the
+ * only thing that can ever turn hang stack capture on. The cases that matter
+ * are the ones where the flag is absent or arrives late — both must leave
+ * capture off rather than assume.
+ */
+import { describe, expect, it, vi, beforeEach } from "vitest";
+import { render } from "@testing-library/react";
+
+const configState: { featureFlags: Record<string, boolean> } = { featureFlags: {} };
+
+vi.mock("@multica/core/config", () => ({
+ useConfigStore: (selector: (s: typeof configState) => unknown) => selector(configState),
+ featureFlagEnabled: (
+ flags: Record<string, boolean> | undefined,
+ key: string,
+ defaultValue = false,
+ ) => flags?.[key] ?? defaultValue,
+}));
+
+import { DiagnosticsControlReporter } from "./diagnostics-control-reporter";
+import { HANG_STACK_CAPTURE_FLAG } from "../../../shared/diagnostics-control";
+
+const setDiagnosticsControl = vi.fn();
+
+beforeEach(() => {
+ setDiagnosticsControl.mockClear();
+ configState.featureFlags = {};
+ Object.defineProperty(window, "desktopAPI", {
+ configurable: true,
+ value: { setDiagnosticsControl },
+ });
+});
+
+describe("DiagnosticsControlReporter", () => {
+ it("publishes off when the backend has never heard of the flag", () => {
+ render(<DiagnosticsControlReporter />);
+
+ expect(setDiagnosticsControl).toHaveBeenCalledWith({ stackCaptureEnabled: false });
+ });
+
+ it("publishes off when the flag is explicitly disabled", () => {
+ configState.featureFlags = { [HANG_STACK_CAPTURE_FLAG]: false };
+
+ render(<DiagnosticsControlReporter />);
+
+ expect(setDiagnosticsControl).toHaveBeenCalledWith({ stackCaptureEnabled: false });
+ });
+
+ it("publishes on when the flag is enabled", () => {
+ configState.featureFlags = { [HANG_STACK_CAPTURE_FLAG]: true };
+
+ render(<DiagnosticsControlReporter />);
+
+ expect(setDiagnosticsControl).toHaveBeenCalledWith({ stackCaptureEnabled: true });
+ });
+
+ // Config is fetched after auth, so the flags are empty on first render. A
+ // component that read them once would publish "off" and never correct it.
+ it("re-publishes when the flag arrives after mount", () => {
+ const { rerender } = render(<DiagnosticsControlReporter />);
+ expect(setDiagnosticsControl).toHaveBeenCalledWith({ stackCaptureEnabled: false });
+
+ configState.featureFlags = { [HANG_STACK_CAPTURE_FLAG]: true };
+ rerender(<DiagnosticsControlReporter />);
+
+ expect(setDiagnosticsControl).toHaveBeenLastCalledWith({ stackCaptureEnabled: true });
+ });
+
+ it("re-publishes when the flag is revoked", () => {
+ configState.featureFlags = { [HANG_STACK_CAPTURE_FLAG]: true };
+ const { rerender } = render(<DiagnosticsControlReporter />);
+
+ configState.featureFlags = { [HANG_STACK_CAPTURE_FLAG]: false };
+ rerender(<DiagnosticsControlReporter />);
+
+ expect(setDiagnosticsControl).toHaveBeenLastCalledWith({ stackCaptureEnabled: false });
+ });
+
+ it("does not re-publish an unchanged value", () => {
+ const { rerender } = render(<DiagnosticsControlReporter />);
+ expect(setDiagnosticsControl).toHaveBeenCalledTimes(1);
+
+ rerender(<DiagnosticsControlReporter />);
+
+ expect(setDiagnosticsControl).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/apps/desktop/src/renderer/src/platform/diagnostics-control-reporter.tsx b/apps/desktop/src/renderer/src/platform/diagnostics-control-reporter.tsx
new file mode 100644
index 0000000000..93879aed36
--- /dev/null
+++ b/apps/desktop/src/renderer/src/platform/diagnostics-control-reporter.tsx
@@ -0,0 +1,30 @@
+import { useEffect } from "react";
+import { useConfigStore, featureFlagEnabled } from "@multica/core/config";
+import { HANG_STACK_CAPTURE_FLAG } from "../../../shared/diagnostics-control";
+
+/**
+ * Carries the server's diagnostics kill switch to the main process.
+ *
+ * The main process is the party that holds a debugger channel open and reads
+ * stacks out of a hung renderer, but it has no HTTP client and no session — it
+ * cannot read `/api/config` itself. So the renderer, which already has the
+ * flags, forwards the one bit main needs.
+ *
+ * Main starts fail-closed and only enables capture on an explicit `true`, so a
+ * config that never arrives, a backend that has never heard of the flag, and a
+ * renderer that never mounts this all land on "off".
+ */
+export function DiagnosticsControlReporter() {
+ // Subscribed, not read once: the flags arrive asynchronously after auth, so
+ // a component that read them at mount would publish the empty pre-config
+ // state and never correct it.
+ const stackCaptureEnabled = useConfigStore((state) =>
+ featureFlagEnabled(state.featureFlags, HANG_STACK_CAPTURE_FLAG),
+ );
+
+ useEffect(() => {
+ window.desktopAPI.setDiagnosticsControl({ stackCaptureEnabled });
+ }, [stackCaptureEnabled]);
+
+ return null;
+}
diff --git a/apps/desktop/src/shared/diagnostics-control.test.ts b/apps/desktop/src/shared/diagnostics-control.test.ts
new file mode 100644
index 0000000000..7f867d5e41
--- /dev/null
+++ b/apps/desktop/src/shared/diagnostics-control.test.ts
@@ -0,0 +1,47 @@
+/**
+ * The kill switch has to be safe in the direction that matters: an ambiguous
+ * or missing signal must leave hang stack capture OFF, because "on" means the
+ * main process holds a debugger channel open against every renderer.
+ */
+import { describe, expect, it } from "vitest";
+
+import {
+ DIAGNOSTICS_CONTROL_OFF,
+ parseDiagnosticsControl,
+} from "./diagnostics-control";
+
+describe("parseDiagnosticsControl", () => {
+ it("enables capture only on an explicit true", () => {
+ expect(parseDiagnosticsControl({ stackCaptureEnabled: true })).toEqual({
+ stackCaptureEnabled: true,
+ });
+ });
+
+ it("stays off for an explicit false", () => {
+ expect(parseDiagnosticsControl({ stackCaptureEnabled: false })).toEqual(
+ DIAGNOSTICS_CONTROL_OFF,
+ );
+ });
+
+ it.each([
+ ["missing field", {}],
+ ["a truthy non-boolean", { stackCaptureEnabled: "true" }],
+ ["a number", { stackCaptureEnabled: 1 }],
+ ["null", null],
+ ["undefined", undefined],
+ ["a string payload", "stackCaptureEnabled"],
+ ["an array", []],
+ ])("stays off for %s", (_label, payload) => {
+ expect(parseDiagnosticsControl(payload)).toEqual(DIAGNOSTICS_CONTROL_OFF);
+ });
+
+ it("ignores unknown keys rather than inheriting them", () => {
+ expect(
+ parseDiagnosticsControl({ stackCaptureEnabled: true, somethingElse: true }),
+ ).toEqual({ stackCaptureEnabled: true });
+ });
+
+ it("defaults to off", () => {
+ expect(DIAGNOSTICS_CONTROL_OFF.stackCaptureEnabled).toBe(false);
+ });
+});
diff --git a/apps/desktop/src/shared/diagnostics-control.ts b/apps/desktop/src/shared/diagnostics-control.ts
new file mode 100644
index 0000000000..06b9dd1a34
--- /dev/null
+++ b/apps/desktop/src/shared/diagnostics-control.ts
@@ -0,0 +1,35 @@
+export const DIAGNOSTICS_CONTROL_CHANNEL = "diagnostics:control";
+
+/**
+ * Server-driven feature flag that gates hang stack capture.
+ *
+ * Lives in `/api/config`'s `feature_flags`, so it can be flipped off for the
+ * whole fleet without shipping a release — which is the point: attaching a
+ * debugger to every renderer is the kind of thing that must be revocable
+ * faster than an app update can roll out.
+ */
+export const HANG_STACK_CAPTURE_FLAG = "desktop_hang_stack_capture";
+
+export interface DiagnosticsControl {
+ /** Whether the main process may hold a debugger channel and read stacks. */
+ stackCaptureEnabled: boolean;
+}
+
+/** What the main process assumes until the renderer says otherwise. */
+export const DIAGNOSTICS_CONTROL_OFF: DiagnosticsControl = {
+ stackCaptureEnabled: false,
+};
+
+/**
+ * Read a control payload sent by the renderer, FAIL-CLOSED.
+ *
+ * Anything that is not literally `true` means off: a malformed payload, a
+ * renderer older than this build, a flag the backend has never heard of, a
+ * config request that failed. The only way capture turns on is an explicit
+ * `true` from a config the client actually received.
+ */
+export function parseDiagnosticsControl(value: unknown): DiagnosticsControl {
+ if (!value || typeof value !== "object") return DIAGNOSTICS_CONTROL_OFF;
+ const input = value as Record<string, unknown>;
+ return { stackCaptureEnabled: input.stackCaptureEnabled === true };
+}
diff --git a/apps/desktop/src/shared/hang-stack.test.ts b/apps/desktop/src/shared/hang-stack.test.ts
new file mode 100644
index 0000000000..411e386c85
--- /dev/null
+++ b/apps/desktop/src/shared/hang-stack.test.ts
@@ -0,0 +1,123 @@
+/**
+ * Frames are rebuilt at both ends — capture and egress — because the on-disk
+ * breadcrumb between them is barely validated. These cases pin what "rebuilt"
+ * means: four scalars, and nothing that could be dereferenced into user data.
+ */
+import { describe, expect, it } from "vitest";
+
+import {
+ HANG_STACK_MAX_FRAMES,
+ redactFrameUrl,
+ sanitizeHangStackFrames,
+} from "./hang-stack";
+
+const cdpFrame = {
+ functionName: "parseMarkdownChunked",
+ url: "file:///Applications/Multica.app/Contents/Resources/app.asar/out/renderer/assets/index-abc.js",
+ location: { lineNumber: 412, columnNumber: 17 },
+ // Present on every real paused frame; both dereference into live values.
+ scopeChain: [{ type: "local", object: { objectId: "{secret-scope}" } }],
+ this: { objectId: "{secret-this}" },
+};
+
+describe("sanitizeHangStackFrames", () => {
+ it("keeps the four scalar fields and reduces the url", () => {
+ expect(sanitizeHangStackFrames([cdpFrame])).toEqual([
+ {
+ functionName: "parseMarkdownChunked",
+ url: "assets/index-abc.js",
+ lineNumber: 412,
+ columnNumber: 17,
+ },
+ ]);
+ });
+
+ it("drops scope handles that could be dereferenced into user data", () => {
+ const frames = sanitizeHangStackFrames([cdpFrame]);
+
+ expect(JSON.stringify(frames)).not.toContain("secret");
+ expect(frames?.[0]).not.toHaveProperty("scopeChain");
+ expect(frames?.[0]).not.toHaveProperty("this");
+ });
+
+ it("drops any key a future protocol version might add", () => {
+ const frames = sanitizeHangStackFrames([
+ { ...cdpFrame, functionLocation: { scriptId: "7" }, returnValue: "raw-value" },
+ ]);
+
+ expect(JSON.stringify(frames)).not.toContain("raw-value");
+ expect(frames?.[0]).not.toHaveProperty("returnValue");
+ });
+
+ // A breadcrumb frame has already been flattened; a CDP frame nests position
+ // under `location`. Re-sanitizing an already-sanitized frame must be lossless
+ // or the egress-side rebuild would zero out every line number.
+ it("accepts an already-flattened frame without losing its position", () => {
+ const flattened = {
+ functionName: "setContent",
+ url: "assets/index-abc.js",
+ lineNumber: 90,
+ columnNumber: 4,
+ };
+
+ expect(sanitizeHangStackFrames([flattened])).toEqual([flattened]);
+ expect(sanitizeHangStackFrames(sanitizeHangStackFrames([cdpFrame]))).toEqual(
+ sanitizeHangStackFrames([cdpFrame]),
+ );
+ });
+
+ it("labels an anonymous frame rather than dropping it", () => {
+ expect(sanitizeHangStackFrames([{ functionName: "", location: {} }])).toEqual([
+ { functionName: "(anonymous)", url: "", lineNumber: 0, columnNumber: 0 },
+ ]);
+ });
+
+ it("returns null for a missing or empty frame list", () => {
+ expect(sanitizeHangStackFrames(undefined)).toBeNull();
+ expect(sanitizeHangStackFrames([])).toBeNull();
+ expect(sanitizeHangStackFrames("not-an-array")).toBeNull();
+ });
+
+ it("keeps the top of the stack when it is deeper than the cap", () => {
+ const deep = Array.from({ length: 50 }, (_, i) => ({
+ ...cdpFrame,
+ functionName: `fn${i}`,
+ }));
+
+ expect(sanitizeHangStackFrames(deep, 3).map((f) => f!.functionName)).toEqual([
+ "fn0",
+ "fn1",
+ "fn2",
+ ]);
+ expect(sanitizeHangStackFrames(deep)).toHaveLength(HANG_STACK_MAX_FRAMES);
+ });
+
+ it("skips a non-object entry instead of failing the whole stack", () => {
+ const frames = sanitizeHangStackFrames([null, cdpFrame, "junk"]);
+ expect(frames).toHaveLength(1);
+ });
+});
+
+describe("redactFrameUrl", () => {
+ it("strips the install path, which can contain the OS username", () => {
+ expect(
+ redactFrameUrl("file:///Users/someone/Applications/Multica.app/out/renderer/main.js"),
+ ).toBe("renderer/main.js");
+ });
+
+ it("is idempotent, so re-sanitizing does not erode the value", () => {
+ const once = redactFrameUrl(
+ "file:///Users/someone/Applications/Multica.app/out/renderer/main.js",
+ );
+ expect(redactFrameUrl(once)).toBe(once);
+ });
+
+ it("drops query and hash", () => {
+ expect(redactFrameUrl("assets/index.js?v=1#L2")).toBe("assets/index.js");
+ });
+
+ it("tolerates a frame with no url", () => {
+ expect(redactFrameUrl(undefined)).toBe("");
+ expect(redactFrameUrl("")).toBe("");
+ });
+});
diff --git a/apps/desktop/src/shared/hang-stack.ts b/apps/desktop/src/shared/hang-stack.ts
new file mode 100644
index 0000000000..04c433fe63
--- /dev/null
+++ b/apps/desktop/src/shared/hang-stack.ts
@@ -0,0 +1,77 @@
+/**
+ * The shape a hang stack is allowed to have, and the only code that builds it.
+ *
+ * Frames cross three boundaries between capture and telemetry: main writes
+ * them into an on-disk breadcrumb, preload hands that file back over IPC, and
+ * the renderer turns it into an event. The breadcrumb is barely validated on
+ * read (it only has to survive version skew), so "sanitized once at capture"
+ * is not a property the egress side can rely on — an older file, a corrupt
+ * file, or a future main-process change could put anything in there.
+ *
+ * Both ends therefore rebuild frames through this module rather than trusting
+ * the other. Whitelisting twice is cheap; a `scopeChain` handle reaching
+ * PostHog is not.
+ */
+
+export interface HangStackFrame {
+ functionName: string;
+ url: string;
+ lineNumber: number;
+ columnNumber: number;
+}
+
+/** Deepest frames are the least useful; keep the top of the stack. */
+export const HANG_STACK_MAX_FRAMES = 20;
+
+/**
+ * Rebuild frames from untrusted input, keeping only the four scalar fields.
+ *
+ * Everything else is dropped by construction — notably `scopeChain` and
+ * `this`, whose object handles can be dereferenced into live user data, and
+ * any key a future protocol version or a future writer might add. Returns null
+ * when there is nothing usable, so callers can omit the field entirely rather
+ * than ship an empty array.
+ */
+export function sanitizeHangStackFrames(
+ rawFrames: unknown,
+ maxFrames: number = HANG_STACK_MAX_FRAMES,
+): HangStackFrame[] | null {
+ if (!Array.isArray(rawFrames) || rawFrames.length === 0) return null;
+
+ const frames: HangStackFrame[] = [];
+ for (const raw of rawFrames.slice(0, maxFrames)) {
+ if (!raw || typeof raw !== "object") continue;
+ const frame = raw as Record<string, unknown>;
+ // CDP nests the position under `location`; a breadcrumb frame has already
+ // been flattened. Accept both so a re-sanitize is lossless.
+ const location = (frame.location ?? frame) as Record<string, unknown>;
+ frames.push({
+ functionName:
+ typeof frame.functionName === "string" && frame.functionName
+ ? frame.functionName
+ : "(anonymous)",
+ url: redactFrameUrl(frame.url),
+ lineNumber: toNumber(location.lineNumber),
+ columnNumber: toNumber(location.columnNumber),
+ });
+ }
+ return frames.length > 0 ? frames : null;
+}
+
+/**
+ * Keep only the bundle-relative tail of a script URL. The full value is a
+ * `file://` path into the install location and can carry the OS username.
+ * Idempotent, so running it again on an already-reduced value is a no-op —
+ * which is what lets the egress side re-apply it to a frame of unknown origin.
+ */
+export function redactFrameUrl(url: unknown): string {
+ if (typeof url !== "string" || !url) return "";
+ const [withoutQuery = ""] = url.split(/[?#]/);
+ const segments = withoutQuery.split("/").filter(Boolean);
+ if (segments.length === 0) return "";
+ return segments.slice(-2).join("/");
+}
+
+function toNumber(value: unknown): number {
+ return typeof value === "number" && Number.isFinite(value) ? value : 0;
+}
diff --git a/packages/core/analytics/index.ts b/packages/core/analytics/index.ts
index 6f403f566c..a4abdb03dc 100644
--- a/packages/core/analytics/index.ts
+++ b/packages/core/analytics/index.ts
@@ -47,7 +47,12 @@ let analyticsEnvironment = "dev";
// only ever carry user-triggered signals on identified users, so the
// buffer stays small (~one step-transition worth).
type PendingOp =
- | { kind: "event"; name: string; props?: Record<string, unknown> }
+ | {
+ kind: "event";
+ name: string;
+ props?: Record<string, unknown>;
+ options?: CaptureEventOptions;
+ }
| { kind: "set"; props: Record<string, unknown> }
| { kind: "exception"; error: unknown; props?: Record<string, unknown> };
const pendingOps: PendingOp[] = [];
@@ -186,7 +191,7 @@ export function initAnalytics(config: AnalyticsConfig | null | undefined): boole
while (pendingOps.length > 0) {
const op = pendingOps.shift()!;
if (op.kind === "event") {
- posthog.capture(op.name, withClientEventProperties(op.props));
+ captureNow(op.name, op.props, op.options);
} else if (op.kind === "exception") {
posthog.captureException(op.error, withClientEventProperties(op.props));
} else {
@@ -242,15 +247,53 @@ export function resetAnalytics(): void {
* Calls before initAnalytics() buffer in order so a late-arriving config
* doesn't silently swallow a step transition.
*/
+export interface CaptureEventOptions {
+ /**
+ * Bypass posthog-js's batching timer and put the event on the wire now.
+ * Batching is a JS timer in the same thread that is about to freeze or be
+ * killed, so a failure report queued normally can be lost exactly when it
+ * matters (MUL-4115: three deterministic hangs, zero events delivered).
+ * Reserve this for failure telemetry — routine events should batch.
+ */
+ sendInstantly?: boolean;
+ /**
+ * Fired once the event has been handed to posthog.capture.
+ *
+ * This is HAND-OFF, not delivery: the request may still be in flight, and
+ * posthog-js exposes no delivery callback to wait on. Never treat it as
+ * permission to discard the only copy of something — a caller that deletes
+ * persisted state here loses it whenever the app dies between hand-off and
+ * the wire (see freeze-flush.ts, which waits out a grace window instead).
+ *
+ * It also never fires on a build with analytics disabled, so anything
+ * waiting on it needs an expiry path of its own.
+ */
+ onCaptured?: () => void;
+}
+
export function captureEvent(
name: string,
props?: Record<string, unknown>,
+ options?: CaptureEventOptions,
): void {
if (!initialized) {
- pendingOps.push({ kind: "event", name, props });
+ pendingOps.push({ kind: "event", name, props, options });
return;
}
- posthog.capture(name, withClientEventProperties(props));
+ captureNow(name, props, options);
+}
+
+function captureNow(
+ name: string,
+ props?: Record<string, unknown>,
+ options?: CaptureEventOptions,
+): void {
+ posthog.capture(
+ name,
+ withClientEventProperties(props),
+ options?.sendInstantly ? { send_instantly: true } : undefined,
+ );
+ options?.onCaptured?.();
}
/**