The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(desktop): consent-gated renderer-crash recorder in the main process
teknium10fce280ee9e5
diff --git a/apps/desktop/electron/desktop-shared-metrics.test.ts b/apps/desktop/electron/desktop-shared-metrics.test.tsindex ed6bc78a0f4..fda4feb869b 100644--- a/apps/desktop/electron/desktop-shared-metrics.test.ts+++ b/apps/desktop/electron/desktop-shared-metrics.test.ts@@ -30,6 +30,7 @@ test('a packaged apply is reported once through the renderer IPC; a checkout hanconst metrics = registerDesktopSharedMetrics()expect(handlers.has('hermes:startup-latency:claim')).toBe(true)+ expect(handlers.has('hermes:desktop-metrics:crash:take')).toBe(true)await metrics.trackUpdateApply(null, strategy('checkout'))expect(handlers.get('hermes:updates:metric:take')!({})).toBeNull()diff --git a/apps/desktop/electron/desktop-shared-metrics.ts b/apps/desktop/electron/desktop-shared-metrics.tsindex 21758391523..f4d57a4c3e0 100644--- a/apps/desktop/electron/desktop-shared-metrics.ts+++ b/apps/desktop/electron/desktop-shared-metrics.ts@@ -1,9 +1,11 @@// Main-process shared-metrics wiring, kept out of main.ts: the once-per-launch startup-latency-// claim and the packaged self-update recorder the renderer drains once a backend is attached.+// claim, the packaged self-update recorder and the consent-gated renderer-crash recorder the+// renderer drains once a backend is attached.import { app, BrowserWindow, ipcMain } from 'electron'import { INSTALL_STAMP } from './install-stamp'+import { registerRendererCrashIpc, RendererCrashRecorder } from './renderer-crash-metrics'import { registerStartupLatencyIpc } from './startup-latency-ipc'import type { UpdaterApplyResultWire, UpdaterStrategy } from './updater/index'import { registerUpdateMetricsIpc, UpdateRunRecorder } from './updater/update-metrics'@@ -13,6 +15,8 @@ export interface DesktopSharedMetrics {/** Run `strategy.apply()`; recorded only when `packaged` (a checkout hand-off is counted by* `hermes update`'s own receipt). */trackUpdateApply(packaged: UpdaterStrategy | null, strategy: UpdaterStrategy): Promise<UpdaterApplyResultWire>+ /** `installWindowRendererLifecycle` hook: counts a live window's renderer loss (no-op until opt-in). */+ recordRendererGone(reason: unknown): void}export function registerDesktopSharedMetrics(): DesktopSharedMetrics {@@ -30,7 +34,12 @@ export function registerDesktopSharedMetrics(): DesktopSharedMetrics {registerUpdateMetricsIpc(ipcMain, recorder)+ const crashes = new RendererCrashRecorder({ dir: app.getPath('userData') })++ registerRendererCrashIpc(ipcMain, crashes)+return {+ recordRendererGone: reason => crashes.record(reason),noteUpdateProgress: stage => recorder.noteProgress(stage),trackUpdateApply: (packaged, strategy) =>recorder.track(packaged?.mechanism, INSTALL_STAMP?.commitDate, () => strategy.apply())diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.tsindex 2512e52c177..40afe37063e 100644--- a/apps/desktop/electron/main.ts+++ b/apps/desktop/electron/main.ts@@ -13606,7 +13606,8 @@ function spawnSecondaryWindow({isIntentionalTeardown: rendererTeardownInProgress,reloadWindowMs: RENDERER_RELOAD_WINDOW_MS,reloadMax: RENDERER_RELOAD_MAX,- recentReloadTimesRef: rendererReloadTimesRef+ recentReloadTimesRef: rendererReloadTimesRef,+ onRendererGone: reason => desktopMetrics.recordRendererGone(reason)})loadWindowUrl(@@ -15113,7 +15114,8 @@ function createWindow() {reloadWindowMs: RENDERER_RELOAD_WINDOW_MS,reloadMax: RENDERER_RELOAD_MAX,recentReloadTimesRef: rendererReloadTimesRef,- reloadOnFailedLoad: true+ reloadOnFailedLoad: true,+ onRendererGone: reason => desktopMetrics.recordRendererGone(reason)})// Electron always passes the event first. The canonical (Electron 36+) shapediff --git a/apps/desktop/electron/preload.ts b/apps/desktop/electron/preload.tsindex c7f992dd29d..fcaf229ad5c 100644--- a/apps/desktop/electron/preload.ts+++ b/apps/desktop/electron/preload.ts@@ -640,6 +640,11 @@ contextBridge.exposeInMainWorld('hermesDesktop', {return () => ipcRenderer.removeListener('hermes:updates:metric:pending', listener)}},+ desktopMetrics: {+ setEnabled: on => ipcRenderer.invoke('hermes:desktop-metrics:set-enabled', on),+ takeRendererCrashes: () => ipcRenderer.invoke('hermes:desktop-metrics:crash:take'),+ ackRendererCrashes: sent => ipcRenderer.invoke('hermes:desktop-metrics:crash:ack', sent)+ },themes: {fetchMarketplace: id => ipcRenderer.invoke('hermes:vscode-theme:fetch', id),searchMarketplace: query => ipcRenderer.invoke('hermes:vscode-theme:search', query)diff --git a/apps/desktop/electron/renderer-crash-metrics.test.ts b/apps/desktop/electron/renderer-crash-metrics.test.tsnew file mode 100644index 00000000000..ad4aea2249a--- /dev/null+++ b/apps/desktop/electron/renderer-crash-metrics.test.ts@@ -0,0 +1,158 @@+import fs from 'node:fs'+import os from 'node:os'+import path from 'node:path'++import { afterEach, beforeEach, describe, expect, test } from 'vitest'++import {+ MAX_PENDING_RENDERER_CRASHES,+ PENDING_RENDERER_CRASH_FILE,+ registerRendererCrashIpc,+ rendererCrashReason,+ RendererCrashRecorder+} from './renderer-crash-metrics'++let dir: string+let file: string++beforeEach(() => {+ dir = fs.mkdtempSync(path.join(process.env.TMPDIR || os.tmpdir(), 'hermes-renderer-crash-'))+ file = path.join(dir, PENDING_RENDERER_CRASH_FILE)+})++afterEach(() => fs.rmSync(dir, { recursive: true, force: true }))++function pending(): unknown {+ return JSON.parse(fs.readFileSync(file, 'utf8'))+}++function enabledRecorder(): RendererCrashRecorder {+ const recorder = new RendererCrashRecorder({ dir })+ recorder.setEnabled(true)++ return recorder+}++test('rendererCrashReason buckets Electron reasons', () => {+ expect(rendererCrashReason('crashed')).toBe('crash')+ expect(rendererCrashReason('oom')).toBe('oom')+ expect(rendererCrashReason('killed')).toBe('killed')++ for (const other of ['launch-failed', 'integrity-failure', 'abnormal-exit', undefined, 7, 'toString']) {+ expect(rendererCrashReason(other)).toBe('other')+ }+})++describe('RendererCrashRecorder', () => {+ test('records nothing until the user opts in', () => {+ const recorder = new RendererCrashRecorder({ dir })++ recorder.record('crashed')++ expect(fs.existsSync(file)).toBe(false)+ expect(recorder.take()).toBeNull()+ })++ test('persists only bucketed reasons, ignores clean-exit, and caps the list', () => {+ const recorder = enabledRecorder()++ recorder.record('crashed')+ recorder.record('clean-exit')+ recorder.record('oom')+ recorder.record('killed')+ recorder.record('launch-failed')++ expect(pending()).toEqual({ v: 1, reasons: ['crash', 'oom', 'killed', 'other'] })++ for (let i = 0; i < 30; i++) {+ recorder.record('killed')+ }++ const reasons = (pending() as { reasons: string[] }).reasons+ expect(reasons).toHaveLength(MAX_PENDING_RENDERER_CRASHES)+ expect(reasons.slice(0, 4)).toEqual(['crash', 'oom', 'killed', 'other'])+ })++ test('revoking consent deletes the pending file and stops recording', () => {+ const recorder = enabledRecorder()++ recorder.record('crashed')+ expect(fs.existsSync(file)).toBe(true)++ recorder.setEnabled(false)+ expect(fs.existsSync(file)).toBe(false)++ recorder.record('crashed')+ expect(fs.existsSync(file)).toBe(false)+ })++ test('take/ack: one claim at a time, a failed send keeps it, a sent ack keeps later crashes', () => {+ const recorder = enabledRecorder()++ recorder.record('crashed')+ recorder.record('oom')++ expect(recorder.take()).toEqual({ reasons: ['crash', 'oom'] })+ expect(recorder.take()).toBeNull()++ recorder.ack(false)+ expect(recorder.take()).toEqual({ reasons: ['crash', 'oom'] })++ recorder.record('killed')+ recorder.ack(true)++ expect(pending()).toEqual({ v: 1, reasons: ['killed'] })+ expect(recorder.take()).toEqual({ reasons: ['killed'] })++ recorder.ack(true)+ expect(fs.existsSync(file)).toBe(false)+ expect(recorder.take()).toBeNull()+ })++ test('a garbage or foreign file is treated as empty; unknown entries are dropped', () => {+ const recorder = enabledRecorder()++ fs.writeFileSync(file, 'not json {')+ expect(recorder.take()).toBeNull()++ fs.writeFileSync(file, JSON.stringify({ v: 2, reasons: ['crash'] }))+ expect(recorder.take()).toBeNull()++ fs.writeFileSync(file, JSON.stringify({ v: 1, reasons: ['crash', '/home/me/secret', 3, 'oom'] }))+ expect(recorder.take()).toEqual({ reasons: ['crash', 'oom'] })+ })++ test('fs errors never escape', () => {+ const boom = () => {+ throw new Error('EACCES')+ }++ const recorder = new RendererCrashRecorder({+ dir,+ fs: { mkdirSync: boom, readFileSync: boom, renameSync: boom, rmSync: boom, writeFileSync: boom } as never+ })++ recorder.setEnabled(true)+ expect(() => recorder.record('crashed')).not.toThrow()+ expect(recorder.take()).toBeNull()+ expect(() => recorder.setEnabled(false)).not.toThrow()+ })+})++test('registerRendererCrashIpc wires consent, take and ack', () => {+ const handlers = new Map<string, (event: unknown, ...args: unknown[]) => unknown>()+ const recorder = new RendererCrashRecorder({ dir })++ registerRendererCrashIpc({ handle: (channel, fn) => handlers.set(channel, fn) }, recorder)++ handlers.get('hermes:desktop-metrics:set-enabled')!({}, 'yes')+ recorder.record('crashed')+ expect(fs.existsSync(file)).toBe(false)++ handlers.get('hermes:desktop-metrics:set-enabled')!({}, true)+ recorder.record('crashed')+ expect(handlers.get('hermes:desktop-metrics:crash:take')!({})).toEqual({ reasons: ['crash'] })++ handlers.get('hermes:desktop-metrics:crash:ack')!({}, true)+ expect(fs.existsSync(file)).toBe(false)+})diff --git a/apps/desktop/electron/renderer-crash-metrics.ts b/apps/desktop/electron/renderer-crash-metrics.tsnew file mode 100644index 00000000000..a60cb0033f7--- /dev/null+++ b/apps/desktop/electron/renderer-crash-metrics.ts@@ -0,0 +1,162 @@+// Consent-gated renderer-crash counter for shared metrics. A crash can take the+// renderer (and its backend socket) down before anything is sent, so the main+// process persists a bucketed reason per render-process-gone and the renderer+// drains the list once a backend is attached (take/ack, like update-metrics.ts).+//+// Only the bucketed reason is stored — never exit codes, paths or window+// titles. Nothing is recorded or kept on disk until the renderer reports the+// user's opt-in, and revoking it deletes the pending file at once.++import fs from 'node:fs'+import path from 'node:path'++export type RendererCrashReason = 'crash' | 'oom' | 'killed' | 'other'++export const PENDING_RENDERER_CRASH_FILE = 'renderer-crash-pending.json'+export const MAX_PENDING_RENDERER_CRASHES = 20++const REASON_BY_ELECTRON: Readonly<Record<string, RendererCrashReason>> = {+ crashed: 'crash',+ oom: 'oom',+ killed: 'killed'+}++const KNOWN_REASONS: ReadonlySet<string> = new Set<RendererCrashReason>(['crash', 'oom', 'killed', 'other'])++export function rendererCrashReason(electronReason: unknown): RendererCrashReason {+ return typeof electronReason === 'string' && Object.hasOwn(REASON_BY_ELECTRON, electronReason)+ ? REASON_BY_ELECTRON[electronReason]+ : 'other'+}++export type RendererCrashFs = Pick<typeof fs, 'mkdirSync' | 'readFileSync' | 'renameSync' | 'rmSync' | 'writeFileSync'>++export interface RendererCrashRecorderOptions {+ dir: string+ fs?: RendererCrashFs+}++export class RendererCrashRecorder {+ private enabled = false+ private inFlight = false+ private taken = 0+ private readonly fs: RendererCrashFs+ private readonly file: string++ constructor(opts: RendererCrashRecorderOptions) {+ this.fs = opts.fs ?? fs+ this.file = path.join(opts.dir, PENDING_RENDERER_CRASH_FILE)+ }++ setEnabled(on: boolean): void {+ this.enabled = on++ if (!on) {+ this.inFlight = false+ this.taken = 0+ this.remove()+ }+ }++ record(electronReason: unknown): void {+ // A clean exit is a renderer shutting down normally, not a crash.+ if (!this.enabled || electronReason === 'clean-exit') {+ return+ }++ const reasons = this.read()++ if (reasons.length >= MAX_PENDING_RENDERER_CRASHES) {+ return+ }++ reasons.push(rendererCrashReason(electronReason))+ this.write(reasons)+ }++ /** Claim the pending reasons for one send; null when disabled, empty, or a claim is unacked. */+ take(): { reasons: RendererCrashReason[] } | null {+ if (!this.enabled || this.inFlight) {+ return null+ }++ const reasons = this.read()++ if (reasons.length === 0) {+ return null+ }++ this.inFlight = true+ this.taken = reasons.length++ return { reasons }+ }++ /** `sent` drops the claimed reasons (keeping any recorded since); false keeps them for the next attach. */+ ack(sent: boolean): void {+ if (!this.inFlight) {+ return+ }++ if (sent) {+ const rest = this.read().slice(this.taken)++ if (rest.length > 0) {+ this.write(rest)+ } else {+ this.remove()+ }+ }++ this.inFlight = false+ this.taken = 0+ }++ private read(): RendererCrashReason[] {+ try {+ const parsed = JSON.parse(String(this.fs.readFileSync(this.file, 'utf8'))) as { v?: unknown; reasons?: unknown }++ if (parsed?.v !== 1 || !Array.isArray(parsed.reasons)) {+ return []+ }++ return parsed.reasons+ .filter((reason): reason is RendererCrashReason => typeof reason === 'string' && KNOWN_REASONS.has(reason))+ .slice(0, MAX_PENDING_RENDERER_CRASHES)+ } catch {+ // Missing or unreadable: nothing pending.+ return []+ }+ }++ private write(reasons: RendererCrashReason[]): void {+ try {+ const tmp = `${this.file}.tmp`+ this.fs.mkdirSync(path.dirname(tmp), { recursive: true })+ this.fs.writeFileSync(tmp, JSON.stringify({ v: 1, reasons }))+ this.fs.renameSync(tmp, this.file)+ } catch {+ // Telemetry never breaks the app.+ }+ }++ private remove(): void {+ try {+ this.fs.rmSync(this.file, { force: true })+ } catch {+ // Retried on the next ack or opt-out.+ }+ }+}++interface IpcHandleTarget {+ handle(channel: string, listener: (event: unknown, ...args: unknown[]) => unknown): void+}++export function registerRendererCrashIpc(ipc: IpcHandleTarget, recorder: RendererCrashRecorder): void {+ ipc.handle('hermes:desktop-metrics:set-enabled', (_event: unknown, on: unknown): void =>+ recorder.setEnabled(on === true)+ )+ ipc.handle('hermes:desktop-metrics:crash:take', (): { reasons: RendererCrashReason[] } | null => recorder.take())+ ipc.handle('hermes:desktop-metrics:crash:ack', (_event: unknown, sent: unknown): void => recorder.ack(sent === true))+}diff --git a/apps/desktop/electron/window-renderer-lifecycle.test.ts b/apps/desktop/electron/window-renderer-lifecycle.test.tsindex 2f7242622e0..599a3a396b7 100644--- a/apps/desktop/electron/window-renderer-lifecycle.test.ts+++ b/apps/desktop/electron/window-renderer-lifecycle.test.ts@@ -584,3 +584,42 @@ test('a killed renderer is never reloaded or surfaced after close or during an iassert.equal(live.reloadCalls.length, 0)assert.equal(terminated.length, 0)})++test('onRendererGone observes a live-window renderer loss but never teardown, and cannot break recovery', async () => {+ const gone: unknown[] = []+ let quitting = false++ const makeWindow = () => {+ const win = makeFakeWindow()++ const { options } = makeOptions(win, 'main', {+ isIntentionalTeardown: () => quitting,+ onRendererGone: (reason: unknown) => {+ gone.push(reason)++ throw new Error('observer failure')+ }+ })++ installWindowRendererLifecycle(win, options)++ return win+ }++ const live = makeWindow()+ live.webContents.emit('render-process-gone', {}, { reason: 'crashed', exitCode: 3 })+ await flushDeferred()++ assert.deepEqual(gone, ['crashed'])+ assert.equal(live.reloadCalls.length, 1)++ const closed = makeWindow()+ closed.setDestroyed(true)+ closed.webContents.emit('render-process-gone', {}, { reason: 'killed', exitCode: 9 })++ quitting = true+ const tearingDown = makeWindow()+ tearingDown.webContents.emit('render-process-gone', {}, { reason: 'killed', exitCode: 9 })++ assert.deepEqual(gone, ['crashed'])+})diff --git a/apps/desktop/electron/window-renderer-lifecycle.ts b/apps/desktop/electron/window-renderer-lifecycle.tsindex 7f7e8110906..091d137c1be 100644--- a/apps/desktop/electron/window-renderer-lifecycle.ts+++ b/apps/desktop/electron/window-renderer-lifecycle.ts@@ -114,6 +114,9 @@ export interface WindowRendererLifecycleOptions {* `did-fail-load` (primary content windows; off by default so OAuth/portal* windows loading remote URLs never auto-reload into a loop). */reloadOnFailedLoad?: boolean+ /** Observes every render-process-gone on a live window (not user close or+ * intentional teardown) with Electron's raw `details.reason`. */+ onRendererGone?: (reason: unknown) => voidnow?: () => number}@@ -289,6 +292,14 @@ export function installWindowRendererLifecycle(log(describeRendererLifecycleEvent({ kind, event: 'render-process-gone', ...details, isDestroyed: destroyed }))+ if (!destroyed && options.onRendererGone) {+ try {+ options.onRendererGone(details?.reason)+ } catch {+ // An observer never changes the recovery path.+ }+ }+const nowMs = safeNow(now)const recent = pruneReloadTimes(budgetRef.current, nowMs, reloadWindowMs)diff --git a/apps/desktop/src/global.d.ts b/apps/desktop/src/global.d.tsindex ff78197c302..b26e9c98600 100644--- a/apps/desktop/src/global.d.ts+++ b/apps/desktop/src/global.d.ts@@ -605,6 +605,14 @@ declare global {ackPendingRun?: (sent: boolean) => Promise<void>onPendingRun?: (callback: () => void) => () => void}+ desktopMetrics?: {+ /** Mirror the user's shared-metrics opt-in; false deletes any pending crash record. */+ setEnabled?: (on: boolean) => Promise<void>+ /** Claim the pending renderer-crash reasons (null when disabled, none, or already claimed). */+ takeRendererCrashes?: () => Promise<{ reasons: Array<'crash' | 'killed' | 'oom' | 'other'> } | null>+ /** `sent` drops the claimed reasons; false keeps them for the next attach. */+ ackRendererCrashes?: (sent: boolean) => Promise<void>+ }uninstall: {summary: () => Promise<DesktopUninstallSummary>run: (mode: DesktopUninstallMode) => Promise<DesktopUninstallResult>