Skip to content

The agent that grows with you

feat(desktop): report packaged self-update outcome via shared_metrics.update_run

teknium1d9fd8587bea5
diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.ts
index 8a77876615a..23d7e0d175b 100644
--- a/apps/desktop/electron/main.ts
+++ b/apps/desktop/electron/main.ts
@@ -560,6 +560,7 @@ 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'
@@ -3352,6 +3353,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)
for (const window of BrowserWindow.getAllWindows()) {
window.webContents.send('hermes:updates:progress', merged)
@@ -3394,6 +3396,16 @@ 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')
+ }
+ }
+})
+
function resolvePackagedUpdateStrategy(): Promise<UpdaterStrategy | null> {
return updateOperation.resolve()
}
@@ -4434,8 +4446,16 @@ async function applyUpdates(): Promise<UpdaterApplyResultWire> {
let handedOff: boolean = false
try {
- const strategy: UpdaterStrategy = (await resolvePackagedUpdateStrategy()) ?? resolveCheckoutUpdateStrategy()
- const result: UpdaterApplyResultWire = await strategy.apply()
+ 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()
+ )
+
handedOff = result.handedOff === true
return result
@@ -18126,6 +18146,8 @@ ipcMain.handle('hermes:updates:apply', async (_event, payload) =>
}))
)
+registerUpdateMetricsIpc(ipcMain, updateRunRecorder)
+
ipcMain.handle('hermes:updates:branch:get', async () => readDesktopUpdateConfig())
ipcMain.handle(
diff --git a/apps/desktop/electron/preload.ts b/apps/desktop/electron/preload.ts
index cfac092d901..c7f992dd29d 100644
--- a/apps/desktop/electron/preload.ts
+++ b/apps/desktop/electron/preload.ts
@@ -630,6 +630,14 @@ contextBridge.exposeInMainWorld('hermesDesktop', {
ipcRenderer.on('hermes:updates:progress', listener)
return () => ipcRenderer.removeListener('hermes:updates:progress', listener)
+ },
+ takePendingRun: () => ipcRenderer.invoke('hermes:updates:metric:take'),
+ ackPendingRun: sent => ipcRenderer.invoke('hermes:updates:metric:ack', sent),
+ onPendingRun: callback => {
+ const listener = () => callback()
+ ipcRenderer.on('hermes:updates:metric:pending', listener)
+
+ return () => ipcRenderer.removeListener('hermes:updates:metric:pending', listener)
}
},
themes: {
diff --git a/apps/desktop/electron/updater/update-metrics.test.ts b/apps/desktop/electron/updater/update-metrics.test.ts
new file mode 100644
index 00000000000..4bc9a824f0a
--- /dev/null
+++ b/apps/desktop/electron/updater/update-metrics.test.ts
@@ -0,0 +1,102 @@
+import fs from 'node:fs'
+import os from 'node:os'
+import path from 'node:path'
+
+import { afterEach, expect, test } from 'vitest'
+
+import { PENDING_UPDATE_RUN_FILE, UpdateRunRecorder, type UpdateRunReport } from './update-metrics'
+
+const dirs: string[] = []
+
+afterEach((): void => {
+ for (const dir of dirs.splice(0)) {
+ fs.rmSync(dir, { recursive: true, force: true })
+ }
+})
+
+function tempDir(): string {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'hermes-update-metrics-'))
+ dirs.push(dir)
+
+ return dir
+}
+
+/** What the renderer does: claim, send, ack with the RPC's fate. */
+async function send(recorder: UpdateRunRecorder, rpc: (run: UpdateRunReport) => Promise<unknown>): Promise<boolean> {
+ const run = recorder.take()
+
+ if (!run) {
+ return false
+ }
+
+ let sent = false
+
+ try {
+ await rpc(run)
+ sent = true
+ } catch {
+ // The record must survive for the next attach.
+ } finally {
+ recorder.ack(sent)
+ }
+
+ return sent
+}
+
+test('a hand-off run is reported once as success after the restart, and deleted only once the RPC resolves', async (): Promise<void> => {
+ const dir = tempDir()
+ const file = path.join(dir, PENDING_UPDATE_RUN_FILE)
+ let now = 1_000_000
+
+ const before = new UpdateRunRecorder({ dir: () => dir, appVersion: () => '1.0.0', now: () => now })
+
+ await before.track('electron-updater', 1_700_000_000, async () => ({ ok: true, handedOff: true }))
+ // Same process after the hand-off: the installer owns the outcome now.
+ expect(before.take()).toBeNull()
+ expect(fs.existsSync(file)).toBe(true)
+
+ now += 45_000
+ const after = new UpdateRunRecorder({ dir: () => dir, appVersion: () => '1.1.0', now: () => now })
+ const sent: UpdateRunReport[] = []
+
+ expect(await send(after, () => Promise.reject(new Error('backend gone')))).toBe(false)
+ expect(fs.existsSync(file)).toBe(true)
+
+ const claimed = after.take()
+ expect(claimed).not.toBeNull()
+ // A second caller while the first claim is unacked sends nothing.
+ expect(await send(after, async run => sent.push(run))).toBe(false)
+ after.ack(true)
+
+ expect(fs.existsSync(file)).toBe(false)
+ expect(await send(after, async run => sent.push(run))).toBe(false)
+ expect(claimed).toEqual({
+ outcome: 'success',
+ mechanism: 'electron-updater',
+ duration_ms: 45_000,
+ from_commit_date: 1_700_000_000
+ })
+})
+
+test('a failed run reports only a bucketed stage, never error text', async (): Promise<void> => {
+ const allowed = new Set(['download', 'verify', 'apply', 'restart', 'other'])
+ const secret = 'ENOENT /Users/alice/Hermes.app https://feed.example/v9.9.9'
+
+ for (const stages of [[], ['fetch'], ['fetch', 'prepare'], ['fetch', 'prepare', 'restart', 'error'], ['weird']]) {
+ const dir = tempDir()
+ const recorder = new UpdateRunRecorder({ dir: () => dir, appVersion: () => '1.0.0' })
+
+ await expect(
+ recorder.track('microsoft-store', null, async () => {
+ stages.forEach((stage: string): void => recorder.noteProgress(stage))
+ throw new Error(secret)
+ })
+ ).rejects.toThrow(secret)
+
+ const report = recorder.take()
+ expect(report?.outcome).toBe('failed')
+ expect(allowed.has(String(report?.failed_stage))).toBe(true)
+ expect(JSON.stringify(report)).not.toMatch(/alice|feed\.example|9\.9\.9|ENOENT/)
+ expect(fs.readFileSync(path.join(dir, PENDING_UPDATE_RUN_FILE), 'utf8')).not.toMatch(/alice|ENOENT/)
+ }
+})
diff --git a/apps/desktop/electron/updater/update-metrics.ts b/apps/desktop/electron/updater/update-metrics.ts
new file mode 100644
index 00000000000..fa114a7c2ad
--- /dev/null
+++ b/apps/desktop/electron/updater/update-metrics.ts
@@ -0,0 +1,256 @@
+// Shared-metrics report for PACKAGED self-updates (electron-updater, App
+// Installer, Store). Checkout hand-offs run `hermes update`, whose receipt the
+// backend already counts, so they never reach this module.
+//
+// A packaged apply usually ends with the installer quitting the app, so the
+// run is persisted as a pending record BEFORE apply starts and reported on the
+// next backend attach; the file is deleted only once the RPC has resolved.
+
+import fs from 'node:fs'
+import path from 'node:path'
+
+import type { UpdaterApplyResultWire } from './index'
+
+export type UpdateRunOutcome = 'success' | 'failed' | 'noop' | 'refused'
+export type UpdateFailedStage = 'download' | 'verify' | 'apply' | 'restart' | 'other'
+
+export const PENDING_UPDATE_RUN_FILE = 'update-metric-pending.json'
+
+const PENDING_TTL_MS = 30 * 24 * 60 * 60 * 1000
+
+// The strategies throw plain Errors with human text; the last progress stage
+// they announced is the only message-free signal of where a run died.
+const FAILED_STAGE_BY_PROGRESS: Readonly<Record<string, UpdateFailedStage>> = {
+ fetch: 'download',
+ prepare: 'verify',
+ restart: 'apply'
+}
+
+/** A run that has no `outcome` yet was handed to the installer; the next launch decides it. */
+export interface PendingUpdateRun {
+ v: 1
+ mechanism: string
+ startedAt: number
+ fromVersion: string
+ fromCommitDate?: number
+ outcome?: UpdateRunOutcome
+ failedStage?: UpdateFailedStage
+ durationMs?: number
+}
+
+/** `shared_metrics.update_run` params (SharedMetricsUpdateRunParams minus the profile the renderer routes by). */
+export interface UpdateRunReport {
+ outcome: UpdateRunOutcome
+ mechanism: string
+ duration_ms: number
+ failed_stage?: UpdateFailedStage
+ from_commit_date?: number
+}
+
+export interface UpdateRunRecorderDeps {
+ dir: () => string
+ appVersion: () => string
+ now?: () => number
+ /** A settled record is ready to send while the backend may still be attached. */
+ onRecorded?: () => void
+}
+
+export function failedStageForProgress(stage: string | null | undefined): UpdateFailedStage {
+ return stage && Object.hasOwn(FAILED_STAGE_BY_PROGRESS, stage) ? FAILED_STAGE_BY_PROGRESS[stage] : 'other'
+}
+
+function settledOutcome(result: UpdaterApplyResultWire): UpdateRunOutcome | null {
+ if (result.handedOff === true) {
+ return null
+ }
+
+ // ok:false is the discontinued-build refusal and manual means "install it
+ // yourself": neither attempted an install, so neither is a failure.
+ return !result.ok || result.manual === true ? 'refused' : 'noop'
+}
+
+function isPendingRun(value: unknown): value is PendingUpdateRun {
+ const run = value as PendingUpdateRun | null
+
+ return (
+ typeof run === 'object' &&
+ run !== null &&
+ run.v === 1 &&
+ typeof run.mechanism === 'string' &&
+ typeof run.startedAt === 'number' &&
+ typeof run.fromVersion === 'string'
+ )
+}
+
+export class UpdateRunRecorder {
+ private active: { run: PendingUpdateRun; stage: string | null } | null = null
+ private handedOff = false
+ private inFlight = false
+
+ constructor(private readonly deps: UpdateRunRecorderDeps) {}
+
+ private get file(): string {
+ return path.join(this.deps.dir(), PENDING_UPDATE_RUN_FILE)
+ }
+
+ private now(): number {
+ return (this.deps.now ?? Date.now)()
+ }
+
+ /** Wrap a packaged apply; `mechanism` undefined (checkout) runs it unrecorded. */
+ async track(
+ mechanism: string | undefined,
+ fromCommitDate: number | null | undefined,
+ apply: () => Promise<UpdaterApplyResultWire>
+ ): Promise<UpdaterApplyResultWire> {
+ if (!mechanism) {
+ return apply()
+ }
+
+ this.begin(mechanism, fromCommitDate)
+
+ try {
+ const result = await apply()
+ this.finish(settledOutcome(result))
+
+ return result
+ } catch (error) {
+ this.finish('failed')
+ throw error
+ }
+ }
+
+ noteProgress(stage: string): void {
+ if (this.active && Object.hasOwn(FAILED_STAGE_BY_PROGRESS, stage)) {
+ this.active.stage = stage
+ }
+ }
+
+ private begin(mechanism: string, fromCommitDate: number | null | undefined): void {
+ const run: PendingUpdateRun = {
+ v: 1,
+ mechanism,
+ startedAt: this.now(),
+ fromVersion: this.deps.appVersion(),
+ ...(typeof fromCommitDate === 'number' ? { fromCommitDate } : {})
+ }
+
+ this.active = { run, stage: null }
+ // Written up front: the installer may quit the app before apply() returns.
+ this.write(run)
+ }
+
+ private finish(outcome: UpdateRunOutcome | null): void {
+ const active = this.active
+ this.active = null
+
+ if (!active) {
+ return
+ }
+
+ if (outcome === null) {
+ this.handedOff = true
+
+ return
+ }
+
+ this.write({
+ ...active.run,
+ outcome,
+ durationMs: this.now() - active.run.startedAt,
+ ...(outcome === 'failed' ? { failedStage: failedStageForProgress(active.stage) } : {})
+ })
+ this.deps.onRecorded?.()
+ }
+
+ private write(run: PendingUpdateRun): void {
+ try {
+ const tmp = `${this.file}.tmp`
+ fs.mkdirSync(path.dirname(tmp), { recursive: true })
+ fs.writeFileSync(tmp, JSON.stringify(run))
+ fs.renameSync(tmp, this.file)
+ } catch {
+ // Telemetry never blocks an update.
+ }
+ }
+
+ private read(): PendingUpdateRun | null {
+ try {
+ const parsed: unknown = JSON.parse(fs.readFileSync(this.file, 'utf8'))
+
+ if (isPendingRun(parsed) && this.now() - parsed.startedAt <= PENDING_TTL_MS) {
+ return parsed
+ }
+
+ this.remove()
+ } catch {
+ // Missing or unreadable: nothing to report.
+ }
+
+ return null
+ }
+
+ private remove(): void {
+ try {
+ fs.rmSync(this.file, { force: true })
+ } catch {
+ // Retried on the next take().
+ }
+ }
+
+ /**
+ * Claim the pending run for one send. Returns null while an apply is running
+ * or has handed off in this process, and while a previous claim is unacked.
+ */
+ take(): UpdateRunReport | null {
+ if (this.active || this.handedOff || this.inFlight) {
+ return null
+ }
+
+ const run = this.read()
+
+ if (!run) {
+ return null
+ }
+
+ this.inFlight = true
+
+ return this.report(run)
+ }
+
+ /** Delete the record only after the RPC resolved; a failed send keeps it for the next attach. */
+ ack(sent: boolean): void {
+ if (!this.inFlight) {
+ return
+ }
+
+ if (sent) {
+ this.remove()
+ }
+
+ this.inFlight = false
+ }
+
+ private report(run: PendingUpdateRun): UpdateRunReport {
+ // A hand-off record is decided here: a new version means the installer finished.
+ const outcome = run.outcome ?? (this.deps.appVersion() !== run.fromVersion ? 'success' : 'failed')
+ const failedStage = run.outcome ? run.failedStage : 'apply'
+
+ return {
+ outcome,
+ mechanism: run.mechanism,
+ duration_ms: run.durationMs ?? Math.max(0, this.now() - run.startedAt),
+ ...(outcome === 'failed' ? { failed_stage: failedStage ?? 'other' } : {}),
+ ...(run.fromCommitDate !== undefined ? { from_commit_date: run.fromCommitDate } : {})
+ }
+ }
+}
+
+interface IpcHandleTarget {
+ handle(channel: string, listener: (event: unknown, ...args: unknown[]) => unknown): void
+}
+
+export function registerUpdateMetricsIpc(ipc: IpcHandleTarget, recorder: UpdateRunRecorder): void {
+ ipc.handle('hermes:updates:metric:take', (): UpdateRunReport | null => recorder.take())
+ ipc.handle('hermes:updates:metric:ack', (_event: unknown, sent: unknown): void => recorder.ack(sent === true))
+}
diff --git a/apps/desktop/src/app/contrib/wiring.tsx b/apps/desktop/src/app/contrib/wiring.tsx
index 43d8ded5d70..e62085b9563 100644
--- a/apps/desktop/src/app/contrib/wiring.tsx
+++ b/apps/desktop/src/app/contrib/wiring.tsx
@@ -88,6 +88,7 @@ import {
setBusy,
setMessages
} from '@/store/session'
+import { reportPendingUpdateRun } from '@/store/shared-metrics'
import { $archivedSessions } from '@/store/sidebar-archive'
import { $titlebarAppActionsSide, titlebarAppActionsClusterCounts } from '@/store/titlebar-app-actions'
import { armWakeWord, stopClientCapture } from '@/store/wake-word'
@@ -941,6 +942,17 @@ export function ContribWiring({ children }: { children: ReactNode }) {
}
}, [gatewayState, requestGateway])
+ useEffect(() => {
+ if (gatewayState !== 'open' || isAuxiliaryWindow()) {
+ return
+ }
+
+ const report = () => void reportPendingUpdateRun(requestGateway)
+ report()
+
+ return window.hermesDesktop?.updates?.onPendingRun?.(report)
+ }, [gatewayState, requestGateway])
+
const activeIsMessaging =
!!selectedStoredSessionId &&
isMessagingSource(messagingSessions.find(s => sessionMatchesStoredId(s, selectedStoredSessionId))?.source)
diff --git a/apps/desktop/src/global.d.ts b/apps/desktop/src/global.d.ts
index dadc84495b0..ff78197c302 100644
--- a/apps/desktop/src/global.d.ts
+++ b/apps/desktop/src/global.d.ts
@@ -7,6 +7,7 @@ import type { HudModifierApi } from '../electron/hud-modifier-types'
import type { MachineProfile } from '../electron/machine-profile'
import type { HermesNotification } from '../electron/notification-types'
import type { PoolLimits } from '../electron/pool-limits'
+import type { UpdateRunReport } from '../electron/updater/update-metrics'
import type { GrowRequest } from '../electron/window-growth'
import type { WakeIndicatorState } from './lib/wake-indicator'
@@ -598,6 +599,11 @@ declare global {
getBranch: () => Promise<{ branch: string }>
setBranch: (name: string) => Promise<{ branch: string }>
onProgress: (callback: (payload: DesktopUpdateProgress) => void) => () => void
+ /** Claim the pending packaged self-update run (null when none or already claimed). */
+ takePendingRun?: () => Promise<UpdateRunReport | null>
+ /** `sent` deletes the claimed record; false keeps it for the next attach. */
+ ackPendingRun?: (sent: boolean) => Promise<void>
+ onPendingRun?: (callback: () => void) => () => void
}
uninstall: {
summary: () => Promise<DesktopUninstallSummary>
diff --git a/apps/desktop/src/store/shared-metrics.ts b/apps/desktop/src/store/shared-metrics.ts
index 5c066987864..7f8ebb66b8b 100644
--- a/apps/desktop/src/store/shared-metrics.ts
+++ b/apps/desktop/src/store/shared-metrics.ts
@@ -76,3 +76,31 @@ export async function answerSharedMetricsOffer(
$sharedMetricsConsent.set(await saveSharedMetricsConsent(request, SHARED_METRICS_CHOICES[choice], { firstRun: true }))
$sharedMetricsDetailsOpen.set(false)
}
+
+/**
+ * Send the packaged self-update run main persisted (it survives the restart
+ * that applied it). Main keeps the record until the RPC resolves, and its claim
+ * makes concurrent callers a no-op. Fire-and-forget: errors are swallowed.
+ */
+export async function reportPendingUpdateRun(request: SharedMetricsRequester): Promise<void> {
+ const updates = window.hermesDesktop?.updates
+
+ try {
+ const run = await updates?.takePendingRun?.()
+
+ if (!run) {
+ return
+ }
+
+ let sent = false
+
+ try {
+ await request('shared_metrics.update_run', { ...run })
+ sent = true
+ } finally {
+ await updates?.ackPendingRun?.(sent)
+ }
+ } catch {
+ // Telemetry never surfaces; an unsent record retries on the next attach.
+ }
+}
diff --git a/apps/shared/src/gateway-contract.generated.ts b/apps/shared/src/gateway-contract.generated.ts
index 1abeb8ee371..9d88dc37695 100644
--- a/apps/shared/src/gateway-contract.generated.ts
+++ b/apps/shared/src/gateway-contract.generated.ts
@@ -674,6 +674,18 @@ export interface SharedMetricsStartupLatencyParams {
export interface SharedMetricsStartupLatencyResult {
ok: boolean
}
+/** One Desktop PACKAGED self-update (electron-updater / App Installer / Store). Source-checkout hand-offs run ``hermes update`` and are counted from its receipt, never here. Raw words; the backend buckets them: ``outcome`` success|failed|noop|refused, ``failed_stage`` download|verify|apply|restart, ``mechanism`` the updater strategy kind, ``duration_ms`` wall time, ``from_commit_date`` the updated-from build's commit time (epoch seconds) when known. */
+export interface SharedMetricsUpdateRunParams {
+ profile?: string | null
+ outcome: string
+ failed_stage?: string | null
+ mechanism?: string | null
+ duration_ms?: number | null
+ from_commit_date?: number | null
+}
+export interface SharedMetricsUpdateRunResult {
+ ok: boolean
+}
export interface ModelOptionsParams {
profile?: string | null
session_id?: string | null
@@ -5176,6 +5188,8 @@ export interface RpcMethods {
'shared_metrics.startup_latency': { params: SharedMetricsStartupLatencyParams; result: SharedMetricsStartupLatencyResult }
/** Pure read of the focused profile's shared-metrics opt-ins (collection, upload, answered). */
'shared_metrics.status': { params: ProfileParams; result: SharedMetricsConsentResult }
+ /** Count one Desktop packaged self-update outcome (fire-and-forget; a no-op unless shared metrics are on). */
+ 'shared_metrics.update_run': { params: SharedMetricsUpdateRunParams; result: SharedMetricsUpdateRunResult }
/** Run a safe (non-dangerous) shell command captured for ``!cmd`` / inline substitution. */
'shell.exec': { params: ShellExecParams; result: ShellExecResult }
/** Skills hub backend: list the profile's skills or search / browse / inspect / install from the hub. */
@@ -5462,6 +5476,7 @@ export const RPC_METHODS = [
'shared_metrics.slash_command',
'shared_metrics.startup_latency',
'shared_metrics.status',
+ 'shared_metrics.update_run',
'shell.exec',
'skills.manage',
'skills.reload',
diff --git a/apps/shared/src/gateway-contract.openrpc.json b/apps/shared/src/gateway-contract.openrpc.json
index 3185d05a844..117904febb8 100644
--- a/apps/shared/src/gateway-contract.openrpc.json
+++ b/apps/shared/src/gateway-contract.openrpc.json
@@ -3660,6 +3660,24 @@
}
}
},
+ {
+ "name": "shared_metrics.update_run",
+ "summary": "Count one Desktop packaged self-update outcome (fire-and-forget; a no-op unless shared metrics are on).",
+ "params": [
+ {
+ "name": "params",
+ "schema": {
+ "$ref": "#/components/schemas/SharedMetricsUpdateRunParams"
+ }
+ }
+ ],
+ "result": {
+ "name": "result",
+ "schema": {
+ "$ref": "#/components/schemas/SharedMetricsUpdateRunResult"
+ }
+ }
+ },
{
"name": "shell.exec",
"summary": "Run a safe (non-dangerous) shell command captured for ``!cmd`` / inline substitution.",
@@ -32109,6 +32127,95 @@
"title": "SharedMetricsStartupLatencyResult",
"type": "object"
},
+ "SharedMetricsUpdateRunParams": {
+ "additionalProperties": false,
+ "description": "One Desktop PACKAGED self-update (electron-updater / App Installer / Store). Source-checkout\nhand-offs run ``hermes update`` and are counted from its receipt, never here. Raw words; the\nbackend buckets them: ``outcome`` success|failed|noop|refused, ``failed_stage``\ndownload|verify|apply|restart, ``mechanism`` the updater strategy kind, ``duration_ms`` wall\ntime, ``from_commit_date`` the updated-from build's commit time (epoch seconds) when known.",
+ "properties": {
+ "profile": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Profile"
+ },
+ "outcome": {
+ "title": "Outcome",
+ "type": "string"
+ },
+ "failed_stage": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Failed Stage"
+ },
+ "mechanism": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Mechanism"
+ },
+ "duration_ms": {
+ "anyOf": [
+ {
+ "type": "number"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Duration Ms"
+ },
+ "from_commit_date": {
+ "anyOf": [
+ {
+ "type": "number"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "From Commit Date"
+ }
+ },
+ "required": [
+ "outcome"
+ ],
+ "title": "SharedMetricsUpdateRunParams",
+ "type": "object"
+ },
+ "SharedMetricsUpdateRunResult": {
+ "additionalProperties": false,
+ "properties": {
+ "ok": {
+ "title": "Ok",
+ "type": "boolean"
+ }
+ },
+ "required": [
+ "ok"
+ ],
+ "title": "SharedMetricsUpdateRunResult",
+ "type": "object"
+ },
"ShellExecParams": {
"additionalProperties": false,
"properties": {
diff --git a/hermes_cli/observability/shared_metrics_contract.py b/hermes_cli/observability/shared_metrics_contract.py
index cefa9e867c8..13f80b08ace 100644
--- a/hermes_cli/observability/shared_metrics_contract.py
+++ b/hermes_cli/observability/shared_metrics_contract.py
@@ -289,7 +289,6 @@ DESKTOP_UPDATE_STAGES = frozenset({"apply", "download", "restart", "verify"})
UPDATE_FAILED_STAGES = UPDATE_STAGES | DESKTOP_UPDATE_STAGES | {"none", "other"}
UPDATE_STAGE_OUTCOMES = frozenset({"failed", "skipped", "success"})
UPDATE_DURATION_BUCKETS = frozenset({"lt_30s", "30s_to_2m", "2m_to_5m", "5m_to_15m", "gte_15m"})
-VERSION_AGE_BUCKETS = frozenset({"lt_7d", "7d_to_30d", "30d_to_90d", "gte_90d", "unknown"})
# package = an OS/app-store style installer applied the update (Desktop packaged builds).
UPDATE_APPLY_MODES = frozenset({"external", "git", "package", "unknown", "zip"})
PROCESS_KINDS = frozenset({"cli", "cron", "gateway", "other", "serve", "tui"})
diff --git a/tests/tui_gateway/test_shared_metrics_update_run_rpc.py b/tests/tui_gateway/test_shared_metrics_update_run_rpc.py
new file mode 100644
index 00000000000..09bdbc79cca
--- /dev/null
+++ b/tests/tui_gateway/test_shared_metrics_update_run_rpc.py
@@ -0,0 +1,25 @@
+"""shared_metrics.update_run: Desktop reports a packaged self-update as bounded kind=desktop dims only."""
+
+from __future__ import annotations
+
+from hermes_cli.observability import relay_shared_metrics
+from hermes_cli.observability import shared_metrics_contract as contract
+import tui_gateway.server as server
+
+
+def test_desktop_update_run_is_bounded_and_never_carries_raw_text(monkeypatch):
+ rows: list[tuple[str, dict]] = []
+ monkeypatch.setattr(relay_shared_metrics, "enabled", lambda: True)
+ monkeypatch.setattr(relay_shared_metrics, "record_process_mark", lambda mark, data: rows.append((mark, data)))
+
+ response = server.handle_request({"jsonrpc": "2.0", "id": "r1", "method": "shared_metrics.update_run", "params": {
+ "outcome": "failed", "failed_stage": "ENOENT: /Users/alice/Library/Caches/update.zip",
+ "mechanism": "electron-updater", "duration_ms": 400_000, "from_commit_date": 0,
+ }})
+
+ assert response["result"] == {"ok": True}
+ assert rows == [(contract.UPDATE_RUN_MARK, {
+ "apply_mode": "package", "duration_bucket": "5m_to_15m", "failed_stage": "other",
+ "from_version_age_bucket": "gte_90d", "kind": "desktop", "outcome": "failed",
+ })]
+ assert contract.counter_dimensions_are_valid(contract.UPDATE_RUN_METRIC, rows[0][1])
diff --git a/tui_gateway/contracts/config_free_tier_control.py b/tui_gateway/contracts/config_free_tier_control.py
index a08c30bcc57..3c6e166ed25 100644
--- a/tui_gateway/contracts/config_free_tier_control.py
+++ b/tui_gateway/contracts/config_free_tier_control.py
@@ -276,6 +276,30 @@ method("shared_metrics.startup_latency", params=SharedMetricsStartupLatencyParam
doc="Record one client launch-to-ready latency (fire-and-forget; a no-op unless shared metrics are on).")
+# ---- v4 reliability ----
+class SharedMetricsUpdateRunParams(ProfileParams):
+ """One Desktop PACKAGED self-update (electron-updater / App Installer / Store). Source-checkout
+ hand-offs run ``hermes update`` and are counted from its receipt, never here. Raw words; the
+ backend buckets them: ``outcome`` success|failed|noop|refused, ``failed_stage``
+ download|verify|apply|restart, ``mechanism`` the updater strategy kind, ``duration_ms`` wall
+ time, ``from_commit_date`` the updated-from build's commit time (epoch seconds) when known."""
+
+ outcome: str
+ failed_stage: str | None = None
+ mechanism: str | None = None
+ duration_ms: float | None = None
+ from_commit_date: float | None = None
+
+
+class SharedMetricsUpdateRunResult(Result):
+ ok: bool
+
+
+method("shared_metrics.update_run", params=SharedMetricsUpdateRunParams, result=SharedMetricsUpdateRunResult,
+ doc="Count one Desktop packaged self-update outcome (fire-and-forget; a no-op unless shared metrics are on).")
+# ---- end v4 reliability ----
+
+
# ── model.options ─────────────────────────────────────────────────────────────────────────────
diff --git a/tui_gateway/methods_shared_metrics.py b/tui_gateway/methods_shared_metrics.py
index fc61bb79cf4..4c21eb00501 100644
--- a/tui_gateway/methods_shared_metrics.py
+++ b/tui_gateway/methods_shared_metrics.py
@@ -111,5 +111,22 @@ def _(rid, params: dict) -> dict:
return _ok(rid, {"ok": True})
+# ---- v4 reliability ----
+@method("shared_metrics.update_run")
+@_profile_scoped
+def _(rid, params: dict) -> dict:
+ """Desktop reports each packaged self-update once (a pending record survives the restart that
+ applies it and is sent on the next backend attach). Always ``{ok: true}``."""
+ from hermes_cli.observability.shared_metrics_update import record_desktop_update
+
+ record_desktop_update(
+ outcome=params.get("outcome"), failed_stage=params.get("failed_stage"),
+ duration_ms=params.get("duration_ms"), mechanism=params.get("mechanism"),
+ from_commit_date=params.get("from_commit_date"),
+ )
+ return _ok(rid, {"ok": True})
+# ---- end v4 reliability ----
+
+
def register(server) -> None:
bind_module(globals(), server, skip=("_",))