Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
refactor(diagnostics): drop the dead hang telemetry (MUL-5345) (#6433)
Naiyuan Qingaaedb864a01a
diff --git a/apps/desktop/src/main/diagnostics-control-registry.test.ts b/apps/desktop/src/main/diagnostics-control-registry.test.tsdeleted file mode 100644index 5e4e6beaaa..0000000000--- a/apps/desktop/src/main/diagnostics-control-registry.test.ts+++ /dev/null@@ -1,103 +0,0 @@-/**- * 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.tsdeleted file mode 100644index fa7d64b146..0000000000--- a/apps/desktop/src/main/diagnostics-control-registry.ts+++ /dev/null@@ -1,58 +0,0 @@-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/index.ts b/apps/desktop/src/main/index.tsindex b71805ef38..17b75327f5 100644--- a/apps/desktop/src/main/index.ts+++ b/apps/desktop/src/main/index.ts@@ -32,13 +32,6 @@ import {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,@@ -150,35 +143,6 @@ const rendererRouteContexts = new WeakMap<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" },@@ -489,7 +453,6 @@ 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) =>@@ -573,7 +536,6 @@ function createIssueWindow(context: IssueWindowContext): void {const routeContext = rendererRouteContexts.get(window.webContents);return routeContext ? { desktopRoute: routeContext } : {};},- captureStack: () => captureStackIfEnabled(window.webContents),persistBreadcrumb: is.dev? undefined: (payload) =>@@ -766,14 +728,6 @@ if (!gotTheLock) {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// boot. If desktop.json exists but is invalid, renderer receives the// blocking error and must not silently fall back to the cloud defaults.diff --git a/apps/desktop/src/main/renderer-recovery.test.ts b/apps/desktop/src/main/renderer-recovery.test.tsindex 5de27083b4..22d75394e0 100644--- a/apps/desktop/src/main/renderer-recovery.test.ts+++ b/apps/desktop/src/main/renderer-recovery.test.ts@@ -208,7 +208,7 @@ describe("freeze/crash breadcrumb state machine", () => {expect(clearBreadcrumb).not.toHaveBeenCalled();});- it("recovering after a written breadcrumb clears it (no double-count, no false recovered:false)", async () => {+ it("recovering after a written breadcrumb clears it, so the in-thread watchdog is the only reporter", async () => {vi.useFakeTimers();const fixture = makeWindow();const { persistBreadcrumb, clearBreadcrumb } = install(fixture);@@ -269,89 +269,3 @@ 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.tsindex 61e4fefbea..b079be2e67 100644--- a/apps/desktop/src/main/renderer-recovery.ts+++ b/apps/desktop/src/main/renderer-recovery.ts@@ -33,14 +33,6 @@ 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;};@@ -55,7 +47,6 @@ export function installRendererRecoveryHandlers(getDiagnosticContext,persistBreadcrumb,clearBreadcrumb,- captureStack,log = noopDevLog,unresponsivePromptDelayMs = 1500,}: RendererRecoveryOptions,@@ -104,19 +95,14 @@ export function installRendererRecoveryHandlers(if (isDev || unresponsivePromptTimer) return;unresponsivePromptTimer = setTimeout(() => {unresponsivePromptTimer = null;- void reportHang();+ 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 reportHang = () => {const payload: ReloadPromptPayload = {kind: "unresponsive",- context: mergeDiagnosticContext(stack ? { stack } : {}),+ context: mergeDiagnosticContext({}),};persistBreadcrumb?.(payload);unresponsiveBreadcrumbWritten = true;@@ -206,18 +192,6 @@ 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.tsdeleted file mode 100644index cabda6c911..0000000000--- a/apps/desktop/src/main/renderer-stack-capture.test.ts+++ /dev/null@@ -1,274 +0,0 @@-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.tsdeleted file mode 100644index d169e4aa2b..0000000000--- a/apps/desktop/src/main/renderer-stack-capture.ts+++ /dev/null@@ -1,193 +0,0 @@-// 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.tsindex 460ef55488..524810f213 100644--- a/apps/desktop/src/preload/index.d.ts+++ b/apps/desktop/src/preload/index.d.ts@@ -2,7 +2,6 @@ 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,@@ -74,8 +73,6 @@ 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.tsindex 85f68eefcf..4d96bf9f37 100644--- a/apps/desktop/src/preload/index.ts+++ b/apps/desktop/src/preload/index.ts@@ -10,10 +10,6 @@ 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,@@ -206,10 +202,6 @@ 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.tsxindex b88866c0af..de894d01eb 100644--- a/apps/desktop/src/renderer/src/App.tsx+++ b/apps/desktop/src/renderer/src/App.tsx@@ -24,7 +24,6 @@ import { RESOURCES } from "@multica/views/locales";import { DesktopClientUsageReporter } from "./platform/client-usage-reporter";import { DiagnosticRouteReporter } from "./platform/diagnostic-route-reporter";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";@@ -452,7 +451,6 @@ export default function App() {><DesktopAuthSessionBridge />{windowContext.kind === "main" && <DiagnosticRouteReporter />}- <DiagnosticsControlReporter />{windowContext.kind === "main" && (<DesktopClientUsageReporterapiUrl={runtimeConfigResult.config.apiUrl}diff --git a/apps/desktop/src/renderer/src/freeze-flush.test.ts b/apps/desktop/src/renderer/src/freeze-flush.test.tsindex 35698220fb..7d291b3772 100644--- a/apps/desktop/src/renderer/src/freeze-flush.test.ts+++ b/apps/desktop/src/renderer/src/freeze-flush.test.ts@@ -28,10 +28,6 @@ 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 },- ],},};@@ -117,21 +113,13 @@ describe("ack is not delivery", () => {});describe("telemetry props carry no raw identifiers", () => {- it("ships the bucketed route and the stack", () => {+ it("ships the bucketed route and nothing else", () => {expect(buildFreezeEventProps(hang)).toEqual({source: "main-unresponsive",- recovered: false,breadcrumb_ts: hang.ts,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,});});@@ -161,22 +149,22 @@ describe("telemetry props carry no raw identifiers", () => {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", () => {+ // MUL-5345: stack capture is gone, but a machine upgrading from v0.4.13–+ // v0.4.18 can still have a pending breadcrumb whose context holds a captured+ // stack — including the live handles the old capture path never shipped but+ // the on-disk file could carry. The whitelist is what keeps that off the+ // wire now that nothing sanitizes frames anymore.+ it("drops a stack left in a breadcrumb written by an older build", () => {const props = buildFreezeEventProps({...hang,context: {+ ...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",},],},@@ -184,29 +172,11 @@ describe("telemetry props carry no raw identifiers", () => {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");- }+ expect(serialized).not.toContain("blockMainThread");+ 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", () => {@@ -221,11 +191,11 @@ describe("telemetry props carry no raw identifiers", () => {it("cannot have its own fields overridden by the context", () => {const props = buildFreezeEventProps({...hang,- context: { ...hang.context, source: "spoofed", recovered: true },+ context: { ...hang.context, source: "spoofed", breadcrumb_ts: 1 },});expect(props.source).toBe("main-unresponsive");- expect(props.recovered).toBe(false);+ expect(props.breadcrumb_ts).toBe(hang.ts);});it("keeps the crash reason as two scalars", () => {@@ -247,7 +217,6 @@ describe("telemetry props carry no raw identifiers", () => {expect(props).toEqual({source: "main-unresponsive",- recovered: false,breadcrumb_ts: hang.ts,crashed_version: "0.4.11",});diff --git a/apps/desktop/src/renderer/src/freeze-flush.ts b/apps/desktop/src/renderer/src/freeze-flush.tsindex e9814fb2f2..22ef3d2bb1 100644--- a/apps/desktop/src/renderer/src/freeze-flush.ts+++ b/apps/desktop/src/renderer/src/freeze-flush.ts@@ -1,6 +1,5 @@import type { CaptureEventOptions } from "@multica/core/analytics";import type { FreezeBreadcrumb } from "../../shared/freeze-breadcrumb";-import { sanitizeHangStackFrames } from "../../shared/hang-stack";// Reporting a failure the previous session couldn't report itself.//@@ -87,11 +86,9 @@ export function buildFreezeEventProps(return {source: crashed ? "render-process-gone" : "main-unresponsive",- recovered: false,breadcrumb_ts: breadcrumb.ts,crashed_version: breadcrumb.version,...routeProps(context.desktopRoute),- ...stackProps(context.stack),...crashProps(context.details),};}@@ -111,33 +108,6 @@ 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.tsxdeleted file mode 100644index b8f129e9fd..0000000000--- a/apps/desktop/src/renderer/src/platform/diagnostics-control-reporter.test.tsx+++ /dev/null@@ -1,88 +0,0 @@-/**- * 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.tsxdeleted file mode 100644index 93879aed36..0000000000--- a/apps/desktop/src/renderer/src/platform/diagnostics-control-reporter.tsx+++ /dev/null@@ -1,30 +0,0 @@-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.tsdeleted file mode 100644index 7f867d5e41..0000000000--- a/apps/desktop/src/shared/diagnostics-control.test.ts+++ /dev/null@@ -1,47 +0,0 @@-/**- * 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.tsdeleted file mode 100644index 06b9dd1a34..0000000000--- a/apps/desktop/src/shared/diagnostics-control.ts+++ /dev/null@@ -1,35 +0,0 @@-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.tsdeleted file mode 100644index 411e386c85..0000000000--- a/apps/desktop/src/shared/hang-stack.test.ts+++ /dev/null@@ -1,123 +0,0 @@-/**- * 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.tsdeleted file mode 100644index 04c433fe63..0000000000--- a/apps/desktop/src/shared/hang-stack.ts+++ /dev/null@@ -1,77 +0,0 @@-/**- * 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/server/internal/featureflags/keys.go b/server/internal/featureflags/keys.goindex b85f590595..16300020ef 100644--- a/server/internal/featureflags/keys.go+++ b/server/internal/featureflags/keys.go@@ -13,12 +13,6 @@ const (// The access model exists to gate Composio sharing, so the two ship on the// same switch.ComposioMCPApps = "composio_mcp_apps"- // DesktopHangStackCapture gates reading a JS call stack out of a hung- // desktop renderer (MUL-5345). Capture holds a debugger channel open on- // every renderer, so the desktop client is fail-closed: it stays off unless- // this key arrives as an explicit true. That makes publishing the key here- // mandatory — a key the client never receives can never be turned on.- DesktopHangStackCapture = "desktop_hang_stack_capture"// agentBuilderCompat is no longer a release flag. Keep publishing the key// as enabled so installed desktop clients that still gate the AI creation// entry on this config decision receive the permanently enabled behavior.@@ -38,17 +32,12 @@ const (var frontendPublicFlags = []string{ComposioMCPApps,- DesktopHangStackCapture,}func ComposioMCPAppsEnabled(ctx context.Context, flags *featureflag.Service) bool {return flags.IsEnabled(ctx, ComposioMCPApps, false)}-func DesktopHangStackCaptureEnabled(ctx context.Context, flags *featureflag.Service) bool {- return flags.IsEnabled(ctx, DesktopHangStackCapture, false)-}-func EvaluateFrontendPublicFlags(ctx context.Context, flags *featureflag.Service) map[string]bool {out := make(map[string]bool, len(frontendPublicFlags)+3)for _, key := range frontendPublicFlags {diff --git a/server/internal/featureflags/keys_test.go b/server/internal/featureflags/keys_test.goindex ede92ae568..3ec72eaa8a 100644--- a/server/internal/featureflags/keys_test.go+++ b/server/internal/featureflags/keys_test.go@@ -12,26 +12,15 @@ func TestResourceLabelsCompatDecisionStaysEnabled(t *testing.T) {}}-// MUL-5345: the desktop client is fail-closed on this flag, so it stays off-// unless the key arrives as an explicit true. A key that is never published-// can therefore never be turned on — which is exactly what happened when the-// desktop side shipped without this entry: hang stack capture was inert in-// production and no amount of flag configuration could have enabled it.-func TestDesktopHangStackCaptureIsPublishedToClients(t *testing.T) {+// MUL-5345: hang stack capture is gone from this build, but v0.4.13–v0.4.18 are+// installed and still hold a debugger channel open on every renderer whenever+// this key arrives as `true`. Those clients are fail-closed on absence, so NOT+// publishing the key is what disarms them — re-adding it would put a flag flip+// back within reach of a fleet that can no longer produce a usable stack.+func TestDesktopHangStackCaptureIsNotPublished(t *testing.T) {flags := EvaluateFrontendPublicFlags(context.Background(), nil)- if _, published := flags[DesktopHangStackCapture]; !published {- t.Fatal("desktop hang stack capture flag must be published, or the client can never enable it")- }-}--func TestDesktopHangStackCaptureDefaultsToOff(t *testing.T) {- ctx := context.Background()- if DesktopHangStackCaptureEnabled(ctx, nil) {- t.Fatal("hang stack capture must default to off")- }- flags := EvaluateFrontendPublicFlags(ctx, nil)- if flags[DesktopHangStackCapture] {- t.Fatal("published default must be off until it is deliberately enabled")+ if _, published := flags["desktop_hang_stack_capture"]; published {+ t.Fatal("hang stack capture must stay unpublished so installed clients keep their debugger channels closed")}}