Skip to content

The agent that grows with you

refactor(hermes_cli/web_routers/analytics): extract _fold_session_only_rows/_model_capabilities, dedupe usage-key tuples, drop orphaned comment block

Teknium953939d7c700
diff --git a/hermes_cli/web_routers/analytics.py b/hermes_cli/web_routers/analytics.py
index e55bc6e0086..d42257e2306 100644
--- a/hermes_cli/web_routers/analytics.py
+++ b/hermes_cli/web_routers/analytics.py
@@ -4,15 +4,16 @@ Extracted from ``hermes_cli.web_server``; helpers/state that tests monkeypatch o
``web_server`` stay there and are imported lazily at call time (cycle-safe).
"""
-import yaml
import asyncio
import time
-from fastapi import APIRouter
-from hermes_cli.web_deps import late
-from fastapi import HTTPException, Query
+from typing import Any, Dict, List, Optional
+
+import yaml
+from fastapi import APIRouter, HTTPException, Query
+
from hermes_cli.config import get_config_path, read_raw_config
+from hermes_cli.web_deps import late
from hermes_cli.web_models import RawConfigUpdate
-from typing import Any, Dict, List, Optional
router = APIRouter()
@@ -27,22 +28,7 @@ _open_session_db_for_profile = late("_open_session_db_for_profile")
_profile_scope = late("_profile_scope")
save_config = late("save_config")
-
-# ---------------------------------------------------------------------------
-# Computer Use (cua-driver) — cross-platform readiness + macOS permission grant
-#
-# cua-driver runs on macOS, Windows, and Linux. The desktop card reflects
-# per-OS readiness: on macOS the Accessibility + Screen Recording TCC grants
-# (which attach to cua-driver's OWN identity, com.trycua.driver — not Hermes,
-# so no app entitlement is involved); elsewhere, driver health from
-# `cua-driver doctor`. The grant flow is macOS-only (no TCC toggles to request
-# on Windows/Linux).
-# ---------------------------------------------------------------------------
-
-
-# ---------------------------------------------------------------------------
-# Raw YAML config endpoint
-# ---------------------------------------------------------------------------
+# ── Raw YAML config ──────────────────────────────────────────────────────────
@router.get("/api/config/raw")
@@ -70,13 +56,12 @@ async def update_config_raw(body: RawConfigUpdate, profile: Optional[str] = None
parsed = yaml.safe_load(body.yaml_text)
if not isinstance(parsed, dict):
raise HTTPException(status_code=400, detail="YAML must be a mapping")
- approvals_mode_changed = False
with _profile_scope(body.profile or profile):
- # Full-document replacement: the editor owns the whole file; do not
- # merge omitted sections back from disk (#62723).
+ # Full-document replacement: the editor owns the whole file; never
+ # merge omitted sections back from disk.
approvals_mode_changed = _approval_mode_of(parsed) != _approval_mode_of(read_raw_config())
save_config(parsed, merge_existing=False)
- # Same indicator refresh as the schema-driven save above.
+ # Same indicator refresh as the schema-driven save.
if approvals_mode_changed and not _is_other_profile(body.profile or profile):
_broadcast_gateway_session_info()
return {"ok": True}
@@ -120,11 +105,8 @@ def _get_usage_analytics(days: int = 30, profile: Optional[str] = None):
""", (cutoff,))
by_model = [dict(r) for r in cur2.fetchall()]
- # Fold in auxiliary usage (vision, compression, title_generation, ...)
- # recorded per (model, task) in session_model_usage. Aux calls never
- # touch the sessions counters, so this is add-only — no double count.
- # Without it the models list shows only the main agent model even when
- # aux models are actively burning tokens (issue #23270).
+ # Fold in auxiliary usage (vision, compression, ...) from session_model_usage.
+ # Aux calls never touch the sessions counters, so this is add-only — no double count.
aux_rows = _aux_usage_rows(db, cutoff)
by_model = _merge_aux_into_by_model(by_model, aux_rows)
@@ -145,15 +127,11 @@ def _get_usage_analytics(days: int = 30, profile: Optional[str] = None):
return {
"daily": daily,
"by_model": by_model,
- # Aux-task summary across models (vision, compression, ...). Lets
- # the dashboard answer "what is compression costing me" directly.
- "by_task": _aux_task_summary(aux_rows),
+ "by_task": _aux_task_summary(aux_rows), # "what is compression costing me"
"totals": totals,
"period_days": days,
"skills": usage["skills"],
- # Per-tool-name call counts (already computed by InsightsEngine);
- # the desktop Capabilities page aggregates these per toolset.
- "tools": usage["tools"],
+ "tools": usage["tools"], # per-tool-name counts; desktop aggregates per toolset
}
finally:
db.close()
@@ -171,12 +149,80 @@ async def get_usage_analytics(
return await asyncio.to_thread(_get_usage_analytics, days, profile)
-def _get_models_analytics(days: int = 30, profile: Optional[str] = None):
- """Rich per-model analytics for the Models dashboard page.
+_USAGE_KEYS = (
+ "input_tokens", "output_tokens", "cache_read_tokens", "reasoning_tokens",
+ "estimated_cost", "actual_cost", "api_calls", "tool_calls",
+)
+
+
+def _has_usage(row: Dict[str, Any]) -> bool:
+ return any((row.get(key) or 0) != 0 for key in _USAGE_KEYS)
+
- Returns token/cost/session breakdown per model plus capability metadata
- from models.dev (context window, vision, tools, reasoning, etc.).
+def _fold_session_only_rows(raw_rows: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
+ """Fold model rows that carry no billing_provider and no usage into the single
+ accounted provider row for that model.
+
+ Session rows can be created before the first billable call finishes; if that early row
+ records only the model name while a later row has real accounting, the Models page used
+ to show a duplicate "0 tokens / — API calls" card. Only folds when ownership is
+ unambiguous (exactly one provider row).
"""
+ rows_by_model: Dict[str, List[Dict[str, Any]]] = {}
+ for row in raw_rows:
+ rows_by_model.setdefault(row.get("model") or "", []).append(row)
+
+ rows: List[Dict[str, Any]] = []
+ for model_rows in rows_by_model.values():
+ provider_rows = [r for r in model_rows if r.get("billing_provider")]
+ if len(provider_rows) != 1:
+ rows.extend(model_rows)
+ continue
+ target = provider_rows[0]
+ for row in model_rows:
+ if row is target or row.get("billing_provider") or _has_usage(row):
+ continue
+ target["sessions"] = (target.get("sessions") or 0) + (row.get("sessions") or 0)
+ target["last_used_at"] = max(target.get("last_used_at") or 0, row.get("last_used_at") or 0)
+ total_tokens = (target.get("input_tokens") or 0) + (target.get("output_tokens") or 0)
+ sessions = target.get("sessions") or 0
+ target["avg_tokens_per_session"] = total_tokens / sessions if sessions else 0
+ rows.append(target)
+ rows.extend(
+ r for r in model_rows
+ if r is not target and (r.get("billing_provider") or _has_usage(r))
+ )
+ return rows
+
+
+def _model_capabilities(provider: str, model_name: str) -> dict:
+ """models.dev capability metadata for the card; {} when unknown or lookup fails."""
+ try:
+ from agent.models_dev import get_model_capabilities
+ mc = get_model_capabilities(provider=provider, model=model_name)
+ except Exception:
+ return {}
+ if mc is None:
+ return {}
+ return {
+ "supports_tools": mc.supports_tools,
+ "supports_vision": mc.supports_vision,
+ "supports_reasoning": mc.supports_reasoning,
+ "context_window": mc.context_window,
+ "max_output_tokens": mc.max_output_tokens,
+ "model_family": mc.model_family,
+ }
+
+
+_MODEL_CARD_KEYS = (
+ "input_tokens", "output_tokens", "cache_read_tokens", "reasoning_tokens",
+ "estimated_cost", "actual_cost", "sessions", "api_calls", "tool_calls",
+ "last_used_at", "avg_tokens_per_session",
+)
+
+
+def _get_models_analytics(days: int = 30, profile: Optional[str] = None):
+ """Per-model token/cost/session breakdown plus models.dev capability metadata."""
db = _open_session_db_for_profile(profile, read_only=True)
try:
cutoff = time.time() - (days * 86400)
@@ -201,10 +247,8 @@ def _get_models_analytics(days: int = 30, profile: Optional[str] = None):
""", (cutoff,))
raw_rows = [dict(r) for r in cur.fetchall()]
- # Add auxiliary usage as (model, provider) rows so aux-only models
- # (dedicated vision/compression models) appear on the Models page
- # instead of being invisible (issue #23270). Keyed by
- # model+billing_provider to match the GROUP BY above.
+ # Aux-only models (dedicated vision/compression) as (model, provider) rows,
+ # keyed like the GROUP BY above, so they appear on the Models page.
for aux in _aux_usage_rows(db, cutoff):
raw_rows.append({
"model": aux.get("model") or "unknown",
@@ -223,65 +267,7 @@ def _get_models_analytics(days: int = 30, profile: Optional[str] = None):
"aux_task": aux.get("task") or "",
})
- # Session rows can be created before the first billable provider call
- # finishes. If that early row records only the model name, and a later
- # row for the same model has real accounting + billing_provider, the
- # Models page used to show a duplicate "0 tokens / — API calls" card
- # next to the real provider card. Fold those session-only rows into
- # the single accounted provider row when the ownership is unambiguous.
- rows_by_model: Dict[str, List[Dict[str, Any]]] = {}
- for row in raw_rows:
- rows_by_model.setdefault(row.get("model") or "", []).append(row)
-
- rows: List[Dict[str, Any]] = []
- for model_rows in rows_by_model.values():
- provider_rows = [r for r in model_rows if r.get("billing_provider")]
- if len(provider_rows) == 1:
- target = provider_rows[0]
- for row in model_rows:
- if row is target or row.get("billing_provider"):
- continue
- has_usage = any(
- (row.get(key) or 0) != 0
- for key in (
- "input_tokens",
- "output_tokens",
- "cache_read_tokens",
- "reasoning_tokens",
- "estimated_cost",
- "actual_cost",
- "api_calls",
- "tool_calls",
- )
- )
- if has_usage:
- continue
- target["sessions"] = (target.get("sessions") or 0) + (row.get("sessions") or 0)
- target["last_used_at"] = max(target.get("last_used_at") or 0, row.get("last_used_at") or 0)
- total_tokens = (target.get("input_tokens") or 0) + (target.get("output_tokens") or 0)
- sessions = target.get("sessions") or 0
- target["avg_tokens_per_session"] = total_tokens / sessions if sessions else 0
- rows.append(target)
- rows.extend(
- r for r in model_rows
- if r is not target
- and (r.get("billing_provider") or any(
- (r.get(key) or 0) != 0
- for key in (
- "input_tokens",
- "output_tokens",
- "cache_read_tokens",
- "reasoning_tokens",
- "estimated_cost",
- "actual_cost",
- "api_calls",
- "tool_calls",
- )
- ))
- )
- else:
- rows.extend(model_rows)
-
+ rows = _fold_session_only_rows(raw_rows)
rows.sort(
key=lambda r: (r.get("input_tokens") or 0) + (r.get("output_tokens") or 0),
reverse=True,
@@ -290,38 +276,11 @@ def _get_models_analytics(days: int = 30, profile: Optional[str] = None):
models = []
for row in rows:
provider = row.get("billing_provider") or ""
- model_name = row["model"]
- caps = {}
- try:
- from agent.models_dev import get_model_capabilities
- mc = get_model_capabilities(provider=provider, model=model_name)
- if mc is not None:
- caps = {
- "supports_tools": mc.supports_tools,
- "supports_vision": mc.supports_vision,
- "supports_reasoning": mc.supports_reasoning,
- "context_window": mc.context_window,
- "max_output_tokens": mc.max_output_tokens,
- "model_family": mc.model_family,
- }
- except Exception:
- pass
-
models.append({
- "model": model_name,
+ "model": row["model"],
"provider": provider,
- "input_tokens": row["input_tokens"],
- "output_tokens": row["output_tokens"],
- "cache_read_tokens": row["cache_read_tokens"],
- "reasoning_tokens": row["reasoning_tokens"],
- "estimated_cost": row["estimated_cost"],
- "actual_cost": row["actual_cost"],
- "sessions": row["sessions"],
- "api_calls": row["api_calls"],
- "tool_calls": row["tool_calls"],
- "last_used_at": row["last_used_at"],
- "avg_tokens_per_session": row["avg_tokens_per_session"],
- "capabilities": caps,
+ **{key: row[key] for key in _MODEL_CARD_KEYS},
+ "capabilities": _model_capabilities(provider, row["model"]),
})
totals_cur = db._conn.execute("""
@@ -338,11 +297,7 @@ def _get_models_analytics(days: int = 30, profile: Optional[str] = None):
""", (cutoff,))
totals = dict(totals_cur.fetchone())
- return {
- "models": models,
- "totals": totals,
- "period_days": days,
- }
+ return {"models": models, "totals": totals, "period_days": days}
finally:
db.close()
@@ -352,6 +307,5 @@ async def get_models_analytics(
days: int = Query(30, ge=1, le=365),
profile: Optional[str] = None,
):
- # ``days`` clamped to 1-365 (idea from #74778) — see get_usage_analytics.
"""Return model analytics without blocking the serving event loop."""
return await asyncio.to_thread(_get_models_analytics, days, profile)