Skip to content

The agent that grows with you

refactor(desktop): move shared-metrics wiring out of main.ts

teknium162914682ef4e
diff --git a/apps/desktop/electron/desktop-shared-metrics.test.ts b/apps/desktop/electron/desktop-shared-metrics.test.ts
new file mode 100644
index 00000000000..ed6bc78a0f4
--- /dev/null
+++ b/apps/desktop/electron/desktop-shared-metrics.test.ts
@@ -0,0 +1,44 @@
+import fs from 'node:fs'
+import os from 'node:os'
+import path from 'node:path'
+
+import { afterAll, expect, test, vi } from 'vitest'
+
+const handlers = new Map<string, (...args: unknown[]) => unknown>()
+const userData = fs.mkdtempSync(path.join(os.tmpdir(), 'hermes-desktop-metrics-'))
+const sent: string[] = []
+
+vi.mock('electron', () => ({
+ app: { getPath: () => userData, getVersion: () => '1.0.0' },
+ BrowserWindow: { getAllWindows: () => [{ webContents: { send: (channel: string) => sent.push(channel) } }] },
+ ipcMain: {
+ handle: (channel: string, fn: (...args: unknown[]) => unknown) => {
+ handlers.set(channel, fn)
+ }
+ }
+}))
+
+vi.mock('./install-stamp', () => ({ INSTALL_STAMP: { commitDate: 1_700_000_000 } }))
+
+const { registerDesktopSharedMetrics } = await import('./desktop-shared-metrics')
+
+afterAll(() => fs.rmSync(userData, { recursive: true, force: true }))
+
+const strategy = (mechanism: string) => ({ mechanism, apply: async () => ({ ok: true, handedOff: false }) }) as never
+
+test('a packaged apply is reported once through the renderer IPC; a checkout hand-off never is', async () => {
+ const metrics = registerDesktopSharedMetrics()
+
+ expect(handlers.has('hermes:startup-latency:claim')).toBe(true)
+
+ await metrics.trackUpdateApply(null, strategy('checkout'))
+ expect(handlers.get('hermes:updates:metric:take')!({})).toBeNull()
+
+ await metrics.trackUpdateApply(strategy('electron-updater'), strategy('electron-updater'))
+ expect(sent).toContain('hermes:updates:metric:pending')
+ expect(handlers.get('hermes:updates:metric:take')!({})).toMatchObject({
+ mechanism: 'electron-updater',
+ outcome: 'noop',
+ from_commit_date: 1_700_000_000
+ })
+})
diff --git a/apps/desktop/electron/desktop-shared-metrics.ts b/apps/desktop/electron/desktop-shared-metrics.ts
new file mode 100644
index 00000000000..21758391523
--- /dev/null
+++ b/apps/desktop/electron/desktop-shared-metrics.ts
@@ -0,0 +1,38 @@
+// 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.
+
+import { app, BrowserWindow, ipcMain } from 'electron'
+
+import { INSTALL_STAMP } from './install-stamp'
+import { registerStartupLatencyIpc } from './startup-latency-ipc'
+import type { UpdaterApplyResultWire, UpdaterStrategy } from './updater/index'
+import { registerUpdateMetricsIpc, UpdateRunRecorder } from './updater/update-metrics'
+
+export interface DesktopSharedMetrics {
+ noteUpdateProgress(stage: string): void
+ /** 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>
+}
+
+export function registerDesktopSharedMetrics(): DesktopSharedMetrics {
+ registerStartupLatencyIpc()
+
+ const recorder = new UpdateRunRecorder({
+ dir: () => app.getPath('userData'),
+ appVersion: () => app.getVersion(),
+ onRecorded: () => {
+ for (const window of BrowserWindow.getAllWindows()) {
+ window.webContents.send('hermes:updates:metric:pending')
+ }
+ }
+ })
+
+ registerUpdateMetricsIpc(ipcMain, recorder)
+
+ return {
+ 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.ts
index 23d7e0d175b..2512e52c177 100644
--- a/apps/desktop/electron/main.ts
+++ b/apps/desktop/electron/main.ts
@@ -213,6 +213,7 @@ import {
resolveDesktopWindowLaunch
} from './desktop-profile'
import { registryPrimaryBootRoute, resolveDesktopRemoteRoute, v1SshTerminalPoolKey } from './desktop-remote-route'
+import { type DesktopSharedMetrics, registerDesktopSharedMetrics } from './desktop-shared-metrics'
import {
buildPosixCleanupScript,
buildWindowsCleanupScript,
@@ -505,7 +506,6 @@ import { collectSshConfigHosts, parseSshGOutput } from './ssh-config'
import { createSshProbeConnection, pickLocalPort, redactSecrets, SshConnection } from './ssh-connection'
import { createSshIsolatedKeepaliveRegistry } from './ssh-isolated-keepalive'
import { createSshTeardownTracker } from './ssh-teardown'
-import { registerStartupLatencyIpc } from './startup-latency-ipc'
import { createStreamThrottle } from './stream-throttle'
import { installSystemCaTrust } from './system-ca'
import { registerTerminalIpc } from './terminal-ipc'
@@ -560,7 +560,6 @@ import {
import { startRelaunchWaiter } from './updater/relaunch-waiter'
import { preflightStateDb } from './updater/state-db-preflight'
import { createStoreStrategy } from './updater/store-client'
-import { registerUpdateMetricsIpc, UpdateRunRecorder } from './updater/update-metrics'
import { isExternalVenvHolder, isHermesOwnedVenvDaemon } from './venv-holder-select'
import { fetchMarketplaceThemes, searchMarketplaceThemes } from './vscode-marketplace'
import { createWakeIndicatorWindowController } from './wake-indicator-window'
@@ -3353,7 +3352,7 @@ function runGit(args, options: any = {}): Promise<{ code: number; stdout: string
function emitUpdateProgress(payload) {
const merged = { stage: 'idle', message: '', percent: null, error: null, ...payload, at: Date.now() }
rememberLog(`[updates] ${merged.stage}: ${merged.message || merged.error || ''}`)
- updateRunRecorder.noteProgress(merged.stage)
+ desktopMetrics.noteUpdateProgress(merged.stage)
for (const window of BrowserWindow.getAllWindows()) {
window.webContents.send('hermes:updates:progress', merged)
@@ -3396,15 +3395,7 @@ let updateInFlight = false
*/
const updateOperation: UpdateOperation = new UpdateOperation(createPackagedUpdateStrategy)
-const updateRunRecorder: UpdateRunRecorder = new UpdateRunRecorder({
- dir: () => app.getPath('userData'),
- appVersion: () => app.getVersion(),
- onRecorded: () => {
- for (const window of BrowserWindow.getAllWindows()) {
- window.webContents.send('hermes:updates:metric:pending')
- }
- }
-})
+const desktopMetrics: DesktopSharedMetrics = registerDesktopSharedMetrics()
function resolvePackagedUpdateStrategy(): Promise<UpdaterStrategy | null> {
return updateOperation.resolve()
@@ -4448,14 +4439,7 @@ async function applyUpdates(): Promise<UpdaterApplyResultWire> {
try {
const packaged: UpdaterStrategy | null = await resolvePackagedUpdateStrategy()
const strategy: UpdaterStrategy = packaged ?? resolveCheckoutUpdateStrategy()
-
- // Only packaged runs: a checkout hand-off is counted by `hermes update`'s receipt.
- const result: UpdaterApplyResultWire = await updateRunRecorder.track(
- packaged?.mechanism,
- INSTALL_STAMP?.commitDate,
- () => strategy.apply()
- )
-
+ const result: UpdaterApplyResultWire = await desktopMetrics.trackUpdateApply(packaged, strategy)
handedOff = result.handedOff === true
return result
@@ -18112,7 +18096,6 @@ registerGitIpc({ resolveGitBinary, resolveGhBinary })
// Client-side loopback callback for MCP OAuth against remote backends — see
// mcp-oauth-callback-ipc.ts.
registerMcpOauthCallbackIpc()
-registerStartupLatencyIpc()
// Embedded terminal PTY host (hermes:terminal:*) — see terminal-ipc.ts.
const terminalIpc = registerTerminalIpc({
@@ -18146,8 +18129,6 @@ ipcMain.handle('hermes:updates:apply', async (_event, payload) =>
}))
)
-registerUpdateMetricsIpc(ipcMain, updateRunRecorder)
-
ipcMain.handle('hermes:updates:branch:get', async () => readDesktopUpdateConfig())
ipcMain.handle(