The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(telemetry): renderer-crash consent and pending crashes are per window and profile
teknium1aa83040ca452
diff --git a/apps/desktop/electron/desktop-shared-metrics.ts b/apps/desktop/electron/desktop-shared-metrics.tsindex f4d57a4c3e0..a55b8691234 100644--- a/apps/desktop/electron/desktop-shared-metrics.ts+++ b/apps/desktop/electron/desktop-shared-metrics.ts@@ -15,8 +15,9 @@ 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+ /** `installWindowRendererLifecycle` hook: counts a live window's renderer loss (no-op unless that+ * window's focused profile collects). */+ recordRendererGone(windowId: number, reason: unknown): void}export function registerDesktopSharedMetrics(): DesktopSharedMetrics {@@ -39,7 +40,7 @@ export function registerDesktopSharedMetrics(): DesktopSharedMetrics {registerRendererCrashIpc(ipcMain, crashes)return {- recordRendererGone: reason => crashes.record(reason),+ recordRendererGone: (windowId, reason) => crashes.record(windowId, 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 40afe37063e..c3b08a36247 100644--- a/apps/desktop/electron/main.ts+++ b/apps/desktop/electron/main.ts@@ -13607,7 +13607,7 @@ function spawnSecondaryWindow({reloadWindowMs: RENDERER_RELOAD_WINDOW_MS,reloadMax: RENDERER_RELOAD_MAX,recentReloadTimesRef: rendererReloadTimesRef,- onRendererGone: reason => desktopMetrics.recordRendererGone(reason)+ onRendererGone: reason => desktopMetrics.recordRendererGone(win.webContents.id, reason)})loadWindowUrl(@@ -14967,6 +14967,7 @@ function createWindow() {// the #38216 Windows sandbox relaunch check on suppression) is the same// policy this window used before it moved into the shared helper, so a// crashed peer renderer now logs and recovers exactly like the primary one.+ const mainContentsId = mainWindow.webContents.idinstallWindowRendererLifecycle(mainWindow, {kind: 'main',callbacks: {@@ -15115,7 +15116,7 @@ function createWindow() {reloadMax: RENDERER_RELOAD_MAX,recentReloadTimesRef: rendererReloadTimesRef,reloadOnFailedLoad: true,- onRendererGone: reason => desktopMetrics.recordRendererGone(reason)+ onRendererGone: reason => desktopMetrics.recordRendererGone(mainContentsId, 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 fcaf229ad5c..ecb076b4028 100644--- a/apps/desktop/electron/preload.ts+++ b/apps/desktop/electron/preload.ts@@ -641,7 +641,7 @@ contextBridge.exposeInMainWorld('hermesDesktop', {}},desktopMetrics: {- setEnabled: on => ipcRenderer.invoke('hermes:desktop-metrics:set-enabled', on),+ setEnabled: (on, profile) => ipcRenderer.invoke('hermes:desktop-metrics:set-enabled', on, profile),takeRendererCrashes: () => ipcRenderer.invoke('hermes:desktop-metrics:crash:take'),ackRendererCrashes: sent => ipcRenderer.invoke('hermes:desktop-metrics:crash:ack', sent)},diff --git a/apps/desktop/electron/renderer-crash-metrics.test.ts b/apps/desktop/electron/renderer-crash-metrics.test.tsindex ad4aea2249a..77e44e77824 100644--- a/apps/desktop/electron/renderer-crash-metrics.test.ts+++ b/apps/desktop/electron/renderer-crash-metrics.test.ts@@ -26,13 +26,17 @@ function pending(): unknown {return JSON.parse(fs.readFileSync(file, 'utf8'))}+const W = 1+function enabledRecorder(): RendererCrashRecorder {const recorder = new RendererCrashRecorder({ dir })- recorder.setEnabled(true)+ recorder.setEnabled(W, 'local|default', true)return recorder}+const reasonsOnDisk = () => (pending() as { entries: { reason: string }[] }).entries.map(entry => entry.reason)+test('rendererCrashReason buckets Electron reasons', () => {expect(rendererCrashReason('crashed')).toBe('crash')expect(rendererCrashReason('oom')).toBe('oom')@@ -47,28 +51,27 @@ describe('RendererCrashRecorder', () => {test('records nothing until the user opts in', () => {const recorder = new RendererCrashRecorder({ dir })- recorder.record('crashed')+ recorder.record(W, 'crashed')expect(fs.existsSync(file)).toBe(false)- expect(recorder.take()).toBeNull()+ expect(recorder.take(W)).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')+ for (const reason of ['crashed', 'clean-exit', 'oom', 'killed', 'launch-failed']) {+ recorder.record(W, reason)+ }- expect(pending()).toEqual({ v: 1, reasons: ['crash', 'oom', 'killed', 'other'] })+ expect(reasonsOnDisk()).toEqual(['crash', 'oom', 'killed', 'other'])+ expect(JSON.stringify(pending())).not.toContain('default')for (let i = 0; i < 30; i++) {- recorder.record('killed')+ recorder.record(W, 'killed')}- const reasons = (pending() as { reasons: string[] }).reasons+ const reasons = reasonsOnDisk()expect(reasons).toHaveLength(MAX_PENDING_RENDERER_CRASHES)expect(reasons.slice(0, 4)).toEqual(['crash', 'oom', 'killed', 'other'])})@@ -76,50 +79,73 @@ describe('RendererCrashRecorder', () => {test('revoking consent deletes the pending file and stops recording', () => {const recorder = enabledRecorder()- recorder.record('crashed')+ recorder.record(W, 'crashed')expect(fs.existsSync(file)).toBe(true)- recorder.setEnabled(false)+ recorder.setEnabled(W, 'local|default', false)expect(fs.existsSync(file)).toBe(false)- recorder.record('crashed')+ recorder.record(W, 'crashed')expect(fs.existsSync(file)).toBe(false)})+ test('consent is per window and entries per profile: another profile neither records, drains nor purges them', () => {+ const recorder = new RendererCrashRecorder({ dir })+ const [a, b] = [1, 2]++ recorder.setEnabled(a, 'local|alpha', false) // window a: profile alpha, collection off+ recorder.setEnabled(b, 'local|beta', true) // window b: profile beta, on+ recorder.record(a, 'crashed')+ expect(fs.existsSync(file)).toBe(false)++ recorder.setEnabled(a, 'local|alpha', true)+ recorder.record(a, 'oom')+ expect(recorder.take(b)).toBeNull()++ recorder.setEnabled(b, 'local|beta', false)+ expect(recorder.take(a)).toEqual({ reasons: ['oom'] })+ })+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')+ const peer = 2++ recorder.setEnabled(peer, 'local|default', true)+ recorder.record(W, 'crashed')+ recorder.record(W, 'oom')- expect(recorder.take()).toEqual({ reasons: ['crash', 'oom'] })- expect(recorder.take()).toBeNull()+ expect(recorder.take(W)).toEqual({ reasons: ['crash', 'oom'] })+ expect(recorder.take(peer)).toBeNull()- recorder.ack(false)- expect(recorder.take()).toEqual({ reasons: ['crash', 'oom'] })+ recorder.ack(W, false)+ expect(recorder.take(W)).toEqual({ reasons: ['crash', 'oom'] })- recorder.record('killed')- recorder.ack(true)+ recorder.record(W, 'killed')+ recorder.ack(W, true)- expect(pending()).toEqual({ v: 1, reasons: ['killed'] })- expect(recorder.take()).toEqual({ reasons: ['killed'] })+ expect(reasonsOnDisk()).toEqual(['killed'])+ expect(recorder.take(W)).toEqual({ reasons: ['killed'] })- recorder.ack(true)+ recorder.ack(W, true)expect(fs.existsSync(file)).toBe(false)- expect(recorder.take()).toBeNull()+ expect(recorder.take(W)).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()+ expect(recorder.take(W)).toBeNull()- fs.writeFileSync(file, JSON.stringify({ v: 2, reasons: ['crash'] }))- expect(recorder.take()).toBeNull()+ fs.writeFileSync(file, JSON.stringify({ v: 1, reasons: ['crash'] })) // untagged: whose it was is unknown+ expect(recorder.take(W)).toBeNull()- fs.writeFileSync(file, JSON.stringify({ v: 1, reasons: ['crash', '/home/me/secret', 3, 'oom'] }))- expect(recorder.take()).toEqual({ reasons: ['crash', 'oom'] })+ recorder.record(W, 'crashed')+ const [{ profile }] = (pending() as { entries: { profile: string }[] }).entries+ const junk = [{ profile, reason: '/home/me/secret' }, { profile, reason: 3 }, null, { profile, reason: 'oom' }]+ fs.writeFileSync(file, JSON.stringify({ v: 2, entries: [{ profile, reason: 'crash' }, ...junk] }))+ expect(recorder.take(W)).toEqual({ reasons: ['crash', 'oom'] })})test('fs errors never escape', () => {@@ -132,27 +158,29 @@ describe('RendererCrashRecorder', () => {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()+ recorder.setEnabled(W, 'p', true)+ expect(() => recorder.record(W, 'crashed')).not.toThrow()+ expect(recorder.take(W)).toBeNull()+ expect(() => recorder.setEnabled(W, 'p', false)).not.toThrow()})})-test('registerRendererCrashIpc wires consent, take and ack', () => {+test('registerRendererCrashIpc wires consent, take and ack to the calling window', () => {const handlers = new Map<string, (event: unknown, ...args: unknown[]) => unknown>()const recorder = new RendererCrashRecorder({ dir })+ const from = { sender: { id: 7 } }registerRendererCrashIpc({ handle: (channel, fn) => handlers.set(channel, fn) }, recorder)- handlers.get('hermes:desktop-metrics:set-enabled')!({}, 'yes')- recorder.record('crashed')+ handlers.get('hermes:desktop-metrics:set-enabled')!(from, 'yes', 'local|default')+ recorder.record(7, '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:set-enabled')!(from, true, 'local|default')+ recorder.record(7, 'crashed')+ expect(handlers.get('hermes:desktop-metrics:crash:take')!({ sender: { id: 8 } })).toBeNull()+ expect(handlers.get('hermes:desktop-metrics:crash:take')!(from)).toEqual({ reasons: ['crash'] })- handlers.get('hermes:desktop-metrics:crash:ack')!({}, true)+ handlers.get('hermes:desktop-metrics:crash:ack')!(from, true)expect(fs.existsSync(file)).toBe(false)})diff --git a/apps/desktop/electron/renderer-crash-metrics.ts b/apps/desktop/electron/renderer-crash-metrics.tsindex a60cb0033f7..e79482d6555 100644--- a/apps/desktop/electron/renderer-crash-metrics.ts+++ b/apps/desktop/electron/renderer-crash-metrics.ts@@ -3,10 +3,14 @@// 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.-+// Consent is per window: each window reports its focused profile's switch, a+// crash is kept only when the crashed window's own profile collects, and each+// entry is tagged with that profile so only a window of the same profile drains+// it (and that profile turning off drops only its entries). Stored: the bucketed+// reason plus a hash of the profile key — never the name, exit codes, paths or+// window titles.++import { createHash } from 'node:crypto'import fs from 'node:fs'import path from 'node:path'@@ -36,10 +40,23 @@ export interface RendererCrashRecorderOptions {fs?: RendererCrashFs}+interface PendingCrash {+ profile: string+ reason: RendererCrashReason+}++function profileKey(profile: unknown): string {+ return createHash('sha256')+ .update(String(profile ?? ''))+ .digest('hex')+ .slice(0, 16)+}+export class RendererCrashRecorder {- private enabled = false- private inFlight = false- private taken = 0+ /** webContents id → profile key, only for windows whose focused profile collects. */+ private readonly consent = new Map<number, string>()+ /** profile key → the window holding an unacked take() and how many entries it claimed. */+ private readonly claims = new Map<string, { count: number; windowId: number }>()private readonly fs: RendererCrashFsprivate readonly file: string@@ -48,80 +65,92 @@ export class RendererCrashRecorder {this.file = path.join(opts.dir, PENDING_RENDERER_CRASH_FILE)}- setEnabled(on: boolean): void {- this.enabled = on+ /** One window's focused profile and its switch; off drops that profile's pending crashes. */+ setEnabled(windowId: number, profile: unknown, on: boolean): void {+ const key = profileKey(profile)++ if (on) {+ this.consent.set(windowId, key)- if (!on) {- this.inFlight = false- this.taken = 0- this.remove()+ return}++ this.consent.delete(windowId)+ this.claims.delete(key)+ this.write(this.read().filter(entry => entry.profile !== key))}- record(electronReason: unknown): void {+ record(windowId: number, electronReason: unknown): void {+ const profile = this.consent.get(windowId)+// A clean exit is a renderer shutting down normally, not a crash.- if (!this.enabled || electronReason === 'clean-exit') {+ if (!profile || electronReason === 'clean-exit') {return}- const reasons = this.read()+ const entries = this.read()- if (reasons.length >= MAX_PENDING_RENDERER_CRASHES) {+ if (entries.length >= MAX_PENDING_RENDERER_CRASHES) {return}- reasons.push(rendererCrashReason(electronReason))- this.write(reasons)+ entries.push({ profile, reason: rendererCrashReason(electronReason) })+ this.write(entries)}- /** 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) {+ /** Claim this window's profile's pending reasons; null when it does not collect, none, or another+ * window's claim is unacked (the same window re-claims: its renderer reloaded before acking). */+ take(windowId: number): { reasons: RendererCrashReason[] } | null {+ const profile = this.consent.get(windowId)+ const claim = profile ? this.claims.get(profile) : undefined++ if (!profile || (claim && claim.windowId !== windowId)) {return null}const reasons = this.read()+ .filter(entry => entry.profile === profile)+ .map(entry => entry.reason)if (reasons.length === 0) {return null}- this.inFlight = true- this.taken = reasons.length+ this.claims.set(profile, { count: reasons.length, windowId })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) {+ ack(windowId: number, sent: boolean): void {+ const [profile, claim] = [...this.claims].find(([, held]) => held.windowId === windowId) ?? []++ if (!profile || !claim) {return}- if (sent) {- const rest = this.read().slice(this.taken)+ this.claims.delete(profile)- if (rest.length > 0) {- this.write(rest)- } else {- this.remove()- }+ if (sent) {+ let drop = claim.count+ this.write(this.read().filter(entry => entry.profile !== profile || drop-- <= 0))}-- this.inFlight = false- this.taken = 0}- private read(): RendererCrashReason[] {+ private read(): PendingCrash[] {try {- const parsed = JSON.parse(String(this.fs.readFileSync(this.file, 'utf8'))) as { v?: unknown; reasons?: unknown }+ const parsed = JSON.parse(String(this.fs.readFileSync(this.file, 'utf8'))) as { v?: unknown; entries?: unknown }- if (parsed?.v !== 1 || !Array.isArray(parsed.reasons)) {+ if (parsed?.v !== 2 || !Array.isArray(parsed.entries)) {return []}- return parsed.reasons- .filter((reason): reason is RendererCrashReason => typeof reason === 'string' && KNOWN_REASONS.has(reason))+ return parsed.entries+ .filter(+ (entry): entry is PendingCrash =>+ typeof entry?.profile === 'string' && typeof entry.reason === 'string' && KNOWN_REASONS.has(entry.reason)+ )+ .map(({ profile, reason }) => ({ profile, reason })).slice(0, MAX_PENDING_RENDERER_CRASHES)} catch {// Missing or unreadable: nothing pending.@@ -129,22 +158,20 @@ export class RendererCrashRecorder {}}- private write(reasons: RendererCrashReason[]): void {+ private write(entries: PendingCrash[]): void {try {+ if (entries.length === 0) {+ this.fs.rmSync(this.file, { force: true })++ return+ }+const tmp = `${this.file}.tmp`this.fs.mkdirSync(path.dirname(tmp), { recursive: true })- this.fs.writeFileSync(tmp, JSON.stringify({ v: 1, reasons }))+ this.fs.writeFileSync(tmp, JSON.stringify({ v: 2, entries }))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.+ // Telemetry never breaks the app; a failed removal is retried on the next ack or opt-out.}}}@@ -153,10 +180,21 @@ interface IpcHandleTarget {handle(channel: string, listener: (event: unknown, ...args: unknown[]) => unknown): void}+/** The calling window's webContents id (-1 for a caller without one: never consents). */+function senderId(event: unknown): number {+ const id = (event as { sender?: { id?: unknown } } | null)?.sender?.id++ return typeof id === 'number' ? id : -1+}+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:set-enabled', (event: unknown, on: unknown, profile: unknown): void =>+ recorder.setEnabled(senderId(event), profile, on === true)+ )+ ipc.handle('hermes:desktop-metrics:crash:take', (event: unknown): { reasons: RendererCrashReason[] } | null =>+ recorder.take(senderId(event))+ )+ ipc.handle('hermes:desktop-metrics:crash:ack', (event: unknown, sent: unknown): void =>+ recorder.ack(senderId(event), sent === 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/src/global.d.ts b/apps/desktop/src/global.d.tsindex b26e9c98600..95b05a46596 100644--- a/apps/desktop/src/global.d.ts+++ b/apps/desktop/src/global.d.ts@@ -606,9 +606,9 @@ declare global {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). */+ /** Mirror this window's focused profile and its opt-in; false deletes that profile's pending crashes. */+ setEnabled?: (on: boolean, profile: string) => Promise<void>+ /** Claim this window's profile's pending renderer-crash reasons (null when off, none, or 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>diff --git a/website/docs/developer-guide/relay-shared-metrics.md b/website/docs/developer-guide/relay-shared-metrics.mdindex a03a455b898..c411307dc38 100644--- a/website/docs/developer-guide/relay-shared-metrics.md+++ b/website/docs/developer-guide/relay-shared-metrics.md@@ -340,7 +340,7 @@ session/bot/profile names, paths and setting values never leave.| `hermes.desktop.feature_use` | area (panes, command palette, model/session pickers, voice, Bot Mode, skins, projects, each settings page, full pages, `other`) | Which Desktop areas are used at all, counted at most once per area per UTC day per profile (latched in the profile's local database, so a second window or a backend restart never re-counts). || `hermes.desktop.action_use` | action (the app's command/keybinding ids plus a few named buttons, else `other`), via (`click`/`shortcut`/`palette`/`menu`), count bucket | Which buttons and commands people press, and how: aggregated in the app per profile and reported once per finished day (no per-press rows). The row lands in the period of the day it describes, not the day it was sent; each day is recorded once per profile however many windows or backend restarts report it, and a day older than 8 days is dropped. || `hermes.desktop.mode_use` | mode (`sessions`/`bots`), active-minutes bucket, messages-sent bucket, bot-count bucket | How Desktop time splits between Bot Mode and regular Sessions. One row per mode used that day, in that day's period (same once-per-profile-per-day latch as `action_use`); active time sums gaps between interactions of up to 5 minutes. |-| `hermes.desktop.friction` | kind (`notice_dismissed`, `error_toast`, `renderer_crash`, `backend_disconnect`, `slow_frame`), detail (notice id, error category, crash reason, drop reason, frame-duration bucket) | What gets in the way. Error toasts carry only their code-defined category; renderer crashes are recorded by the app shell and reported after the window comes back; slow frames are long frames while the window is visible, capped per day. |+| `hermes.desktop.friction` | kind (`notice_dismissed`, `error_toast`, `renderer_crash`, `backend_disconnect`, `slow_frame`), detail (notice id, error category, crash reason, drop reason, frame-duration bucket) | What gets in the way. Error toasts carry only their code-defined category; renderer crashes are recorded by the app shell only when the crashed window's own profile collects, and reported by a window of that profile after it comes back; slow frames are long frames while the window is visible, capped per day. || `hermes.desktop.dislike` | signal (`quick_close`, `cancelled`, `setting_off_default`, `rage_click`, `undo`, `feature_disabled`), target, setting, direction | Signals that a feature is unwanted: a pane closed within 5s of opening, a dialog/flow backed out of, a setting moved to or away from its default (the key only; the backend compares the saved value to the default itself), three clicks on one control within a second, an undo, a shipped feature switched off. Capped per signal per day. || `hermes.desktop.onboarding` | step (first-run steps: provider picker, sign-in, API key, local endpoint, model pick, choose later, free-tier screen, guided setup cards, consent, first message), event (`reached`/`completed`/`abandoned`) | Where first run stops. Each step event once per profile (latched in a small per-profile file); `abandoned` is a step still open when the app next starts. Switching collection off in the Desktop deletes those latches with the app's own copy. |