Skip to content

The agent that grows with you

feat(tui,desktop): report launch-to-ready latency once per launch

teknium1ce80e8d81a16
diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.ts
index c271d8b1731..8a77876615a 100644
--- a/apps/desktop/electron/main.ts
+++ b/apps/desktop/electron/main.ts
@@ -505,6 +505,7 @@ 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'
@@ -18091,6 +18092,7 @@ 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({
diff --git a/apps/desktop/electron/preload.ts b/apps/desktop/electron/preload.ts
index 6b29866bbbb..cfac092d901 100644
--- a/apps/desktop/electron/preload.ts
+++ b/apps/desktop/electron/preload.ts
@@ -313,6 +313,7 @@ contextBridge.exposeInMainWorld('hermesDesktop', {
},
api: request => ipcRenderer.invoke('hermes:api', request),
notify: payload => ipcRenderer.invoke('hermes:notify', payload),
+ claimStartupLatency: () => ipcRenderer.invoke('hermes:startup-latency:claim'),
requestMicrophoneAccess: () => ipcRenderer.invoke('hermes:requestMicrophoneAccess'),
readWindowBelow: () => ipcRenderer.invoke('hermes:window:readBelow'),
readFileDataUrl: filePath => ipcRenderer.invoke('hermes:readFileDataUrl', filePath),
diff --git a/apps/desktop/electron/startup-latency-ipc.test.ts b/apps/desktop/electron/startup-latency-ipc.test.ts
new file mode 100644
index 00000000000..6a04695b6fc
--- /dev/null
+++ b/apps/desktop/electron/startup-latency-ipc.test.ts
@@ -0,0 +1,29 @@
+import { expect, test, vi } from 'vitest'
+
+const handlers = new Map<string, (...args: unknown[]) => unknown>()
+
+vi.mock('electron', () => ({
+ ipcMain: {
+ handle: (channel: string, fn: (...args: unknown[]) => unknown) => {
+ handlers.set(channel, fn)
+ }
+ }
+}))
+
+const { registerStartupLatencyIpc } = await import('./startup-latency-ipc')
+
+test('the launch latency is claimable once per app launch, whichever window asks', () => {
+ registerStartupLatencyIpc()
+
+ const claim = handlers.get('hermes:startup-latency:claim')
+
+ expect(claim).toBeDefined()
+
+ const first = claim!({})
+
+ expect(typeof first).toBe('number')
+ expect(first as number).toBeGreaterThanOrEqual(0)
+ // A renderer reload, a second window or a post-reconnect boot all land here.
+ expect(claim!({})).toBeNull()
+ expect(claim!({})).toBeNull()
+})
diff --git a/apps/desktop/electron/startup-latency-ipc.ts b/apps/desktop/electron/startup-latency-ipc.ts
new file mode 100644
index 00000000000..66ce7b976f2
--- /dev/null
+++ b/apps/desktop/electron/startup-latency-ipc.ts
@@ -0,0 +1,25 @@
+import { ipcMain } from 'electron'
+
+/** Launch -> first renderer gateway attach, claimable once per main process. Renderer
+ * reloads, extra windows and backend reconnects all re-run the renderer boot, so the
+ * latch must live here (the one object that spans the whole app launch). */
+export function createStartupLatencyClaim(uptimeSeconds: () => number = () => process.uptime()): () => null | number {
+ let claimed = false
+
+ return () => {
+ if (claimed) {
+ return null
+ }
+
+ claimed = true
+
+ // Main-process uptime starts at Electron launch, before any window or backend exists.
+ return Math.max(0, Math.round(uptimeSeconds() * 1000))
+ }
+}
+
+export function registerStartupLatencyIpc(): void {
+ const claim = createStartupLatencyClaim()
+
+ ipcMain.handle('hermes:startup-latency:claim', () => claim())
+}
diff --git a/apps/desktop/src/app/gateway/hooks/use-gateway-boot.ts b/apps/desktop/src/app/gateway/hooks/use-gateway-boot.ts
index 1bfa972fb1c..940cdffd912 100644
--- a/apps/desktop/src/app/gateway/hooks/use-gateway-boot.ts
+++ b/apps/desktop/src/app/gateway/hooks/use-gateway-boot.ts
@@ -10,6 +10,7 @@ import {
import { useEffect, useRef } from 'react'
import { createGatewayEventDedupe } from '@/app/gateway/gateway-event-dedupe'
+import { reportStartupLatency } from '@/app/gateway/report-startup-latency'
import { shouldApplyPostBootProgressError } from '@/components/boot-failure-reauth'
import type { DesktopBootProgress, HermesConnection, HermesWindowState } from '@/global'
import { HermesGateway } from '@/hermes'
@@ -1452,6 +1453,8 @@ export function useGatewayBoot({
return
}
+ void reportStartupLatency(desktop, (method, params) => gateway.request(method, params))
+
// Profile adoption must land first: refreshSessions scopes its fetch by
// $profileScope ← $activeGatewayProfile. The remaining three fetches
// (cwd seed, config, sessions) are independent REST calls — running
diff --git a/apps/desktop/src/app/gateway/report-startup-latency.test.ts b/apps/desktop/src/app/gateway/report-startup-latency.test.ts
new file mode 100644
index 00000000000..b567ea5e746
--- /dev/null
+++ b/apps/desktop/src/app/gateway/report-startup-latency.test.ts
@@ -0,0 +1,29 @@
+import { describe, expect, it, vi } from 'vitest'
+
+import { reportStartupLatency } from './report-startup-latency'
+
+describe('reportStartupLatency', () => {
+ it('sends the metric once even when the renderer boots again (reload, reconnect, extra window)', async () => {
+ // The main-process latch: a number for the first claim of the launch, null afterwards.
+ const claimStartupLatency = vi.fn().mockResolvedValueOnce(1234).mockResolvedValue(null)
+
+ // Older backends reject the unknown method; the report must swallow it.
+ const request = vi.fn().mockRejectedValue(new Error('method not found'))
+
+ await reportStartupLatency({ claimStartupLatency }, request)
+ await reportStartupLatency({ claimStartupLatency }, request)
+ await reportStartupLatency({ claimStartupLatency }, request)
+
+ expect(request).toHaveBeenCalledTimes(1)
+ expect(request).toHaveBeenCalledWith('shared_metrics.startup_latency', { elapsed_ms: 1234, surface: 'desktop_attach' })
+ })
+
+ it('skips the metric on an Electron shell without the claim bridge', async () => {
+ const request = vi.fn()
+
+ await reportStartupLatency({}, request)
+ await reportStartupLatency(undefined, request)
+
+ expect(request).not.toHaveBeenCalled()
+ })
+})
diff --git a/apps/desktop/src/app/gateway/report-startup-latency.ts b/apps/desktop/src/app/gateway/report-startup-latency.ts
new file mode 100644
index 00000000000..674250647e3
--- /dev/null
+++ b/apps/desktop/src/app/gateway/report-startup-latency.ts
@@ -0,0 +1,23 @@
+type GatewayRequest = (
+ method: 'shared_metrics.startup_latency',
+ params: { elapsed_ms: number; surface: 'desktop_attach' }
+) => Promise<unknown>
+
+/** Fire-and-forget: the main process hands out the launch latency to exactly one renderer
+ * boot per app launch; the backend buckets it and drops it unless the user opted in.
+ * An older Electron shell (no bridge) or backend (no method) just skips the metric. */
+export async function reportStartupLatency(
+ desktop: Pick<Window['hermesDesktop'], 'claimStartupLatency'> | undefined,
+ request: GatewayRequest
+): Promise<void> {
+ const elapsedMs = (await desktop?.claimStartupLatency?.().catch(() => null)) ?? null
+
+ if (elapsedMs === null) {
+ return
+ }
+
+ // Declared, not env-detected: a URL/cloud backend has no HERMES_DESKTOP to tell it who attached.
+ await request('shared_metrics.startup_latency', { elapsed_ms: elapsedMs, surface: 'desktop_attach' }).catch(
+ () => undefined
+ )
+}
diff --git a/apps/desktop/src/global.d.ts b/apps/desktop/src/global.d.ts
index 661a1995a17..dadc84495b0 100644
--- a/apps/desktop/src/global.d.ts
+++ b/apps/desktop/src/global.d.ts
@@ -264,6 +264,8 @@ declare global {
}
api: <T>(request: HermesApiRequest) => Promise<T>
notify: (payload: HermesNotification) => Promise<boolean>
+ /** Launch -> ready ms for the first caller per app launch, null afterwards. Absent on older shells. */
+ claimStartupLatency?: () => Promise<null | number>
requestMicrophoneAccess: () => Promise<boolean>
/** read_window_below tool: metadata for the OS window directly underneath this one (never pixels). */
readWindowBelow?: () => Promise<{
diff --git a/ui-tui/src/__tests__/createGatewayEventHandler.test.ts b/ui-tui/src/__tests__/createGatewayEventHandler.test.ts
index 0052c10898c..3e374c90175 100644
--- a/ui-tui/src/__tests__/createGatewayEventHandler.test.ts
+++ b/ui-tui/src/__tests__/createGatewayEventHandler.test.ts
@@ -35,7 +35,7 @@ const buildCtx = (appended: Msg[]) =>
setInput: vi.fn()
},
gateway: {
- gw: { request: vi.fn() },
+ gw: { request: vi.fn(async () => null) },
rpc: vi.fn(async () => null)
},
session: {
diff --git a/ui-tui/src/__tests__/startupLatency.test.ts b/ui-tui/src/__tests__/startupLatency.test.ts
new file mode 100644
index 00000000000..65a36dba028
--- /dev/null
+++ b/ui-tui/src/__tests__/startupLatency.test.ts
@@ -0,0 +1,58 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+
+import { createGatewayEventHandler } from '../app/createGatewayEventHandler.js'
+import { resetOverlayState } from '../app/overlayStore.js'
+import { resetTurnState } from '../app/turnStore.js'
+import { resetUiState } from '../app/uiStore.js'
+
+const ref = <T>(current: T) => ({ current })
+
+const buildCtx = (request: ReturnType<typeof vi.fn>) =>
+ ({
+ composer: { dequeue: () => undefined, queueEditRef: ref(null), sendQueued: vi.fn(), setInput: vi.fn() },
+ gateway: { gw: { request }, rpc: vi.fn(async () => null) },
+ session: {
+ STARTUP_RESUME_ID: '',
+ colsRef: ref(80),
+ newSession: vi.fn(),
+ resetSession: vi.fn(),
+ resumeById: vi.fn(),
+ setCatalog: vi.fn()
+ },
+ submission: { submitRef: { current: vi.fn() } },
+ system: { bellOnComplete: false, sys: vi.fn() },
+ transcript: { appendMessage: vi.fn(), panel: vi.fn(), setHistoryItems: vi.fn() },
+ voice: { setProcessing: vi.fn(), setRecording: vi.fn(), setVoiceEnabled: vi.fn() }
+ }) as any
+
+const latencyCalls = (request: ReturnType<typeof vi.fn>) =>
+ request.mock.calls.filter(([method]) => method === 'shared_metrics.startup_latency')
+
+describe('startup latency metric', () => {
+ beforeEach(() => {
+ resetOverlayState()
+ resetUiState()
+ resetTurnState()
+ })
+
+ it('reports launch->ready once per process across repeated gateway.ready and handler remounts', () => {
+ // Older backends reject the unknown method; the report must not surface that.
+ const request = vi.fn(async () => {
+ throw new Error('method not found')
+ })
+
+ const ready = { payload: {}, type: 'gateway.ready' } as any
+ const onEvent = createGatewayEventHandler(buildCtx(request))
+
+ onEvent(ready)
+ onEvent(ready)
+ // A reconnect after a gateway respawn can rebuild the handler; still no second report.
+ createGatewayEventHandler(buildCtx(request))(ready)
+
+ const calls = latencyCalls(request)
+
+ expect(calls).toHaveLength(1)
+ expect(calls[0]![1]).toEqual({ elapsed_ms: expect.any(Number), surface: 'tui' })
+ expect(calls[0]![1].elapsed_ms).toBeGreaterThanOrEqual(0)
+ })
+})
diff --git a/ui-tui/src/app/createGatewayEventHandler.ts b/ui-tui/src/app/createGatewayEventHandler.ts
index afb54e80666..79299c98d86 100644
--- a/ui-tui/src/app/createGatewayEventHandler.ts
+++ b/ui-tui/src/app/createGatewayEventHandler.ts
@@ -34,6 +34,7 @@ import type { GatewayEventHandlerContext, NoticeLevel } from './interfaces.js'
import { getOverlayState, patchOverlayState } from './overlayStore.js'
import { flashGoodVibes, flashPet } from './petFlashStore.js'
import { forgetServerRequest } from './serverRequestStore.js'
+import { reportStartupLatency } from './startupLatency.js'
import { turnController } from './turnController.js'
import { getTurnState } from './turnStore.js'
import { getUiState, patchUiState } from './uiStore.js'
@@ -437,7 +438,7 @@ const normalizeSubagentStatus = (status: unknown, fallback: SubagentStatus): Sub
export function createGatewayEventHandler(ctx: GatewayEventHandlerContext): (ev: AnyGatewayEvent) => void {
syncThemeToTerminalBackground()
- const { rpc } = ctx.gateway
+ const { gw, rpc } = ctx.gateway
const { STARTUP_RESUME_ID, newSession, recoverSidRef, resumeById, setCatalog } = ctx.session
const { bellOnComplete, bellOnPrompt, stdout, sys } = ctx.system
@@ -683,6 +684,8 @@ export function createGatewayEventHandler(ctx: GatewayEventHandlerContext): (ev:
applySkin(skin)
}
+ reportStartupLatency(gw)
+
// Kick off the config fetch once the gateway is actually ready. If handler
// construction does this during React render, a startup transport error can
// report through sys(), mutate transcript state, and trip React's
diff --git a/ui-tui/src/app/startupLatency.ts b/ui-tui/src/app/startupLatency.ts
new file mode 100644
index 00000000000..74709480a4d
--- /dev/null
+++ b/ui-tui/src/app/startupLatency.ts
@@ -0,0 +1,22 @@
+import type { GatewayClient } from '../gatewayClient.js'
+
+// Module-level so a gateway reconnect/respawn (a fresh gateway.ready, or a remounted
+// handler) never re-reports: the metric is launch -> first ready, once per TUI process.
+let reported = false
+
+/** Node process start is the earliest moment the TUI owns, so uptime at the first
+ * gateway.ready is the launch latency. The backend buckets it and drops it unless the
+ * user opted in; older backends lack the method, so errors are swallowed. */
+export function reportStartupLatency(gw: Pick<GatewayClient, 'request'>): void {
+ if (reported) {
+ return
+ }
+
+ reported = true
+ gw.request('shared_metrics.startup_latency', {
+ elapsed_ms: Math.round(process.uptime() * 1000),
+ surface: 'tui'
+ }).catch(
+ () => undefined
+ )
+}