Skip to content

The agent that grows with you

feat: shared_metrics.status/set RPCs for Desktop consent

teknium1b685eb90c04f
diff --git a/apps/shared/src/gateway-contract.generated.ts b/apps/shared/src/gateway-contract.generated.ts
index 8d17a583d2d..f960cb28828 100644
--- a/apps/shared/src/gateway-contract.generated.ts
+++ b/apps/shared/src/gateway-contract.generated.ts
@@ -643,6 +643,19 @@ export interface FreeTierProvisionResult {
export interface FreeTierAckNoticeResult {
acked: boolean
}
+/** The focused profile's ``telemetry.shared_metrics`` opt-ins. ``send`` is never true while ``enabled`` is false; ``decided`` = either key is written in config.yaml (the shipped defaults are not an answer). */
+export interface SharedMetricsConsentResult {
+ enabled: boolean
+ send: boolean
+ decided: boolean
+}
+/** ``send`` is ignored unless ``enabled``; ``first_run`` marks the Desktop first-run answer. */
+export interface SharedMetricsSetParams {
+ profile?: string | null
+ enabled: boolean
+ send?: boolean
+ first_run?: boolean
+}
export interface ModelOptionsParams {
profile?: string | null
session_id?: string | null
@@ -5135,6 +5148,10 @@ export interface RpcMethods {
'setup.runtime_check': { params: SetupRuntimeCheckParams; result: SetupRuntimeCheckResult }
/** Loose provider check: is ANY provider auth state discoverable for the (launch or named) profile. */
'setup.status': { params: ProfileParams; result: SetupStatusResult }
+ /** Write both shared-metrics opt-ins at once (send requires collection) and reconcile consent windows. */
+ 'shared_metrics.set': { params: SharedMetricsSetParams; result: SharedMetricsConsentResult }
+ /** Pure read of the focused profile's shared-metrics opt-ins (collection, upload, answered). */
+ 'shared_metrics.status': { params: ProfileParams; result: SharedMetricsConsentResult }
/** Run a safe (non-dangerous) shell command captured for ``!cmd`` / inline substitution. */
'shell.exec': { params: ShellExecParams; result: ShellExecResult }
/** Skills hub backend: list the profile's skills or search / browse / inspect / install from the hub. */
@@ -5417,6 +5434,8 @@ export const RPC_METHODS = [
'session.workspace.move',
'setup.runtime_check',
'setup.status',
+ 'shared_metrics.set',
+ 'shared_metrics.status',
'shell.exec',
'skills.manage',
'skills.reload',
diff --git a/apps/shared/src/gateway-contract.openrpc.json b/apps/shared/src/gateway-contract.openrpc.json
index fc40e122f96..388f9639e70 100644
--- a/apps/shared/src/gateway-contract.openrpc.json
+++ b/apps/shared/src/gateway-contract.openrpc.json
@@ -3588,6 +3588,42 @@
}
}
},
+ {
+ "name": "shared_metrics.set",
+ "summary": "Write both shared-metrics opt-ins at once (send requires collection) and reconcile consent windows.",
+ "params": [
+ {
+ "name": "params",
+ "schema": {
+ "$ref": "#/components/schemas/SharedMetricsSetParams"
+ }
+ }
+ ],
+ "result": {
+ "name": "result",
+ "schema": {
+ "$ref": "#/components/schemas/SharedMetricsConsentResult"
+ }
+ }
+ },
+ {
+ "name": "shared_metrics.status",
+ "summary": "Pure read of the focused profile's shared-metrics opt-ins (collection, upload, answered).",
+ "params": [
+ {
+ "name": "params",
+ "schema": {
+ "$ref": "#/components/schemas/ProfileParams"
+ }
+ }
+ ],
+ "result": {
+ "name": "result",
+ "schema": {
+ "$ref": "#/components/schemas/SharedMetricsConsentResult"
+ }
+ }
+ },
{
"name": "shell.exec",
"summary": "Run a safe (non-dangerous) shell command captured for ``!cmd`` / inline substitution.",
@@ -31854,6 +31890,68 @@
"title": "SetupStatusResult",
"type": "object"
},
+ "SharedMetricsConsentResult": {
+ "additionalProperties": false,
+ "description": "The focused profile's ``telemetry.shared_metrics`` opt-ins. ``send`` is never true while\n``enabled`` is false; ``decided`` = either key is written in config.yaml (the shipped defaults\nare not an answer).",
+ "properties": {
+ "enabled": {
+ "title": "Enabled",
+ "type": "boolean"
+ },
+ "send": {
+ "title": "Send",
+ "type": "boolean"
+ },
+ "decided": {
+ "title": "Decided",
+ "type": "boolean"
+ }
+ },
+ "required": [
+ "enabled",
+ "send",
+ "decided"
+ ],
+ "title": "SharedMetricsConsentResult",
+ "type": "object"
+ },
+ "SharedMetricsSetParams": {
+ "additionalProperties": false,
+ "description": "``send`` is ignored unless ``enabled``; ``first_run`` marks the Desktop first-run answer.",
+ "properties": {
+ "profile": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Profile"
+ },
+ "enabled": {
+ "title": "Enabled",
+ "type": "boolean"
+ },
+ "send": {
+ "default": false,
+ "title": "Send",
+ "type": "boolean"
+ },
+ "first_run": {
+ "default": false,
+ "title": "First Run",
+ "type": "boolean"
+ }
+ },
+ "required": [
+ "enabled"
+ ],
+ "title": "SharedMetricsSetParams",
+ "type": "object"
+ },
"ShellExecParams": {
"additionalProperties": false,
"properties": {
diff --git a/tests/tui_gateway/test_shared_metrics_consent_rpc.py b/tests/tui_gateway/test_shared_metrics_consent_rpc.py
new file mode 100644
index 00000000000..785e889ccc8
--- /dev/null
+++ b/tests/tui_gateway/test_shared_metrics_consent_rpc.py
@@ -0,0 +1,69 @@
+"""shared_metrics.status / shared_metrics.set: the Desktop consent path keeps the CLI wizard's
+invariants (sending needs collection, every change reconciles the consent windows) and lands in the
+profile the request names, never the launch profile."""
+
+from __future__ import annotations
+
+import sqlite3
+from pathlib import Path
+
+import hermes_yaml as yaml
+
+import tui_gateway.server as server
+
+
+def _bind_homes(monkeypatch, tmp_path: Path) -> tuple[Path, Path]:
+ launch, worker = tmp_path / "launch", tmp_path / "profiles" / "code"
+ for home in (launch, worker):
+ home.mkdir(parents=True)
+ (home / "config.yaml").write_text(yaml.safe_dump({"model": {"provider": "nous"}}), encoding="utf-8")
+ monkeypatch.setattr(server, "_hermes_home", launch)
+ monkeypatch.setenv("HERMES_HOME", str(launch))
+ monkeypatch.setattr(server, "_profile_home", lambda name: worker if (name or "").strip() == "code" else None)
+ server._cfg_cache = server._cfg_sig = server._cfg_path = None
+ return launch, worker
+
+
+def _call(method: str, params: dict) -> dict:
+ return server._methods[method]("rid", params)["result"]
+
+
+def _shared_metrics(home: Path) -> dict:
+ cfg = yaml.safe_load((home / "config.yaml").read_text(encoding="utf-8")) or {}
+ return (cfg.get("telemetry") or {}).get("shared_metrics") or {}
+
+
+def _windows(home: Path) -> list[tuple]:
+ db = home / "telemetry" / "shared_metrics" / "metrics.sqlite3"
+ with sqlite3.connect(db) as conn:
+ return conn.execute("SELECT opened_at, closed_at FROM send_consent_windows ORDER BY rowid").fetchall()
+
+
+def test_send_without_collection_is_normalized_off_and_closes_the_consent_window(tmp_path, monkeypatch):
+ launch, worker = _bind_homes(monkeypatch, tmp_path)
+
+ assert _call("shared_metrics.set", {"profile": "code", "enabled": True, "send": True}) == {
+ "enabled": True, "send": True, "decided": True}
+ [(opened, closed)] = _windows(worker)
+ assert opened and closed is None
+
+ # send=true alone is refused: collection off withdraws send consent, in config AND in the store.
+ assert _call("shared_metrics.set", {"profile": "code", "enabled": False, "send": True}) == {
+ "enabled": False, "send": False, "decided": True}
+ assert _shared_metrics(worker) == {"enabled": False, "send": False}
+ [(_, closed)] = _windows(worker)
+ assert closed is not None
+
+ assert _shared_metrics(launch) == {}
+ assert not (launch / "telemetry").exists()
+
+
+def test_status_is_undecided_until_a_key_is_written(tmp_path, monkeypatch):
+ _launch, worker = _bind_homes(monkeypatch, tmp_path)
+
+ assert _call("shared_metrics.status", {"profile": "code"}) == {"enabled": False, "send": False, "decided": False}
+
+ # An answer given in `hermes setup` (only `enabled: false` written) counts as decided.
+ (worker / "config.yaml").write_text(
+ yaml.safe_dump({"telemetry": {"shared_metrics": {"enabled": False}}}), encoding="utf-8")
+ assert _call("shared_metrics.status", {"profile": "code"}) == {"enabled": False, "send": False, "decided": True}
diff --git a/tui_gateway/contracts/config_free_tier_control.py b/tui_gateway/contracts/config_free_tier_control.py
index be17c41fe10..759298557cf 100644
--- a/tui_gateway/contracts/config_free_tier_control.py
+++ b/tui_gateway/contracts/config_free_tier_control.py
@@ -2,7 +2,8 @@
image generation and structured session control.
Handlers: ``tui_gateway/methods_config.py`` (``config.get``, ``setup.*``, ``diagnostics.share_nous``),
-``methods_config_set.py`` (``config.set``), ``methods_free_tier.py``, ``methods_complete.py``
+``methods_config_set.py`` (``config.set``), ``methods_free_tier.py``, ``methods_shared_metrics.py``,
+``methods_complete.py``
(``model.options``), ``methods_connectors.py``, ``methods_images.py``, ``methods_session_control.py``
and ``methods_session.py`` (``verification.status``).
"""
@@ -210,6 +211,35 @@ method("free_tier.ack_notice", params=ProfileParams, result=FreeTierAckNoticeRes
doc="Mark the one-time availability notice as shown on the free-tier identity.")
+# ── shared metrics consent ────────────────────────────────────────────────────────────────────
+
+
+class SharedMetricsConsentResult(Result):
+ """The focused profile's ``telemetry.shared_metrics`` opt-ins. ``send`` is never true while
+ ``enabled`` is false; ``decided`` = either key is written in config.yaml (the shipped defaults
+ are not an answer)."""
+
+ enabled: bool
+ send: bool
+ decided: bool
+
+
+method("shared_metrics.status", params=ProfileParams, result=SharedMetricsConsentResult,
+ doc="Pure read of the focused profile's shared-metrics opt-ins (collection, upload, answered).")
+
+
+class SharedMetricsSetParams(ProfileParams):
+ """``send`` is ignored unless ``enabled``; ``first_run`` marks the Desktop first-run answer."""
+
+ enabled: bool
+ send: bool = False
+ first_run: bool = False
+
+
+method("shared_metrics.set", params=SharedMetricsSetParams, result=SharedMetricsConsentResult,
+ doc="Write both shared-metrics opt-ins at once (send requires collection) and reconcile consent windows.")
+
+
# ── model.options ─────────────────────────────────────────────────────────────────────────────
diff --git a/tui_gateway/methods_shared_metrics.py b/tui_gateway/methods_shared_metrics.py
new file mode 100644
index 00000000000..b1313358d40
--- /dev/null
+++ b/tui_gateway/methods_shared_metrics.py
@@ -0,0 +1,90 @@
+"""Shared-metrics consent JSON-RPC handlers (the Desktop twin of ``hermes setup``'s Shared Metrics
+section). Both opt-ins live in the focused profile's config.yaml exactly where the wizard writes
+them — ``telemetry.shared_metrics.enabled`` (local collection) and ``.send`` (daily upload) — so the
+CLI and the app can never disagree about the answer. ``shared_metrics.set`` enforces the wizard's
+invariant (sending needs collection) and reconciles the consent windows in the local store on every
+change, through the same single writer the wizard uses.
+Bodies are rebound onto server.py's globals (method_ctx.bind_module) and reference them bare.
+"""
+
+import logging
+
+from .method_ctx import HandlerRegistry, bind_module
+
+logger = logging.getLogger(__name__)
+_registry = HandlerRegistry()
+method = _registry.method
+_profile_scoped = _registry.profile_scoped
+
+
+def _shared_metrics_section(cfg) -> dict:
+ telemetry = cfg.get("telemetry") if isinstance(cfg, dict) else None
+ section = telemetry.get("shared_metrics") if isinstance(telemetry, dict) else None
+ return section if isinstance(section, dict) else {}
+
+
+def _shared_metrics_consent(cfg) -> dict:
+ """``decided`` = the user answered somewhere (either key written explicitly); the shipped
+ defaults are not an answer, so a profile that never saw the question reads undecided."""
+ section = _shared_metrics_section(cfg)
+ enabled = section.get("enabled") is True
+ return {
+ "enabled": enabled,
+ "send": enabled and section.get("send") is True,
+ "decided": "enabled" in section or "send" in section,
+ }
+
+
+def _shared_metrics_record_setup_completed(cfg) -> None:
+ """Desktop's setup ends at this first-run answer. A no-op unless collection is on."""
+ try:
+ from hermes_cli.observability.shared_metrics_events import record_setup_completed
+ except ImportError: # the events module lands with the shared-metrics v3 PR
+ return
+ model = cfg.get("model") if isinstance(cfg, dict) else None
+ provider = model.get("provider") if isinstance(model, dict) else None
+ record_setup_completed(surface="desktop", provider=provider if isinstance(provider, str) and provider else None)
+
+
+@method("shared_metrics.status")
+@_profile_scoped
+def _(rid, params: dict) -> dict:
+ """``{enabled, send, decided}`` for the focused profile. A pure read of config.yaml (no defaults
+ merged, so ``decided`` sees only what the user wrote)."""
+ try:
+ return _ok(rid, _shared_metrics_consent(_load_cfg()))
+ except Exception as e:
+ return _err(rid, 5095, str(e))
+
+
+@method("shared_metrics.set")
+@_profile_scoped
+def _(rid, params: dict) -> dict:
+ """Write both opt-ins at once and reconcile the consent windows. ``send`` is forced off when
+ ``enabled`` is off (the wizard's rule: sending cannot outlive collection, and turning collection
+ off withdraws send consent). ``first_run`` marks the Desktop first-run answer, which also records
+ the setup-completed metric. Answers the stored ``{enabled, send, decided}``."""
+ enabled = params.get("enabled") is True
+ send = enabled and params.get("send") is True
+ try:
+ cfg = _load_cfg_raw()
+ telemetry = cfg.get("telemetry")
+ if not isinstance(telemetry, dict):
+ telemetry = cfg["telemetry"] = {}
+ section = telemetry.get("shared_metrics")
+ if not isinstance(section, dict):
+ section = telemetry["shared_metrics"] = {}
+ section["enabled"], section["send"] = enabled, send
+ _save_cfg(cfg)
+ except Exception as e:
+ return _err(rid, 5096, str(e))
+ from hermes_cli.setup import _record_send_consent_change
+ # Unconditional, like the wizard: a send key already false may still have an open window.
+ _record_send_consent_change(enabled=send)
+ if params.get("first_run") is True:
+ _shared_metrics_record_setup_completed(cfg)
+ return _ok(rid, _shared_metrics_consent(cfg))
+
+
+def register(server) -> None:
+ bind_module(globals(), server, skip=("_",))
diff --git a/tui_gateway/server.py b/tui_gateway/server.py
index ec5e223d250..c0b8fb502e3 100644
--- a/tui_gateway/server.py
+++ b/tui_gateway/server.py
@@ -178,6 +178,7 @@ _LONG_HANDLERS = frozenset({
"wake.status", "session.active_list", "session.branch", "session.compress", "session.list",
"session.resume", "session.workspace.move", "shell.exec", "skills.manage", "slash.exec",
"command.dispatch", # /goal draft invokes the auxiliary model; never block the RPC reader
+ "shared_metrics.set", # consent reconcile waits on the metrics store's write lock
})
_rpc_pool_workers = max(2, env_int("HERMES_TUI_RPC_POOL_WORKERS", 8))
@@ -3486,7 +3487,7 @@ from . import ( # noqa: E402
methods_vault as _methods_vault, methods_free_tier as _methods_free_tier,
methods_connectors as _methods_connectors, methods_connectors_account as _methods_connectors_account,
methods_display as _methods_display, methods_display_watch as _methods_display_watch,
- methods_onboarding as _methods_onboarding)
+ methods_onboarding as _methods_onboarding, methods_shared_metrics as _methods_shared_metrics)
for _m in (
_session_transports, _session_reaper, _session_lifecycle, _session_workdir, _compute_host_bridge, _model_switch,
@@ -3497,6 +3498,7 @@ for _m in (
_methods_config_set, _methods_complete, _methods_tools, _methods_profiles, _methods_images,
_methods_bot_relay, _prompt_turn, _billing_view, _methods_projects, _methods_session_foreign,
_methods_session_control, _methods_subagents, _methods_vault, _methods_free_tier, _methods_connectors,
- _methods_connectors_account, _methods_display, _methods_display_watch, _methods_onboarding):
+ _methods_connectors_account, _methods_display, _methods_display_watch, _methods_onboarding,
+ _methods_shared_metrics):
_m.register(sys.modules[__name__])
del _m