The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(desktop): wire love/hate telemetry into existing interactions
teknium198fa444d1664
diff --git a/apps/desktop/src/app/chat/composer/controls.tsx b/apps/desktop/src/app/chat/composer/controls.tsxindex 1a70a448ebb..9e74e8b7b3a 100644--- a/apps/desktop/src/app/chat/composer/controls.tsx+++ b/apps/desktop/src/app/chat/composer/controls.tsx@@ -7,6 +7,7 @@ import { useI18n } from '@/i18n'import { triggerHaptic } from '@/lib/haptics'import { Ear, EarOff, iconSize, Layers3, Loader2, Square } from '@/lib/icons'import { cn } from '@/lib/utils'+import { recordAction } from '@/store/desktop-metrics'import { $hudMode, closeHud, resetHudLayout } from '@/store/hud'import { $wakeWord, toggleWakeWord } from '@/store/wake-word'@@ -157,6 +158,7 @@ export function ComposerControls({aria-label={showStop ? c.stop : c.send}className={PRIMARY_ICON_BTN}disabled={disabled || !canSubmit}+ onClick={() => recordAction(showStop ? 'composer.cancel' : 'composer.send', 'click')}type="submit">{showStop ? (diff --git a/apps/desktop/src/app/chat/composer/hooks/use-composer-voice.ts b/apps/desktop/src/app/chat/composer/hooks/use-composer-voice.tsindex 6c085e87560..ef4b271a4c7 100644--- a/apps/desktop/src/app/chat/composer/hooks/use-composer-voice.ts+++ b/apps/desktop/src/app/chat/composer/hooks/use-composer-voice.ts@@ -16,6 +16,7 @@ import { toLiveHistory } from '@/lib/voice-live'import { clearWakeIndicator, syncWakeIndicatorWithVoice } from '@/lib/wake-indicator'import { $voiceConversationStartRequest, takeVoiceConversationStart } from '@/store/composer'import { resetBrowseState } from '@/store/composer-input-history'+import { recordFeatureUse } from '@/store/desktop-metrics'import { $gateway } from '@/store/gateway'import { notify, notifyError } from '@/store/notifications'import { $voiceLiveStatus, refreshVoiceLiveStatus, selectedVoiceChatMode } from '@/store/voice-live'@@ -269,6 +270,7 @@ export function useComposerVoice({setLiveEngineActive(live)setVoiceConversationActive(true)+ recordFeatureUse('voice_conversation')}, [t])useEffect(() => {diff --git a/apps/desktop/src/app/chat/composer/hooks/use-voice-recorder.ts b/apps/desktop/src/app/chat/composer/hooks/use-voice-recorder.tsindex 937f2d3bc03..ce18316e322 100644--- a/apps/desktop/src/app/chat/composer/hooks/use-voice-recorder.ts+++ b/apps/desktop/src/app/chat/composer/hooks/use-voice-recorder.ts@@ -1,6 +1,7 @@import { useEffect, useRef, useState } from 'react'import { useI18n } from '@/i18n'+import { recordFeatureUse } from '@/store/desktop-metrics'import { notify, notifyError } from '@/store/notifications'import type { VoiceActivityState, VoiceStatus } from '../types'@@ -89,6 +90,7 @@ export function useVoiceRecorder({startedAtRef.current = Date.now()setElapsedSeconds(0)setVoiceStatus('recording')+ recordFeatureUse('voice_dictation')intervalRef.current = window.setInterval(() => setElapsedSeconds((Date.now() - startedAtRef.current) / 1000), 250)const cap = Math.max(1, Math.min(Math.trunc(maxRecordingSeconds), 600))timeoutRef.current = window.setTimeout(() => void stop(), cap * 1000)diff --git a/apps/desktop/src/app/chat/composer/start-voice-button.tsx b/apps/desktop/src/app/chat/composer/start-voice-button.tsxindex 25d2031f6e6..888add695ad 100644--- a/apps/desktop/src/app/chat/composer/start-voice-button.tsx+++ b/apps/desktop/src/app/chat/composer/start-voice-button.tsx@@ -5,6 +5,7 @@ import { useI18n } from '@/i18n'import { triggerHaptic } from '@/lib/haptics'import { AudioLines, ChevronDown, iconSize } from '@/lib/icons'import { cn } from '@/lib/utils'+import { recordAction } from '@/store/desktop-metrics'import { GHOST_ICON_BTN, PRIMARY_ICON_BTN } from './control-classes'import { useVoiceEngineName, VoiceEngineRows } from './voice-engine-rows'@@ -40,6 +41,7 @@ export function StartVoiceButton({disabled={disabled}onClick={() => {triggerHaptic('open')+ recordAction('composer.voice', 'click')onStart()}}size="icon"diff --git a/apps/desktop/src/app/chat/sidebar/index.tsx b/apps/desktop/src/app/chat/sidebar/index.tsxindex c1fb61a44ee..cca843d5bf5 100644--- a/apps/desktop/src/app/chat/sidebar/index.tsx+++ b/apps/desktop/src/app/chat/sidebar/index.tsx@@ -32,6 +32,7 @@ import { cn } from '@/lib/utils'import { $connectionsRegistry } from '@/store/connection-registry-state'import { $activeConnectionId } from '@/store/connections'import { $cronJobs } from '@/store/cron'+import { recordAction } from '@/store/desktop-metrics'import { $interfaceMode, $showsAdvancedChrome, shownInMode } from '@/store/interface-mode'import { $bindings } from '@/store/keybinds'import {@@ -1638,6 +1639,10 @@ export function ChatSidebar({$newChatProfile.set(null)}+ if (item.keybindActionId) {+ recordAction(item.keybindActionId, 'click')+ }+onNavigate(item)}}onPointerDown={event => {diff --git a/apps/desktop/src/app/command-palette/index.tsx b/apps/desktop/src/app/command-palette/index.tsxindex 3e5873b8d8c..245a85c95cc 100644--- a/apps/desktop/src/app/command-palette/index.tsx+++ b/apps/desktop/src/app/command-palette/index.tsx@@ -70,6 +70,7 @@ import {closeCommandPalette,setCommandPaletteOpen} from '@/store/command-palette'+import { completeFlow, recordAction } from '@/store/desktop-metrics'import { $bindings, bindingsFor } from '@/store/keybinds'import { $dismissedAutoProjectIds, $pinnedSessionIds, filterVisibleProjects } from '@/store/layout'import { openPetGenerate } from '@/store/pet-generate'@@ -1565,6 +1566,9 @@ function CommandPaletteBody({ onExited }: { onExited: () => void }) {return}+ completeFlow('command_palette')+ recordAction(item.action ?? 'other', 'palette')+if (item.runWithEvent) {item.runWithEvent(lastSelectMods.current)} else {diff --git a/apps/desktop/src/app/contrib/hooks/desktop-onboarding-metrics.ts b/apps/desktop/src/app/contrib/hooks/desktop-onboarding-metrics.tsnew file mode 100644index 00000000000..72491670e52--- /dev/null+++ b/apps/desktop/src/app/contrib/hooks/desktop-onboarding-metrics.ts@@ -0,0 +1,148 @@+/**+ * First-run funnel telemetry (hermes.desktop.onboarding). Observes the+ * onboarding stores' own transitions — the provider picker, the guided intro,+ * free-tier sign-in — and maps them onto the closed step set; nothing here+ * changes onboarding behavior. Manual (Settings "add provider") flows are not+ * first run and are ignored.+ */++import { closeOnboardingStep, recordDislike, recordOnboarding } from '@/store/desktop-metrics'+import { $freeTierSignIn, type FreeTierSignInState } from '@/store/free-tier-sign-in'+import { $desktopOnboarding, type DesktopOnboardingState } from '@/store/onboarding'+import { $onboardingGate, type OnboardingPhase } from '@/store/onboarding-gate'++const OAUTH_PENDING = new Set(['awaiting_user', 'error', 'external_pending', 'polling', 'starting', 'submitting'])++function providerStepFor(state: DesktopOnboardingState): 'provider_api_key' | 'provider_local' | null {+ return state.localEndpoint ? 'provider_local' : state.mode === 'apikey' ? 'provider_api_key' : null+}++export function onboardingTransition(prev: DesktopOnboardingState, next: DesktopOnboardingState): void {+ if (prev.manual || next.manual) {+ return+ }++ if (next.configured === false && prev.configured !== false && !next.firstRunSkipped) {+ recordOnboarding('provider_setup', 'reached')+ }++ const prevStep = providerStepFor(prev)+ const nextStep = providerStepFor(next)++ if (next.configured === false && nextStep && nextStep !== prevStep) {+ recordOnboarding(nextStep, 'reached')+ }++ if (next.flow.status !== prev.flow.status) {+ if (next.flow.status === 'starting') {+ recordOnboarding('provider_oauth', 'reached')+ } else if (next.flow.status === 'success') {+ recordOnboarding('provider_oauth', 'completed')+ } else if (next.flow.status === 'confirming_model') {+ recordOnboarding('model_pick', 'reached')+ } else if (+ next.flow.status === 'idle' &&+ OAUTH_PENDING.has(prev.flow.status) &&+ next.configured !== true &&+ !next.firstRunSkipped+ ) {+ // The sign-in was backed out of (Cancel / Back), not finished.+ recordDislike('cancelled', 'provider_oauth')+ closeOnboardingStep('provider_oauth')+ }+ }++ // Only a picker the user actually saw (configured was false) completes a step: the boot readiness+ // probe flips unknown → configured on every launch of an already-set-up install.+ if (next.configured === true && prev.configured === false) {+ if (prev.flow.status === 'confirming_model') {+ recordOnboarding('model_pick', 'completed')+ }++ if (prevStep) {+ recordOnboarding(prevStep, 'completed')+ }++ recordOnboarding('provider_setup', 'completed')+ }++ if (next.firstRunSkipped && !prev.firstRunSkipped) {+ recordOnboarding('choose_later', 'completed')++ for (const step of ['provider_setup', 'provider_oauth', 'provider_api_key', 'provider_local', 'model_pick'] as const) {+ closeOnboardingStep(step)+ }+ }++ if (next.freeTierReady !== prev.freeTierReady) {+ recordOnboarding('free_tier_ready', next.freeTierReady ? 'reached' : 'completed')+ }+}++export function guidePhaseTransition(prev: OnboardingPhase, next: OnboardingPhase): void {+ if (prev === next) {+ return+ }++ if (next === 'cinematic') {+ recordOnboarding('intro', 'reached')+ } else if (prev === 'cinematic') {+ recordOnboarding('intro', 'completed')+ }++ if (next === 'guided') {+ recordOnboarding('guide', 'reached')+ } else if (next === 'skipped') {+ recordOnboarding('guide_skip', 'completed')+ closeOnboardingStep('guide')+ } else if (next === 'done') {+ recordOnboarding('guide', 'completed')+ }+}++const SIGN_IN_OPEN = new Set(['code', 'failed', 'finishing', 'requested', 'setting_up'])++export function signInTransition(prev: FreeTierSignInState, next: FreeTierSignInState): void {+ if (prev.status === next.status) {+ return+ }++ if (next.status === 'requested') {+ recordOnboarding('sign_in', 'reached')+ } else if (next.status === 'completed' || next.status === 'already_signed_in') {+ recordOnboarding('sign_in', 'completed')+ } else if (next.status === 'closed' && SIGN_IN_OPEN.has(prev.status)) {+ recordDislike('cancelled', 'free_tier_sign_in')+ closeOnboardingStep('sign_in')+ }+}++/** Subscribe the three first-run stores; returns the unsubscribe. */+export function observeOnboardingMetrics(): () => void {+ let onboarding = $desktopOnboarding.get()+ let phase = $onboardingGate.get().phase+ let signIn = $freeTierSignIn.get()++ const stops = [+ $desktopOnboarding.listen(next => {+ const prev = onboarding++ onboarding = next+ onboardingTransition(prev, next)+ }),+ $onboardingGate.listen(next => {+ const prev = phase++ phase = next.phase+ guidePhaseTransition(prev, next.phase)+ }),+ $freeTierSignIn.listen(next => {+ const prev = signIn++ signIn = next+ signInTransition(prev, next)+ })+ ]++ return () => stops.forEach(stop => stop())+}diff --git a/apps/desktop/src/app/contrib/hooks/use-desktop-integrations.ts b/apps/desktop/src/app/contrib/hooks/use-desktop-integrations.tsindex bf0b8f7538b..2682a697b06 100644--- a/apps/desktop/src/app/contrib/hooks/use-desktop-integrations.ts+++ b/apps/desktop/src/app/contrib/hooks/use-desktop-integrations.ts@@ -12,6 +12,7 @@ import { resolveDeepLinkAction } from '@/lib/deeplink-routes'import { pathFromHermesDeepLink, resolveHermesOpenPath } from '@/lib/hermes-open-target'import { storedSessionIdForNotification } from '@/lib/session-ids'import { announceNewSessionDraftKey } from '@/store/composer'+import { recordAction } from '@/store/desktop-metrics'import { requestMcpInstallFromDeepLink } from '@/store/mcp-deeplink-install'import { startMcpHealthChecker, stopMcpHealthChecker } from '@/store/mcp-health'import {@@ -494,7 +495,10 @@ export function useDesktopIntegrations({// File > Open Folder… — same open-folder-as-project upsert as the ⌘O keybind.useEffect(() => {- const unsubscribe = window.hermesDesktop?.onOpenFolderRequested?.(() => void openFolderAsProject())+ const unsubscribe = window.hermesDesktop?.onOpenFolderRequested?.(() => {+ recordAction('workspace.openFolder', 'menu')+ void openFolderAsProject()+ })return () => unsubscribe?.()}, [])diff --git a/apps/desktop/src/app/contrib/hooks/use-desktop-metrics.ts b/apps/desktop/src/app/contrib/hooks/use-desktop-metrics.tsnew file mode 100644index 00000000000..7328e5a99c0--- /dev/null+++ b/apps/desktop/src/app/contrib/hooks/use-desktop-metrics.ts@@ -0,0 +1,227 @@+/**+ * Wires Desktop love/hate telemetry (store/desktop-metrics.ts) to the app's+ * existing state: the focused gateway + its collection switch, routes, open+ * overlays, workspace mode, user interaction, long frames and the profile+ * count. Main window only; renders nothing.+ */++import { useEffect } from 'react'++import { contributedRoutes } from '@/app/routes'+import { $workspaceMode } from '@/components/pane-shell/workspace-scope'+import { $commandPaletteOpen } from '@/store/command-palette'+import {+ bindDesktopMetrics,+ cancelPendingBackendDrop,+ noteInteraction,+ persistDesktopMetricsNow,+ recordFeatureUse,+ recordFriction,+ routeArea,+ setDesktopBotCount,+ setDesktopMetricsGate,+ slowFrameBucket,+ tickDesktopMetrics,+ trackArea,+ trackFlow+} from '@/store/desktop-metrics'+import { $findInPage } from '@/store/find-in-page'+import { $gatewaySwitching } from '@/store/gateway-switch'+import { SESSION_SEARCH_FOCUS_EVENT } from '@/store/layout'+import { $profiles, $profilesByConnection } from '@/store/profile'+import { $modelPickerOpen, $sessionPickerOpen } from '@/store/session'+import { $switcherOpen } from '@/store/session-switcher'+import {+ $sharedMetricsConsent,+ readSharedMetricsConsent,+ type SharedMetricsConsent,+ type SharedMetricsRequester+} from '@/store/shared-metrics'++import { observeOnboardingMetrics } from './desktop-onboarding-metrics'++const DAY_TICK_MS = 10 * 60_000+const INTERACTION_THROTTLE_MS = 1000++function gateFor(consent: SharedMetricsConsent | null): 'off' | 'on' | null {+ return consent ? (consent.enabled ? 'on' : 'off') : null+}++function botCount(): number {+ const byConnection = [...$profilesByConnection.get().values()].reduce((sum, list) => sum + list.length, 0)++ return byConnection || $profiles.get().length+}++/** Long frames (Long Animation Frames where available, else long tasks) while the window is visible. */+function observeSlowFrames(): () => void {+ if (typeof PerformanceObserver === 'undefined') {+ return () => undefined+ }++ const types = PerformanceObserver.supportedEntryTypes ?? []+ const type = types.includes('long-animation-frame') ? 'long-animation-frame' : types.includes('longtask') ? 'longtask' : null++ if (!type) {+ return () => undefined+ }++ const observer = new PerformanceObserver(list => {+ if (document.visibilityState !== 'visible') {+ return+ }++ for (const entry of list.getEntries()) {+ const bucket = slowFrameBucket(entry.duration)++ if (bucket) {+ recordFriction('slow_frame', bucket)+ }+ }+ })++ try {+ observer.observe({ buffered: false, type })+ } catch {+ return () => undefined+ }++ return () => observer.disconnect()+}++export function useDesktopMetrics({+ enabled,+ gatewayOpen,+ pathname,+ profile,+ requestGateway+}: {+ enabled: boolean+ gatewayOpen: boolean+ pathname: string+ profile: string+ requestGateway: SharedMetricsRequester+}): void {+ // The focused gateway and its collection switch (re-read on every attach and profile switch).+ useEffect(() => {+ if (!enabled || !gatewayOpen) {+ bindDesktopMetrics(null)++ return+ }++ let cancelled = false++ bindDesktopMetrics(requestGateway)+ void readSharedMetricsConsent(requestGateway).then(consent => {+ // An unreadable answer (older backend, flap) keeps the last known gate.+ if (!cancelled && consent) {+ setDesktopMetricsGate(gateFor(consent))+ }+ })++ return () => {+ cancelled = true+ }+ }, [enabled, gatewayOpen, profile, requestGateway])++ // A first-run answer or a Settings change lands in the consent atom.+ useEffect(() => {+ if (!enabled) {+ return+ }++ return $sharedMetricsConsent.listen(consent => {+ if (consent) {+ setDesktopMetricsGate(gateFor(consent))+ }+ })+ }, [enabled])++ useEffect(() => {+ const area = enabled ? routeArea(pathname, contributedRoutes().map(route => route.path)) : null++ if (area) {+ recordFeatureUse(area)+ }+ }, [enabled, pathname])++ useEffect(() => {+ if (!enabled) {+ return+ }++ const overlay = (area: 'command_palette' | 'model_picker' | 'session_picker' | 'session_switcher') => (open: boolean) => {+ if (open) {+ recordFeatureUse(area)+ }++ trackFlow(area, open)+ }++ let findActive = $findInPage.get().active+ const onSessionSearch = () => recordFeatureUse('session_search')++ const onInteraction = (() => {+ let last = 0++ return () => {+ const now = Date.now()++ if (now - last >= INTERACTION_THROTTLE_MS) {+ last = now+ noteInteraction(now)+ }+ }+ })()++ const onVisibility = () => {+ if (document.visibilityState === 'hidden') {+ persistDesktopMetricsNow()+ } else {+ tickDesktopMetrics()+ }+ }++ const stops = [+ $commandPaletteOpen.listen(overlay('command_palette')),+ $modelPickerOpen.listen(overlay('model_picker')),+ $sessionPickerOpen.listen(overlay('session_picker')),+ $switcherOpen.listen(overlay('session_switcher')),+ $findInPage.listen(next => {+ if (next.active && !findActive) {+ recordFeatureUse('find_in_page')+ }++ findActive = next.active+ }),+ // Bot Mode is the `bots` workspace (components/pane-shell/workspace-scope.ts).+ $workspaceMode.listen(mode => trackArea('bot_mode', mode === 'bots')),+ $gatewaySwitching.listen(switching => switching && cancelPendingBackendDrop()),+ $profiles.listen(() => setDesktopBotCount(botCount())),+ $profilesByConnection.listen(() => setDesktopBotCount(botCount())),+ observeSlowFrames(),+ observeOnboardingMetrics()+ ]++ setDesktopBotCount(botCount())+ window.addEventListener(SESSION_SEARCH_FOCUS_EVENT, onSessionSearch)+ window.addEventListener('pointerdown', onInteraction, { capture: true, passive: true })+ window.addEventListener('keydown', onInteraction, { capture: true, passive: true })+ window.addEventListener('wheel', onInteraction, { capture: true, passive: true })+ document.addEventListener('visibilitychange', onVisibility)+ window.addEventListener('pagehide', persistDesktopMetricsNow)+ const tick = window.setInterval(() => tickDesktopMetrics(), DAY_TICK_MS)++ return () => {+ stops.forEach(stop => stop())+ window.removeEventListener(SESSION_SEARCH_FOCUS_EVENT, onSessionSearch)+ window.removeEventListener('pointerdown', onInteraction, { capture: true })+ window.removeEventListener('keydown', onInteraction, { capture: true })+ window.removeEventListener('wheel', onInteraction, { capture: true })+ document.removeEventListener('visibilitychange', onVisibility)+ window.removeEventListener('pagehide', persistDesktopMetricsNow)+ window.clearInterval(tick)+ }+ }, [enabled])+}diff --git a/apps/desktop/src/app/contrib/hooks/use-session-tile-delegate.ts b/apps/desktop/src/app/contrib/hooks/use-session-tile-delegate.tsindex 1fc9422685a..0f11346d76d 100644--- a/apps/desktop/src/app/contrib/hooks/use-session-tile-delegate.ts+++ b/apps/desktop/src/app/contrib/hooks/use-session-tile-delegate.ts@@ -14,6 +14,7 @@ import { translateNow } from '@/i18n/runtime'import { type ChatMessage, chatMessageText, toChatMessages } from '@/lib/chat-messages'import { markReasoningEffortPending } from '@/lib/chat-runtime'import { profileScopeForSessionOwner, refreshIfTranscriptStale } from '@/lib/stale-transcript-guard'+import { noteMessageSent } from '@/store/desktop-metrics'import { notify } from '@/store/notifications'import {isReadOnlyRuntimeId,@@ -488,6 +489,8 @@ export function useSessionTileDelegate({requestForStoredSession<T>(storedSessionId, method, params ?? {}, timeoutMs): requestGateway+ noteMessageSent($sessionTiles.get().find(tile => tile.runtimeId === runtimeId)?.workspaceMode ?? 'sessions')+await withSessionNotFoundResume(runtimeId,storedSessionId,diff --git a/apps/desktop/src/app/contrib/wiring.tsx b/apps/desktop/src/app/contrib/wiring.tsxindex e62085b9563..44ea4c8a9f4 100644--- a/apps/desktop/src/app/contrib/wiring.tsx+++ b/apps/desktop/src/app/contrib/wiring.tsx@@ -163,6 +163,7 @@ import {useBackgroundSync} from './hooks/use-background-sync'import { useDesktopIntegrations } from './hooks/use-desktop-integrations'+import { useDesktopMetrics } from './hooks/use-desktop-metrics'import { usePetBridge } from './hooks/use-pet-bridge'import { useQuickEntryBridge } from './hooks/use-quick-entry-bridge'import { useSessionTileDelegate } from './hooks/use-session-tile-delegate'@@ -953,6 +954,14 @@ export function ContribWiring({ children }: { children: ReactNode }) {return window.hermesDesktop?.updates?.onPendingRun?.(report)}, [gatewayState, requestGateway])+ useDesktopMetrics({+ enabled: !isAuxiliaryWindow(),+ gatewayOpen: gatewayState === 'open',+ pathname: location.pathname,+ profile: activeGatewayProfile,+ requestGateway+ })+const activeIsMessaging =!!selectedStoredSessionId &&isMessagingSource(messagingSessions.find(s => sessionMatchesStoredId(s, selectedStoredSessionId))?.source)diff --git a/apps/desktop/src/app/gateway/hooks/use-gateway-boot.ts b/apps/desktop/src/app/gateway/hooks/use-gateway-boot.tsindex 940cdffd912..dd0c9270214 100644--- a/apps/desktop/src/app/gateway/hooks/use-gateway-boot.ts+++ b/apps/desktop/src/app/gateway/hooks/use-gateway-boot.ts@@ -32,6 +32,7 @@ import {setDesktopBootStep} from '@/store/boot'import { resetBackgroundPollingGuard } from '@/store/composer-status'+import { noteBackendDrop, noteBackendExited } from '@/store/desktop-metrics'import {$gateway,activeGateway,@@ -330,6 +331,9 @@ export function useGatewayBoot({// reconnectAttempt, reconnectFailingSince and escalated reset only once an// open proves stable (isStableOpen), judged when the socket closes.let openedAt: number | null = null+ // Why the next post-open close happens, when this hook closes the socket itself+ // (friction telemetry): a liveness timeout is a real drop, a manual reconnect is not.+ let ownCloseReason: 'manual' | 'timeout' | null = null// Consecutive unanswered liveness probes (#95327): a busy-but-healthy// backend can fail one probe; only a STREAK proves a genuinely dead// socket while turns are in flight. Reset on any successful probe or a@@ -672,6 +676,7 @@ export function useGatewayBoot({}livenessProbeFailures = 0+ ownCloseReason = 'timeout'gateway.close()}}@@ -1069,6 +1074,12 @@ export function useGatewayBoot({resetReconnectBackoff()}+ // The connected→disconnected edge after a healthy boot, not a switch or our own manual close.+ if (openedAt !== null && bootCompleted && !$gatewaySwitching.get() && ownCloseReason !== 'manual') {+ noteBackendDrop(ownCloseReason === 'timeout' ? 'timeout' : null)+ }++ ownCloseReason = nullopenedAt = nullif (bootCompleted && !$gatewaySwitching.get()) {@@ -1173,6 +1184,7 @@ export function useGatewayBoot({// Only explicit recovery may retry a credential that requires sign-in.primaryReauthError = nullreauthNotified = false+ ownCloseReason = 'manual'gateway.close()clearReconnectTimer()resetReconnectBackoff()@@ -1316,6 +1328,8 @@ export function useGatewayBoot({return}+ noteBackendExited()+// While the boot overlay is up it already shows the failure with its own// Retry, and the reconnect handler below is a no-op before boot completes// — a toast whose button does nothing would only mislead. Fail thediff --git a/apps/desktop/src/app/hooks/use-keybinds.ts b/apps/desktop/src/app/hooks/use-keybinds.tsindex 2e224b90865..a835962821a 100644--- a/apps/desktop/src/app/hooks/use-keybinds.ts+++ b/apps/desktop/src/app/hooks/use-keybinds.ts@@ -31,6 +31,7 @@ import { composerFocusKeysAllowed, isComposerFocusSoftCombo, typeToFocusChar } fimport { stepReasoningEffort, writeSessionReasoningEffort } from '@/lib/reasoning-step'import { openWorktreeDialog } from '@/store/coding-status'import { $commandPaletteOpen, openCommandPalettePage, toggleCommandPalette } from '@/store/command-palette'+import { recordAction, recordDislike } from '@/store/desktop-metrics'import {$findInPage,findNext as findNextMatch,@@ -481,6 +482,8 @@ export function useKeybinds(deps: KeybindRuntimeDeps): void {if (step.type === 'set') {setBinding(capturing, step.combos)+ } else {+ recordDislike('cancelled', 'keybind_capture')}endCapture()@@ -566,6 +569,8 @@ export function useKeybinds(deps: KeybindRuntimeDeps): void {continue}+ recordAction(actionId, 'shortcut')+return}}diff --git a/apps/desktop/src/app/model-picker-overlay.tsx b/apps/desktop/src/app/model-picker-overlay.tsxindex 9ad25f312dd..d5c0e122c5b 100644--- a/apps/desktop/src/app/model-picker-overlay.tsx+++ b/apps/desktop/src/app/model-picker-overlay.tsx@@ -8,6 +8,7 @@ import { ModelPickerDialog } from '@/components/model-picker'import type { HermesGateway } from '@/hermes'import { resolveModelPickerOwner } from '@/lib/model-picker-owner'import { useStoreSelector } from '@/lib/use-session-slice'+import { completeFlow } from '@/store/desktop-metrics'import {$activeSessionId,$currentModel,@@ -91,7 +92,10 @@ export function ModelPickerOverlay({currentProvider={currentProvider}gw={gateway}onOpenChange={setModelPickerOpen}- onSelect={selection => (pickerOwner.route ? selectFocusedModel : onSelect)({ ...selection, sessionId })}+ onSelect={selection => {+ completeFlow('model_picker')+ ;(pickerOwner.route ? selectFocusedModel : onSelect)({ ...selection, sessionId })+ }}open={open}ownerConnectionId={pickerOwner.connectionId}profile={pickerOwner.profile}diff --git a/apps/desktop/src/app/right-sidebar/terminal/reveal-focus.ts b/apps/desktop/src/app/right-sidebar/terminal/reveal-focus.tsindex 6f56e24471f..85b718b1040 100644--- a/apps/desktop/src/app/right-sidebar/terminal/reveal-focus.ts+++ b/apps/desktop/src/app/right-sidebar/terminal/reveal-focus.ts@@ -2,6 +2,7 @@ import { paletteToggle } from '@/app/command-palette/contrib'import { isPaneVisible, togglePaneVisible } from '@/components/pane-shell/tree/store'import { Terminal } from '@/lib/icons'import { isFocusWithin } from '@/lib/keybinds/combo'+import { trackArea } from '@/store/desktop-metrics'const TERMINAL_FOCUS_SCOPE = '[data-terminal]'@@ -53,6 +54,7 @@ export function toggleTerminalPane(): void {const revealed = !isPaneVisible('terminal')togglePaneVisible('terminal')+ trackArea('terminal_pane', revealed)if (revealed) {focusRevealedTerminal()diff --git a/apps/desktop/src/app/session-picker-overlay.tsx b/apps/desktop/src/app/session-picker-overlay.tsxindex 65344fcac26..0656345dc30 100644--- a/apps/desktop/src/app/session-picker-overlay.tsx+++ b/apps/desktop/src/app/session-picker-overlay.tsx@@ -1,6 +1,7 @@import { useStore } from '@nanostores/react'import { SessionPickerDialog } from '@/components/session-picker'+import { completeFlow } from '@/store/desktop-metrics'import { $gatewayState, $selectedStoredSessionId, $sessionPickerOpen, setSessionPickerOpen } from '@/store/session'interface SessionPickerOverlayProps {@@ -25,7 +26,11 @@ export function SessionPickerOverlay({ onResume }: SessionPickerOverlayProps) {<SessionPickerDialogactiveStoredSessionId={activeStoredSessionId}onOpenChange={setSessionPickerOpen}- onResume={onResume}+ onResume={(...args: Parameters<typeof onResume>) => {+ completeFlow('session_picker')++ return onResume(...args)+ }}open={open}/>)diff --git a/apps/desktop/src/app/session/hooks/use-prompt-actions/submit.ts b/apps/desktop/src/app/session/hooks/use-prompt-actions/submit.tsindex 6a991ac1113..8a9367b5dad 100644--- a/apps/desktop/src/app/session/hooks/use-prompt-actions/submit.ts+++ b/apps/desktop/src/app/session/hooks/use-prompt-actions/submit.ts@@ -21,6 +21,7 @@ import {revokeDiscardedAttachmentPreviews,terminalContextBlocksFromDraft} from '@/store/composer'+import { noteMessageSent } from '@/store/desktop-metrics'import { $hudMode } from '@/store/hud'import { clearNotifications, notify, notifyError } from '@/store/notifications'import { consumePendingCredentialWarning, requestDesktopOnboarding } from '@/store/onboarding'@@ -35,7 +36,7 @@ import {setMessages,touchSessionActivity} from '@/store/session'-import { $sessionStates } from '@/store/session-states'+import { $sessionStates, $sessionTiles } from '@/store/session-states'import type { SessionInfo } from '@/types/hermes'import {@@ -906,6 +907,9 @@ export function useSubmitPrompt(deps: SubmitPromptDeps) {try {const recoverStoredSessionId = targetStoredSessionId ?? selectedStoredSessionIdRef.current+ // A bot's chat is a tile scoped to the `bots` workspace; the primary chat is Sessions mode.+ noteMessageSent($sessionTiles.get().find(tile => tile.runtimeId === sessionId)?.workspaceMode ?? 'sessions')+const submitted = await withSessionNotFoundResume(sessionId,recoverStoredSessionId,diff --git a/apps/desktop/src/app/settings/config-settings.tsx b/apps/desktop/src/app/settings/config-settings.tsxindex 0af976ed781..b264cc88fce 100644--- a/apps/desktop/src/app/settings/config-settings.tsx+++ b/apps/desktop/src/app/settings/config-settings.tsx@@ -20,6 +20,7 @@ import {refreshDataUrlReadMaxMb,setDataUrlReadMaxMb} from '@/store/data-url-read-max'+import { recordSettingsSaved } from '@/store/desktop-metrics'import { $disableF12, setDisableF12 } from '@/store/disable-f12'import { $alwaysExternalLinks, setAlwaysExternalLinks } from '@/store/external-links'import { $keepAwake, setKeepAwake } from '@/store/keep-awake'@@ -232,6 +233,9 @@ function ConfigSettingsInner({// Mirror the saved record into the shared cache so MCP/model surfaces// reflect the edit without their own refetch.writeConfigCache(snapshot)+ const savedScope = writeScope ?? scopeProfile++ recordSettingsSaved(patch, typeof savedScope === 'string' ? savedScope : savedScope?.profile)if (saveVersionRef.current === v) {// The repo-discovery scan reads the ACTIVE profile's workspacediff --git a/apps/desktop/src/app/settings/index.tsx b/apps/desktop/src/app/settings/index.tsxindex 859697e5813..befd85956d6 100644--- a/apps/desktop/src/app/settings/index.tsx+++ b/apps/desktop/src/app/settings/index.tsx@@ -32,6 +32,7 @@ import { cn } from '@/lib/utils'import { $commandPaletteOpen, openCommandPalettePage } from '@/store/command-palette'import { confirm } from '@/store/confirm'import { $activeConnectionId } from '@/store/connections'+import { recordFeatureUse, settingsArea } from '@/store/desktop-metrics'import { bindingsFor } from '@/store/keybinds'import { $localModelsEnabled } from '@/store/local-models-flag'import { notifyError } from '@/store/notifications'@@ -96,6 +97,8 @@ export function SettingsView({ onClose, onConfigSaved, onMainModelChanged }: Set}, [navigate, search])const [activeView] = useRouteEnumParam('tab', SETTINGS_VIEWS, 'config:model' as SettingsViewId)++ useEffect(() => recordFeatureUse(settingsArea(activeView)), [activeView])const params = new URLSearchParams(search)const requestedSubpage = params.get('page')const subpage = resolveSettingsSubpage(activeView, params)diff --git a/apps/desktop/src/app/settings/shared-metrics-settings.tsx b/apps/desktop/src/app/settings/shared-metrics-settings.tsxindex d6090e34029..85c9bd60430 100644--- a/apps/desktop/src/app/settings/shared-metrics-settings.tsx+++ b/apps/desktop/src/app/settings/shared-metrics-settings.tsx@@ -4,6 +4,7 @@ import { useCallback, useEffect, useState } from 'react'import { DocsLink } from '@/components/onboarding/flow'import { useI18n } from '@/i18n'import { $activeConnectionId } from '@/store/connections'+import { setDesktopMetricsGate } from '@/store/desktop-metrics'import { requestGatewayForAgent } from '@/store/gateway'import { notifyError } from '@/store/notifications'import { $settingsScopeProfile } from '@/store/settings-scope'@@ -60,7 +61,14 @@ export function SharedMetricsSettings() {setConsent({ ...flags, send: flags.enabled && flags.send, decided: true })try {- setConsent(await saveSharedMetricsConsent(request, flags))+ const saved = await saveSharedMetricsConsent(request, flags)++ setConsent(saved)++ // This page applies to the focused profile: Desktop telemetry follows its switch at once.+ if (saved && scopeProfile === null) {+ setDesktopMetricsGate(saved.enabled ? 'on' : 'off')+ }} catch (err) {setConsent(previous)notifyError(err, copy.saveFailed)diff --git a/apps/desktop/src/app/shell/titlebar-controls.tsx b/apps/desktop/src/app/shell/titlebar-controls.tsxindex 7b1f18057ff..7c6beb8537c 100644--- a/apps/desktop/src/app/shell/titlebar-controls.tsx+++ b/apps/desktop/src/app/shell/titlebar-controls.tsx@@ -15,6 +15,7 @@ import { useI18n } from '@/i18n'import { triggerHaptic } from '@/lib/haptics'import { formatModifierToken } from '@/lib/keybinds/combo'import { cn } from '@/lib/utils'+import { recordAction } from '@/store/desktop-metrics'import { toggleHud } from '@/store/hud'import { $interfaceMode, shownInMode, type Tiered } from '@/store/interface-mode'import {@@ -394,6 +395,10 @@ function TitlebarToolButton({ navigate, tool }: { navigate: ReturnType<typeof usdata-tour={tool.tour}disabled={tool.disabled}onClick={event => {+ if (tool.actionId) {+ recordAction(tool.actionId, 'click')+ }+if (tool.to) {navigate(tool.to)}diff --git a/apps/desktop/src/components/assistant-ui/thread/assistant-message.tsx b/apps/desktop/src/components/assistant-ui/thread/assistant-message.tsxindex ffb8cc7f001..7f08e4f8360 100644--- a/apps/desktop/src/components/assistant-ui/thread/assistant-message.tsx+++ b/apps/desktop/src/components/assistant-ui/thread/assistant-message.tsx@@ -65,6 +65,7 @@ import { markAssistantIdSpoken } from '@/lib/spoken-reply'import { useEnterAnimation } from '@/lib/use-enter-animation'import { cn } from '@/lib/utils'import { playSpeechText, stopVoicePlayback } from '@/lib/voice-playback'+import { DESKTOP_BUTTON_ACTIONS, recordAction } from '@/store/desktop-metrics'import { openFreeTierSignIn } from '@/store/free-tier-sign-in'import { notifyError } from '@/store/notifications'import { startManualProviderOAuth } from '@/store/onboarding'@@ -939,7 +940,14 @@ const ErrorRecoveryActions: FC = () => {)}{plan.retry && (<ActionBarPrimitive.Reload asChild>- <button className="aui-error-action" onClick={() => triggerHaptic('submit')} type="button">+ <button+ className="aui-error-action"+ onClick={() => {+ triggerHaptic('submit')+ recordAction(DESKTOP_BUTTON_ACTIONS.messageRetry, 'click')+ }}+ type="button"+ ><RefreshCwIcon className="size-3" />{copy.errorRetry}</button>@@ -1028,7 +1036,13 @@ const AssistantActionBar: FC<MessageActionProps & { durationS?: number }> = ({<GitForkIcon className="size-3.5" /></TooltipIconButton>)}- <CopyButton appearance="icon" buttonSize="icon" label={copy.copy} text={getMessageText} />+ <CopyButton+ appearance="icon"+ buttonSize="icon"+ label={copy.copy}+ onCopied={() => recordAction(DESKTOP_BUTTON_ACTIONS.messageCopy, 'click')}+ text={getMessageText}+ />{fullResponseAvailable && (<CopyButton appearance="icon" buttonSize="icon" label={copy.copyFullResponse} text={getFullResponseText} />)}@@ -1039,7 +1053,13 @@ const AssistantActionBar: FC<MessageActionProps & { durationS?: number }> = ({messageId={messageId}/><ActionBarPrimitive.Reload asChild>- <TooltipIconButton onClick={() => triggerHaptic('submit')} tooltip={copy.refresh}>+ <TooltipIconButton+ onClick={() => {+ triggerHaptic('submit')+ recordAction(DESKTOP_BUTTON_ACTIONS.messageRetry, 'click')+ }}+ tooltip={copy.refresh}+ ><RefreshCwIcon className="size-3.5" /></TooltipIconButton></ActionBarPrimitive.Reload>diff --git a/apps/desktop/src/components/billing-banner.tsx b/apps/desktop/src/components/billing-banner.tsxindex 27aaaf0e038..a98e23a79ae 100644--- a/apps/desktop/src/components/billing-banner.tsx+++ b/apps/desktop/src/components/billing-banner.tsx@@ -5,6 +5,7 @@ import { Button } from '@/components/ui/button'import { Codicon } from '@/components/ui/codicon'import { useI18n } from '@/i18n'import { $billingBlock, billingCtaLabel, clearBillingBlock, runBillingRecovery } from '@/store/billing-block'+import { recordFriction } from '@/store/desktop-metrics'function firstLine(text: string): string {return (text || '').split('\n')[0]?.trim() ?? ''@@ -49,7 +50,10 @@ export function BillingBanner({ sessionId }: { sessionId: null | string }) {<Buttonaria-label={copy.dismiss}className="size-4 rounded-md text-muted-foreground/60 hover:text-foreground/90"- onClick={() => clearBillingBlock(sessionId)}+ onClick={() => {+ recordFriction('notice_dismissed', 'billing_banner')+ clearBillingBlock(sessionId)+ }}size="icon-xs"type="button"variant="ghost"diff --git a/apps/desktop/src/components/free-tier/notice-strip.tsx b/apps/desktop/src/components/free-tier/notice-strip.tsxindex 2651838c299..c2e8ce2e523 100644--- a/apps/desktop/src/components/free-tier/notice-strip.tsx+++ b/apps/desktop/src/components/free-tier/notice-strip.tsx@@ -6,6 +6,7 @@ import { StatusRow } from '@/components/chat/status-row'import { Button } from '@/components/ui/button'import { Codicon } from '@/components/ui/codicon'import { useI18n } from '@/i18n'+import { recordFriction } from '@/store/desktop-metrics'import { ackFreeTierNotice, claimFreeTierNotice, freeTierNoticeClaim, releaseFreeTierNotice } from '@/store/free-tier'import { openFreeTierSignIn } from '@/store/free-tier-sign-in'import { setModelPickerOpen } from '@/store/session'@@ -82,7 +83,10 @@ export function FreeTierNoticeStrip() {</Button><ButtonclassName="text-muted-foreground/75 hover:text-foreground/90"- onClick={() => consume()}+ onClick={() => {+ recordFriction('notice_dismissed', 'free_tier_notice')+ consume()+ }}size="micro"type="button"variant="text"diff --git a/apps/desktop/src/components/notifications.tsx b/apps/desktop/src/components/notifications.tsxindex 41881168378..897f7546c84 100644--- a/apps/desktop/src/components/notifications.tsx+++ b/apps/desktop/src/components/notifications.tsx@@ -11,6 +11,7 @@ import { useI18n } from '@/i18n'import { triggerHaptic } from '@/lib/haptics'import { AlertCircle, AlertTriangle, CheckCircle2, type IconComponent, Info } from '@/lib/icons'import { cn } from '@/lib/utils'+import { noticeIdForToast, recordFriction } from '@/store/desktop-metrics'import {$notifications,type AppNotification,@@ -21,6 +22,17 @@ import {type ToneVariant = 'default' | 'destructive' | 'warning' | 'success'+/** A user dismissal (✕, swipe, clear all) is friction, counted by the toast's code-defined id only.+ * Timers, action buttons and programmatic clears are not dismissals and go straight to the store. */+function noteUserDismissed(id: string) {+ recordFriction('notice_dismissed', noticeIdForToast(id))+}++function userDismiss(id: string) {+ noteUserDismissed(id)+ dismissNotification(id)+}+const tone: Record<NotificationKind, { icon: IconComponent; iconClass: string; variant: ToneVariant }> = {error: { icon: AlertCircle, iconClass: 'text-destructive', variant: 'destructive' },warning: { icon: AlertTriangle, iconClass: 'text-primary', variant: 'warning' },@@ -129,7 +141,16 @@ function TopCenterStack({<Button className="-ml-2" onClick={onToggleExpanded} size="xs" type="button" variant="text">{expanded ? copy.hide : copy.show} {copy.more(older.length)}</Button>- <Button className="-mr-2" onClick={clearNotifications} size="xs" type="button" variant="text">+ <Button+ className="-mr-2"+ onClick={() => {+ notifications.forEach(notification => noteUserDismissed(notification.id))+ clearNotifications()+ }}+ size="xs"+ type="button"+ variant="text"+ >{copy.clearAll}</Button></div>@@ -172,7 +193,7 @@ function BottomRightStack({{expanded ? copy.hide : copy.show} {copy.more(older.length)}</Button><Button- onClick={() => notifications.forEach(notification => dismissNotification(notification.id))}+ onClick={() => notifications.forEach(notification => userDismiss(notification.id))}size="xs"variant="text">@@ -199,7 +220,7 @@ export function NotificationDeck({getKey={notification => notification.id}items={notifications}onSwipe={(notification, _side, action) => {- void action.depart(() => dismissNotification(notification.id))+ void action.depart(() => userDismiss(notification.id))}}surfaceClassName={cn(STACK_SURFACE, 'rounded-lg')}swipeDirections={['left', 'right']}@@ -318,7 +339,7 @@ function NotificationItem({ notification, stack }: { notification: AppNotificaticlassName="col-start-3 -mr-1 text-muted-foreground"disabled={stack.busy || !stack.active}onClick={() => {- void stack.depart(() => dismissNotification(notification.id))+ void stack.depart(() => userDismiss(notification.id))}}size="icon-xs"type="button"diff --git a/apps/desktop/src/components/onboarding-chat/directive.tsx b/apps/desktop/src/components/onboarding-chat/directive.tsxindex 7c05fd8c722..7e673d34440 100644--- a/apps/desktop/src/components/onboarding-chat/directive.tsx+++ b/apps/desktop/src/components/onboarding-chat/directive.tsx@@ -6,7 +6,9 @@ import { useSessionView } from '@/app/chat/session-view'import { FirstBuildCard, HandoffCard, ProgressCard } from '@/components/onboarding-chat/cards/build'import type { CardProps } from '@/components/onboarding-chat/cards/frame'import { ConnectorsCard, LayoutCard, LookCard } from '@/components/onboarding-chat/cards/setup'+import { type DesktopOnboardingStep, recordOnboarding } from '@/store/desktop-metrics'import { $onboardingAnswers, setOnboardingAnswers } from '@/store/onboarding-answers'+import { $onboardingGate } from '@/store/onboarding-gate'type AnswerField = 'name' | 'context'@@ -15,6 +17,14 @@ const DATA_STEPS = new Map<string, AnswerField>([['working', 'context']])+/** Guided-setup cards counted as first-run funnel steps (hermes.desktop.onboarding). */+const FUNNEL_STEPS = new Map<string, DesktopOnboardingStep>([+ ['connectors', 'guide_connectors'],+ ['first', 'guide_first_build'],+ ['layout', 'guide_layout'],+ ['look', 'guide_look']+])+const STEP_CARDS = new Map<string, (props: CardProps) => React.ReactNode>([['connectors', ConnectorsCard],['first', FirstBuildCard],@@ -44,6 +54,15 @@ export function OnboardingChatDirective({ attrs, streaming }: { attrs: Record<stconst identity = JSON.stringify([storedId ?? runtimeId, messageId])const step = attrs.step ?? ''+ useEffect(() => {+ const funnelStep = FUNNEL_STEPS.get(step)++ // Only while the guide is live — a finished setup transcript re-renders its cards on every visit.+ if (funnelStep && $onboardingGate.get().phase === 'guided') {+ recordOnboarding(funnelStep, 'reached')+ }+ }, [step])+const field = DATA_STEPS.get(step)if (field) {diff --git a/apps/desktop/src/components/tips/index.tsx b/apps/desktop/src/components/tips/index.tsxindex 480f889b7cb..ccdaa561951 100644--- a/apps/desktop/src/components/tips/index.tsx+++ b/apps/desktop/src/components/tips/index.tsx@@ -20,6 +20,7 @@ import { useEffect, useState } from 'react'import { useI18n } from '@/i18n'import { resolveTipAnchor } from '@/lib/tips/anchor'+import { recordFriction } from '@/store/desktop-metrics'import { $activeTip, dismissTip, retireActiveTip } from '@/store/tips'import { TipBubble } from './tip-bubble'@@ -101,7 +102,10 @@ export function TipHost() {action={tip.action}anchor={anchor}keybind={tip.keybind}- onClose={retireActiveTip}+ onClose={() => {+ recordFriction('notice_dismissed', 'tip')+ retireActiveTip()+ }}side={tip.side}text={tip.text}title={tip.title}diff --git a/apps/desktop/src/store/backdrop.ts b/apps/desktop/src/store/backdrop.tsindex 340c5b5cba3..20fcc26932a 100644--- a/apps/desktop/src/store/backdrop.ts+++ b/apps/desktop/src/store/backdrop.ts@@ -2,6 +2,8 @@ import { atom } from 'nanostores'import { persistBoolean, storedBoolean } from '@/lib/storage'+import { recordFeatureToggle } from './desktop-metrics'+const KEY = 'hermes.desktop.backdrop.v1'/** Whether the faint statue image renders behind the chat transcript. */@@ -10,5 +12,6 @@ export const $backdrop = atom(storedBoolean(KEY, false))$backdrop.subscribe(on => persistBoolean(KEY, on))export function setBackdrop(on: boolean) {+ recordFeatureToggle('backdrop', $backdrop.get(), on)$backdrop.set(on)}diff --git a/apps/desktop/src/store/composer-popout.ts b/apps/desktop/src/store/composer-popout.tsindex befb3f52c80..7844d9d2da8 100644--- a/apps/desktop/src/store/composer-popout.ts+++ b/apps/desktop/src/store/composer-popout.ts@@ -3,6 +3,8 @@ import { atom } from 'nanostores'import { chatSurfaceRoot } from '@/app/chat/surface-vars'import { persistBoolean, persistString, storedBoolean, storedString } from '@/lib/storage'+import { recordFeatureToggle } from './desktop-metrics'+const POPOUT_STORAGE_KEY = 'hermes.desktop.composerPopout.window.v1'const POPOUT_GESTURES_ENABLED_STORAGE_KEY = 'hermes.desktop.composerPopout.gesturesEnabled'const ZONES_STORAGE_KEY = 'hermes.desktop.composerPopout.zones.v1'@@ -103,6 +105,7 @@ export function setComposerPoppedOut(poppedOut: boolean) {}export function setComposerPopoutGesturesEnabled(value: boolean) {+ recordFeatureToggle('composer_popout_gestures', $composerPopoutGesturesEnabled.get(), value)$composerPopoutGesturesEnabled.set(value)persistBoolean(POPOUT_GESTURES_ENABLED_STORAGE_KEY, value)diff --git a/apps/desktop/src/store/composer.ts b/apps/desktop/src/store/composer.tsindex 17459519ffd..0e9907bcaf9 100644--- a/apps/desktop/src/store/composer.ts+++ b/apps/desktop/src/store/composer.ts@@ -3,6 +3,8 @@ import { atom } from 'nanostores'import { deriveDraftTitle } from '@/lib/draft-title'import { triggerHaptic } from '@/lib/haptics'+import { recordDislike, recordFriction } from './desktop-metrics'+/** Release blob: chip previews created for OS image drops (see #63682). */export function revokeAttachmentPreviewUrl(url?: string | null) {if (url?.startsWith('blob:')) {@@ -599,6 +601,7 @@ export function adoptGoneSessionDraft(): boolean {}export function dismissRestoredDraftNotice(): void {+ recordFriction('notice_dismissed', 'restored_draft')$restoredDraftNotice.set(null)}@@ -620,6 +623,7 @@ export function undoRestoredDraft(liveText: string): boolean {const current = draftsBySession.get(NEW_SESSION_DRAFT_KEY)stashSessionDraft(notice.fromKey, notice.text, current?.attachments ?? [])clearSessionDraft(null)+ recordDislike('undo', 'restored_draft')return true}diff --git a/apps/desktop/src/store/desktop-metrics.test.ts b/apps/desktop/src/store/desktop-metrics.test.tsnew file mode 100644index 00000000000..161e494ffed--- /dev/null+++ b/apps/desktop/src/store/desktop-metrics.test.ts@@ -0,0 +1,418 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'++import { $workspaceMode } from '@/components/pane-shell/workspace-scope'++import {+ bindDesktopMetrics,+ closeOnboardingStep,+ completeFlow,+ configPatchKeys,+ DESKTOP_METRICS_STATE_KEY,+ noteAreaClosed,+ noteBackendDrop,+ noteBackendExited,+ noteInteraction,+ noteMessageSent,+ noticeIdForToast,+ recordAction,+ recordDislike,+ recordFeatureToggle,+ recordFeatureUse,+ recordFriction,+ recordOnboarding,+ recordSettingsSaved,+ resetDesktopMetricsForTests,+ routeArea,+ setDesktopBotCount,+ setDesktopMetricsGate,+ settingsArea,+ slowFrameBucket,+ tickDesktopMetrics,+ trackArea,+ trackFlow+} from './desktop-metrics'++type Call = [string, Record<string, unknown>]++function requester(result: Record<string, unknown> = { ok: true }) {+ const calls: Call[] = []++ const request = vi.fn(async (method: string, params?: Record<string, unknown>) => {+ calls.push([method, params ?? {}])++ return (method === 'shared_metrics.desktop_daily' ? { recorded: true, ...result } : result) as never+ })++ return { calls, request }+}++const stored = () => window.localStorage.getItem(DESKTOP_METRICS_STATE_KEY)+const methods = (calls: Call[]) => calls.map(([method]) => method)+const flush = () => new Promise(resolve => setTimeout(resolve, 0))++const DAY1 = Date.UTC(2026, 8, 27, 12, 0, 0)+const DAY2 = Date.UTC(2026, 8, 28, 12, 0, 0)++let bridge: { ackRendererCrashes: ReturnType<typeof vi.fn>; setEnabled: ReturnType<typeof vi.fn>; takeRendererCrashes: ReturnType<typeof vi.fn> }++beforeEach(() => {+ vi.useFakeTimers({ toFake: ['Date'] })+ vi.setSystemTime(DAY1)+ window.localStorage.clear()+ resetDesktopMetricsForTests()+ $workspaceMode.set('sessions')+ bridge = {+ ackRendererCrashes: vi.fn(async () => undefined),+ setEnabled: vi.fn(async () => undefined),+ takeRendererCrashes: vi.fn(async () => null)+ }+ ;(window as unknown as { hermesDesktop: unknown }).hermesDesktop = { desktopMetrics: bridge }+})++afterEach(() => {+ resetDesktopMetricsForTests()+ vi.useRealTimers()+ delete (window as unknown as { hermesDesktop?: unknown }).hermesDesktop+})++function exerciseEverything() {+ recordFeatureUse('terminal_pane')+ trackArea('file_pane', true)+ trackArea('file_pane', false)+ recordFriction('error_toast', 'timeout')+ recordFriction('slow_frame', '250ms_to_1s')+ recordOnboarding('provider_setup', 'reached')+ recordAction('composer.send', 'click')+ recordAction('composer.send', 'click')+ recordAction('composer.send', 'click')+ recordDislike('feature_disabled', 'tips')+ recordSettingsSaved({ display: { show_reasoning: false } })+ recordFeatureToggle('tips', true, false)+ trackFlow('command_palette', true)+ trackFlow('command_palette', false)+ noteInteraction(DAY1)+ noteInteraction(DAY1 + 60_000)+ noteMessageSent('bots')+ setDesktopBotCount(3)+ noteBackendDrop(null)+}++describe('consent gate', () => {+ it('collection off: nothing is persisted and nothing is sent', async () => {+ const { calls, request } = requester()++ setDesktopMetricsGate('off')+ bindDesktopMetrics(request)+ exerciseEverything()+ vi.setSystemTime(DAY2)+ tickDesktopMetrics()+ await flush()++ expect(calls).toEqual([])+ expect(stored()).toBeNull()+ expect(bridge.setEnabled).toHaveBeenCalledWith(false)+ expect(bridge.takeRendererCrashes).not.toHaveBeenCalled()+ })++ it('an unknown gate (before the switch is read) records nothing either', async () => {+ const { calls, request } = requester()++ bindDesktopMetrics(request)+ exerciseEverything()+ await flush()++ expect(calls).toEqual([])+ expect(stored()).toBeNull()+ })++ it('turning collection off purges the local record and drops anything queued', async () => {+ setDesktopMetricsGate('on')+ recordFeatureUse('projects') // queued: no gateway bound yet+ recordAction('session.new', 'shortcut')+ expect(stored()).not.toBeNull()++ setDesktopMetricsGate('off')+ expect(stored()).toBeNull()++ const { calls, request } = requester()++ bindDesktopMetrics(request)+ setDesktopMetricsGate('on')+ await flush()++ expect(calls).toEqual([])+ })+})++describe('feature use', () => {+ it('counts each area once per UTC day', async () => {+ const { calls, request } = requester()++ setDesktopMetricsGate('on')+ bindDesktopMetrics(request)+ recordFeatureUse('terminal_pane')+ recordFeatureUse('terminal_pane')+ recordFeatureUse('settings_config_model')+ vi.setSystemTime(DAY2)+ recordFeatureUse('terminal_pane')+ await flush()++ expect(calls.filter(([m]) => m === 'shared_metrics.desktop_feature_use').map(([, p]) => p.area)).toEqual([+ 'terminal_pane',+ 'settings_config_model',+ 'terminal_pane'+ ])+ })++ it('maps settings views and routes onto closed area ids', () => {+ expect(settingsArea('config:model')).toBe('settings_config_model')+ expect(settingsArea('connections')).toBe('settings_gateway')+ expect(settingsArea('some-plugin:page')).toBe('settings_other')+ expect(routeArea('/capabilities')).toBe('capabilities')+ expect(routeArea('/42f1c0de')).toBeNull()+ expect(routeArea('/settings')).toBeNull()+ expect(routeArea('/my-plugin', ['/my-plugin'])).toBe('extension_page')+ })+})++describe('friction', () => {+ it('buckets slow frames and caps them per day', async () => {+ const { calls, request } = requester()++ setDesktopMetricsGate('on')+ bindDesktopMetrics(request)++ expect(slowFrameBucket(80)).toBeNull()+ expect(slowFrameBucket(120)).toBe('100ms_to_250ms')+ expect(slowFrameBucket(6000)).toBe('gte_5s')++ for (let i = 0; i < 50; i++) {+ recordFriction('slow_frame', '1s_to_5s')+ }++ await flush()+ expect(calls.length).toBe(5)+ })++ it('maps notification ids onto closed notice ids, never the raw id', () => {+ expect(noticeIdForToast('desktop-update-available')).toBe('update_available')+ expect(noticeIdForToast('billing-block:abc123')).toBe('billing_block')+ expect(noticeIdForToast('gateway-error:/Users/me/secret')).toBe('gateway_error')+ expect(noticeIdForToast('toast-42')).toBe('other')+ })++ it('classifies a backend drop after the settle window, and a switch cancels it', async () => {+ vi.useFakeTimers({ now: DAY1 })+ const { calls, request } = requester()++ setDesktopMetricsGate('on')+ bindDesktopMetrics(request)++ noteBackendDrop(null)+ noteBackendExited()+ await vi.advanceTimersByTimeAsync(3500)+ noteBackendDrop('timeout')+ await vi.advanceTimersByTimeAsync(3500)++ expect(calls.filter(([m]) => m === 'shared_metrics.desktop_friction').map(([, p]) => p.detail)).toEqual([+ 'backend_exit',+ 'timeout'+ ])+ })++ it('reports renderer crashes main persisted, then acks the claim', async () => {+ bridge.takeRendererCrashes.mockResolvedValueOnce({ reasons: ['oom', 'crash'] })+ const { calls, request } = requester()++ setDesktopMetricsGate('on')+ bindDesktopMetrics(request)+ await flush()+ await flush()++ expect(bridge.setEnabled).toHaveBeenCalledWith(true)+ expect(calls.map(([, p]) => p.detail)).toEqual(['oom', 'crash'])+ expect(bridge.ackRendererCrashes).toHaveBeenCalledWith(true)+ })+})++describe('onboarding', () => {+ it('sends each step event once per install and calls a step left open by an earlier launch abandoned', async () => {+ const { calls, request } = requester()++ setDesktopMetricsGate('on')+ bindDesktopMetrics(request)+ recordOnboarding('provider_setup', 'reached')+ recordOnboarding('provider_setup', 'reached')+ recordOnboarding('guide', 'reached')+ closeOnboardingStep('guide')+ await flush()+ expect(calls.map(([, p]) => `${p.step}:${p.event}`)).toEqual(['provider_setup:reached', 'guide:reached'])++ // Next launch: a fresh module (new launch id) reading the same storage.+ vi.resetModules()+ const next = await import('./desktop-metrics')+ const second = requester()++ next.setDesktopMetricsGate('on')+ next.bindDesktopMetrics(second.request)+ await flush()++ expect(second.calls.map(([, p]) => `${p.step}:${p.event}`)).toEqual(['provider_setup:abandoned'])+ next.resetDesktopMetricsForTests()+ })+})++describe('daily report: action use + mode use', () => {+ it('aggregates presses and mode time locally and sends one report per finished day', async () => {+ const { calls, request } = requester()++ setDesktopMetricsGate('on')+ bindDesktopMetrics(request)++ recordAction('composer.send', 'click', DAY1)+ recordAction('composer.send', 'click', DAY1 + 5000)+ recordAction('session.new', 'shortcut')+ recordAction('session.new', 'palette')+ noteInteraction(DAY1)+ noteInteraction(DAY1 + 120_000) // 2 min active+ noteInteraction(DAY1 + 120_000 + 3_600_000) // an hour idle: not active+ $workspaceMode.set('bots')+ noteInteraction(DAY1 + 120_000 + 3_600_000 + 30_000)+ noteMessageSent()+ noteMessageSent('sessions')+ setDesktopBotCount(4)+ await flush()++ expect(methods(calls)).not.toContain('shared_metrics.desktop_daily')++ vi.setSystemTime(DAY2)+ tickDesktopMetrics()+ await flush()++ const daily = calls.filter(([m]) => m === 'shared_metrics.desktop_daily')++ expect(daily).toHaveLength(1)+ const report = daily[0]![1]++ expect(report.day).toBe('2026-09-27')+ expect(report.bot_count).toBe(4)+ expect(report.actions).toEqual(+ expect.arrayContaining([+ { action: 'composer.send', count: 2, via: 'click' },+ { action: 'session.new', count: 1, via: 'shortcut' },+ { action: 'session.new', count: 1, via: 'palette' }+ ])+ )+ expect(report.modes).toEqual(+ expect.arrayContaining([+ { active_ms: 120_000, messages_sent: 1, mode: 'sessions' },+ { active_ms: 30_000, messages_sent: 1, mode: 'bots' }+ ])+ )++ // Settled → dropped: another tick sends nothing.+ tickDesktopMetrics()+ await flush()+ expect(calls.filter(([m]) => m === 'shared_metrics.desktop_daily')).toHaveLength(1)+ })++ it('keeps a finished day the backend did not record, for a retry', async () => {+ const { calls, request } = requester({ recorded: false })++ setDesktopMetricsGate('on')+ bindDesktopMetrics(request)+ recordAction('composer.send', 'shortcut')+ vi.setSystemTime(DAY2)+ tickDesktopMetrics()+ await flush()+ tickDesktopMetrics()+ await flush()++ expect(calls.filter(([m]) => m === 'shared_metrics.desktop_daily')).toHaveLength(2)+ expect(JSON.parse(stored()!).pending).toHaveLength(1)+ })+})++describe('dislike signals', () => {+ it('rage click: three clicks on one action inside a second, once per burst', async () => {+ const { calls, request } = requester()++ setDesktopMetricsGate('on')+ bindDesktopMetrics(request)++ for (const at of [0, 200, 400, 600, 800]) {+ recordAction('composer.send', 'click', DAY1 + at)+ }++ recordAction('composer.send', 'shortcut', DAY1 + 900)+ await flush()++ const dislikes = calls.filter(([m]) => m === 'shared_metrics.desktop_dislike').map(([, p]) => p)++ expect(dislikes).toEqual([{ signal: 'rage_click', target: 'composer.send' }])+ })++ it('quick close: an area closed within 5s of opening', async () => {+ const { calls, request } = requester()++ setDesktopMetricsGate('on')+ bindDesktopMetrics(request)+ trackArea('terminal_pane', true, DAY1)+ trackArea('terminal_pane', false, DAY1 + 2000)+ recordFeatureUse('review_pane', DAY1)+ noteAreaClosed('review_pane', DAY1 + 60_000)+ await flush()++ expect(calls.filter(([m]) => m === 'shared_metrics.desktop_dislike').map(([, p]) => p)).toEqual([+ { signal: 'quick_close', target: 'terminal_pane' }+ ])+ })++ it('cancelled: a flow closed without completing; a completed one is not', async () => {+ const { calls, request } = requester()++ setDesktopMetricsGate('on')+ bindDesktopMetrics(request)+ trackFlow('model_picker', true)+ completeFlow('model_picker')+ trackFlow('model_picker', false)+ trackFlow('command_palette', true)+ trackFlow('command_palette', false)+ await flush()++ expect(calls.map(([, p]) => p)).toEqual([{ signal: 'cancelled', target: 'command_palette' }])+ })++ it('settings: sends only the config keys, never the values; feature toggles only on the off edge', async () => {+ const { calls, request } = requester()++ setDesktopMetricsGate('on')+ bindDesktopMetrics(request)+ recordSettingsSaved({ display: { show_reasoning: false, skin: 'secret-skin-name' } }, 'work')+ recordFeatureToggle('tips', false, true)+ recordFeatureToggle('tips', true, false)+ await flush()++ expect(calls.map(([, p]) => p)).toEqual([+ { profile: 'work', setting: 'display.show_reasoning', signal: 'setting_off_default', target: 'setting' },+ { profile: 'work', setting: 'display.skin', signal: 'setting_off_default', target: 'setting' },+ { signal: 'feature_disabled', target: 'tips' }+ ])+ expect(JSON.stringify(calls)).not.toContain('secret-skin-name')+ expect(configPatchKeys({ a: { b: [1, 2], c: { d: null } } })).toEqual(['a.b', 'a.c.d'])+ })++ it('caps each signal per day', async () => {+ const { calls, request } = requester()++ setDesktopMetricsGate('on')+ bindDesktopMetrics(request)++ for (let i = 0; i < 100; i++) {+ recordDislike('undo', 'closed_tab')+ }++ await flush()+ expect(calls).toHaveLength(20)+ })+})diff --git a/apps/desktop/src/store/desktop-metrics.ts b/apps/desktop/src/store/desktop-metrics.tsnew file mode 100644index 00000000000..4eaadfbf41c--- /dev/null+++ b/apps/desktop/src/store/desktop-metrics.ts@@ -0,0 +1,961 @@+/**+ * Desktop love/hate telemetry: which areas get used, which buttons get+ * pressed, what gets in the way, what gets turned off, and where first run+ * stops. No UI of its own — every fact is a counter wired into an existing+ * interaction, reported over the shared-metrics RPCs (`shared_metrics.desktop_*`).+ *+ * Opt-in only. Everything here is gated on `$desktopMetricsGate`, the focused+ * profile's `telemetry.shared_metrics.enabled` as last read from the backend+ * (the same switch the consent strip and Settings › Privacy write). While it is+ * not `on` nothing is persisted and nothing is sent; turning it off purges the+ * local state and tells main to drop its pending renderer-crash record.+ *+ * Every value is a code-defined id from the closed sets below (mirrored by+ * hermes_cli/observability/shared_metrics_contract.py, which collapses any+ * stranger to `other`). Never a session id, path, message, bot name or setting+ * value.+ *+ * Local state (localStorage `hermes.desktop.metrics.v1`, written only while on):+ * the UTC day, areas already reported today, per-day caps, today's aggregated+ * action counts and per-mode activity, finished days awaiting the backend's ack,+ * and the onboarding latch (steps sent / steps still open).+ */++import { atom } from 'nanostores'++import { $workspaceMode } from '@/components/pane-shell/workspace-scope'+import { readJson, writeJson } from '@/lib/storage'++import type { SharedMetricsRequester } from './shared-metrics'++// ── closed vocabularies ───────────────────────────────────────────────────────++/** Settings views (SETTINGS_VIEWS in app/settings/index.tsx) → area. */+const SETTINGS_AREAS: Record<string, DesktopFeatureArea> = {+ about: 'settings_about',+ billing: 'settings_billing',+ 'config:advanced': 'settings_config_advanced',+ 'config:appearance': 'settings_config_appearance',+ 'config:browser': 'settings_config_browser',+ 'config:chat': 'settings_config_chat',+ 'config:memory': 'settings_config_memory',+ 'config:model': 'settings_config_model',+ 'config:safety': 'settings_config_safety',+ 'config:voice': 'settings_config_voice',+ 'config:workspace': 'settings_config_workspace',+ // Legacy alias: the Connections tab redirects to Gateways.+ connections: 'settings_gateway',+ gateway: 'settings_gateway',+ keybinds: 'settings_keybinds',+ keys: 'settings_keys',+ notifications: 'settings_notifications',+ providers: 'settings_providers',+ sessions: 'settings_sessions',+ vault: 'settings_vault'+}++export type DesktopFeatureArea =+ | 'agents'+ | 'artifacts'+ | 'bot_mode'+ | 'browser_pane'+ | 'capabilities'+ | 'command_center'+ | 'command_palette'+ | 'cron'+ | 'extension_page'+ | 'file_pane'+ | 'find_in_page'+ | 'kanban'+ | 'messaging'+ | 'model_picker'+ | 'other'+ | 'profiles'+ | 'projects'+ | 'review_pane'+ | 'session_import'+ | 'session_picker'+ | 'session_search'+ | 'session_switcher'+ | 'settings_about'+ | 'settings_billing'+ | 'settings_config_advanced'+ | 'settings_config_appearance'+ | 'settings_config_browser'+ | 'settings_config_chat'+ | 'settings_config_memory'+ | 'settings_config_model'+ | 'settings_config_safety'+ | 'settings_config_voice'+ | 'settings_config_workspace'+ | 'settings_gateway'+ | 'settings_keybinds'+ | 'settings_keys'+ | 'settings_notifications'+ | 'settings_other'+ | 'settings_providers'+ | 'settings_sessions'+ | 'settings_vault'+ | 'skins'+ | 'starmap'+ | 'terminal_pane'+ | 'voice_conversation'+ | 'voice_dictation'+ | 'webhooks'++/** First path segment of a full-page route (APP_ROUTES) → area. Chat paths carry session ids and map to nothing. */+const ROUTE_AREAS: Record<string, DesktopFeatureArea> = {+ agents: 'agents',+ artifacts: 'artifacts',+ capabilities: 'capabilities',+ 'command-center': 'command_center',+ cron: 'cron',+ kanban: 'kanban',+ messaging: 'messaging',+ profiles: 'profiles',+ 'session-import': 'session_import',+ settings: 'settings_other',+ starmap: 'starmap',+ webhooks: 'webhooks'+}++export function settingsArea(view: string): DesktopFeatureArea {+ return SETTINGS_AREAS[view] ?? 'settings_other'+}++/** The area a full-page route opens, or null for chat/session routes. Contributed+ * plugin pages (one-segment paths the core does not own) are `extension_page`. */+export function routeArea(pathname: string, contributedPaths: readonly string[] = []): DesktopFeatureArea | null {+ const segment = pathname.replace(/^\/+/, '').split(/[/?#]/)[0] ?? ''++ if (!segment || segment === 'settings') {+ return null+ }++ if (ROUTE_AREAS[segment]) {+ return ROUTE_AREAS[segment]+ }++ return contributedPaths.includes(`/${segment}`) ? 'extension_page' : null+}++export type DesktopFrictionKind = 'backend_disconnect' | 'error_toast' | 'notice_dismissed' | 'renderer_crash' | 'slow_frame'++/** notifyError's summary rules (store/notifications.ts) → category. */+export type ErrorToastCategory =+ | 'api_key_missing'+ | 'api_key_rejected'+ | 'disk_full'+ | 'gateway_auth_failed'+ | 'method_not_allowed'+ | 'microphone_permission'+ | 'other'+ | 'pool_slot_timeout'+ | 'restart_required'+ | 'rpc_out_of_sync'+ | 'storage_failure'+ | 'timeout'+ | 'unclassified'++export type DesktopNoticeId =+ | 'artifacts_partial_load'+ | 'background_queue_stuck'+ | 'backend_skew'+ | 'billing_banner'+ | 'billing_block'+ | 'build_discontinued'+ | 'client_behind'+ | 'composer_queue_stuck'+ | 'credits'+ | 'free_tier_notice'+ | 'gateway_error'+ | 'gui_skew'+ | 'install_method'+ | 'mcp_health'+ | 'model_warning'+ | 'onboarding_handoff'+ | 'other'+ | 'restored_draft'+ | 'runtime_not_ready'+ | 'session_compress'+ | 'terminal_backend'+ | 'tip'+ | 'update_available'+ | 'voice_live_unavailable'+ | 'voice_stop_hint'++/** Stable toast ids the Desktop code passes to notify() → notice id. */+const NOTICE_IDS: Record<string, DesktopNoticeId> = {+ 'artifacts-partial-load': 'artifacts_partial_load',+ 'backend-contract-skew': 'backend_skew',+ 'client-update-after-backend': 'client_behind',+ 'composer-queue-stuck': 'composer_queue_stuck',+ 'desktop-build-discontinued': 'build_discontinued',+ 'desktop-update-available': 'update_available',+ 'gui-contract-skew': 'gui_skew',+ 'install-method-not-supported': 'install_method',+ 'onboarding-handoff': 'onboarding_handoff',+ 'runtime-not-ready': 'runtime_not_ready',+ 'terminal-backend-unavailable': 'terminal_backend',+ 'voice-live-unavailable': 'voice_live_unavailable',+ 'voice-stop-hint': 'voice_stop_hint'+}++/** Toast ids with a data suffix (session id, provider, server key): only the prefix counts. */+const NOTICE_PREFIXES: readonly (readonly [string, DesktopNoticeId])[] = [+ ['billing-block:', 'billing_block'],+ ['composer-background-queue-stuck-', 'background_queue_stuck'],+ ['credits.', 'credits'],+ ['gateway-error:', 'gateway_error'],+ ['mcp-health-', 'mcp_health'],+ ['model-warning-confirm-', 'model_warning'],+ ['session-compress:', 'session_compress']+]++export function noticeIdForToast(id: string): DesktopNoticeId {+ return NOTICE_IDS[id] ?? NOTICE_PREFIXES.find(([prefix]) => id.startsWith(prefix))?.[1] ?? 'other'+}++export type RendererCrashDetail = 'crash' | 'killed' | 'oom' | 'other'+export type BackendDisconnectDetail = 'backend_exit' | 'network' | 'other' | 'timeout'+export type SlowFrameBucket = '100ms_to_250ms' | '1s_to_5s' | '250ms_to_1s' | 'gte_5s'++export function slowFrameBucket(durationMs: number): SlowFrameBucket | null {+ if (!(durationMs >= 100)) {+ return null+ }++ return durationMs < 250 ? '100ms_to_250ms' : durationMs < 1000 ? '250ms_to_1s' : durationMs < 5000 ? '1s_to_5s' : 'gte_5s'+}++export type DesktopFrictionDetail =+ | BackendDisconnectDetail+ | DesktopNoticeId+ | ErrorToastCategory+ | RendererCrashDetail+ | SlowFrameBucket++export type DesktopOnboardingStep =+ | 'choose_later'+ | 'consent'+ | 'first_message'+ | 'free_tier_ready'+ | 'guide'+ | 'guide_connectors'+ | 'guide_first_build'+ | 'guide_layout'+ | 'guide_look'+ | 'guide_skip'+ | 'intro'+ | 'model_pick'+ | 'provider_api_key'+ | 'provider_local'+ | 'provider_oauth'+ | 'provider_setup'+ | 'sign_in'++export type DesktopOnboardingEvent = 'abandoned' | 'completed' | 'reached'++/** Button presses that dispatch no keybinding action get a stable id here (and+ * in DESKTOP_BUTTON_ACTION_IDS on the backend). Everything else uses its+ * KEYBIND_ACTIONS id (lib/keybinds/actions.ts). */+export const DESKTOP_BUTTON_ACTIONS = {+ composerAttach: 'composer.attach',+ messageCopy: 'message.copy',+ messageRetry: 'message.retry'+} as const++export type DesktopActionVia = 'click' | 'menu' | 'palette' | 'shortcut'++export type DesktopDislikeSignal =+ | 'cancelled'+ | 'feature_disabled'+ | 'quick_close'+ | 'rage_click'+ | 'setting_off_default'+ | 'undo'++export type DesktopFlowId =+ | 'command_palette'+ | 'free_tier_sign_in'+ | 'keybind_capture'+ | 'model_picker'+ | 'project_create'+ | 'provider_oauth'+ | 'session_picker'+ | 'session_switcher'++export type DesktopFeatureToggle =+ | 'backdrop'+ | 'bot_activity_toasts'+ | 'composer_popout_gestures'+ | 'intro_splash'+ | 'native_notifications'+ | 'notification_kind'+ | 'reactions'+ | 'thread_timeline'+ | 'tips'+ | 'tours'+ | 'vibe_hearts'++export type DesktopUndoTarget = 'closed_tab' | 'restored_draft'++export type DesktopMode = 'bots' | 'sessions'++// ── limits ────────────────────────────────────────────────────────────────────++const STATE_KEY = 'hermes.desktop.metrics.v1'+/** Friction per (kind, detail) per day; slow frames per bucket per day. */+const FRICTION_DAILY_CAP = 20+const SLOW_FRAME_DAILY_CAP = 5+const DISLIKE_DAILY_CAP = 20+const QUICK_CLOSE_MS = 5000+const RAGE_CLICK_WINDOW_MS = 1000+const RAGE_CLICK_COUNT = 3+/** A gap between interactions longer than this is idle, not active time. */+export const ACTIVE_IDLE_GAP_MS = 5 * 60_000+const PENDING_DAYS_MAX = 7+const QUEUE_MAX = 50+const SAVE_DEBOUNCE_MS = 5000+const DROP_SETTLE_MS = 3000++// ── state ─────────────────────────────────────────────────────────────────────++interface ModeDay {+ activeMs: number+ messages: number+}++interface DayAggregate {+ actions: Record<string, number>+ botCount: number+ day: string+ modes: Partial<Record<DesktopMode, ModeDay>>+}++interface MetricsState {+ areas: string[]+ caps: Record<string, number>+ onboarding: { open: Record<string, string>; sent: string[] }+ pending: DayAggregate[]+ today: DayAggregate+ v: 1+}++/** `on`/`off` = the focused profile's collection switch as last read; `null` = not known yet. */+export type DesktopMetricsGate = 'off' | 'on' | null++export const $desktopMetricsGate = atom<DesktopMetricsGate>(null)++/** One id per renderer load: an onboarding step still open from another load was abandoned. */+const LAUNCH_ID = typeof crypto !== 'undefined' && 'randomUUID' in crypto ? crypto.randomUUID() : String(Math.random())++let state: MetricsState | null = null+let request: SharedMetricsRequester | null = null+let queue: [string, Record<string, unknown>][] = []+let saveTimer: ReturnType<typeof setTimeout> | null = null+let flushingDays = false+let botCount = 0+let lastInteractionAt = 0+const areaOpenedAt = new Map<string, number>()+const openFlows = new Map<DesktopFlowId, boolean>()+let pendingDrop: { detail: BackendDisconnectDetail; timer: ReturnType<typeof setTimeout> } | null = null+let lastBackendExitAt = 0+const recentClicks = new Map<string, number[]>()++function utcDay(now = Date.now()): string {+ return new Date(now).toISOString().slice(0, 10)+}++function emptyDay(day: string): DayAggregate {+ return { actions: {}, botCount, day, modes: {} }+}++function dayHasUse(day: DayAggregate): boolean {+ return (+ Object.values(day.actions).some(n => n > 0) ||+ Object.values(day.modes).some(mode => (mode?.activeMs ?? 0) > 0 || (mode?.messages ?? 0) > 0)+ )+}++function finite(value: unknown): number {+ return typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : 0+}++function readDay(raw: unknown): DayAggregate | null {+ if (!raw || typeof raw !== 'object' || typeof (raw as DayAggregate).day !== 'string') {+ return null+ }++ const source = raw as Partial<DayAggregate>+ const actions: Record<string, number> = {}++ for (const [key, count] of Object.entries(source.actions ?? {})) {+ actions[key] = finite(count)+ }++ const modes: DayAggregate['modes'] = {}++ for (const mode of ['bots', 'sessions'] as const) {+ const entry = source.modes?.[mode]++ if (entry) {+ modes[mode] = { activeMs: finite(entry.activeMs), messages: finite(entry.messages) }+ }+ }++ return { actions, botCount: finite(source.botCount), day: source.day as string, modes }+}++function readState(): MetricsState {+ const raw = readJson<Partial<MetricsState>>(STATE_KEY)+ const today = (raw && readDay(raw.today)) || emptyDay(utcDay())++ return {+ areas: Array.isArray(raw?.areas) ? raw.areas.filter(a => typeof a === 'string') : [],+ caps: raw?.caps && typeof raw.caps === 'object' ? { ...raw.caps } : {},+ onboarding: {+ open: raw?.onboarding?.open && typeof raw.onboarding.open === 'object' ? { ...raw.onboarding.open } : {},+ sent: Array.isArray(raw?.onboarding?.sent) ? raw.onboarding.sent.filter(s => typeof s === 'string') : []+ },+ pending: Array.isArray(raw?.pending) ? raw.pending.map(readDay).filter((d): d is DayAggregate => d !== null) : [],+ today,+ v: 1+ }+}++/** Roll a finished day into `pending` (only days with real use) and reset the per-day sets. */+/** Close out a finished day (into `pending`) when the UTC date moved; true when it did. */+function rollDay(current: MetricsState, now = Date.now()): boolean {+ const day = utcDay(now)++ if (current.today.day === day) {+ return false+ }++ if (dayHasUse(current.today)) {+ current.pending = [...current.pending, current.today].slice(-PENDING_DAYS_MAX)+ }++ current.today = emptyDay(day)+ current.areas = []+ current.caps = {}++ return true+}++function persist(): void {+ if (saveTimer) {+ clearTimeout(saveTimer)+ saveTimer = null+ }++ if ($desktopMetricsGate.get() === 'on' && state) {+ writeJson(STATE_KEY, state)+ }+}++function persistSoon(): void {+ if (!saveTimer) {+ saveTimer = setTimeout(persist, SAVE_DEBOUNCE_MS)+ }+}++/** Run `fn` on the live state — only while collection is on. */+function withState<T>(fn: (current: MetricsState) => T): T | undefined {+ if ($desktopMetricsGate.get() !== 'on') {+ return undefined+ }++ state ??= readState()++ if (rollDay(state)) {+ persist()+ }++ return fn(state)+}++function send(method: string, params: Record<string, unknown>): void {+ if ($desktopMetricsGate.get() !== 'on') {+ return+ }++ if (!request) {+ queue = [...queue, [method, params] as [string, Record<string, unknown>]].slice(-QUEUE_MAX)++ return+ }++ void request(method, params).catch(() => undefined)+}++/** Take one slot of a per-day cap; false once it is spent. */+function takeCap(current: MetricsState, key: string, cap: number): boolean {+ const used = current.caps[key] ?? 0++ if (used >= cap) {+ return false+ }++ current.caps[key] = used + 1++ return true+}++// ── recording API (every entry point is a silent no-op unless on) ───────────++/** An area opened. Reported once per UTC day; the open time also arms quick_close. */+export function recordFeatureUse(area: DesktopFeatureArea, now = Date.now()): void {+ withState(current => {+ areaOpenedAt.set(area, now)++ if (current.areas.includes(area)) {+ return+ }++ current.areas = [...current.areas, area]+ persist()+ send('shared_metrics.desktop_feature_use', { area })+ })+}++/** An area closed: within QUICK_CLOSE_MS of opening it is a quick_close dislike. */+export function noteAreaClosed(area: DesktopFeatureArea, now = Date.now()): void {+ const openedAt = areaOpenedAt.get(area)++ areaOpenedAt.delete(area)++ if (openedAt !== undefined && now - openedAt < QUICK_CLOSE_MS) {+ recordDislike('quick_close', area)+ }+}++/** Track a boolean open-state for an area: false→true counts use, true→false may be a quick close. */+export function trackArea(area: DesktopFeatureArea, open: boolean, now = Date.now()): void {+ if (open) {+ recordFeatureUse(area, now)+ } else {+ noteAreaClosed(area, now)+ }+}++/** A flow/dialog opened (true) or closed (false). Closing one that never+ * reached `completeFlow` is a `cancelled` dislike. */+export function trackFlow(flow: DesktopFlowId, open: boolean): void {+ if (open) {+ openFlows.set(flow, false)++ return+ }++ const completed = openFlows.get(flow)++ openFlows.delete(flow)++ if (completed === false) {+ recordDislike('cancelled', flow)+ }+}++/** The open flow did what it was opened for (a palette command ran, a model was picked). */+export function completeFlow(flow: DesktopFlowId): void {+ if (openFlows.has(flow)) {+ openFlows.set(flow, true)+ }+}++/** The primary gateway socket dropped after a healthy boot. Classified a few+ * seconds later: a backend process exit around it makes it `backend_exit`, a+ * gateway switch starting in the window (Restart Hermes recycles the backend+ * before the switch flag rises) cancels it. */+export function noteBackendDrop(reason: 'timeout' | null, now = Date.now()): void {+ if (pendingDrop || $desktopMetricsGate.get() !== 'on') {+ return+ }++ const detail: BackendDisconnectDetail = now - lastBackendExitAt < DROP_SETTLE_MS ? 'backend_exit' : (reason ?? 'network')++ pendingDrop = {+ detail,+ timer: setTimeout(() => {+ const settled = pendingDrop++ pendingDrop = null++ if (settled) {+ recordFriction('backend_disconnect', settled.detail)+ }+ }, DROP_SETTLE_MS)+ }+}++/** Main reported the local backend process exited (not during a switch). */+export function noteBackendExited(now = Date.now()): void {+ lastBackendExitAt = now++ if (pendingDrop) {+ pendingDrop.detail = 'backend_exit'+ }+}++/** A deliberate gateway switch began: a drop still settling was part of it. */+export function cancelPendingBackendDrop(): void {+ if (pendingDrop) {+ clearTimeout(pendingDrop.timer)+ pendingDrop = null+ }+}++export function recordFriction(kind: DesktopFrictionKind, detail: DesktopFrictionDetail): void {+ withState(current => {+ if (!takeCap(current, `friction:${kind}:${detail}`, kind === 'slow_frame' ? SLOW_FRAME_DAILY_CAP : FRICTION_DAILY_CAP)) {+ return+ }++ persistSoon()+ send('shared_metrics.desktop_friction', { detail, kind })+ })+}++export function recordDislike(+ signal: DesktopDislikeSignal,+ target: DesktopFeatureArea | DesktopFeatureToggle | DesktopFlowId | DesktopUndoTarget | string,+ setting?: string,+ profile?: null | string+): void {+ withState(current => {+ if (!takeCap(current, `dislike:${signal}`, DISLIKE_DAILY_CAP)) {+ return+ }++ persistSoon()+ send('shared_metrics.desktop_dislike', {+ ...(setting ? { setting, signal, target: 'setting' } : { signal, target }),+ ...(profile ? { profile } : {})+ })+ })+}++const MAX_SETTING_KEYS_PER_SAVE = 10++/** Dotted leaf keys of a config patch (`display.show_reasoning`). Arrays are leaves. */+export function configPatchKeys(patch: unknown, prefix = ''): string[] {+ if (!patch || typeof patch !== 'object' || Array.isArray(patch)) {+ return prefix ? [prefix] : []+ }++ return Object.entries(patch as Record<string, unknown>).flatMap(([key, value]) =>+ configPatchKeys(value, prefix ? `${prefix}.${key}` : key)+ )+}++/** A Settings autosave landed. Only the keys go out; the backend reads the saved+ * values itself and records whether each moved to or away from its default. */+export function recordSettingsSaved(patch: unknown, profile?: null | string): void {+ for (const key of configPatchKeys(patch).slice(0, MAX_SETTING_KEYS_PER_SAVE)) {+ recordDislike('setting_off_default', 'setting', key, profile)+ }+}++/** A shipped feature toggled. Only the on→off edge is a signal. */+export function recordFeatureToggle(toggle: DesktopFeatureToggle, wasOn: boolean, isOn: boolean): void {+ if (wasOn && !isOn) {+ recordDislike('feature_disabled', toggle)+ }+}++/** A button/shortcut/palette/menu press, aggregated per day and reported once in the daily report. */+export function recordAction(action: string, via: DesktopActionVia, now = Date.now()): void {+ withState(current => {+ const key = `${action}|${via}`++ current.today.actions[key] = (current.today.actions[key] ?? 0) + 1+ persistSoon()+ })++ if (via !== 'click' || $desktopMetricsGate.get() !== 'on') {+ return+ }++ const clicks = [...(recentClicks.get(action) ?? []).filter(at => now - at < RAGE_CLICK_WINDOW_MS), now]++ if (clicks.length >= RAGE_CLICK_COUNT) {+ recentClicks.delete(action)+ recordDislike('rage_click', action)+ } else {+ recentClicks.set(action, clicks)+ }+}++/** A user interaction (pointer/key/wheel): active time accrues to the current+ * Desktop mode for every gap up to ACTIVE_IDLE_GAP_MS; a longer gap was idle. */+export function noteInteraction(now = Date.now(), mode: DesktopMode = $workspaceMode.get()): void {+ const gap = lastInteractionAt ? now - lastInteractionAt : 0++ lastInteractionAt = now++ withState(current => {+ const entry = (current.today.modes[mode] ??= { activeMs: 0, messages: 0 })++ if (gap > 0 && gap <= ACTIVE_IDLE_GAP_MS) {+ entry.activeMs += gap+ }++ persistSoon()+ })+}++/** The user sent a message from a session in `mode` (a bot-owned tile is `bots`). */+export function noteMessageSent(mode: DesktopMode = $workspaceMode.get()): void {+ withState(current => {+ const entry = (current.today.modes[mode] ??= { activeMs: 0, messages: 0 })++ entry.messages += 1+ persistSoon()+ const onboarded = current.onboarding.sent.some(key => !key.startsWith('first_message:'))++ if (onboarded) {+ recordOnboarding('first_message', 'completed')+ }+ })+}++/** Configured bots (Bot Mode roster = Hermes profiles) — a count, never names. */+export function setDesktopBotCount(count: number): void {+ botCount = Math.max(0, Math.floor(finite(count)))+ withState(current => {+ current.today.botCount = Math.max(current.today.botCount, botCount)+ })+}++/** One first-run step transition, once per (step, event) per install. A step+ * reached but not completed is remembered; if it is still open on a later+ * load, it was abandoned. */+export function recordOnboarding(step: DesktopOnboardingStep, event: DesktopOnboardingEvent): void {+ withState(current => {+ const open = { ...current.onboarding.open }++ if (event === 'reached') {+ open[step] = LAUNCH_ID+ } else {+ delete open[step]+ }++ current.onboarding.open = open+ const key = `${step}:${event}`+ const fresh = !current.onboarding.sent.includes(key)++ if (fresh) {+ current.onboarding.sent = [...current.onboarding.sent, key]+ }++ persist()++ if (fresh) {+ send('shared_metrics.desktop_onboarding', { event, step })+ }+ })+}++/** A step ended without an event of its own (skipped past, cancelled): no+ * longer open, so the next launch does not call it abandoned. */+export function closeOnboardingStep(step: DesktopOnboardingStep): void {+ withState(current => {+ if (!(step in current.onboarding.open)) {+ return+ }++ const open = { ...current.onboarding.open }++ delete open[step]+ current.onboarding.open = open+ persist()+ })+}++// ── lifecycle ─────────────────────────────────────────────────────────────────++function reportAbandonedSteps(current: MetricsState): void {+ for (const [step, launch] of Object.entries(current.onboarding.open)) {+ if (launch !== LAUNCH_ID) {+ recordOnboarding(step as DesktopOnboardingStep, 'abandoned')+ }+ }+}++async function flushPendingDays(): Promise<void> {+ if (flushingDays || !request || $desktopMetricsGate.get() !== 'on' || !state?.pending.length) {+ return+ }++ flushingDays = true++ try {+ while (state?.pending.length && request !== null && $desktopMetricsGate.get() === 'on') {+ const day = state.pending[0]!++ const result = await request<{ recorded?: boolean }>('shared_metrics.desktop_daily', {+ actions: Object.entries(day.actions)+ .filter(([, count]) => count > 0)+ .map(([key, count]) => {+ const at = key.lastIndexOf('|')++ return { action: key.slice(0, at), count, via: key.slice(at + 1) }+ }),+ bot_count: day.botCount,+ day: day.day,+ modes: (['bots', 'sessions'] as const)+ .filter(mode => day.modes[mode])+ .map(mode => ({ active_ms: day.modes[mode]!.activeMs, messages_sent: day.modes[mode]!.messages, mode }))+ })++ if (result?.recorded !== true || !state) {+ return+ }++ state.pending = state.pending.filter(entry => entry !== day)+ persist()+ }+ } catch {+ // An older backend or a flap: the day stays pending for the next attach.+ } finally {+ flushingDays = false+ }+}++/** Renderer crashes main persisted while this renderer (or its predecessor) was gone. */+async function drainRendererCrashes(): Promise<void> {+ const bridge = window.hermesDesktop?.desktopMetrics++ try {+ const pending = await bridge?.takeRendererCrashes?.()++ if (!pending) {+ return+ }++ let sent = false++ try {+ for (const reason of pending.reasons) {+ recordFriction('renderer_crash', reason)+ }++ sent = $desktopMetricsGate.get() === 'on'+ } finally {+ await bridge?.ackRendererCrashes?.(sent)+ }+ } catch {+ // Telemetry never surfaces.+ }+}++/** Send everything waiting: queued events, finished days, abandoned steps, crashes. */+export function flushDesktopMetrics(): void {+ if ($desktopMetricsGate.get() !== 'on' || !request) {+ return+ }++ const waiting = queue++ queue = []++ for (const [method, params] of waiting) {+ send(method, params)+ }++ withState(current => {+ reportAbandonedSteps(current)+ persist()+ })+ void flushPendingDays()+ void drainRendererCrashes()+}++/** Main records renderer crashes only while this is on; off deletes its pending record. */+function tellMain(on: boolean): void {+ try {+ Promise.resolve(window.hermesDesktop?.desktopMetrics?.setEnabled?.(on)).catch(() => undefined)+ } catch {+ // An older shell without the bridge.+ }+}++/** Apply the focused profile's collection switch. Off purges everything local. */+export function setDesktopMetricsGate(next: DesktopMetricsGate): void {+ const previous = $desktopMetricsGate.get()++ if (next === previous) {+ return+ }++ $desktopMetricsGate.set(next)++ if (next === 'off') {+ if (saveTimer) {+ clearTimeout(saveTimer)+ saveTimer = null+ }++ state = null+ queue = []+ areaOpenedAt.clear()+ openFlows.clear()+ recentClicks.clear()+ cancelPendingBackendDrop()+ writeJson(STATE_KEY, null)+ tellMain(false)++ return+ }++ if (next === 'on') {+ tellMain(true)+ flushDesktopMetrics()+ }+}++/** The requester for the focused profile's gateway (null while it is down: events queue in memory). */+export function bindDesktopMetrics(next: SharedMetricsRequester | null): void {+ request = next+ flushDesktopMetrics()+}++/** Periodic/visibility tick: roll the day over and send what finished. */+export function tickDesktopMetrics(now = Date.now()): void {+ withState(current => {+ if (rollDay(current, now)) {+ persist()+ }+ })+ void flushPendingDays()+}++/** Write any debounced state now (page hide / unload). */+export function persistDesktopMetricsNow(): void {+ persist()+}++/** Test-only: forget in-memory state (localStorage is the test's to clear). */+export function resetDesktopMetricsForTests(): void {+ if (saveTimer) {+ clearTimeout(saveTimer)+ }++ saveTimer = null+ state = null+ request = null+ queue = []+ flushingDays = false+ botCount = 0+ lastInteractionAt = 0+ areaOpenedAt.clear()+ openFlows.clear()+ recentClicks.clear()+ cancelPendingBackendDrop()+ lastBackendExitAt = 0+ $desktopMetricsGate.set(null)+}++export const DESKTOP_METRICS_STATE_KEY = STATE_KEYdiff --git a/apps/desktop/src/store/intro-splash.ts b/apps/desktop/src/store/intro-splash.tsindex ba6937dac18..12acf682ae1 100644--- a/apps/desktop/src/store/intro-splash.ts+++ b/apps/desktop/src/store/intro-splash.ts@@ -2,6 +2,8 @@ import { atom } from 'nanostores'import { persistBoolean, storedBoolean } from '@/lib/storage'+import { recordFeatureToggle } from './desktop-metrics'+const KEY = 'hermes.desktop.intro-splash.v1'/** Whether the wordmark + tagline splash renders on an empty chat. */@@ -10,5 +12,6 @@ export const $introSplash = atom(storedBoolean(KEY, true))$introSplash.subscribe(on => persistBoolean(KEY, on))export function setIntroSplash(on: boolean) {+ recordFeatureToggle('intro_splash', $introSplash.get(), on)$introSplash.set(on)}diff --git a/apps/desktop/src/store/layout.ts b/apps/desktop/src/store/layout.tsindex 2be5eb1a59d..86b518f9302 100644--- a/apps/desktop/src/store/layout.ts+++ b/apps/desktop/src/store/layout.ts@@ -15,6 +15,7 @@ import { type Codec, Codecs, persistentAtom } from '@/lib/persisted'import { arraysEqual, insertUniqueId, readKey } from '@/lib/storage'import { modeBound, modeLayout } from '@/store/interface-mode'+import { trackArea } from './desktop-metrics'import { $paneStates, ensurePaneRegistered, setPaneOpen, setPaneWidthOverride } from './panes'import { $showAllProfiles, setShowAllProfiles } from './profile'import type { PullRequestBucket } from './pull-requests'@@ -581,6 +582,7 @@ export function toggleFileBrowserOpen() {const open = restoreMinimizedTreeSide(fileBrowserSide()) || !$fileBrowserOpen.get()$fileBrowserOpen.set(open)setTreeSideCollapsed(fileBrowserSide(), !open)+ trackArea('file_pane', open)}export function setFileBrowserOpen(open: boolean) {diff --git a/apps/desktop/src/store/native-notifications.ts b/apps/desktop/src/store/native-notifications.tsindex b5fd075e16b..cd0e0c2af6d 100644--- a/apps/desktop/src/store/native-notifications.ts+++ b/apps/desktop/src/store/native-notifications.ts@@ -4,6 +4,7 @@ import { translateNow } from '@/i18n'import { type HermesOpenTarget, resolveHermesOpenPath } from '@/lib/hermes-open-target'import { persistString, storedString } from '@/lib/storage'+import { recordFeatureToggle } from './desktop-metrics'import { $gateway } from './gateway'import { withinNativeNotifyBaseline } from './notify-baseline'import {@@ -93,11 +94,13 @@ function writePrefs(next: NativeNotificationPrefs) {}export function setNativeNotifyEnabled(enabled: boolean) {+ recordFeatureToggle('native_notifications', $nativeNotifyPrefs.get().enabled, enabled)writePrefs({ ...$nativeNotifyPrefs.get(), enabled })}export function setNativeNotifyKind(kind: NativeNotificationKind, on: boolean) {const prev = $nativeNotifyPrefs.get()+ recordFeatureToggle('notification_kind', prev.kinds[kind], on)writePrefs({ ...prev, kinds: { ...prev.kinds, [kind]: on } })}diff --git a/apps/desktop/src/store/notifications.ts b/apps/desktop/src/store/notifications.tsindex ddccd7faac3..a03793a1f11 100644--- a/apps/desktop/src/store/notifications.ts+++ b/apps/desktop/src/store/notifications.ts@@ -2,6 +2,8 @@ import { atom } from 'nanostores'import { translateNow } from '@/i18n'import { isOutOfSyncRpcParams } from '@/lib/gateway-rpc'+import { isTimeoutError } from '@/lib/with-timeout'+import { type ErrorToastCategory, recordFriction } from '@/store/desktop-metrics'import { isLocalBackendSlotWaitTimeout, requestPoolLimitsSettings } from '@/store/pool-limits'import { requestBackendRestart, requestRoute } from '@/store/recovery-requests'@@ -128,6 +130,8 @@ export const RECOVERY_ACTIONS = {const STORAGE_CODE_RE = /['"]code['"]\s*:\s*['"](storage_[a-z_]+|disk_full)['"]/iinterface ErrorSummaryRule {+ /** The toast's error category for friction telemetry (a closed code-defined set, never the text). */+ category: ErrorToastCategorytest: (msg: string) => booleansummarize: (msg: string) => string/** Recovery button attached to the toast when this rule matches. */@@ -140,6 +144,7 @@ const ERROR_SUMMARIES: ErrorSummaryRule[] = [// bubbles "no space left" / SQLITE_FULL through notifyError. Match before// generic length truncation so the user gets a clear "free space" toast// instead of a silent send or a raw errno dump.+ category: 'disk_full',test: isDiskFullErrorMessage,summarize: () => translateNow('notifications.errors.diskFull'),action: () => RECOVERY_ACTIONS.openMaintenance()@@ -147,48 +152,60 @@ const ERROR_SUMMARIES: ErrorSummaryRule[] = [{// Any other classified storage failure (locked, corrupt, read-only …):// the Maintenance panel runs the doctor that names the fix.+ category: 'storage_failure',test: msg => STORAGE_CODE_RE.test(msg),summarize: () => translateNow('notifications.errors.storageFailure'),action: () => RECOVERY_ACTIONS.openMaintenance()},{+ category: 'gateway_auth_failed',test: msg => /['"]code['"]\s*:\s*['"]gateway_auth_failed['"]/i.test(msg),summarize: () => translateNow('notifications.errors.gatewayAuthFailed'),action: () => RECOVERY_ACTIONS.openGateways()},{+ category: 'api_key_rejected',test: msg => /incorrect api key provided/i.test(msg) || /['"]code['"]\s*:\s*['"]invalid_api_key['"]/i.test(msg),summarize: () => translateNow('notifications.errors.openaiRejectedApiKey'),action: () => RECOVERY_ACTIONS.openKeys('OPENAI_API_KEY')},{+ category: 'api_key_missing',test: msg => /neither voice_tools_openai_key nor openai_api_key is set/i.test(msg),summarize: () => translateNow('notifications.errors.openaiTtsNeedsKey'),action: () => RECOVERY_ACTIONS.openKeys('OPENAI_API_KEY')},{- test: msg => /ELEVENLABS_API_KEY not set/i.test(msg) || /ElevenLabs STT API error \(HTTP 401\)/i.test(msg),- summarize: msg =>- /ELEVENLABS_API_KEY not set/i.test(msg)- ? translateNow('notifications.errors.elevenLabsNeedsKey')- : translateNow('notifications.errors.elevenLabsRejectedKey'),+ category: 'api_key_missing',+ test: msg => /ELEVENLABS_API_KEY not set/i.test(msg),+ summarize: () => translateNow('notifications.errors.elevenLabsNeedsKey'),action: () => RECOVERY_ACTIONS.openKeys('ELEVENLABS_API_KEY')},{+ category: 'api_key_rejected',+ test: msg => /ElevenLabs STT API error \(HTTP 401\)/i.test(msg),+ summarize: () => translateNow('notifications.errors.elevenLabsRejectedKey'),+ action: () => RECOVERY_ACTIONS.openKeys('ELEVENLABS_API_KEY')+ },+ {+ category: 'method_not_allowed',test: msg => /method not allowed/i.test(msg),summarize: () => translateNow('notifications.errors.methodNotAllowed'),action: () => RECOVERY_ACTIONS.restartHermes()},{+ category: 'microphone_permission',test: msg => /microphone permission/i.test(msg),summarize: () => translateNow('notifications.errors.microphonePermission')},{+ category: 'rpc_out_of_sync',test: msg => isOutOfSyncRpcParams(msg),summarize: () => translateNow('notifications.errors.rpcOutOfSync'),action: () => RECOVERY_ACTIONS.openUpdates()},{+ category: 'restart_required',test: msg => /Restart required:/i.test(msg),summarize: () => translateNow('notifications.errors.codeSkewRestartRequired'),action: () => RECOVERY_ACTIONS.restartHermes()@@ -199,10 +216,14 @@ function summarizeErrorMessage(message: string, fallback: string) {const rule = ERROR_SUMMARIES.find(r => r.test(message))if (rule) {- return { action: rule.action?.(message), message: rule.summarize(message) }+ return { action: rule.action?.(message), category: rule.category, message: rule.summarize(message) }}- return { action: undefined, message: message.length > 180 ? fallback : message || fallback }+ return {+ action: undefined,+ category: 'unclassified' as const,+ message: message.length > 180 ? fallback : message || fallback+ }}// Exported so flows that surface errors inline (e.g. ConfirmDialog's onConfirm@@ -210,18 +231,32 @@ function summarizeErrorMessage(message: string, fallback: string) {export function readableError(error: unknown,fallback: string-): { message: string; detail?: string; action?: NotificationAction } {+): { message: string; detail?: string; action?: NotificationAction; category: ErrorToastCategory } {const raw = error instanceof Error ? error.message : typeof error === 'string' ? error : fallbackconst unwrapped = raw.match(/Error invoking remote method '[^']+': Error: (.+)$/)?.[1] ?? rawconst cleaned = cleanErrorText(unwrapped)const detail = cleaned.match(/"detail"\s*:\s*"([^"]+)"/)?.[1] ?? cleanedconst summary = summarizeErrorMessage(detail, fallback)- return { message: summary.message, detail: detail === summary.message ? undefined : detail, action: summary.action }+ return {+ message: summary.message,+ detail: detail === summary.message ? undefined : detail,+ action: summary.action,+ category: summary.category+ }}export function notify(input: NotificationInput): string {+ return showNotification(input, input.kind === 'error' ? 'other' : null)+}++function showNotification(input: NotificationInput, errorCategory: ErrorToastCategory | null): string {const kind = input.kind ?? 'info'++ if (errorCategory) {+ recordFriction('error_toast', errorCategory)+ }+const id = input.id ?? `${Date.now()}-${notificationCounter++}`const notification: AppNotification = {@@ -280,7 +315,13 @@ export function notifyError(const poolSlotTimeout = isLocalBackendSlotWaitTimeout(error)logErrorToDesktopLog(error, fallback)- return notify({+ const category: ErrorToastCategory = poolSlotTimeout+ ? 'pool_slot_timeout'+ : readable.category === 'unclassified' && isTimeoutError(error)+ ? 'timeout'+ : readable.category++ return showNotification({action: poolSlotTimeout? {label: translateNow('desktop.poolSlotTimeoutOpenSettings'),@@ -293,7 +334,7 @@ export function notifyError(title: fallback,message: poolSlotTimeout ? translateNow('desktop.poolSlotTimeoutBody') : readable.message,detail: poolSlotTimeout ? readable.message : readable.detail- })+ }, category)}export function dismissNotification(id: string) {diff --git a/apps/desktop/src/store/preview.ts b/apps/desktop/src/store/preview.tsindex f3d05c537b5..6f300d0d061 100644--- a/apps/desktop/src/store/preview.ts+++ b/apps/desktop/src/store/preview.ts@@ -3,6 +3,7 @@ import { atom, computed } from 'nanostores'import { readJson, writeKey } from '@/lib/storage'import { normalize } from '@/lib/text'+import { recordFeatureUse } from './desktop-metrics'import { $rightRailActiveTabId, type RightRailTabId, selectRightRailTab } from './layout'import { clearExplicitPreviewOpen, noteExplicitPreviewOpen } from './preview-explicit'import { normalizeProfileKey } from './profile'@@ -618,6 +619,7 @@ export function openBrowserTab() {const tabs = $previewTabs.get()const current = tabs.find(tab => tab.id === browserTabId(tabs))+ recordFeatureUse('browser_pane')openPreview(current?.target ?? blankPage())}@@ -625,6 +627,7 @@ export function openBrowserTab() {export function newBrowserTab() {const id = mintBrowserTabId()+ recordFeatureUse('browser_pane')$previewTabs.set([...$previewTabs.get(), { id, target: blankPage() }])noteExplicitPreviewOpen(id)selectRightRailTab(id)diff --git a/apps/desktop/src/store/projects.ts b/apps/desktop/src/store/projects.tsindex 013c7f3093e..7960b099c41 100644--- a/apps/desktop/src/store/projects.ts+++ b/apps/desktop/src/store/projects.ts@@ -47,6 +47,8 @@ import {} from '@/store/session-removal'import type { ProjectInfo, ProjectsPayload } from '@/types/hermes'+import { recordFeatureUse } from './desktop-metrics'+// First-class, per-profile Projects (named, multi-folder workspaces). State is// served by the live gateway's `projects.*` JSON-RPC methods, which wrap the// per-profile projects.db store. The sidebar groups sessions by project folder@@ -93,6 +95,7 @@ export const $reposScanning = atom(false)// point). Never opens a session.export function enterProject(id: string): void {$projectScope.set(id)+ recordFeatureUse('projects')// Only explicit, persisted projects (ids are `p_<hex>`) become active. Auto// projects (ids are filesystem paths) and the Home bucket have no durable rowdiff --git a/apps/desktop/src/store/reactions-enabled.ts b/apps/desktop/src/store/reactions-enabled.tsindex 5adea9a4e3d..da4ce98c386 100644--- a/apps/desktop/src/store/reactions-enabled.ts+++ b/apps/desktop/src/store/reactions-enabled.ts@@ -15,11 +15,14 @@ import { atom } from 'nanostores'import { persistString, storedString } from '@/lib/storage'import { mirrorDisplayToggle } from '@/store/display-toggles'+import { recordFeatureToggle } from './desktop-metrics'+const KEY = 'hermes.desktop.reactions.v1'export const $reactionsEnabled = atom<boolean>(typeof window === 'undefined' ? false : storedString(KEY) === 'on')export function setReactionsEnabled(enabled: boolean): void {+ recordFeatureToggle('reactions', $reactionsEnabled.get(), enabled)$reactionsEnabled.set(enabled)}diff --git a/apps/desktop/src/store/review.ts b/apps/desktop/src/store/review.tsindex 25120515cba..b2985a45ef3 100644--- a/apps/desktop/src/store/review.ts+++ b/apps/desktop/src/store/review.ts@@ -12,6 +12,7 @@ import { Codecs, persistentAtom } from '@/lib/persisted'import { modeBound } from '@/store/interface-mode'import { refreshRepoStatus, repoStatusForCwd } from './coding-status'+import { noteAreaClosed, recordFeatureUse } from './desktop-metrics'import { stampSessionPrBranch } from './pull-requests'import { $busy, $currentCwd, $selectedStoredSessionId, $sessions } from './session'import { $workspaceChangeTick } from './workspace-events'@@ -273,11 +274,13 @@ export function openReview(scopeCwd: null | string = null, scopeTarget = 'main')$reviewScopeCwd.set(scopeCwd?.trim() || null)$reviewScopeTarget.set(scopeTarget.trim() || 'main')$reviewOpen.set(true)+ recordFeatureUse('review_pane')void refreshReview()void refreshShipInfo()}export function closeReview(): void {+ noteAreaClosed('review_pane')$reviewOpen.set(false)$reviewScopeCwd.set(null)$reviewScopeTarget.set('main')diff --git a/apps/desktop/src/store/session-states.ts b/apps/desktop/src/store/session-states.tsindex 6014cdf2137..3c23e2ee978 100644--- a/apps/desktop/src/store/session-states.ts+++ b/apps/desktop/src/store/session-states.ts@@ -42,6 +42,7 @@ import type { SessionInfo } from '@/types/hermes'import { dropStatusDrawersForProfile, migrateStatusDrawersForProfile } from './composer-status-drawer'import { registryConnectionKind } from './connection-registry-state'+import { recordDislike } from './desktop-metrics'import { dialedGatewayModeFor } from './gateway'import { dropPreviewTabsForProfile, migratePreviewTabsForProfile, setPreviewScope } from './preview'import { dropPreviewArtifactsForProfile, migratePreviewArtifactsForProfile } from './preview-status'@@ -2748,6 +2749,7 @@ export function reopenLastClosedTile(): void {ownerRoute: tile.ownerRoute})focusOpenSession(storedSessionId)+ recordDislike('undo', 'closed_tab')return}diff --git a/apps/desktop/src/store/session-switcher.ts b/apps/desktop/src/store/session-switcher.tsindex ffbcccdace2..a3eda6a5504 100644--- a/apps/desktop/src/store/session-switcher.ts+++ b/apps/desktop/src/store/session-switcher.ts@@ -2,6 +2,7 @@ import { atom } from 'nanostores'import type { SessionInfo } from '@/types/hermes'+import { completeFlow } from './desktop-metrics'import { $selectedStoredSessionId, $sessions } from './session'// Mac-style session switcher (^Tab). Quick tap jumps on keydown; the HUD opens@@ -117,6 +118,11 @@ export function commitOnCtrlUp(): string | null {}const target = highlightedSessionId()++ if (target) {+ completeFlow('session_switcher')+ }+closeSwitcher()return targetdiff --git a/apps/desktop/src/store/shared-metrics.ts b/apps/desktop/src/store/shared-metrics.tsindex 7f8ebb66b8b..973df6f6d76 100644--- a/apps/desktop/src/store/shared-metrics.ts+++ b/apps/desktop/src/store/shared-metrics.ts@@ -1,6 +1,8 @@import type { SharedMetricsConsentResult } from '@hermes/shared'import { atom } from 'nanostores'+import { recordOnboarding, setDesktopMetricsGate } from './desktop-metrics'+/** Public page describing exactly what shared metrics contain and how consent windows work. */export const SHARED_METRICS_DOCS_URL = 'https://hermes-agent.nousresearch.com/docs/developer-guide/relay-shared-metrics'@@ -73,7 +75,15 @@ export async function answerSharedMetricsOffer(request: SharedMetricsRequester,choice: SharedMetricsChoice): Promise<void> {- $sharedMetricsConsent.set(await saveSharedMetricsConsent(request, SHARED_METRICS_CHOICES[choice], { firstRun: true }))+ const consent = await saveSharedMetricsConsent(request, SHARED_METRICS_CHOICES[choice], { firstRun: true })++ if (consent) {+ // Gate first: the consent answer is itself a first-run step, counted only when it opted in.+ setDesktopMetricsGate(consent.enabled ? 'on' : 'off')+ recordOnboarding('consent', 'completed')+ }++ $sharedMetricsConsent.set(consent)$sharedMetricsDetailsOpen.set(false)}diff --git a/apps/desktop/src/store/thread-timeline.ts b/apps/desktop/src/store/thread-timeline.tsindex 12167f38806..f339e814506 100644--- a/apps/desktop/src/store/thread-timeline.ts+++ b/apps/desktop/src/store/thread-timeline.ts@@ -2,6 +2,8 @@ import { atom } from 'nanostores'import { persistBoolean, storedBoolean } from '@/lib/storage'+import { recordFeatureToggle } from './desktop-metrics'+const HIDE_THREAD_TIMELINE_STORAGE_KEY = 'hermes.desktop.hideThreadTimeline'/** Desktop-local appearance preference, shared by all threads in this window. */@@ -10,5 +12,6 @@ export const $hideThreadTimeline = atom(storedBoolean(HIDE_THREAD_TIMELINE_STORA$hideThreadTimeline.subscribe(value => persistBoolean(HIDE_THREAD_TIMELINE_STORAGE_KEY, value))export function setHideThreadTimeline(value: boolean) {+ recordFeatureToggle('thread_timeline', !$hideThreadTimeline.get(), !value)$hideThreadTimeline.set(value)}diff --git a/apps/desktop/src/store/tips.ts b/apps/desktop/src/store/tips.tsindex cb62e7b6027..da5aac8eb30 100644--- a/apps/desktop/src/store/tips.ts+++ b/apps/desktop/src/store/tips.ts@@ -32,6 +32,8 @@ import { Codecs, persistentAtom } from '@/lib/persisted'import { TIP_CATALOG, type TipSide } from '@/lib/tips/catalog'import { mirrorDisplayToggle } from '@/store/display-toggles'+import { recordFeatureToggle } from './desktop-metrics'+/** Hours, not minutes. The catalog is ten tips and it should take weeks. */const COOLDOWN_MS = 6 * 60 * 60_000@@ -106,6 +108,8 @@ export const $tipShownAt = persistentAtom<Record<string, number>>()export function setTipsEnabled(enabled: boolean): void {+ recordFeatureToggle('tips', $tipsEnabled.get(), enabled)+if (!enabled) {// Including whichever one is up: the switch is answering a bubble on// screen as often as it is answering the idea of them.diff --git a/apps/desktop/src/store/tours.ts b/apps/desktop/src/store/tours.tsindex f7a15185bff..cab47171e2b 100644--- a/apps/desktop/src/store/tours.ts+++ b/apps/desktop/src/store/tours.ts@@ -14,6 +14,8 @@import { Codecs, persistentAtom } from '@/lib/persisted'import { mirrorDisplayToggle } from '@/store/display-toggles'+import { recordFeatureToggle } from './desktop-metrics'+const KEY = 'hermes.desktop.tours.v1'export const $toursEnabled = persistentAtom(KEY, true, Codecs.bool)@@ -23,5 +25,6 @@ export const $toursEnabled = persistentAtom(KEY, true, Codecs.bool)mirrorDisplayToggle('display.in_app_tours', KEY, $toursEnabled)export function setToursEnabled(enabled: boolean): void {+ recordFeatureToggle('tours', $toursEnabled.get(), enabled)$toursEnabled.set(enabled)}diff --git a/apps/desktop/src/store/vibe-hearts-enabled.ts b/apps/desktop/src/store/vibe-hearts-enabled.tsindex a0e88f7980e..4eab877ac22 100644--- a/apps/desktop/src/store/vibe-hearts-enabled.ts+++ b/apps/desktop/src/store/vibe-hearts-enabled.ts@@ -11,6 +11,8 @@ import { atom } from 'nanostores'import { persistString, storedString } from '@/lib/storage'+import { recordFeatureToggle } from './desktop-metrics'+const KEY = 'hermes.desktop.vibeHearts.v1'// Absent key and anything other than "off" keep hearts on, matching the@@ -18,6 +20,7 @@ const KEY = 'hermes.desktop.vibeHearts.v1'export const $vibeHeartsEnabled = atom<boolean>(typeof window === 'undefined' ? true : storedString(KEY) !== 'off')export function setVibeHeartsEnabled(enabled: boolean): void {+ recordFeatureToggle('vibe_hearts', $vibeHeartsEnabled.get(), enabled)$vibeHeartsEnabled.set(enabled)}diff --git a/apps/desktop/src/themes/context.tsx b/apps/desktop/src/themes/context.tsxindex add78d7143c..892802c8045 100644--- a/apps/desktop/src/themes/context.tsx+++ b/apps/desktop/src/themes/context.tsx@@ -16,6 +16,7 @@ import { createContext, type ReactNode, useCallback, useContext, useEffect, useMimport { $registryVersion } from '@/contrib/registry'import { matchesQuery, useMediaQuery } from '@/hooks/use-media-query'import { persistString, persistStringRecord, storedString, storedStringRecord } from '@/lib/storage'+import { recordFeatureUse } from '@/store/desktop-metrics'import { $activeGatewayProfile, normalizeProfileKey } from '@/store/profile'import { $connection } from '@/store/session'import { setAppearance } from '@/store/translucency'@@ -539,12 +540,14 @@ export function ThemeProvider({ children }: { children: ReactNode }) {const setTheme = useCallback((name: string) => {const next = normalizeSkin(name)+ recordFeatureUse('skins')setPreview(null)setThemeNameState(next)skinPref.assign(liveProfile(), next)}, [])const setMode = useCallback((next: ThemeMode) => {+ recordFeatureUse('skins')setPreview(null)setModeState(next)modePref.assign(liveProfile(), next)