Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
feat(observability): log child-process-gone, window hangs and WebGL context losses
Brandon Bridgesc82bf82932b7
diff --git a/CLAUDE.md b/CLAUDE.mdindex dfd213f40..fde016d4d 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -250,6 +250,24 @@ PTY output flows main → renderer over per-session channels (`pty:data:<sessioninput flows renderer → main over `pty:write`. node-pty is kept **external** in the bundle(`externalizeDepsPlugin` in `electron.vite.config.ts`) because it's a native module.+**Process death and hangs are telemetry, never triggers** (audit roadmap #6, tmux-2 / obs-5).+Until then the only handler was `render-process-gone`, and it logged nothing, so a GPU-process+crash or a renderer hang left no trace. Now app `child-process-gone` (`{type, reason, exitCode,+name}`, per-type session count; `clean-exit` at info, every other reason at warn), the main window's+`unresponsive` → `responsive` pair (one line per hang, duration measured from Electron's own hang+timeout so it is a lower bound) and `render-process-gone` each write a `[process]` line to the+debug log ring (`main/process-health-log.ts`, wired in `index.ts`). `child-process-gone` is+registered before `ready` because the GPU process can die during boot. None of them reloads,+relaunches or kills anything: Chromium respawns the GPU process itself, and repeated GPU deaths+can trip its per-domain 3D-API block "until restart" (the audit's tmux-4), so provoking more of+them degrades the session. In the renderer, `webgl-budget.ts` counts EXTERNAL WebGL losses by+kind through `handle.contextLost(kind)` — `lost` (the addon's `onContextLoss`: still lost after+its 3s window) and `restored` (a GPU reset the browser recovered, which `TerminalNode` rebuilds on+a fresh addon) — and writes one `[webgl]` warn per loss carrying the session totals, which main's+`console-message` mirror puts in the ring. Our own `loseWebglContexts` releases are counted as+`released` and never logged per event (routine churn on every pan). A Server Edition tab has no+main, so its `[webgl]` lines stay in the browser console.+## Key abstraction: TerminalTransportThis is the load-bearing design decision. The renderer depends only on thediff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex 5c7dc80ed..b5fae7db6 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -1043,6 +1043,13 @@ happened synchronously at your `console.log`, and wrapping that call in `try/cat(measured on node 22). If you write to a stream that can go away, attach an `'error'` listener andlatch the writer off — `installLogSink` (`src/core/log-sink.ts`) is the worked example. Issue #382.+**A dead or hung process is logged, never acted on.** `child-process-gone`, window+`unresponsive`/`responsive` and external WebGL context losses each write one tagged line to the+debug log ring (`main/process-health-log.ts`, `[webgl]` in `terminal/webgl-budget.ts`) and nothing+else. Chromium respawns its own GPU process; a reload or relaunch on top of that turns a GPU reset+into a lost session. If you add a loss path, report it through `handle.contextLost(kind)` so the+external counts stay apart from our own `loseWebglContexts` releases.+**A retry budget must measure the thing it is waiting for, and running out must be VISIBLE.** Thearmed-launch loop (canvas-control `--after`, and the cold open a `--project` node gets) delivered itsheld command on a flat 5 × 400 ms budget started when the *canvas* held the node — so on a colddiff --git a/src/main/index.ts b/src/main/index.tsindex c6be3a355..848e1ec4b 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -22,6 +22,14 @@ import { IPC } from '../shared/ipc'// in-memory and redacted at its push boundary; the panel/IPC side is gated on the setting.const logBuffer = new LogBuffer()installLogSink(logBuffer)+// Process-death telemetry (audit roadmap #6, tmux-2 / obs-5): a GPU-process crash used to leave+// no trace at all. Registered here, before 'ready', because the GPU process launches during boot+// and can die there. LOG ONLY — Chromium respawns the GPU process itself; see process-health-log.ts.+const childProcessGoneLine = createChildProcessGoneLog()+app.on('child-process-gone', (_event, details) => {+ const { level, msg } = childProcessGoneLine(details)+ console[level](`[process] ${msg}`)+})import { nativeMux, setNativeWindowsAgentOptIn, useNativeSsh } from '../core/remote-ssh/native/native-runtime'import { writeFilesToClipboard } from './clipboard-files'import { writeWindowsFileDrop } from './clipboard-files-win'@@ -189,6 +197,7 @@ import {import { answerHeldPermission, isStructuredTicket, type HeldPermissionIo } from '../core/agents/permission-decision'import type { AnswerPermissionPayload } from '../shared/agents/permission-answer'import { setMainWindow, getMainWindow, sendToMain, closeAction, createCrashReloadPolicy } from './main-window'+import { createChildProcessGoneLog, createHangTracker, formatRenderProcessGone } from './process-health-log'import { WINDOW_VISIBILITY_EVENTS, windowVisibilitySignal } from './window-visibility'import {MENU_ITEM_ID_CLOSE,@@ -1389,7 +1398,21 @@ function createWindow(): BrowserWindow {})}const crashReload = createCrashReloadPolicy()+ // Renderer hangs (audit roadmap #6): Electron declares one after its own input-ack timeout and+ // clears it on the next ack. Paired into one line with a duration; logged, never acted on.+ const hangs = createHangTracker()+ win.on('unresponsive', () => {+ const line = hangs.unresponsive(Date.now())+ if (line) console[line.level](`[process] ${line.msg}`)+ })+ win.on('responsive', () => {+ const line = hangs.responsive(Date.now())+ if (line) console[line.level](`[process] ${line.msg}`)+ })win.webContents.on('render-process-gone', (_event, details) => {+ // The ring's only record that the page died — the reload below wipes the renderer's own console.+ const gone = formatRenderProcessGone(details)+ console[gone.level](`[process] ${gone.msg}`)ptyManager.dropClient(presenceId)// A dead renderer sends no disarm and no focus-lost report. The reloaded page mounts no// recorder and no terminal, so without this the user would come back to an app where ⌘W doesdiff --git a/src/main/process-health-log.test.ts b/src/main/process-health-log.test.tsnew file mode 100644index 000000000..ce99ba7af--- /dev/null+++ b/src/main/process-health-log.test.ts@@ -0,0 +1,83 @@+import { describe, it, expect } from 'vitest'+import { createChildProcessGoneLog, createHangTracker, formatRenderProcessGone } from './process-health-log'++describe('createChildProcessGoneLog', () => {+ it('logs a GPU crash at warn with type, reason, exitCode and a per-type session count', () => {+ const log = createChildProcessGoneLog()+ expect(log({ type: 'GPU', reason: 'crashed', exitCode: 11 })).toEqual({+ level: 'warn',+ msg: 'GPU process gone: reason=crashed exitCode=11 — #1 GPU this session'+ })+ expect(log({ type: 'GPU', reason: 'killed', exitCode: 9 }).msg).toContain('#2 GPU this session')+ })++ it('counts each process type on its own', () => {+ const log = createChildProcessGoneLog()+ log({ type: 'GPU', reason: 'crashed', exitCode: 11 })+ expect(log({ type: 'Utility', reason: 'oom', exitCode: 0, name: 'Audio Service' }).msg).toBe(+ 'Utility (Audio Service) process gone: reason=oom exitCode=0 — #1 Utility this session'+ )+ })++ it('treats a clean-exit as routine (info), every other reason as a real death (warn)', () => {+ const log = createChildProcessGoneLog()+ expect(log({ type: 'Utility', reason: 'clean-exit', exitCode: 0, serviceName: 'network.mojom.NetworkService' }).level).toBe('info')+ for (const reason of ['abnormal-exit', 'killed', 'crashed', 'oom', 'launch-failed', 'integrity-failure', 'memory-eviction']) {+ expect(log({ type: 'GPU', reason, exitCode: 1 }).level).toBe('warn')+ }+ })++ it('falls back to serviceName when name is absent, and to the bare type when both are', () => {+ const log = createChildProcessGoneLog()+ expect(log({ type: 'Utility', reason: 'crashed', exitCode: 1, serviceName: 'svc' }).msg).toMatch(/^Utility \(svc\) /)+ expect(log({ type: 'Zygote', reason: 'crashed', exitCode: 1 }).msg).toMatch(/^Zygote process gone/)+ })++ it('keeps its count per instance (no module-global state)', () => {+ createChildProcessGoneLog()({ type: 'GPU', reason: 'crashed', exitCode: 11 })+ expect(createChildProcessGoneLog()({ type: 'GPU', reason: 'crashed', exitCode: 11 }).msg).toContain('#1 GPU')+ })+})++describe('formatRenderProcessGone', () => {+ it('warns on a crash, informs on a deliberate teardown', () => {+ expect(formatRenderProcessGone({ reason: 'oom', exitCode: 0 })).toEqual({+ level: 'warn',+ msg: 'renderer process gone: reason=oom exitCode=0'+ })+ expect(formatRenderProcessGone({ reason: 'clean-exit', exitCode: 0 }).level).toBe('info')+ })+})++describe('createHangTracker', () => {+ it('pairs unresponsive → responsive into one hang with its duration', () => {+ const t = createHangTracker()+ expect(t.unresponsive(1000)).toEqual({ level: 'warn', msg: 'window unresponsive — hang #1 this session' })+ const back = t.responsive(4250)+ expect(back?.msg).toMatch(/^window responsive again after 3250 ms /)+ expect(back?.msg).toContain('hang #1')+ })++ it('a repeat unresponsive while hung keeps the FIRST timestamp and logs nothing', () => {+ const t = createHangTracker()+ t.unresponsive(1000)+ expect(t.unresponsive(2000)).toBeNull()+ expect(t.responsive(5000)?.msg).toContain('after 4000 ms')+ })++ it('a responsive with no open hang logs nothing (an unmeasured duration is not zero)', () => {+ const t = createHangTracker()+ expect(t.responsive(1000)).toBeNull()+ t.unresponsive(2000)+ t.responsive(3000)+ expect(t.responsive(4000)).toBeNull()+ })++ it('numbers successive hangs, and never reports a negative duration on a clock step back', () => {+ const t = createHangTracker()+ t.unresponsive(1000)+ t.responsive(2000)+ expect(t.unresponsive(5000)?.msg).toContain('hang #2')+ expect(t.responsive(4000)?.msg).toContain('after 0 ms')+ })+})diff --git a/src/main/process-health-log.ts b/src/main/process-health-log.tsnew file mode 100644index 000000000..716fb9610--- /dev/null+++ b/src/main/process-health-log.ts@@ -0,0 +1,103 @@+// Process-death and hang telemetry for the debug log ring (audit roadmap #6, tmux-2 / obs-5).+//+// Before this, the only process-death handler was the main window's `render-process-gone`, and+// it logged nothing: a GPU-process crash, a utility-process OOM or a multi-second renderer hang+// left no trace anywhere a user could copy out of the app. These helpers only FORMAT a line and+// keep a cheap per-session count; `index.ts` emits it through `console.*` with a `[tag]` prefix,+// which is the log-sink convention (`core/log-sink.ts`) — the ring gets it, redacted, and the dev+// terminal still sees it.+//+// OBSERVE, NEVER ACT. Nothing here reloads, relaunches or kills anything. Chromium respawns a+// dead GPU process itself; relaunching on top of that would turn a recoverable GPU reset into a+// lost session (and the audit's tmux-4 note: repeated GPU deaths can trip Chromium's per-domain+// 3D-API block "until restart", so anything that provokes more of them degrades the session).+//+// Electron-free on purpose (structural types only) so it unit-tests without an Electron runtime.++export type HealthLevel = 'info' | 'warn'++export interface HealthLine {+ level: HealthLevel+ msg: string+}++/** The subset of Electron's `Details` (app 'child-process-gone') we read. */+export interface ChildProcessGoneDetails {+ type: string+ reason: string+ exitCode: number+ name?: string+ serviceName?: string+}++/**+ * Format app 'child-process-gone' and count it per process type for the session. Returns a+ * stateful formatter so the count lives with the app, not in a module global a test would leak.+ *+ * Only `{type, reason, exitCode, name}` — the audit's field list. `name` / `serviceName` are+ * Chromium's fixed service labels ("Audio Service", "Network Service"), never a path or argv.+ *+ * Level: a `clean-exit` is Chromium tearing down a utility process it no longer needs — routine,+ * so `info`, or the ring would fill with non-events. Every other reason (crashed, oom, killed,+ * abnormal-exit, launch-failed, integrity-failure, memory-eviction) is a real death → `warn`.+ */+export function createChildProcessGoneLog(): (d: ChildProcessGoneDetails) => HealthLine {+ const counts = new Map<string, number>()+ return (d) => {+ const n = (counts.get(d.type) ?? 0) + 1+ counts.set(d.type, n)+ const label = d.name || d.serviceName+ const who = label ? `${d.type} (${label})` : d.type+ return {+ level: d.reason === 'clean-exit' ? 'info' : 'warn',+ msg: `${who} process gone: reason=${d.reason} exitCode=${d.exitCode} — #${n} ${d.type} this session`+ }+ }+}++/** Format webContents 'render-process-gone' — the existing crash-reload handler's trace line. */+export function formatRenderProcessGone(d: { reason: string; exitCode: number }): HealthLine {+ return {+ level: d.reason === 'clean-exit' ? 'info' : 'warn',+ msg: `renderer process gone: reason=${d.reason} exitCode=${d.exitCode}`+ }+}++export interface HangTracker {+ /** BrowserWindow 'unresponsive'. Returns the line to log, or null for a repeat while hung. */+ unresponsive(now: number): HealthLine | null+ /** BrowserWindow 'responsive'. Returns the line to log, or null if we never saw it hang. */+ responsive(now: number): HealthLine | null+}++/**+ * Pair BrowserWindow 'unresponsive' / 'responsive' into one hang with a duration. Electron fires+ * 'unresponsive' only after its own hang timeout (several seconds of no input ack), so the+ * logged duration is "from the hang being declared", a lower bound on the real stall — said in+ * the message so nobody reads it as the whole freeze.+ *+ * Edges: a second 'unresponsive' before a 'responsive' keeps the FIRST timestamp (one hang, not+ * two); a 'responsive' with no open hang (listener attached mid-hang, or a reload reset) logs+ * nothing — a duration we cannot measure is not reported as zero.+ */+export function createHangTracker(): HangTracker {+ let since: number | null = null+ let hangs = 0+ return {+ unresponsive(now) {+ if (since !== null) return null+ since = now+ hangs+++ return { level: 'warn', msg: `window unresponsive — hang #${hangs} this session` }+ },+ responsive(now) {+ if (since === null) return null+ const ms = Math.max(0, now - since)+ since = null+ return {+ level: 'warn',+ msg: `window responsive again after ${ms} ms (counted from Electron's hang timeout, so the real stall was longer) — hang #${hangs}`+ }+ }+ }+}diff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsxindex 647719557..1bf4cf4e2 100644--- a/src/renderer/nodes/TerminalNode.tsx+++ b/src/renderer/nodes/TerminalNode.tsx@@ -2701,7 +2701,7 @@ export function TerminalNode({webgl = nullverifyCleanDomState('context-restored')fullRepaint()- webglHandle?.contextLost()+ webglHandle?.contextLost('restored')})// A fresh addon starts from an EMPTY model; the swap's own refresh is the exact one// that gets swallowed when this grant races a park/pause. Repaint unconditionally.diff --git a/src/renderer/terminal/webgl-budget.test.ts b/src/renderer/terminal/webgl-budget.test.tsindex 38c15c970..fcebf4757 100644--- a/src/renderer/terminal/webgl-budget.test.ts+++ b/src/renderer/terminal/webgl-budget.test.ts@@ -4,6 +4,8 @@ import {__resetWebglBudgetForTests,getWebglBudget,loseWebglContexts,+ getWebglLossCounts,+ formatWebglLoss,releaseAllHiddenGrants,setWebglBudget,setWebglEnabled,@@ -816,3 +818,67 @@ describe('loseWebglContexts', () => {expect(loseWebglContexts(null)).toBe(0)})})++describe('WebGL loss telemetry (audit roadmap #6)', () => {+ let warn: ReturnType<typeof vi.spyOn>+ beforeEach(() => {+ vi.useFakeTimers()+ __resetWebglBudgetForTests()+ warn = vi.spyOn(console, 'warn').mockImplementation(() => {})+ })+ afterEach(() => {+ warn.mockRestore()+ __resetWebglBudgetForTests()+ vi.useRealTimers()+ })++ it('counts the two EXTERNAL kinds apart and writes one [webgl] line per loss', () => {+ const a = fakeClient('a')+ const b = fakeClient('b')+ grant(a)+ grant(b)+ a.handle.contextLost() // the addon's onContextLoss (default kind)+ b.handle.contextLost('restored') // lost + restored by the browser, rebuilt by us+ expect(getWebglLossCounts()).toEqual({ lost: 1, restored: 1, released: 0 })+ expect(warn).toHaveBeenCalledTimes(2)+ const [first] = warn.mock.calls[0] as [string]+ const [second] = warn.mock.calls[1] as [string]+ expect(first).toMatch(/^\[webgl\] context lost \(not restored/)+ // `held` is the count AFTER the loss: two were granted, a's is gone.+ expect(first).toContain(`1 lost, 0 restored externally; 0 released by us; 1/${WEBGL_BUDGET} held`)+ expect(second).toContain('restored by the browser')+ expect(second).toContain(`1 lost, 1 restored externally; 0 released by us; 0/${WEBGL_BUDGET} held`)+ })++ it('counts a loss reported through a superseded handle, without touching the live grant', () => {+ const old = fakeClient('a')+ grant(old)+ const live = fakeClient('a') // re-register under the same id supersedes `old`+ grant(live)+ old.handle.contextLost()+ expect(getWebglLossCounts().lost).toBe(1)+ expect(live.rec.held).toBe(true)+ })++ it('counts self-inflicted releases separately and never logs them per event', () => {+ const lose = vi.fn()+ const canvas = { getContext: (t: string) => (t === 'webgl2' ? { getExtension: () => ({ loseContext: lose }) } : null) }+ loseWebglContexts([canvas, canvas] as never)+ expect(getWebglLossCounts()).toEqual({ lost: 0, restored: 0, released: 2 })+ expect(warn).not.toHaveBeenCalled()+ })++ it('a reset zeroes the counters', () => {+ const a = fakeClient('a')+ grant(a)+ a.handle.contextLost()+ __resetWebglBudgetForTests()+ expect(getWebglLossCounts()).toEqual({ lost: 0, restored: 0, released: 0 })+ })++ it('formats the line from its inputs alone', () => {+ expect(formatWebglLoss('lost', { lost: 3, restored: 12, released: 40 }, 8, 14)).toBe(+ '[webgl] context lost (not restored within the addon window) — this session: 3 lost, 12 restored externally; 40 released by us; 8/14 held'+ )+ })+})diff --git a/src/renderer/terminal/webgl-budget.ts b/src/renderer/terminal/webgl-budget.tsindex 9fdcf5f2b..a56e4a3ce 100644--- a/src/renderer/terminal/webgl-budget.ts+++ b/src/renderer/terminal/webgl-budget.ts@@ -355,9 +355,52 @@ export function loseWebglContexts(canvases: ArrayLike<HTMLCanvasElement> | null)// fail open — losing a context is an optimization, never worth breaking release for.}}+ lossCounts.released += lostreturn lost}+/**+ * Per-session WebGL loss telemetry (audit roadmap #6, tmux-2 / obs-5). Before this a GPU reset+ * left no trace: the terminals silently fell back to the DOM renderer and were re-granted, and+ * the only evidence was a user saying "the text went soft for a second". Each EXTERNAL loss now+ * writes one `[webgl]` warn — which main's `console-message` mirror carries into the debug log+ * ring with its tag (in a Server Edition browser tab it stays in the tab's console: no main, a+ * documented degrade) — and the line carries the running totals so a soak can read the budget's+ * real loss rate off any single entry.+ *+ * The two external kinds are counted apart because they are different failures:+ * - `lost`: the addon's own `onContextLoss` — the context stayed lost past the addon's 3s+ * restore window (force-eviction, or a GPU that did not come back).+ * - `restored`: the browser lost AND restored it (a GPU-process reset; sleep/wake) and we+ * rebuilt on a fresh addon instead of trusting the in-place recovery (TerminalNode.tsx).+ * `released` is the SELF-INFLICTED kind — `loseWebglContexts` on our own release — counted+ * separately so it is never mistaken for the browser taking contexts away, and never logged per+ * event (it is routine churn on every pan). Plain integer increments: free on the hot path.+ */+export type WebglLossKind = 'lost' | 'restored'+const lossCounts = { lost: 0, restored: 0, released: 0 }++export function getWebglLossCounts(): { lost: number; restored: number; released: number } {+ return { ...lossCounts }+}++/** The `[webgl]` line for one external loss, with the session totals (exported for the test). */+export function formatWebglLoss(+ kind: WebglLossKind,+ counts: { lost: number; restored: number; released: number },+ held: number,+ ceiling: number+): string {+ const what =+ kind === 'lost'+ ? 'context lost (not restored within the addon window)'+ : 'context lost and restored by the browser (GPU reset; rebuilding on a fresh addon)'+ return (+ `[webgl] ${what} — this session: ${counts.lost} lost, ${counts.restored} restored ` ++ `externally; ${counts.released} released by us; ${held}/${ceiling} held`+ )+}+/*** How long a client must stay continuously visible before it is granted a context. Absorbs fast* pans that sweep a node across the viewport for only a frame or two (which must not acquire).@@ -383,8 +426,9 @@ export interface WebglClientCallbacks {export interface WebglClientHandle {/** Report this node's viewport visibility (driven by its IntersectionObserver). */setVisible(visible: boolean): void- /** Report that the addon's own `onContextLoss` fired: drop this grant from the accounting. */- contextLost(): void+ /** Report that the context was lost from outside: drop this grant from the accounting.+ * `kind` only labels the telemetry (see `WebglLossKind`); the accounting is identical. */+ contextLost(kind?: WebglLossKind): void/** Node unmount: release any held context, cancel timers, and forget this client. */dispose(): void}@@ -596,8 +640,18 @@ export function registerWebglClient(id: string, callbacks: WebglClientCallbacks)const c = clients.get(id)if (c === client) setVisible(c, visible)},- contextLost() {+ contextLost(kind: WebglLossKind = 'lost') {+ // Counted BEFORE the stale-handle guard: the browser took a real context either way; only+ // the accounting below belongs to the live registration.+ lossCounts[kind] += 1const c = clients.get(id)+ try {+ // `held` AFTER this loss: the live grant being dropped below no longer holds a context.+ const held = grantCount() - (c === client && client.granted ? 1 : 0)+ console.warn(formatWebglLoss(kind, lossCounts, held, budget))+ } catch {+ /* telemetry must never break the loss path */+ }if (c !== client) return// The browser (or our own dispose) already tore the context down; drop the accounting.c.granted = false@@ -650,6 +704,9 @@ export function __resetWebglBudgetForTests(): void {devicePixelRatio = Number.POSITIVE_INFINITYgestureActive = falseowed.clear()+ lossCounts.lost = 0+ lossCounts.restored = 0+ lossCounts.released = 0if (drainTimer) {clearTimeout(drainTimer)drainTimer = null