The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(telemetry): Desktop daily report and feature use latch durably per profile, in the usage day's period
teknium11a07b7259a47
diff --git a/hermes_cli/observability/shared_metrics_desktop.py b/hermes_cli/observability/shared_metrics_desktop.pyindex c491d5b240e..a0afeaa1dd7 100644--- a/hermes_cli/observability/shared_metrics_desktop.py+++ b/hermes_cli/observability/shared_metrics_desktop.py@@ -1,36 +1,44 @@"""Shared-metrics facts the Desktop app reports about itself: area use, friction, first-run steps,dislike signals, and one daily report (Bot Mode / Sessions split, button presses per action).-The renderer dedupes on its side (a per-day set persisted only while collection is on); the backend-latches again here so a second window, a reconnect replay or a cleared localStorage cannot inflate a-row: feature use once per (profile, UTC day, area), friction and dislike capped per (profile, UTC day),-onboarding once per (profile, step, event) ever, the daily report once per (profile, usage day). Every value collapses onto the closed-sets in ``shared_metrics_contract``; raw client words are never recorded. All latches are claimed only-after the ``enabled()`` gate (inside the ``_emit`` builders), so a disabled profile writes nothing.+The renderer dedupes on its side (per-profile state persisted only while collection is on); the+backend latches again so a second window, a reconnect replay, a backend restart or a cleared+localStorage cannot inflate a row. Feature use (once per profile, UTC day, area) and the daily report+(once per profile and usage day, counted in the usage day's period) latch durably in the profile's+shared-metrics store, in the same transaction as the row; onboarding latches once per (profile, step,+event) ever in a file; friction and dislike are capped per (profile, UTC day) in this process. Every+value collapses onto the closed sets in ``shared_metrics_contract``; raw client words are never+recorded. Every latch is claimed only after the ``enabled()`` gate, so a disabled profile writes nothing."""from __future__ import annotations+import loggingimport os+import platformimport reimport threading-from datetime import datetime, timezone+from datetime import date, datetime, timedelta, timezonefrom typing import Anyfrom . import shared_metrics_contract as contractfrom .shared_metrics_events import _emit+logger = logging.getLogger(__name__)+# Per-day ceiling for one (kind, detail) friction pair: a toast loop or a janky session still shows# up as "a lot", but cannot flood the store.FRICTION_DAILY_CAP = 50ONBOARDING_LATCH_DIRNAME = "desktop_onboarding"DAILY_ACTION_ROWS_MAX = 200+DAILY_REPORT_STATE_KEY = "desktop_daily_reported"+# The renderer holds a finished day for at most 7 days; anything older (or in the future) is settled+# unrecorded, which keeps the durable per-day latch bounded.+DAILY_REPORT_WINDOW_DAYS = 8_DAY = re.compile(r"\d{4}-\d{2}-\d{2}")_LATCH_LOCK = threading.Lock()# (home, day, key) -> count; pruned to the current day so the process never grows it._daily: dict[tuple[str, str, str], int] = {}-# (home, usage day) already reported by a daily Desktop report in this process.-_reported_days: set[tuple[str, str]] = set()def _utc_day() -> str:@@ -77,9 +85,18 @@ def friction_pair(kind: Any, detail: Any) -> tuple[str, str] | None:return kind_word, detail_word if detail_word in details else "other"-def _feature_use_fields(*, area: Any) -> dict[str, str] | None:- value = feature_area(area)- return {"area": value} if _claim_daily(f"area:{value}") else None+def _store_and_resource() -> tuple[Any, dict[str, str]]:+ """The active profile's store and client resource (the subscriber's), for rows that latch+ durably or belong to a past period and so cannot ride the relay's current-day marks."""+ from hermes_cli.config import detect_install_method+ from hermes_cli.version_info import get_version_info++ from .shared_metrics import SharedMetricsStore++ return SharedMetricsStore(), contract.client_resource(+ get_version_info().base_version, os_name=platform.system(), architecture=platform.machine(),+ install_method=detect_install_method(),+ )def _friction_fields(*, kind: Any, detail: Any) -> dict[str, str] | None:@@ -194,38 +211,49 @@ def _action_rows(actions: Any) -> list[tuple[str, dict[str, str]]]:]+def _daily_rollup(usage_day: str, oldest: str, marks: list[tuple[str, dict[str, str]]], resource: dict[str, str]):+ """``update_rollup_state`` step: the usage day's rows, unless that day was already reported."""+ def update(state: dict[str, Any] | None) -> tuple[dict[str, Any], list[tuple[str, dict, dict, str]]]:+ days = [d for d in (state or {}).get("days", []) if isinstance(d, str) and d >= oldest]+ if usage_day in days:+ return {"days": days}, []+ return {"days": sorted([*days, usage_day])}, [(mark, data, resource, usage_day) for mark, data in marks]+ return update++def record_desktop_daily(*, day: Any, modes: Any, actions: Any, bot_count: Any) -> bool:- """Record one finished Desktop day: a mode_use row per mode used (with the bot count) and an- action_use row per (action, via). True once the day is settled (saved, already reported, or- collection off) so the client drops its copy; False keeps it for the next attach."""+ """Record one finished Desktop day, in that day's period: a mode_use row per mode used (with the+ bot count) and an action_use row per (action, via). True once the day is settled (saved, already+ reported, empty or out of range) so the client drops its copy; False keeps it for the next attach,+ including when this profile's collection is off (the client's own gate decides what it keeps)."""try:from .relay_shared_metrics import enabled- from .shared_metrics_events import emit_savedif not enabled():- return True- usage_day = day if isinstance(day, str) and _DAY.fullmatch(day) else None- if usage_day is None:- return True- marks = _mode_rows(modes, bot_count) + _action_rows(actions)- if not marks:- return True- with _LATCH_LOCK:- latch = (_home(), usage_day)- if latch in _reported_days:- return True- _reported_days.add(latch)- settled = emit_saved(marks) == len(marks)- if not settled:- with _LATCH_LOCK:- _reported_days.discard(latch)- return settled+ return False+ today = _utc_day()+ oldest = (date.fromisoformat(today) - timedelta(days=DAILY_REPORT_WINDOW_DAYS)).isoformat()+ usage_day = day if isinstance(day, str) and _DAY.fullmatch(day) and oldest <= day <= today else None+ marks = _mode_rows(modes, bot_count) + _action_rows(actions) if usage_day else []+ if marks:+ store, resource = _store_and_resource()+ store.update_rollup_state(DAILY_REPORT_STATE_KEY, _daily_rollup(usage_day, oldest, marks, resource))+ return Trueexcept Exception:+ logger.debug("Desktop daily report not recorded", exc_info=True)return Falsedef record_desktop_feature_use(*, area: Any) -> None:- _emit(contract.DESKTOP_FEATURE_USE_MARK, _feature_use_fields, area=area)+ """Once per (profile, UTC day, area), latched in the store with the row (never raises)."""+ try:+ from .relay_shared_metrics import enabled++ if enabled():+ store, resource = _store_and_resource()+ store.record_counter_once_per_day(contract.DESKTOP_FEATURE_USE_METRIC, {"area": feature_area(area)}, resource)+ except Exception:+ logger.debug("Desktop feature use not recorded", exc_info=True)def record_desktop_friction(*, kind: Any, detail: Any) -> None:diff --git a/tests/hermes_cli/test_shared_metrics_desktop.py b/tests/hermes_cli/test_shared_metrics_desktop.pyindex 14bde14f7d5..b6effbd3aec 100644--- a/tests/hermes_cli/test_shared_metrics_desktop.py+++ b/tests/hermes_cli/test_shared_metrics_desktop.py@@ -1,11 +1,13 @@"""v5 desktop: hermes.desktop.{feature_use,friction,onboarding,dislike,mode_use,action_use}.-Every value the Desktop sends collapses onto a closed code-defined set, the backend latches again so a-replay cannot inflate a row, and a disabled profile writes nothing (not even a latch file)."""+Every value the Desktop sends collapses onto a closed code-defined set, the backend latches again (durably,+in the profile's store, for feature use and the daily report) so a replay, a second window or a backend+restart cannot inflate a row, and a disabled profile writes nothing (not even a latch file)."""from __future__ import annotationsimport json+import sqlite3from pathlib import Pathfrom types import SimpleNamespace@@ -14,8 +16,11 @@ import pytestfrom hermes_cli.observability import relay_shared_metricsfrom hermes_cli.observability import shared_metrics_contract as contractfrom hermes_cli.observability import shared_metrics_desktop as desktop+from hermes_cli.observability.shared_metrics import SharedMetricsStoreimport tui_gateway.server as server+TODAY = "2026-09-27"+@pytest.fixturedef marks(tmp_path, monkeypatch):@@ -37,10 +42,16 @@ def marks(tmp_path, monkeypatch):monkeypatch.setattr(relay_shared_metrics, "record_process_marks_saved", saved, raising=False)monkeypatch.setattr(desktop, "_daily", {})- monkeypatch.setattr(desktop, "_reported_days", set())+ monkeypatch.setattr(desktop, "_utc_day", lambda: TODAY)yield SimpleNamespace(rows=captured, policy=policy, home=home, store=store)+def _stored(metric: str) -> list[tuple[str, dict, int]]:+ """``(period_start, dimensions, value)`` rows the profile's store holds for one metric."""+ return [(r["period_start"], r["dimensions"], r["value"])+ for r in SharedMetricsStore().counter_snapshot() if r["metric_name"] == metric]++def _rpc(method: str, **params) -> dict:return server.handle_request({"jsonrpc": "2.0", "id": "r1", "method": method, "params": params})@@ -54,9 +65,8 @@ def test_feature_use_counts_each_area_once_per_day_and_collapses_unknown_areas(mfor area in ("terminal_pane", "terminal_pane", "settings_config_voice", "settings_brand_new_tab", "/Users/x"):assert _rpc("shared_metrics.desktop_feature_use", area=area)["result"] == {"ok": True}- assert [data["area"] for _, data in marks.rows] == [- "terminal_pane", "settings_config_voice", "settings_other", "other"]- _assert_valid(marks.rows)+ assert sorted((dims["area"], value) for _, dims, value in _stored(contract.DESKTOP_FEATURE_USE_METRIC)) == [+ ("other", 1), ("settings_config_voice", 1), ("settings_other", 1), ("terminal_pane", 1)]def test_friction_detail_is_checked_against_its_own_kind_and_capped_per_day(marks):@@ -94,14 +104,14 @@ def test_disabled_profile_records_nothing_and_leaves_no_latch(marks):daily = _rpc("shared_metrics.desktop_daily", day="2026-09-26",modes=[{"mode": "sessions", "active_ms": 60_000, "messages_sent": 3}])- assert daily["result"] == {"recorded": True} # settled: the client drops the day+ assert daily["result"] == {"recorded": False} # never "settled" into another profile's off switchassert marks.rows == []- assert desktop._daily == {} and desktop._reported_days == set()+ assert desktop._daily == {}assert not (marks.home / "telemetry").exists()marks.policy["on"] = True # the earlier calls claimed nothing, so opting in later still counts_rpc("shared_metrics.desktop_feature_use", area="projects")- assert [d["area"] for _, d in marks.rows] == ["projects"]+ assert [dims["area"] for _, dims, _ in _stored(contract.DESKTOP_FEATURE_USE_METRIC)] == ["projects"]def test_daily_report_records_used_modes_and_bucketed_actions_once_per_day(marks):@@ -120,24 +130,39 @@ def test_daily_report_records_used_modes_and_bucketed_actions_once_per_day(marksassert _rpc("shared_metrics.desktop_daily", **params)["result"] == {"recorded": True}assert _rpc("shared_metrics.desktop_daily", **params)["result"] == {"recorded": True} # replay: no rows- assert marks.rows == [- (contract.DESKTOP_MODE_USE_MARK, {"active_minutes_bucket": "30m_to_2h", "bot_count_bucket": "3_to_5",- "messages_sent_bucket": "11_to_25", "mode": "sessions"}),- (contract.DESKTOP_ACTION_USE_MARK, {"action": "other", "count_bucket": "1", "via": "palette"}),- (contract.DESKTOP_ACTION_USE_MARK, {"action": "view.toggleSidebar", "count_bucket": "2", "via": "click"}),- (contract.DESKTOP_ACTION_USE_MARK, {"action": "view.toggleSidebar", "count_bucket": "26_to_100",- "via": "shortcut"}),+ assert _stored(contract.DESKTOP_MODE_USE_METRIC) == [+ ("2026-09-26", {"active_minutes_bucket": "30m_to_2h", "bot_count_bucket": "3_to_5",+ "messages_sent_bucket": "11_to_25", "mode": "sessions"}, 1)]+ assert _stored(contract.DESKTOP_ACTION_USE_METRIC) == [+ ("2026-09-26", {"action": "other", "count_bucket": "1", "via": "palette"}, 1),+ ("2026-09-26", {"action": "view.toggleSidebar", "count_bucket": "2", "via": "click"}, 1),+ ("2026-09-26", {"action": "view.toggleSidebar", "count_bucket": "26_to_100", "via": "shortcut"}, 1),]- _assert_valid(marks.rows)-def test_daily_report_that_the_store_refuses_stays_with_the_client(marks):- marks.store["saves"] = False+def test_a_day_and_an_area_count_once_across_windows_and_backend_restarts_in_the_usage_days_period(marks, monkeypatch):+ day = {"day": "2026-09-20", "modes": [{"mode": "sessions", "active_ms": 60_000, "messages_sent": 3}],+ "actions": [{"action": "composer.send", "count": 4, "via": "shortcut"}]}+ for _ in range(2): # two windows / a restarted backend: nothing of the first process survives+ monkeypatch.setattr(desktop, "_daily", {})+ monkeypatch.setattr(desktop, "_reported_days", set(), raising=False)+ assert _rpc("shared_metrics.desktop_daily", **day)["result"] == {"recorded": True}+ _rpc("shared_metrics.desktop_feature_use", area="terminal_pane")++ assert [(p, v) for p, _, v in _stored(contract.DESKTOP_ACTION_USE_METRIC)] == [("2026-09-20", 1)]+ assert [(p, v) for p, _, v in _stored(contract.DESKTOP_MODE_USE_METRIC)] == [("2026-09-20", 1)]+ assert [v for _, _, v in _stored(contract.DESKTOP_FEATURE_USE_METRIC)] == [1]+++def test_daily_report_that_the_store_refuses_stays_with_the_client(marks, monkeypatch):+ real = SharedMetricsStore.update_rollup_state+ monkeypatch.setattr(SharedMetricsStore, "update_rollup_state",+ lambda self, *a: (_ for _ in ()).throw(sqlite3.OperationalError("database is locked")))params = {"day": "2026-09-26", "modes": [{"mode": "bots", "active_ms": 1, "messages_sent": 0}]}assert _rpc("shared_metrics.desktop_daily", **params)["result"] == {"recorded": False}- marks.store["saves"] = True+ monkeypatch.setattr(SharedMetricsStore, "update_rollup_state", real)assert _rpc("shared_metrics.desktop_daily", **params)["result"] == {"recorded": True}- assert [d["active_minutes_bucket"] for _, d in marks.rows] == ["lt_5m"]+ assert [d["active_minutes_bucket"] for _, d, _ in _stored(contract.DESKTOP_MODE_USE_METRIC)] == ["lt_5m"]def test_dislike_targets_are_closed_per_signal(marks):diff --git a/website/docs/developer-guide/relay-shared-metrics.md b/website/docs/developer-guide/relay-shared-metrics.mdindex 43c9190b686..bc6f15fe112 100644--- a/website/docs/developer-guide/relay-shared-metrics.md+++ b/website/docs/developer-guide/relay-shared-metrics.md@@ -337,9 +337,9 @@ session/bot/profile names, paths and setting values never leave.| Metric | Dimensions | Question it answers ||---|---|---|-| `hermes.desktop.feature_use` | area (panes, command palette, model/session pickers, voice, Bot Mode, skins, projects, each settings page, full pages, `other`) | Which Desktop areas are used at all, counted at most once per area per UTC day per install. |-| `hermes.desktop.action_use` | action (the app's command/keybinding ids plus a few named buttons, else `other`), via (`click`/`shortcut`/`palette`/`menu`), count bucket | Which buttons and commands people press, and how: aggregated in the app and reported once per finished day (no per-press rows). |-| `hermes.desktop.mode_use` | mode (`sessions`/`bots`), active-minutes bucket, messages-sent bucket, bot-count bucket | How Desktop time splits between Bot Mode and regular Sessions. One row per mode used that day; active time sums gaps between interactions of up to 5 minutes. |+| `hermes.desktop.feature_use` | area (panes, command palette, model/session pickers, voice, Bot Mode, skins, projects, each settings page, full pages, `other`) | Which Desktop areas are used at all, counted at most once per area per UTC day per profile (latched in the profile's local database, so a second window or a backend restart never re-counts). |+| `hermes.desktop.action_use` | action (the app's command/keybinding ids plus a few named buttons, else `other`), via (`click`/`shortcut`/`palette`/`menu`), count bucket | Which buttons and commands people press, and how: aggregated in the app per profile and reported once per finished day (no per-press rows). The row lands in the period of the day it describes, not the day it was sent; each day is recorded once per profile however many windows or backend restarts report it, and a day older than 8 days is dropped. |+| `hermes.desktop.mode_use` | mode (`sessions`/`bots`), active-minutes bucket, messages-sent bucket, bot-count bucket | How Desktop time splits between Bot Mode and regular Sessions. One row per mode used that day, in that day's period (same once-per-profile-per-day latch as `action_use`); active time sums gaps between interactions of up to 5 minutes. || `hermes.desktop.friction` | kind (`notice_dismissed`, `error_toast`, `renderer_crash`, `backend_disconnect`, `slow_frame`), detail (notice id, error category, crash reason, drop reason, frame-duration bucket) | What gets in the way. Error toasts carry only their code-defined category; renderer crashes are recorded by the app shell and reported after the window comes back; slow frames are long frames while the window is visible, capped per day. || `hermes.desktop.dislike` | signal (`quick_close`, `cancelled`, `setting_off_default`, `rage_click`, `undo`, `feature_disabled`), target, setting, direction | Signals that a feature is unwanted: a pane closed within 5s of opening, a dialog/flow backed out of, a setting moved to or away from its default (the key only; the backend compares the saved value to the default itself), three clicks on one control within a second, an undo, a shipped feature switched off. Capped per signal per day. || `hermes.desktop.onboarding` | step (first-run steps: provider picker, sign-in, API key, local endpoint, model pick, choose later, free-tier screen, guided setup cards, consent, first message), event (`reached`/`completed`/`abandoned`) | Where first run stops. Each step event once per install; `abandoned` is a step still open when the app next starts. |