Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
feat(costs): a Spend & Tokens section that prices every token by provider, model and role
rubenluetke10-beep0a3a871c3b22
diff --git a/docs/jarvis-cli-reference.md b/docs/jarvis-cli-reference.mdindex ed93d49067..fdd9af1468 100644--- a/docs/jarvis-cli-reference.md+++ b/docs/jarvis-cli-reference.md@@ -78,6 +78,12 @@ _Generated from the curated command tree by `scripts/ci/gen_cli_reference.py`- `jarvis contacts list` — List contacts.- `jarvis contacts show <slug>` — Show one contact.+## costs++- `jarvis costs entries --days --provider --model --role --surface --search --sort --limit --offset` — The individual model calls behind the totals.+- `jarvis costs rates --days` — The rate card per model — and which models have no published rate.+- `jarvis costs summary --days --provider --model --role --surface --search` — Totals plus the breakdown by provider, model, role, surface and day.+## docs- `jarvis docs list` — List documentation pages.diff --git a/docs/jarvis-cli.md b/docs/jarvis-cli.mdindex d4471c4c5a..363803660b 100644--- a/docs/jarvis-cli.md+++ b/docs/jarvis-cli.md@@ -22,9 +22,9 @@ The CLI is a **thin HTTP client over the REST API**, in two layers:reachable.2. **Curated layer (`jarvis <group> <command>`)** — hand-written, ergonomiccommands for the common domains: `brain`, `config`, `missions`, `wiki`,- `sessions`, `skills`, `outputs`, `board`, `workflows`, `conductor`, `contacts`,- `telephony`, `marketplace`, `mcps`, `docs`, `frontier`, plus `auth`, `system`,- `tasks`.+ `sessions`, `skills`, `outputs`, `board`, `costs`, `workflows`, `conductor`,+ `contacts`, `telephony`, `marketplace`, `mcps`, `docs`, `frontier`, plus+ `auth`, `system`, `tasks`.Because the CLI only ever calls the same routes the WebUI calls, it inherits allof Jarvis's safety machinery (risk tiers, the atomic config-write pipeline, thediff --git a/jarvis/cli_ctl/__main__.py b/jarvis/cli_ctl/__main__.pyindex 79c2043320..1c7415e740 100644--- a/jarvis/cli_ctl/__main__.py+++ b/jarvis/cli_ctl/__main__.py@@ -27,6 +27,7 @@ from jarvis.cli_ctl.commands import computer_use as computer_use_cmdfrom jarvis.cli_ctl.commands import conductor as conductor_cmdfrom jarvis.cli_ctl.commands import config as config_cmdfrom jarvis.cli_ctl.commands import contacts as contacts_cmd+from jarvis.cli_ctl.commands import costs as costs_cmdfrom jarvis.cli_ctl.commands import docs as docs_cmdfrom jarvis.cli_ctl.commands import friends as friends_cmdfrom jarvis.cli_ctl.commands import frontier as frontier_cmd@@ -129,6 +130,7 @@ app.add_typer(telephony_cmd.app, name="telephony")app.add_typer(marketplace_cmd.app, name="marketplace")app.add_typer(mcps_cmd.app, name="mcps")app.add_typer(clis_cmd.app, name="clis")+app.add_typer(costs_cmd.app, name="costs")app.add_typer(docs_cmd.app, name="docs")app.add_typer(frontier_cmd.app, name="frontier")app.add_typer(ide_cmd.app, name="ide")diff --git a/jarvis/cli_ctl/commands/costs.py b/jarvis/cli_ctl/commands/costs.pynew file mode 100644index 0000000000..feb6e8c77f--- /dev/null+++ b/jarvis/cli_ctl/commands/costs.py@@ -0,0 +1,83 @@+"""costs: what the app spent, per provider, model and role (/api/costs).++The same read model the Spend & Tokens section renders. Handy from a terminal+or a coding agent: ``jarvis --json costs summary --days 7`` answers "what did+this week cost, and where did it go" without opening the app.++Filters take comma-separated values (``--provider grok,gemini-live``); the+route accepts that spelling as well as repeated query parameters.+"""+from __future__ import annotations++import typer++from jarvis.cli_ctl import invoke++app = typer.Typer(+ no_args_is_help=True,+ help="Spend and token accounting: totals, line items, rates.",+)++_DAYS = typer.Option(30, "--days", help="Rolling window in days; 0 = everything recorded.")+_PROVIDER = typer.Option("", "--provider", help="Comma-separated provider ids.")+_MODEL = typer.Option("", "--model", help="Comma-separated model ids.")+_ROLE = typer.Option("", "--role", help="realtime | tool | pipeline | agent | worker.")+_SURFACE = typer.Option("", "--surface", help="voice | agent-chat | mission.")+_SEARCH = typer.Option("", "--search", help="Match model, provider or label.")+++def _filters(+ days: int, provider: str, model: str, role: str, surface: str, search: str+) -> dict[str, object]:+ params: dict[str, object] = {"days": days}+ for key, value in (+ ("provider", provider),+ ("model", model),+ ("role", role),+ ("surface", surface),+ ("search", search),+ ):+ if value.strip():+ params[key] = value.strip()+ return params+++def summary(+ days: int = _DAYS,+ provider: str = _PROVIDER,+ model: str = _MODEL,+ role: str = _ROLE,+ surface: str = _SURFACE,+ search: str = _SEARCH,+) -> None:+ """Totals plus the breakdown by provider, model, role, surface and day."""+ invoke.run(+ "GET",+ "/api/costs/summary",+ params=_filters(days, provider, model, role, surface, search),+ )+++def entries(+ days: int = _DAYS,+ provider: str = _PROVIDER,+ model: str = _MODEL,+ role: str = _ROLE,+ surface: str = _SURFACE,+ search: str = _SEARCH,+ sort: str = typer.Option("recent", "--sort", help="recent | cost | tokens."),+ limit: int = typer.Option(50, "--limit"),+ offset: int = typer.Option(0, "--offset"),+) -> None:+ """The individual model calls behind the totals."""+ params = _filters(days, provider, model, role, surface, search)+ params.update({"sort": sort, "limit": limit, "offset": offset})+ invoke.run("GET", "/api/costs/entries", params=params)+++def rates(days: int = _DAYS) -> None:+ """The rate card per model — and which models have no published rate."""+ invoke.run("GET", "/api/costs/pricing", params={"days": days})diff --git a/jarvis/costs/__init__.py b/jarvis/costs/__init__.pynew file mode 100644index 0000000000..60ebc45f99--- /dev/null+++ b/jarvis/costs/__init__.py@@ -0,0 +1,45 @@+"""Spend & token accounting — a read model over what the app already records.++Nothing here writes. Every number is derived from stores that other parts of+the app fill on their own (``sessions.db``, ``missions.db``,+``agent_chat.db``), so the section shows historic spend the moment it is+opened and can never race a live voice turn for a write lock.++Public surface:++- :class:`~jarvis.costs.model.CostEntry` — one normalised, priced line item.+- :func:`~jarvis.costs.sources.collect_entries` — read every source.+- :func:`~jarvis.costs.aggregate.build_report` — group, total, rank.+"""+from __future__ import annotations++from .aggregate import CostReport, build_report+from .model import (+ ROLE_AGENT,+ ROLE_PIPELINE,+ ROLE_REALTIME,+ ROLE_TOOL,+ ROLE_WORKER,+ SURFACE_AGENT_CHAT,+ SURFACE_MISSION,+ SURFACE_VOICE,+ CostEntry,+)+from .sources import CostSources, collect_entries, default_sources++__all__ = [+ "ROLE_AGENT",+ "ROLE_PIPELINE",+ "ROLE_REALTIME",+ "ROLE_TOOL",+ "ROLE_WORKER",+ "SURFACE_AGENT_CHAT",+ "SURFACE_MISSION",+ "SURFACE_VOICE",+ "CostEntry",+ "CostReport",+ "CostSources",+ "build_report",+ "collect_entries",+ "default_sources",+]diff --git a/jarvis/costs/aggregate.py b/jarvis/costs/aggregate.pynew file mode 100644index 0000000000..7e395628d9--- /dev/null+++ b/jarvis/costs/aggregate.py@@ -0,0 +1,324 @@+"""Grouping and totals — the shape the section actually renders.++One pass over the entries fills every breakdown at once (provider, model,+role, surface, day, and the most expensive references), because the list is+small enough to hold in memory and re-scanning it per dimension would only+add ways for two numbers on the same screen to disagree.++The totals deliberately keep three quantities apart that a naive sum blurs:++- what was **billed** (a recorded or re-derived price),+- what is **free** (local engines, subscription seats, ``:free`` models),+- what is **unaccounted** — tokens at a rate nobody publishes.++A dashboard that folds the third into the first reads "cheap" when it means+"unknown", which is the exact failure this section exists to prevent.+"""+from __future__ import annotations++from collections import defaultdict+from dataclasses import dataclass, field+from datetime import datetime, timedelta+from typing import Any++from .model import CostEntry++# Range shorter than this many days → hourly buckets, so "today" is a curve+# rather than a single bar.+_HOURLY_RANGE_MS = 3 * 24 * 60 * 60 * 1000+++@dataclass(slots=True)+class Bucket:+ """Running totals for one group key."""++ key: str+ cost_usd: float = 0.0+ tokens_in: int = 0+ tokens_out: int = 0+ tokens_cached: int = 0+ entries: int = 0+ gap_tokens: int = 0+ last_ts_ms: int = 0+ #: Secondary dimension — which providers/models/roles fed this bucket.+ members: dict[str, float] = field(default_factory=lambda: defaultdict(float))++ def add(self, entry: CostEntry, member: str = "") -> None:+ self.cost_usd += entry.cost_usd+ self.tokens_in += entry.tokens_in+ self.tokens_out += entry.tokens_out+ self.tokens_cached += entry.tokens_cached+ self.entries += 1+ if entry.is_gap:+ self.gap_tokens += entry.tokens_total+ self.last_ts_ms = max(self.last_ts_ms, entry.ts_ms)+ if member:+ self.members[member] += entry.cost_usd++ def to_dict(self, total_cost: float, total_tokens: int) -> dict[str, Any]:+ tokens = self.tokens_in + self.tokens_out + self.tokens_cached+ ranked = sorted(self.members.items(), key=lambda kv: -kv[1])+ return {+ "key": self.key,+ "cost_usd": round(self.cost_usd, 6),+ "tokens_in": self.tokens_in,+ "tokens_out": self.tokens_out,+ "tokens_cached": self.tokens_cached,+ "tokens_total": tokens,+ "entries": self.entries,+ "gap_tokens": self.gap_tokens,+ "last_ts_ms": self.last_ts_ms,+ "cost_share": round(self.cost_usd / total_cost, 6) if total_cost > 0 else 0.0,+ "token_share": round(tokens / total_tokens, 6) if total_tokens > 0 else 0.0,+ "members": [m for m, _ in ranked[:3]],+ # Second dimension of the same bucket: what a day cost per+ # role, what a provider cost per model. The stacked chart and+ # the row tooltips read from this — without it the section+ # would need a second request per dimension to say anything+ # about composition.+ "breakdown": {m: round(v, 6) for m, v in ranked[:8]},+ }+++@dataclass(slots=True)+class CostReport:+ """Everything one request of the section needs, already summed."""++ since_ms: int+ until_ms: int+ bucket: str+ totals: dict[str, Any]+ by_provider: list[dict[str, Any]]+ by_model: list[dict[str, Any]]+ by_role: list[dict[str, Any]]+ by_surface: list[dict[str, Any]]+ series: list[dict[str, Any]]+ top_refs: list[dict[str, Any]]+ models: list[dict[str, Any]]++ def to_dict(self) -> dict[str, Any]:+ return {+ "since_ms": self.since_ms,+ "until_ms": self.until_ms,+ "bucket": self.bucket,+ "totals": self.totals,+ "by_provider": self.by_provider,+ "by_model": self.by_model,+ "by_role": self.by_role,+ "by_surface": self.by_surface,+ "series": self.series,+ "top_refs": self.top_refs,+ "models": self.models,+ }+++def filter_entries(+ entries: list[CostEntry],+ *,+ providers: set[str] | None = None,+ models: set[str] | None = None,+ roles: set[str] | None = None,+ surfaces: set[str] | None = None,+ search: str = "",+) -> list[CostEntry]:+ """Narrow the line items. An empty filter set means "everything"."""+ needle = search.strip().casefold()++ def keep(e: CostEntry) -> bool:+ if providers and e.provider not in providers:+ return False+ if models and e.model not in models:+ return False+ if roles and e.role not in roles:+ return False+ if surfaces and e.surface not in surfaces:+ return False+ if needle and needle not in f"{e.model} {e.provider} {e.label}".casefold():+ return False+ return True++ return [e for e in entries if keep(e)]+++def build_report(+ entries: list[CostEntry],+ *,+ since_ms: int,+ until_ms: int,+ top_n: int = 12,+) -> CostReport:+ """Roll the entries up into every breakdown the section shows."""+ providers: dict[str, Bucket] = {}+ models: dict[str, Bucket] = {}+ roles: dict[str, Bucket] = {}+ surfaces: dict[str, Bucket] = {}+ series: dict[str, Bucket] = {}+ refs: dict[str, Bucket] = {}+ ref_labels: dict[str, str] = {}+ ref_surface: dict[str, str] = {}+ price_sources: dict[str, dict[str, Any]] = {}++ total_cost = 0.0+ tokens_in = tokens_out = tokens_cached = 0+ gap_tokens = gap_entries = 0+ free_tokens = 0+ derived_cost = 0.0++ hourly = (until_ms - since_ms) <= _HOURLY_RANGE_MS+ bucket_kind = "hour" if hourly else "day"++ for e in entries:+ total_cost += e.cost_usd+ tokens_in += e.tokens_in+ tokens_out += e.tokens_out+ tokens_cached += e.tokens_cached+ if e.is_gap:+ gap_tokens += e.tokens_total+ gap_entries += 1+ if e.price_source == "free":+ free_tokens += e.tokens_total+ if e.price_source == "derived":+ derived_cost += e.cost_usd++ _bucket(providers, e.provider).add(e, member=e.model or e.role)+ _bucket(models, e.model or f"{e.provider} (unnamed)").add(e, member=e.provider)+ _bucket(roles, e.role).add(e, member=e.provider)+ _bucket(surfaces, e.surface).add(e, member=e.role)+ _bucket(series, _stamp(e.ts_ms, hourly)).add(e, member=e.role)++ if e.ref_id:+ _bucket(refs, e.ref_id).add(e, member=e.model or e.provider)+ if e.label and not ref_labels.get(e.ref_id):+ ref_labels[e.ref_id] = e.label+ ref_surface.setdefault(e.ref_id, e.surface)++ if e.model:+ slot = price_sources.setdefault(+ e.model,+ {"model": e.model, "provider": e.provider, "sources": set(), "tokens": 0},+ )+ slot["sources"].add(e.price_source)+ slot["tokens"] += e.tokens_total++ total_tokens = tokens_in + tokens_out + tokens_cached+ totals = {+ "cost_usd": round(total_cost, 6),+ "tokens_in": tokens_in,+ "tokens_out": tokens_out,+ "tokens_cached": tokens_cached,+ "tokens_total": total_tokens,+ "entries": len(entries),+ "gap_tokens": gap_tokens,+ "gap_entries": gap_entries,+ "free_tokens": free_tokens,+ "estimated_usd": round(derived_cost, 6),+ "first_ts_ms": entries[0].ts_ms if entries else 0,+ "last_ts_ms": entries[-1].ts_ms if entries else 0,+ }++ return CostReport(+ since_ms=since_ms,+ until_ms=until_ms,+ bucket=bucket_kind,+ totals=totals,+ by_provider=_ranked(providers, total_cost, total_tokens, top_n),+ by_model=_ranked(models, total_cost, total_tokens, top_n),+ by_role=_ranked(roles, total_cost, total_tokens, len(roles) or 1),+ by_surface=_ranked(surfaces, total_cost, total_tokens, len(surfaces) or 1),+ series=_series(series, total_cost, total_tokens, hourly),+ top_refs=[+ {+ **row,+ "label": ref_labels.get(row["key"], ""),+ "surface": ref_surface.get(row["key"], ""),+ }+ for row in _ranked(refs, total_cost, total_tokens, top_n)+ ],+ models=sorted(+ (+ {+ "model": slot["model"],+ "provider": slot["provider"],+ "price_sources": sorted(slot["sources"]),+ "tokens_total": slot["tokens"],+ }+ for slot in price_sources.values()+ ),+ key=lambda m: -int(m["tokens_total"]),+ ),+ )+++# ---------------------------------------------------------------------------+# Helpers+# ---------------------------------------------------------------------------+++def _bucket(store: dict[str, Bucket], key: str) -> Bucket:+ key = key or "unknown"+ slot = store.get(key)+ if slot is None:+ slot = Bucket(key=key)+ store[key] = slot+ return slot+++def _stamp(ts_ms: int, hourly: bool) -> str:+ """Local-time bucket key — the user reasons in their own day, not UTC."""+ dt = datetime.fromtimestamp(max(0, ts_ms) / 1000)+ return dt.strftime("%Y-%m-%dT%H:00") if hourly else dt.strftime("%Y-%m-%d")+++def _ranked(+ store: dict[str, Bucket], total_cost: float, total_tokens: int, limit: int+) -> list[dict[str, Any]]:+ rows = sorted(+ store.values(),+ # Cost first; a bucket that spent nothing still ranks by the tokens it+ # burned, which is what makes unpriced models visible at all.+ key=lambda b: (-b.cost_usd, -(b.tokens_in + b.tokens_out + b.tokens_cached)),+ )+ return [b.to_dict(total_cost, total_tokens) for b in rows[:limit]]+++# A chart that only draws the days something happened compresses quiet+# stretches: three idle days look like one. Past this many buckets the gap+# filling stops — a multi-year range would otherwise render thousands of+# empty bars nobody can read anyway.+_MAX_SERIES_BUCKETS = 400+++def _series(+ store: dict[str, Bucket], total_cost: float, total_tokens: int, hourly: bool+) -> list[dict[str, Any]]:+ """The time series with every empty bucket in between filled in.++ Filled from the FIRST bucket that has data, not from the start of the+ requested window: a 90-day window whose data begins on day 60 should not+ open with 60 empty bars.+ """+ keys = sorted(store)+ if not keys:+ return []+ for key in _gap_keys(keys[0], keys[-1], hourly):+ store.setdefault(key, Bucket(key=key))+ return [store[key].to_dict(total_cost, total_tokens) for key in sorted(store)]+++def _gap_keys(first: str, last: str, hourly: bool) -> list[str]:+ """Every bucket key strictly between two stamps, in order."""+ fmt = "%Y-%m-%dT%H:00" if hourly else "%Y-%m-%d"+ step = timedelta(hours=1) if hourly else timedelta(days=1)+ try:+ cursor = datetime.strptime(first, fmt)+ end = datetime.strptime(last, fmt)+ except ValueError:+ # Silence is right: an unparsable stamp only costs the gap filling.+ # The series itself is already complete, so a chart with a few+ # missing zero-bars beats failing the whole report.+ return []+ keys: list[str] = []+ while cursor < end and len(keys) < _MAX_SERIES_BUCKETS:+ cursor += step+ keys.append(cursor.strftime(fmt))+ return keysdiff --git a/jarvis/costs/model.py b/jarvis/costs/model.pynew file mode 100644index 0000000000..b79c59f651--- /dev/null+++ b/jarvis/costs/model.py@@ -0,0 +1,168 @@+"""The normalised line item every cost source is reduced to.++Two vocabularies carry the whole section:++**Surface** — which part of the app spent it (voice, agent chat, a mission).+**Role** — what the model was doing in that surface. A realtime voice turn+that delegates one tool call to a text model spends on TWO roles at once, and+they bill at wildly different rates (Live-API audio tokens run 4-40x the text+rate of the same family), so a report that only knows "provider" hides the+single most useful answer: *what kind of work* the money went to.++Pricing honesty is the other half. A recorded ``cost_usd`` of 0.0 means one of+four very different things, and the UI must be able to tell them apart:++``recorded`` the source priced the call itself (realtime audio rates included)+``derived`` the source stored 0.0, we re-priced it from the rate tables+``free`` a local engine or an explicitly free model — 0.0 is the truth+``unknown`` tokens were spent, no rate exists anywhere — 0.0 is a GAP++Only ``unknown`` is a hole in the accounting, and it is reported as tokens,+never quietly folded into the total as if it were free.+"""+from __future__ import annotations++from dataclasses import dataclass+from typing import Any, Literal++# ---------------------------------------------------------------------------+# Vocabulary+# ---------------------------------------------------------------------------++SURFACE_VOICE = "voice"+SURFACE_AGENT_CHAT = "agent-chat"+SURFACE_MISSION = "mission"++ROLE_REALTIME = "realtime"+"""Speech-to-speech model — audio tokens, billed per Live/Realtime API rates."""++ROLE_TOOL = "tool"+"""Text model a realtime turn delegated a tool call to (``prefer_tool_model``)."""++ROLE_PIPELINE = "pipeline"+"""Brain of a classic STT → brain → TTS turn (the ``fast`` / ``deep`` tiers)."""++ROLE_AGENT = "agent"+"""A coding-agent turn (Claude Code, Codex, …) run from the chat surface."""++ROLE_WORKER = "worker"+"""An autonomous mission worker."""++ROLES: tuple[str, ...] = (ROLE_REALTIME, ROLE_TOOL, ROLE_PIPELINE, ROLE_AGENT, ROLE_WORKER)+SURFACES: tuple[str, ...] = (SURFACE_VOICE, SURFACE_AGENT_CHAT, SURFACE_MISSION)++PriceSource = Literal["recorded", "derived", "free", "unknown"]++# Providers that run on the user's own hardware: 0.00 is the correct price,+# not a missing one. Matched on the provider id as the stores record it.+LOCAL_PROVIDERS: frozenset[str] = frozenset(+ {+ "local",+ "local-realtime",+ "ollama",+ "llamacpp",+ "llama-cpp",+ "lmstudio",+ "vllm",+ "whisper-local",+ }+)++# Subscription-billed runners: the seat is paid monthly, per-call metering+# does not apply. Their tokens still count, their marginal cost does not.+SUBSCRIPTION_PROVIDERS: frozenset[str] = frozenset(+ {+ "codex-subscription-realtime",+ "codex-subscription",+ "claude-subscription",+ }+)+++@dataclass(frozen=True, slots=True)+class CostEntry:+ """One priced unit of spend, whatever produced it.++ ``tokens_cached`` is counted separately because cache reads are billed at+ a fraction of the input rate; a source that does not report them leaves+ it at 0 rather than folding them into ``tokens_in``.+ """++ ts_ms: int+ surface: str+ role: str+ provider: str+ model: str+ tokens_in: int+ tokens_out: int+ tokens_cached: int+ cost_usd: float+ price_source: PriceSource+ ref_id: str+ """Session / mission id — the thing a user can go look at."""+ label: str+ """Short human-readable handle for ``ref_id`` (session title, prompt head)."""++ @property+ def tokens_total(self) -> int:+ return self.tokens_in + self.tokens_out + self.tokens_cached++ @property+ def is_gap(self) -> bool:+ """True when tokens were spent at a price nobody knows."""+ return self.price_source == "unknown" and self.tokens_total > 0++ def to_dict(self) -> dict[str, Any]:+ return {+ "ts_ms": self.ts_ms,+ "surface": self.surface,+ "role": self.role,+ "provider": self.provider,+ "model": self.model,+ "tokens_in": self.tokens_in,+ "tokens_out": self.tokens_out,+ "tokens_cached": self.tokens_cached,+ "tokens_total": self.tokens_total,+ "cost_usd": round(self.cost_usd, 6),+ "price_source": self.price_source,+ "ref_id": self.ref_id,+ "label": self.label,+ }+++def price_entry(+ *,+ provider: str,+ model: str,+ tokens_in: int,+ tokens_out: int,+ recorded_usd: float,+) -> tuple[float, PriceSource]:+ """Settle what a call actually cost and how confident that number is.++ A recorded price always wins — the source that made the call knew the+ modality (audio vs text) and we do not. Everything else is re-derived from+ the shared rate tables so a model the price table gained later stops+ showing up as free.+ """+ if recorded_usd > 0:+ return float(recorded_usd), "recorded"++ tokens = max(0, tokens_in) + max(0, tokens_out)+ if tokens <= 0:+ # Nothing was consumed — a 0.0 with no tokens is not a pricing gap.+ return 0.0, "recorded"++ key = (provider or "").strip().casefold()+ if key in LOCAL_PROVIDERS or key in SUBSCRIPTION_PROVIDERS:+ return 0.0, "free"+ if model.strip().casefold().endswith(":free"):+ return 0.0, "free"++ # Lazy import: jarvis.brain.cost pulls the catalog cache and is not worth+ # loading for a request that never reaches an unpriced row.+ from jarvis.brain.cost import calculate_cost_usd, resolve_rates++ if not model or resolve_rates(model) is None:+ return 0.0, "unknown"+ return calculate_cost_usd(model, tokens_in, tokens_out), "derived"diff --git a/jarvis/costs/sources.py b/jarvis/costs/sources.pynew file mode 100644index 0000000000..9e8e87eecf--- /dev/null+++ b/jarvis/costs/sources.py@@ -0,0 +1,446 @@+"""Readers that turn each store's own shape into :class:`CostEntry` rows.++Every reader is defensive by design: a missing file, an older schema without+the column it wants, or a corrupt row must degrade to "this source+contributed nothing" and never to a failed request. A fresh install has none+of these databases yet, and the section still has to open.++Read-only, always: connections are opened in SQLite's immutable URI mode where+possible so a live voice turn writing to the same file is never blocked.+"""+from __future__ import annotations++import json+import logging+import sqlite3+from collections.abc import Iterator+from dataclasses import dataclass+from pathlib import Path++from .model import (+ ROLE_AGENT,+ ROLE_PIPELINE,+ ROLE_REALTIME,+ ROLE_TOOL,+ ROLE_WORKER,+ SURFACE_AGENT_CHAT,+ SURFACE_MISSION,+ SURFACE_VOICE,+ CostEntry,+ price_entry,+)++log = logging.getLogger(__name__)++_LABEL_MAX = 90++# A realtime provider reports its usage under this finish reason. It is the+# one reliable marker that separates audio spend from the text model a turn+# delegated to — both land in the same event stream.+_REALTIME_FINISH = "realtime_usage"++# Voice tiers that are not realtime run the classic pipeline.+_REALTIME_TIER = "realtime"+++@dataclass(frozen=True, slots=True)+class CostSources:+ """Where the read model looks. Absent files are simply skipped."""++ sessions_db: Path | None = None+ missions_db: Path | None = None+ agent_chat_db: Path | None = None++ def existing(self) -> list[Path]:+ candidates = (self.sessions_db, self.missions_db, self.agent_chat_db)+ return [p for p in candidates if p and p.exists()]++ def newest_mtime(self) -> float:+ """Latest mtime across the sources — the cache key for a report."""+ stamps = []+ for p in self.existing():+ try:+ stamps.append(p.stat().st_mtime)+ except OSError as exc: # pragma: no cover — race with a prune+ log.debug("cost source %s not stat-able: %s", p, exc)+ return max(stamps, default=0.0)+++def default_sources(data_dir: Path | None = None) -> CostSources:+ """Resolve the stores from the configured data directory.++ The data dir — not the process CWD — decides, so a second instance+ (``JARVIS_INSTANCE=dev``, which points ``memory.data_dir`` at ``data-dev/``)+ reports its own spend rather than the default app's.+ """+ root = data_dir+ if root is None:+ from jarvis.core import config as cfg++ root = Path(cfg.DATA_DIR)+ root = Path(root)+ return CostSources(+ sessions_db=root / "sessions.db",+ missions_db=root / "missions.db",+ agent_chat_db=root / "agent_chat.db",+ )+++# ---------------------------------------------------------------------------+# SQLite helpers+# ---------------------------------------------------------------------------+++def _connect(path: Path | None) -> sqlite3.Connection | None:+ """Open a read-only connection, or ``None`` when the file is unusable."""+ if path is None or not path.exists():+ return None+ try:+ conn = sqlite3.connect(f"file:{path.as_posix()}?mode=ro", uri=True, timeout=2.0)+ conn.row_factory = sqlite3.Row+ return conn+ except sqlite3.Error as exc:+ log.warning("cost read model: %s not readable (%s)", path, exc)+ return None+++def _has_table(conn: sqlite3.Connection, name: str) -> bool:+ row = conn.execute(+ "SELECT 1 FROM sqlite_master WHERE type='table' AND name=? LIMIT 1", (name,)+ ).fetchone()+ return row is not None+++def _clip(text: object, limit: int = _LABEL_MAX) -> str:+ s = " ".join(str(text or "").split())+ return s if len(s) <= limit else s[: limit - 1] + "…"+++def _int(value: object) -> int:+ try:+ return int(value or 0) # type: ignore[call-overload]+ except (TypeError, ValueError):+ # Silence is right: one malformed cell in a historic row means that+ # counter is 0, not that the section fails to open. The row still+ # carries its provider, model and timestamp.+ return 0+++def _float(value: object) -> float:+ try:+ return float(value or 0.0) # type: ignore[arg-type]+ except (TypeError, ValueError):+ # Silence is right for the same reason as _int: a broken price cell+ # falls back to 0.0 and is then re-derived from the rate tables.+ return 0.0+++# ---------------------------------------------------------------------------+# Voice — sessions.db+# ---------------------------------------------------------------------------+++def _voice_entries(path: Path | None, since_ms: int, until_ms: int) -> Iterator[CostEntry]:+ """Voice spend, at the finest granularity the store offers.++ ``voice_events`` records one ``BrainTurnCompleted`` per model call, which+ is what makes the realtime/tool split visible: a single realtime turn that+ delegates a tool call emits one event with ``realtime_usage`` (the audio+ model) and one with a normal finish reason (the text model that ran the+ tool). ``voice_turns`` only keeps the turn's winning provider, so it is+ used for the turn context — and as the fallback for turns recorded before+ the event stream existed.+ """+ conn = _connect(path)+ if conn is None:+ return+ try:+ if not _has_table(conn, "voice_turns"):+ return+ turns: dict[str, dict[str, object]] = {}+ for row in conn.execute(+ "SELECT id, session_id, started_ms, tier, provider, model, "+ " tokens_in, tokens_out, cost_usd, user_text "+ "FROM voice_turns WHERE started_ms BETWEEN ? AND ?",+ (since_ms, until_ms),+ ):+ turns[str(row["id"])] = dict(row)++ covered: set[str] = set()+ if _has_table(conn, "voice_events"):+ for row in conn.execute(+ "SELECT turn_id, session_id, ts_ms, payload_json FROM voice_events "+ "WHERE kind = 'BrainTurnCompleted' AND ts_ms BETWEEN ? AND ?",+ (since_ms, until_ms),+ ):+ try:+ payload = json.loads(row["payload_json"] or "{}")+ except (TypeError, ValueError) as exc:+ log.debug("cost read model: unparsable voice event payload (%s)", exc)+ continue+ if not isinstance(payload, dict):+ continue+ turn_id = str(row["turn_id"] or "")+ turn = turns.get(turn_id)+ if turn is not None:+ covered.add(turn_id)+ finish = str(payload.get("finish_reason") or "")+ tier = str((turn or {}).get("tier") or "")+ yield _voice_entry(+ ts_ms=_int(row["ts_ms"]),+ role=_voice_role(finish, tier),+ provider=str(payload.get("provider") or ""),+ model=str(payload.get("model") or ""),+ tokens_in=_int(payload.get("tokens_in")),+ tokens_out=_int(payload.get("tokens_out")),+ recorded_usd=_float(payload.get("cost_usd")),+ ref_id=str(row["session_id"] or ""),+ label=_clip((turn or {}).get("user_text")),+ )++ for turn_id, turn in turns.items():+ if turn_id in covered:+ continue+ tokens = _int(turn.get("tokens_in")) + _int(turn.get("tokens_out"))+ if tokens <= 0 and _float(turn.get("cost_usd")) <= 0:+ continue+ tier = str(turn.get("tier") or "")+ yield _voice_entry(+ ts_ms=_int(turn.get("started_ms")),+ role=ROLE_REALTIME if tier == _REALTIME_TIER else ROLE_PIPELINE,+ provider=str(turn.get("provider") or ""),+ model=str(turn.get("model") or ""),+ tokens_in=_int(turn.get("tokens_in")),+ tokens_out=_int(turn.get("tokens_out")),+ recorded_usd=_float(turn.get("cost_usd")),+ ref_id=str(turn.get("session_id") or ""),+ label=_clip(turn.get("user_text")),+ )+ except sqlite3.Error as exc:+ log.warning("cost read model: voice source failed (%s)", exc)+ finally:+ conn.close()+++def _voice_role(finish_reason: str, tier: str) -> str:+ """Which model in the turn spent this.++ Audio usage names itself. Anything else inside a realtime turn is the+ delegated tool model; outside one it is the pipeline brain.+ """+ if finish_reason == _REALTIME_FINISH:+ return ROLE_REALTIME+ return ROLE_TOOL if tier == _REALTIME_TIER else ROLE_PIPELINE+++def _voice_entry(+ *,+ ts_ms: int,+ role: str,+ provider: str,+ model: str,+ tokens_in: int,+ tokens_out: int,+ recorded_usd: float,+ ref_id: str,+ label: str,+) -> CostEntry:+ cost, source = price_entry(+ provider=provider,+ model=model,+ tokens_in=tokens_in,+ tokens_out=tokens_out,+ recorded_usd=recorded_usd,+ )+ return CostEntry(+ ts_ms=ts_ms,+ surface=SURFACE_VOICE,+ role=role,+ provider=provider or "unknown",+ model=model,+ tokens_in=tokens_in,+ tokens_out=tokens_out,+ tokens_cached=0,+ cost_usd=cost,+ price_source=source,+ ref_id=ref_id,+ label=label,+ )+++# ---------------------------------------------------------------------------+# Agent chat — agent_chat.db+# ---------------------------------------------------------------------------++# Every runner names its usage differently; these are the buckets each key+# belongs in. Cache CREATION is billed like input (at a premium), cache READS+# are the cheap bucket — they are kept apart so the UI can show both.+_AGENT_IN_KEYS = (+ "input_tokens",+ "prompt_tokens",+ "cache_creation_input_tokens",+ "cache_write_input_tokens",+)+_AGENT_OUT_KEYS = (+ "output_tokens",+ "completion_tokens",+ "reasoning_output_tokens",+ "thinking_tokens",+)+_AGENT_CACHED_KEYS = ("cache_read_input_tokens", "cached_input_tokens", "cache_read_tokens")+++def _agent_chat_entries(path: Path | None, since_ms: int, until_ms: int) -> Iterator[CostEntry]:+ """One entry per finished agent-chat turn (Claude Code, Codex, …)."""+ conn = _connect(path)+ if conn is None:+ return+ try:+ if not _has_table(conn, "agent_chat_events"):+ return+ sessions: dict[str, sqlite3.Row] = {}+ if _has_table(conn, "agent_chat_sessions"):+ for row in conn.execute(+ "SELECT session_id, title, provider, model FROM agent_chat_sessions"+ ):+ sessions[str(row["session_id"])] = row++ for row in conn.execute(+ "SELECT session_id, ts_ms, payload FROM agent_chat_events "+ "WHERE kind = 'turn_finished' AND ts_ms BETWEEN ? AND ?",+ (since_ms, until_ms),+ ):+ try:+ payload = json.loads(row["payload"] or "{}")+ except (TypeError, ValueError) as exc:+ log.debug("cost read model: unparsable agent chat payload (%s)", exc)+ continue+ if not isinstance(payload, dict):+ continue+ usage = payload.get("usage")+ usage = usage if isinstance(usage, dict) else {}+ tokens_in = sum(_int(usage.get(k)) for k in _AGENT_IN_KEYS)+ tokens_out = sum(_int(usage.get(k)) for k in _AGENT_OUT_KEYS)+ tokens_cached = sum(_int(usage.get(k)) for k in _AGENT_CACHED_KEYS)+ recorded = _float(payload.get("cost_usd"))+ if tokens_in + tokens_out + tokens_cached <= 0 and recorded <= 0:+ continue+ session = sessions.get(str(row["session_id"] or ""))+ provider = str(session["provider"] if session is not None else "") or "agent-cli"+ model = str(session["model"] if session is not None else "")+ cost, source = price_entry(+ provider=provider,+ model=model,+ tokens_in=tokens_in,+ tokens_out=tokens_out,+ recorded_usd=recorded,+ )+ yield CostEntry(+ ts_ms=_int(row["ts_ms"]),+ surface=SURFACE_AGENT_CHAT,+ role=ROLE_AGENT,+ provider=provider,+ model=model,+ tokens_in=tokens_in,+ tokens_out=tokens_out,+ tokens_cached=tokens_cached,+ cost_usd=cost,+ price_source=source,+ ref_id=str(row["session_id"] or ""),+ label=_clip(session["title"] if session is not None else ""),+ )+ except sqlite3.Error as exc:+ log.warning("cost read model: agent chat source failed (%s)", exc)+ finally:+ conn.close()+++# ---------------------------------------------------------------------------+# Missions — missions.db+# ---------------------------------------------------------------------------+++def _mission_entries(path: Path | None, since_ms: int, until_ms: int) -> Iterator[CostEntry]:+ """Autonomous worker spend, per draft the worker delivered.++ ``WorkerDraftReady`` carries the worker's own ``tokens_used`` / ``cost_usd``.+ A worker driven by a subscription CLI reports zeros — that is the honest+ number (the seat is paid monthly), and it is labelled as such rather than+ left looking like missing data.+ """+ conn = _connect(path)+ if conn is None:+ return+ try:+ if not _has_table(conn, "mission_events") or not _has_table(conn, "missions"):+ return+ prompts: dict[str, str] = {+ str(r["id"]): _clip(r["prompt"])+ for r in conn.execute("SELECT id, prompt FROM missions")+ }+ for row in conn.execute(+ "SELECT mission_id, worker_id, ts_ms, payload_json FROM mission_events "+ "WHERE event_type = 'WorkerDraftReady' AND ts_ms BETWEEN ? AND ?",+ (since_ms, until_ms),+ ):+ try:+ payload = json.loads(row["payload_json"] or "{}")+ except (TypeError, ValueError) as exc:+ log.debug("cost read model: unparsable mission payload (%s)", exc)+ continue+ if not isinstance(payload, dict):+ continue+ tokens = _int(payload.get("tokens_used"))+ recorded = _float(payload.get("cost_usd"))+ if tokens <= 0 and recorded <= 0:+ continue+ provider = str(payload.get("provider") or "mission-worker")+ model = str(payload.get("model") or "")+ cost, source = price_entry(+ provider=provider,+ model=model,+ tokens_in=tokens,+ tokens_out=0,+ recorded_usd=recorded,+ )+ mission_id = str(row["mission_id"] or "")+ yield CostEntry(+ ts_ms=_int(row["ts_ms"]),+ surface=SURFACE_MISSION,+ role=ROLE_WORKER,+ provider=provider,+ model=model,+ # The worker reports a single total; splitting it into a made-up+ # in/out ratio would be a lie, so it counts as input.+ tokens_in=tokens,+ tokens_out=0,+ tokens_cached=0,+ cost_usd=cost,+ price_source=source,+ ref_id=mission_id,+ label=prompts.get(mission_id, ""),+ )+ except sqlite3.Error as exc:+ log.warning("cost read model: mission source failed (%s)", exc)+ finally:+ conn.close()+++# ---------------------------------------------------------------------------+# Public+# ---------------------------------------------------------------------------+++def collect_entries(+ sources: CostSources,+ *,+ since_ms: int = 0,+ until_ms: int = 2**62,+) -> list[CostEntry]:+ """Every priced line item across all sources, newest last."""+ entries: list[CostEntry] = []+ entries.extend(_voice_entries(sources.sessions_db, since_ms, until_ms))+ entries.extend(_agent_chat_entries(sources.agent_chat_db, since_ms, until_ms))+ entries.extend(_mission_entries(sources.missions_db, since_ms, until_ms))+ entries.sort(key=lambda e: e.ts_ms)+ return entriesdiff --git a/jarvis/plugins/tool/navigate.py b/jarvis/plugins/tool/navigate.pyindex c625b67977..99073babe4 100644--- a/jarvis/plugins/tool/navigate.py+++ b/jarvis/plugins/tool/navigate.py@@ -31,6 +31,8 @@ KNOWN: frozenset[str] = frozenset("tasks","sessions","run_inspector",+ # Spend & Tokens.+ "costs","clis","cli-test-hub","board",@@ -110,6 +112,17 @@ _ALIASES: dict[str, str] = {"transcription": "sessions","session": "sessions","cli": "clis",+ "kosten": "costs", # i18n-allow: input vocab+ "kostenübersicht": "costs", # i18n-allow: input vocab+ "verbrauch": "costs", # i18n-allow: input vocab+ "token-kosten": "costs", # i18n-allow: input vocab+ "token": "costs",+ "tokens": "costs",+ "spend": "costs",+ "spending": "costs",+ "billing": "costs",+ "costes": "costs", # i18n-allow: input vocab+ "gastos": "costs", # i18n-allow: input vocab"cli test hub": "cli-test-hub","test hub": "cli-test-hub","testhub": "cli-test-hub",diff --git a/jarvis/ui/web/costs_routes.py b/jarvis/ui/web/costs_routes.pynew file mode 100644index 0000000000..07343a7126--- /dev/null+++ b/jarvis/ui/web/costs_routes.py@@ -0,0 +1,398 @@+"""REST routes for the Spend & Tokens section.++Endpoints::++ GET /api/costs/summary Totals + every breakdown for a time range+ GET /api/costs/entries The individual line items behind those totals+ GET /api/costs/pricing The rate card each seen model was priced with++Wired in by the WebServer in ``_build_app()``::++ from .costs_routes import router as costs_router+ app.include_router(costs_router)++There is no store to inject: the section is a read model over the databases+the rest of the app already writes (see ``jarvis/costs/``). The only state+here is a small in-process cache keyed on the sources' mtime, so repeatedly+switching a filter in the UI does not re-read three SQLite files each time.++Loopback-only (the server binds to 127.0.0.1) — no auth token needed.+"""+from __future__ import annotations++import logging+import threading+import time+from pathlib import Path+from typing import Annotated, Any++from fastapi import APIRouter, Query, Request+from pydantic import BaseModel, Field++from jarvis.costs import CostEntry, CostSources, build_report, collect_entries, default_sources+from jarvis.costs.aggregate import filter_entries+from jarvis.costs.model import ROLES, SURFACES++log = logging.getLogger(__name__)++router = APIRouter(prefix="/api/costs", tags=["costs"])++# Default exchange rate when jarvis.toml carries no [cost] section. The UI+# labels EUR as a conversion, never as a billed amount — providers bill USD.+_FALLBACK_EUR_PER_USD = 0.92++_DAY_MS = 24 * 60 * 60 * 1000+++# ---------------------------------------------------------------------------+# Response models+# ---------------------------------------------------------------------------+++class Bucket(BaseModel):+ key: str+ cost_usd: float+ tokens_in: int+ tokens_out: int+ tokens_cached: int+ tokens_total: int+ entries: int+ gap_tokens: int+ last_ts_ms: int+ cost_share: float+ token_share: float+ members: list[str] = Field(default_factory=list)+ breakdown: dict[str, float] = Field(default_factory=dict)+ """Cost per member of the bucket's second dimension (day → role, …)."""+++class RefBucket(Bucket):+ label: str = ""+ surface: str = ""+++class Totals(BaseModel):+ cost_usd: float+ tokens_in: int+ tokens_out: int+ tokens_cached: int+ tokens_total: int+ entries: int+ gap_tokens: int+ """Tokens spent at a rate no price table knows — the accounting hole."""+ gap_entries: int+ free_tokens: int+ """Tokens on local engines, subscription seats or ``:free`` models."""+ estimated_usd: float+ """Share of ``cost_usd`` this section re-derived rather than read back."""+ first_ts_ms: int+ last_ts_ms: int+++class ModelRow(BaseModel):+ model: str+ provider: str+ price_sources: list[str]+ tokens_total: int+++class Facets(BaseModel):+ """Filter options, always built from the UNfiltered range.++ A filter that removes its own options is a dead end — picking a provider+ must never make the other providers disappear from the picker.+ """++ providers: list[str]+ models: list[str]+ roles: list[str]+ surfaces: list[str]+++class Currency(BaseModel):+ eur_per_usd: float+ source: str+ """``config`` when jarvis.toml set a rate, ``default`` otherwise."""+++class CostSummary(BaseModel):+ since_ms: int+ until_ms: int+ bucket: str+ """``day`` or ``hour`` — the granularity of ``series``."""+ totals: Totals+ by_provider: list[Bucket]+ by_model: list[Bucket]+ by_role: list[Bucket]+ by_surface: list[Bucket]+ series: list[Bucket]+ top_refs: list[RefBucket]+ models: list[ModelRow]+ facets: Facets+ currency: Currency+ sources_present: list[str]+ """Which stores actually existed — an empty section is explainable."""+++class EntryRow(BaseModel):+ ts_ms: int+ surface: str+ role: str+ provider: str+ model: str+ tokens_in: int+ tokens_out: int+ tokens_cached: int+ tokens_total: int+ cost_usd: float+ price_source: str+ ref_id: str+ label: str+++class EntriesPage(BaseModel):+ items: list[EntryRow]+ total: int+ limit: int+ offset: int+++class RateRow(BaseModel):+ model: str+ input_usd_per_mtok: float | None+ output_usd_per_mtok: float | None+ audio_input_usd_per_mtok: float | None = None+ audio_output_usd_per_mtok: float | None = None+ known: bool+++class PricingResponse(BaseModel):+ rates: list[RateRow]+ currency: Currency+++# ---------------------------------------------------------------------------+# Entry cache — three SQLite reads per request would be wasteful, not wrong+# ---------------------------------------------------------------------------+++class _EntryCache:+ """Caches the collected entries until a source file changes.++ The key is (data dir, newest source mtime, range). A live voice turn+ updates sessions.db, the mtime moves, the next request re-reads — so the+ section is never stale, and switching a filter costs nothing.+ """++ _TTL_S = 15.0++ def __init__(self) -> None:+ self._lock = threading.Lock()+ self._key: tuple[Any, ...] | None = None+ self._entries: list[CostEntry] = []+ self._at = 0.0++ def get(self, sources: CostSources, since_ms: int, until_ms: int) -> list[CostEntry]:+ key = (+ str(sources.sessions_db),+ round(sources.newest_mtime(), 3),+ since_ms,+ until_ms,+ )+ now = time.monotonic()+ with self._lock:+ if self._key == key and (now - self._at) < self._TTL_S:+ return self._entries+ entries = collect_entries(sources, since_ms=since_ms, until_ms=until_ms)+ with self._lock:+ self._key = key+ self._entries = entries+ self._at = now+ return entries+++_cache = _EntryCache()+++# ---------------------------------------------------------------------------+# Helpers+# ---------------------------------------------------------------------------+++def _sources(request: Request) -> CostSources:+ """Point the read model at the data dir this instance actually uses."""+ cfg = getattr(request.app.state, "config", None)+ data_dir = getattr(getattr(cfg, "memory", None), "data_dir", None)+ return default_sources(Path(data_dir) if data_dir else None)+++def _currency() -> Currency:+ """Read ``[cost].eur_per_usd`` from the active config file.++ Read straight from the TOML rather than through the config model: the+ ``[cost]`` section predates the typed schema and carries no other reader,+ and a display-only exchange rate is not worth a schema migration.+ """+ try:+ import tomllib++ from jarvis.core.config import resolve_config_path++ path = resolve_config_path()+ if path.exists():+ data = tomllib.loads(path.read_text(encoding="utf-8-sig"))+ raw = data.get("cost", {}).get("eur_per_usd")+ if isinstance(raw, int | float) and raw > 0:+ return Currency(eur_per_usd=float(raw), source="config")+ except (OSError, ValueError) as exc:+ # A malformed config must not take the section down; the fallback+ # rate is clearly labelled as such in the response.+ log.debug("costs: exchange rate not readable from config (%s)", exc)+ return Currency(eur_per_usd=_FALLBACK_EUR_PER_USD, source="default")+++def _range(days: int, since_ms: int | None, until_ms: int | None) -> tuple[int, int]:+ """Explicit bounds win; otherwise the last ``days`` days up to now.++ ``days=0`` means "everything ever recorded" — the section is also a+ lifetime ledger, not only a rolling window.+ """+ now = int(time.time() * 1000)+ end = until_ms if until_ms is not None else now+ if since_ms is not None:+ return since_ms, end+ if days <= 0:+ return 0, end+ return end - days * _DAY_MS, end+++def _facets(entries: list[CostEntry]) -> Facets:+ providers = sorted({e.provider for e in entries if e.provider})+ models = sorted({e.model for e in entries if e.model})+ roles = [r for r in ROLES if any(e.role == r for e in entries)]+ surfaces = [s for s in SURFACES if any(e.surface == s for e in entries)]+ return Facets(providers=providers, models=models, roles=roles, surfaces=surfaces)+++def _split(values: list[str] | None) -> set[str]:+ """Accept both repeated params and one comma-separated value."""+ out: set[str] = set()+ for raw in values or []:+ out.update(part.strip() for part in raw.split(",") if part.strip())+ return out+++# ---------------------------------------------------------------------------+# Routes+# ---------------------------------------------------------------------------++[email protected]("/summary", response_model=CostSummary, summary="Spend and token totals")+async def get_summary(+ request: Request,+ days: Annotated[int, Query(ge=0, le=3650)] = 30,+ since_ms: Annotated[int | None, Query(ge=0)] = None,+ until_ms: Annotated[int | None, Query(ge=0)] = None,+ provider: Annotated[list[str] | None, Query()] = None,+ model: Annotated[list[str] | None, Query()] = None,+ role: Annotated[list[str] | None, Query()] = None,+ surface: Annotated[list[str] | None, Query()] = None,+ search: str = "",+ top: Annotated[int, Query(ge=1, le=100)] = 12,+) -> CostSummary:+ """Every breakdown of what the app spent: by provider, model, role, day.++ ``days=0`` reports everything ever recorded. Filters narrow the numbers+ but never the filter options themselves.+ """+ sources = _sources(request)+ start, end = _range(days, since_ms, until_ms)+ entries = _cache.get(sources, start, end)+ selected = filter_entries(+ entries,+ providers=_split(provider),+ models=_split(model),+ roles=_split(role),+ surfaces=_split(surface),+ search=search,+ )+ report = build_report(selected, since_ms=start, until_ms=end, top_n=top)+ payload = report.to_dict()+ payload["facets"] = _facets(entries).model_dump()+ payload["currency"] = _currency().model_dump()+ payload["sources_present"] = [p.name for p in sources.existing()]+ return CostSummary.model_validate(payload)++[email protected]("/entries", response_model=EntriesPage, summary="Individual spend line items")+async def get_entries(+ request: Request,+ days: Annotated[int, Query(ge=0, le=3650)] = 30,+ since_ms: Annotated[int | None, Query(ge=0)] = None,+ until_ms: Annotated[int | None, Query(ge=0)] = None,+ provider: Annotated[list[str] | None, Query()] = None,+ model: Annotated[list[str] | None, Query()] = None,+ role: Annotated[list[str] | None, Query()] = None,+ surface: Annotated[list[str] | None, Query()] = None,+ search: str = "",+ sort: Annotated[str, Query(pattern="^(recent|cost|tokens)$")] = "recent",+ limit: Annotated[int, Query(ge=1, le=500)] = 100,+ offset: Annotated[int, Query(ge=0)] = 0,+) -> EntriesPage:+ """The rows behind the totals — one per model call, newest first."""+ sources = _sources(request)+ start, end = _range(days, since_ms, until_ms)+ entries = filter_entries(+ _cache.get(sources, start, end),+ providers=_split(provider),+ models=_split(model),+ roles=_split(role),+ surfaces=_split(surface),+ search=search,+ )+ if sort == "cost":+ entries = sorted(entries, key=lambda e: -e.cost_usd)+ elif sort == "tokens":+ entries = sorted(entries, key=lambda e: -e.tokens_total)+ else:+ entries = sorted(entries, key=lambda e: -e.ts_ms)+ page = entries[offset : offset + limit]+ return EntriesPage(+ items=[EntryRow.model_validate(e.to_dict()) for e in page],+ total=len(entries),+ limit=limit,+ offset=offset,+ )++[email protected]("/pricing", response_model=PricingResponse, summary="Rate card per model")+async def get_pricing(+ request: Request,+ days: Annotated[int, Query(ge=0, le=3650)] = 30,+) -> PricingResponse:+ """What each model seen in the range is priced at, per million tokens.++ A model with ``known=false`` is why a ``gap_tokens`` number is not zero:+ it was used, and neither the built-in table nor the provider feed has a+ rate for it.+ """+ from jarvis.brain.cost import REALTIME_AUDIO_PRICING_USD_PER_MTOK, resolve_rates++ sources = _sources(request)+ start, end = _range(days, None, None)+ seen = {e.model for e in _cache.get(sources, start, end) if e.model}+ rows: list[RateRow] = []+ for name in sorted(seen):+ rates = resolve_rates(name)+ audio = REALTIME_AUDIO_PRICING_USD_PER_MTOK.get(name)+ rows.append(+ RateRow(+ model=name,+ input_usd_per_mtok=rates[0] if rates else None,+ output_usd_per_mtok=rates[1] if rates else None,+ audio_input_usd_per_mtok=audio[0] if audio else None,+ audio_output_usd_per_mtok=audio[1] if audio else None,+ known=rates is not None or audio is not None,+ )+ )+ return PricingResponse(rates=rows, currency=_currency())diff --git a/jarvis/ui/web/frontend/src/components/costs/CostTrendChart.tsx b/jarvis/ui/web/frontend/src/components/costs/CostTrendChart.tsxnew file mode 100644index 0000000000..192bd7f858--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/costs/CostTrendChart.tsx@@ -0,0 +1,244 @@+/**+ * The spend curve — one bar per day (or hour), split by what it went to.+ *+ * Two modes, because "how much" has two honest answers here: money, stacked by+ * role, and tokens, stacked by direction (in / out / cache reads). They are+ * deliberately not one chart with a second axis — a dollar bar and a token bar+ * on the same grid invite reading a shape that is not there.+ */+import { useMemo } from "react";+import {+ Bar,+ BarChart,+ CartesianGrid,+ Cell,+ ResponsiveContainer,+ Tooltip,+ XAxis,+ YAxis,+} from "recharts";+import type { CostBucket } from "@/hooks/useCosts";+import { useT } from "@/i18n";+import {+ ROLE_ORDER,+ formatBucketFull,+ formatBucketTick,+ formatMoney,+ formatTokens,+ roleColor,+ roleLabelKey,+} from "./costFormat";++export type TrendMetric = "cost" | "tokens";++interface Props {+ series: CostBucket[];+ bucket: "day" | "hour";+ metric: TrendMetric;+ currency: "usd" | "eur";+ eurPerUsd: number;+ /** Bar the pointer selects; clicking it filters the section to that bucket. */+ onSelect?: (key: string) => void;+}++interface Point {+ key: string;+ total: number;+ tokens_in: number;+ tokens_out: number;+ tokens_cached: number;+ [role: string]: string | number;+}++const AXIS_TINT = "hsl(0 0% 50%)";+const TOKEN_COLORS = {+ tokens_in: "hsl(199 90% 62%)",+ tokens_out: "hsl(50 100% 52%)",+ tokens_cached: "hsl(268 72% 68%)",+} as const;++export function CostTrendChart({+ series,+ bucket,+ metric,+ currency,+ eurPerUsd,+ onSelect,+}: Props) {+ const t = useT();++ // Which role stacks actually occur — an empty stack still renders a legend+ // entry in Recharts, and a legend full of zeroes reads as missing data.+ const roles = useMemo(() => {+ const present = new Set<string>();+ for (const b of series) for (const k of Object.keys(b.breakdown ?? {})) present.add(k);+ return ROLE_ORDER.filter((r) => present.has(r));+ }, [series]);++ const data: Point[] = useMemo(+ () =>+ series.map((b) => {+ const point: Point = {+ key: b.key,+ total: b.cost_usd,+ tokens_in: b.tokens_in,+ tokens_out: b.tokens_out,+ tokens_cached: b.tokens_cached,+ };+ for (const role of roles) point[role] = b.breakdown?.[role] ?? 0;+ return point;+ }),+ [series, roles],+ );++ if (data.length === 0) {+ return (+ <div className="flex h-full min-h-[180px] items-center justify-center text-xs text-muted-foreground">+ {t("costs_view.chart_empty")}+ </div>+ );+ }++ const stacks: { dataKey: string; color: string; labelKey: string }[] =+ metric === "cost"+ ? roles.map((r) => ({ dataKey: r, color: roleColor(r), labelKey: roleLabelKey(r) }))+ : [+ {+ dataKey: "tokens_in",+ color: TOKEN_COLORS.tokens_in,+ labelKey: "costs_view.tokens_in",+ },+ {+ dataKey: "tokens_out",+ color: TOKEN_COLORS.tokens_out,+ labelKey: "costs_view.tokens_out",+ },+ {+ dataKey: "tokens_cached",+ color: TOKEN_COLORS.tokens_cached,+ labelKey: "costs_view.tokens_cached",+ },+ ];++ return (+ <div className="flex h-full min-h-0 flex-col gap-2">+ <ResponsiveContainer+ width="100%"+ height="100%"+ // Same guard as the board's trend chart: without a positive floor the+ // first measure is 0x0 and the bars bake in a collapsed scale.+ minHeight={172}+ minWidth={0}+ initialDimension={{ width: 640, height: 200 }}+ >+ <BarChart data={data} margin={{ top: 8, right: 4, bottom: 0, left: 4 }} barCategoryGap="18%">+ <CartesianGrid vertical={false} stroke="hsl(0 0% 50% / 0.14)" strokeDasharray="2 4" />+ <XAxis+ dataKey="key"+ tickFormatter={(k: string) => formatBucketTick(k, bucket)}+ tick={{ fill: AXIS_TINT, fontSize: 10 }}+ axisLine={false}+ tickLine={false}+ minTickGap={28}+ dy={4}+ />+ <YAxis+ width={52}+ tick={{ fill: AXIS_TINT, fontSize: 10 }}+ axisLine={false}+ tickLine={false}+ tickFormatter={(v: number) =>+ metric === "cost" ? formatMoney(v, eurPerUsd, currency) : formatTokens(v)+ }+ />+ <Tooltip+ cursor={{ fill: "hsl(0 0% 50% / 0.08)" }}+ content={+ <TrendTooltip+ bucket={bucket}+ metric={metric}+ currency={currency}+ eurPerUsd={eurPerUsd}+ stacks={stacks}+ t={t}+ />+ }+ />+ {stacks.map((s, i) => (+ <Bar+ key={s.dataKey}+ dataKey={s.dataKey}+ stackId="a"+ fill={s.color}+ isAnimationActive={false}+ // Only the top segment gets the rounded cap, so a stack reads as+ // one bar rather than a pile of separate pills.+ radius={i === stacks.length - 1 ? [3, 3, 0, 0] : undefined}+ onClick={(entry: { payload?: Point }) =>+ onSelect && entry?.payload ? onSelect(String(entry.payload.key)) : undefined+ }+ >+ {onSelect+ ? data.map((d) => <Cell key={d.key} cursor="pointer" />)+ : null}+ </Bar>+ ))}+ </BarChart>+ </ResponsiveContainer>+ <div className="flex flex-wrap items-center gap-x-4 gap-y-1 px-1">+ {stacks.map((s) => (+ <span key={s.dataKey} className="flex items-center gap-1.5 text-[11px] text-muted-foreground">+ <span className="h-2 w-2 rounded-[2px]" style={{ background: s.color }} />+ {t(s.labelKey)}+ </span>+ ))}+ </div>+ </div>+ );+}++interface TooltipItem {+ dataKey: string;+ value: number;+}++function TrendTooltip(props: {+ active?: boolean;+ payload?: TooltipItem[];+ label?: string;+ bucket: "day" | "hour";+ metric: TrendMetric;+ currency: "usd" | "eur";+ eurPerUsd: number;+ stacks: { dataKey: string; color: string; labelKey: string }[];+ t: (key: string) => string;+}) {+ const { active, payload, label, bucket, metric, currency, eurPerUsd, stacks, t } = props;+ if (!active || !payload || payload.length === 0) return null;+ const total = payload.reduce((sum, p) => sum + (p.value ?? 0), 0);+ const fmt = (v: number) =>+ metric === "cost" ? formatMoney(v, eurPerUsd, currency) : formatTokens(v);++ return (+ <div className="min-w-[170px] rounded-lg border border-border bg-popover/95 px-3 py-2 text-xs shadow-xl backdrop-blur">+ <div className="mb-1.5 font-medium text-foreground">+ {formatBucketFull(String(label ?? ""), bucket)}+ </div>+ {stacks.map((s) => {+ const value = payload.find((p) => p.dataKey === s.dataKey)?.value ?? 0;+ if (!value) return null;+ return (+ <div key={s.dataKey} className="flex items-center gap-2 py-0.5">+ <span className="h-2 w-2 rounded-[2px]" style={{ background: s.color }} />+ <span className="text-muted-foreground">{t(s.labelKey)}</span>+ <span className="ml-auto font-semibold tabular-nums text-foreground">{fmt(value)}</span>+ </div>+ );+ })}+ <div className="mt-1.5 flex items-center gap-2 border-t border-border pt-1.5">+ <span className="text-muted-foreground">{t("costs_view.total")}</span>+ <span className="ml-auto font-semibold tabular-nums text-foreground">{fmt(total)}</span>+ </div>+ </div>+ );+}diff --git a/jarvis/ui/web/frontend/src/components/costs/costFormat.test.ts b/jarvis/ui/web/frontend/src/components/costs/costFormat.test.tsnew file mode 100644index 0000000000..4100a3480f--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/costs/costFormat.test.ts@@ -0,0 +1,73 @@+import { describe, expect, it } from "vitest";+import {+ formatMoney,+ formatShare,+ formatTokens,+ keyColor,+ priceSourceTone,+ roleColor,+} from "./costFormat";++describe("formatMoney", () => {+ it("keeps sub-cent amounts visible instead of rounding them to zero", () => {+ // A single tool call really does cost $0.0004; "$0.00" would tell the user+ // their most frequent call is free.+ expect(formatMoney(0.0004, 0.92, "usd")).toBe("$0.0004");+ });++ it("uses two decimals for ordinary amounts and drops them for large ones", () => {+ expect(formatMoney(11.7, 0.92, "usd")).toBe("$11.70");+ // Locale-agnostic: the grouping separator is the test runner's locale,+ // the point of the assertion is that the cents are gone.+ expect(formatMoney(1234.56, 0.92, "usd")).toMatch(/^\$1[.,]235$/);+ });++ it("converts to EUR at the given rate", () => {+ expect(formatMoney(10, 0.9, "eur")).toBe("€9.00");+ });++ it("renders a true zero without decimals inflation", () => {+ expect(formatMoney(0, 0.92, "usd")).toBe("$0.00");+ });+});++describe("formatTokens", () => {+ it("scales the unit to the magnitude", () => {+ expect(formatTokens(999)).toBe("999");+ expect(formatTokens(1_240)).toBe("1.2k");+ expect(formatTokens(12_823_750)).toBe("12.82M");+ });+});++describe("formatShare", () => {+ it("never rounds a non-zero share down to 0%", () => {+ expect(formatShare(0)).toBe("0%");+ expect(formatShare(0.0002)).toBe("<0.1%");+ expect(formatShare(0.671)).toBe("67%");+ });+});++describe("colours", () => {+ it("gives every role its own fixed hue", () => {+ const roles = ["realtime", "tool", "pipeline", "agent", "worker"];+ expect(new Set(roles.map(roleColor)).size).toBe(roles.length);+ });++ it("keeps an arbitrary key's colour stable across renders", () => {+ expect(keyColor("gemini-live")).toBe(keyColor("gemini-live"));+ expect(keyColor("grok")).not.toBe(keyColor("gemini-live"));+ });++ it("routes a role key through the role palette", () => {+ expect(keyColor("tool")).toBe(roleColor("tool"));+ });+});++describe("priceSourceTone", () => {+ it("marks only an unpriced call as an error tone", () => {+ expect(priceSourceTone("recorded")).toBe("ok");+ expect(priceSourceTone("derived")).toBe("warn");+ expect(priceSourceTone("free")).toBe("off");+ expect(priceSourceTone("unknown")).toBe("error");+ });+});diff --git a/jarvis/ui/web/frontend/src/components/costs/costFormat.ts b/jarvis/ui/web/frontend/src/components/costs/costFormat.tsnew file mode 100644index 0000000000..d8c9b6c7a2--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/costs/costFormat.ts@@ -0,0 +1,147 @@+/**+ * Shared vocabulary of the Spend & Tokens section: colours, formatters, tone.+ *+ * Colours are picked mid-luminance on purpose. They sit on the dark app+ * background and on the light one without a second table, which is the rule+ * every chart in this app follows (see `board/WordsTrendChart`): a hue that+ * only works in one appearance is a bug in the other.+ */+import type { CostRole, CostSurface, PriceSource } from "@/hooks/useCosts";++/** One hue per role — the chart stack, the legend and the tables share it. */+export const ROLE_COLORS: Record<CostRole, string> = {+ realtime: "hsl(199 90% 62%)", // sky — the voice you talk to+ tool: "hsl(50 100% 52%)", // signal yellow — the app's primary+ pipeline: "hsl(268 72% 68%)", // violet — the classic brain path+ agent: "hsl(152 58% 52%)", // green — coding agents+ worker: "hsl(18 88% 62%)", // orange — autonomous missions+};++export const ROLE_ORDER: CostRole[] = ["realtime", "tool", "pipeline", "agent", "worker"];++/** Fallback for a bucket key that is not a role (provider, model, day). */+export const NEUTRAL_COLOR = "hsl(0 0% 62%)";++export function roleColor(key: string): string {+ return ROLE_COLORS[key as CostRole] ?? NEUTRAL_COLOR;+}++/**+ * A stable colour for an arbitrary key (provider or model).+ *+ * Hashed rather than assigned by index so a provider keeps its colour when a+ * filter changes the row order — a bar that changes hue on every re-render+ * reads as a different thing each time.+ */+export function keyColor(key: string): string {+ if (key in ROLE_COLORS) return ROLE_COLORS[key as CostRole];+ let hash = 0;+ for (let i = 0; i < key.length; i += 1) hash = (hash * 31 + key.charCodeAt(i)) | 0;+ const hue = Math.abs(hash) % 360;+ return `hsl(${hue} 62% 60%)`;+}++// ---------------------------------------------------------------------------+// Formatters+// ---------------------------------------------------------------------------++/**+ * Money, at the precision the amount deserves.+ *+ * Sub-cent spend is real here — a single tool call costs $0.0004 — so small+ * amounts keep four decimals instead of rounding to "$0.00", which would tell+ * the user their most frequent call is free.+ */+export function formatMoney(usd: number, eurPerUsd: number, currency: "usd" | "eur"): string {+ const value = currency === "eur" ? usd * eurPerUsd : usd;+ const symbol = currency === "eur" ? "€" : "$";+ const abs = Math.abs(value);+ if (abs === 0) return `${symbol}0.00`;+ if (abs < 0.01) return `${symbol}${value.toFixed(4)}`;+ if (abs < 100) return `${symbol}${value.toFixed(2)}`;+ return `${symbol}${value.toLocaleString(undefined, { maximumFractionDigits: 0 })}`;+}++/** Compact token counts: 1 240 → 1.2k, 12 823 750 → 12.8M. */+export function formatTokens(n: number): string {+ const abs = Math.abs(n);+ if (abs >= 1_000_000_000) return `${(n / 1_000_000_000).toFixed(2)}B`;+ if (abs >= 1_000_000) return `${(n / 1_000_000).toFixed(2)}M`;+ if (abs >= 1_000) return `${(n / 1_000).toFixed(1)}k`;+ return String(n);+}++export function formatExact(n: number): string {+ return n.toLocaleString();+}++export function formatShare(share: number): string {+ if (share <= 0) return "0%";+ if (share < 0.001) return "<0.1%";+ return `${(share * 100).toFixed(share < 0.1 ? 1 : 0)}%`;+}++/** Axis tick for a `day` (`2026-08-23`) or `hour` (`2026-08-23T14:00`) key. */+export function formatBucketTick(key: string, bucket: "day" | "hour"): string {+ const d = new Date(bucket === "hour" ? `${key}:00` : `${key}T00:00:00`);+ if (Number.isNaN(d.getTime())) return key;+ return bucket === "hour"+ ? d.toLocaleTimeString(undefined, { hour: "2-digit", minute: "2-digit" })+ : d.toLocaleDateString(undefined, { day: "numeric", month: "short" });+}++export function formatBucketFull(key: string, bucket: "day" | "hour"): string {+ const d = new Date(bucket === "hour" ? `${key}:00` : `${key}T00:00:00`);+ if (Number.isNaN(d.getTime())) return key;+ return bucket === "hour"+ ? d.toLocaleString(undefined, {+ weekday: "short",+ day: "numeric",+ month: "short",+ hour: "2-digit",+ minute: "2-digit",+ })+ : d.toLocaleDateString(undefined, { weekday: "short", day: "numeric", month: "short" });+}++export function formatTimestamp(ms: number): string {+ if (!ms) return "—";+ return new Date(ms).toLocaleString(undefined, {+ day: "2-digit",+ month: "short",+ hour: "2-digit",+ minute: "2-digit",+ });+}++// ---------------------------------------------------------------------------+// i18n keys — one place decides what a role / surface / price source is called+// ---------------------------------------------------------------------------++export function roleLabelKey(role: string): string {+ return `costs_view.role.${role.replace(/-/g, "_")}`;+}++export function surfaceLabelKey(surface: string): string {+ return `costs_view.surface.${surface.replace(/-/g, "_")}`;+}++export function priceSourceLabelKey(source: string): string {+ return `costs_view.price_source.${source}`;+}++/** Status tone for a price source, matching the shared `StatusDot` tones. */+export function priceSourceTone(source: PriceSource): "ok" | "warn" | "off" | "error" {+ switch (source) {+ case "recorded":+ return "ok";+ case "derived":+ return "warn";+ case "free":+ return "off";+ default:+ return "error";+ }+}++export const ALL_SURFACES: CostSurface[] = ["voice", "agent-chat", "mission"];diff --git a/jarvis/ui/web/frontend/src/components/layout/MainView.tsx b/jarvis/ui/web/frontend/src/components/layout/MainView.tsxindex 7b4b02d2f1..989d634b1c 100644--- a/jarvis/ui/web/frontend/src/components/layout/MainView.tsx+++ b/jarvis/ui/web/frontend/src/components/layout/MainView.tsx@@ -112,6 +112,9 @@ const DocsView = lazyView(() =>const BoardView = lazyView(() =>import("@/views/BoardView").then((m) => ({ default: m.BoardView })),);+const CostsView = lazyView(() =>+ import("@/views/CostsView").then((m) => ({ default: m.CostsView })),+);const RunInspectorView = lazyView(() =>import("@/views/RunInspectorView").then((m) => ({default: m.RunInspectorView,@@ -436,6 +439,8 @@ function SwitchOnActiveSection({ active }: { active: string }) {return <SessionsView />;case "run_inspector":return <RunInspectorView />;+ case "costs":+ return <CostsView />;case "board":return <BoardView />;case "profile":diff --git a/jarvis/ui/web/frontend/src/components/layout/navGroups.ts b/jarvis/ui/web/frontend/src/components/layout/navGroups.tsindex f282380ec1..579969f096 100644--- a/jarvis/ui/web/frontend/src/components/layout/navGroups.ts+++ b/jarvis/ui/web/frontend/src/components/layout/navGroups.ts@@ -30,6 +30,7 @@ import {Terminal,UserCircle2,Users,+ Wallet,Image as ImageIcon,type LucideIcon,} from "lucide-react";@@ -119,6 +120,10 @@ export const NAV_GROUPS: NavItem[][] = [{ id: "tasks", labelKey: "nav.tasks", icon: ListTodo },{ id: "sessions", labelKey: "nav.sessions", icon: Mic },{ id: "run_inspector", labelKey: "nav.run_inspector", icon: Gauge },+ // Spend & Tokens — every token the app spent, priced per provider,+ // model and role. Sits with the other things the user reads back+ // rather than with the settings: it reports, it does not configure.+ { id: "costs", labelKey: "nav.costs", icon: Wallet, fallbackLabel: "Spend" },// Artifacts — everything a run produced: the pages and pictures on a// full-size stage, and every other run (its files, status and controls)// in the same rail. The Outputs section that used to list the runsdiff --git a/jarvis/ui/web/frontend/src/hooks/useCosts.ts b/jarvis/ui/web/frontend/src/hooks/useCosts.tsnew file mode 100644index 0000000000..525cba0d5c--- /dev/null+++ b/jarvis/ui/web/frontend/src/hooks/useCosts.ts@@ -0,0 +1,237 @@+/**+ * React Query hooks for the Spend & Tokens section.+ *+ * Endpoints: see `jarvis/ui/web/costs_routes.py`. The backend is a read model+ * over the databases the app already writes, so every query here is a plain+ * GET — nothing in this section mutates state.+ */+import { useQuery } from "@tanstack/react-query";++// ---------------------------------------------------------------------------+// Wire types — mirror the Pydantic models in costs_routes.py+// ---------------------------------------------------------------------------++/** Which model in a turn spent this. */+export type CostRole = "realtime" | "tool" | "pipeline" | "agent" | "worker";++/** Which part of the app it was spent in. */+export type CostSurface = "voice" | "agent-chat" | "mission";++/**+ * How confident the price is.+ * - `recorded` the source priced the call itself (audio rates included)+ * - `derived` re-priced here from the rate tables+ * - `free` local engine, subscription seat, or a `:free` model+ * - `unknown` tokens spent at a rate nobody publishes — an accounting gap+ */+export type PriceSource = "recorded" | "derived" | "free" | "unknown";++export interface CostBucket {+ key: string;+ cost_usd: number;+ tokens_in: number;+ tokens_out: number;+ tokens_cached: number;+ tokens_total: number;+ entries: number;+ gap_tokens: number;+ last_ts_ms: number;+ cost_share: number;+ token_share: number;+ members: string[];+ /**+ * Cost per member of the bucket's second dimension: a day broken down by+ * role, a provider by model. Drives the stacked chart and the tooltips.+ */+ breakdown: Record<string, number>;+}++export interface CostRefBucket extends CostBucket {+ label: string;+ surface: string;+}++export interface CostTotals {+ cost_usd: number;+ tokens_in: number;+ tokens_out: number;+ tokens_cached: number;+ tokens_total: number;+ entries: number;+ gap_tokens: number;+ gap_entries: number;+ free_tokens: number;+ estimated_usd: number;+ first_ts_ms: number;+ last_ts_ms: number;+}++export interface CostModelRow {+ model: string;+ provider: string;+ price_sources: PriceSource[];+ tokens_total: number;+}++export interface CostFacets {+ providers: string[];+ models: string[];+ roles: CostRole[];+ surfaces: CostSurface[];+}++export interface CostCurrency {+ eur_per_usd: number;+ source: "config" | "default";+}++export interface CostSummary {+ since_ms: number;+ until_ms: number;+ bucket: "day" | "hour";+ totals: CostTotals;+ by_provider: CostBucket[];+ by_model: CostBucket[];+ by_role: CostBucket[];+ by_surface: CostBucket[];+ series: CostBucket[];+ top_refs: CostRefBucket[];+ models: CostModelRow[];+ facets: CostFacets;+ currency: CostCurrency;+ sources_present: string[];+}++export interface CostEntryRow {+ ts_ms: number;+ surface: CostSurface;+ role: CostRole;+ provider: string;+ model: string;+ tokens_in: number;+ tokens_out: number;+ tokens_cached: number;+ tokens_total: number;+ cost_usd: number;+ price_source: PriceSource;+ ref_id: string;+ label: string;+}++export interface CostEntriesPage {+ items: CostEntryRow[];+ total: number;+ limit: number;+ offset: number;+}++export interface CostRateRow {+ model: string;+ input_usd_per_mtok: number | null;+ output_usd_per_mtok: number | null;+ audio_input_usd_per_mtok: number | null;+ audio_output_usd_per_mtok: number | null;+ known: boolean;+}++export interface CostPricing {+ rates: CostRateRow[];+ currency: CostCurrency;+}++// ---------------------------------------------------------------------------+// Query state shared by the summary and the line items+// ---------------------------------------------------------------------------++export interface CostFilters {+ /** Rolling window in days; `0` means everything ever recorded. */+ days: number;+ providers: string[];+ models: string[];+ roles: CostRole[];+ surfaces: CostSurface[];+ search: string;+}++export const EMPTY_FILTERS: CostFilters = {+ days: 30,+ providers: [],+ models: [],+ roles: [],+ surfaces: [],+ search: "",+};++/** Are any filters beyond the time window active? */+export function hasActiveFilters(f: CostFilters): boolean {+ return (+ f.providers.length > 0 ||+ f.models.length > 0 ||+ f.roles.length > 0 ||+ f.surfaces.length > 0 ||+ f.search.trim().length > 0+ );+}++function toParams(f: CostFilters): URLSearchParams {+ const params = new URLSearchParams();+ params.set("days", String(f.days));+ // Repeated params rather than one comma-joined value: a model id may+ // legitimately contain a comma-free but slash-heavy vendor prefix, and+ // repeating keeps the split unambiguous on the backend.+ for (const p of f.providers) params.append("provider", p);+ for (const m of f.models) params.append("model", m);+ for (const r of f.roles) params.append("role", r);+ for (const s of f.surfaces) params.append("surface", s);+ if (f.search.trim()) params.set("search", f.search.trim());+ return params;+}++async function getJson<T>(url: string): Promise<T> {+ const res = await fetch(url);+ if (!res.ok) throw new Error(`${res.status} ${res.statusText}`);+ return (await res.json()) as T;+}++// ---------------------------------------------------------------------------+// Hooks+// ---------------------------------------------------------------------------++export function useCostSummary(filters: CostFilters) {+ const params = toParams(filters);+ return useQuery({+ queryKey: ["costs", "summary", params.toString()],+ queryFn: () => getJson<CostSummary>(`/api/costs/summary?${params.toString()}`),+ // Spend only moves when a turn finishes; a slow poll keeps an open+ // section current without re-reading three SQLite files every second.+ refetchInterval: 30_000,+ staleTime: 10_000,+ });+}++export function useCostEntries(+ filters: CostFilters,+ sort: "recent" | "cost" | "tokens",+ limit: number,+ offset: number,+) {+ const params = toParams(filters);+ params.set("sort", sort);+ params.set("limit", String(limit));+ params.set("offset", String(offset));+ return useQuery({+ queryKey: ["costs", "entries", params.toString()],+ queryFn: () => getJson<CostEntriesPage>(`/api/costs/entries?${params.toString()}`),+ staleTime: 10_000,+ placeholderData: (prev) => prev,+ });+}++export function useCostPricing(days: number, enabled: boolean) {+ return useQuery({+ queryKey: ["costs", "pricing", days],+ queryFn: () => getJson<CostPricing>(`/api/costs/pricing?days=${days}`),+ enabled,+ staleTime: 5 * 60_000,+ });+}diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.jsonindex 0b657c09f8..8483414274 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json@@ -80,6 +80,7 @@"tasks": "Aufgaben","sessions": "Transkription","run_inspector": "Run Inspector",+ "costs": "Kosten","visualization": "Artefakte","clis": "CLIs","cli_test_hub": "CLI Test Hub",@@ -612,7 +613,12 @@"approval_denied": "Abgelehnt — der Agent wurde informiert.","tool_input": "Eingabe","tool_output": "Ausgabe",- "tool_error": "Fehler"+ "tool_error": "Fehler",+ "thinking_for": "Denkt seit {duration}",+ "tokens": "Tokens",+ "tool_running": "Läuft noch…",+ "interrupt_hint": "Esc zum Abbrechen",+ "status_words": "Denkt nach…, Arbeitet…, Gräbt…, Überlegt…, Grübelt…, Sortiert…, Knobelt…, Tüftelt…, Baut zusammen…, Entwirrt…, Kocht…, Werkelt…"},"chats_view": {"title": "Chat",@@ -4938,5 +4944,90 @@"license": "Lizenz","seed_conflict": "Ein Plugin dieses Namens liegt der App schon bei. Dieses hier ersetzt es.","landed_open": "Zeig es mir"+ },+ "costs_view": {+ "title": "Kosten & Tokens",+ "subtitle": "{entries} Aufrufe · {models} Modelle · {providers} Anbieter",+ "subtitle_loading": "Liest, was jeder Anbieter, jedes Modell und jede Rolle gekostet hat",+ "range_label": "Zeitraum",+ "range_days": "{days} T",+ "range_all": "Alles",+ "currency_label": "Währung",+ "search": "Suchen",+ "search_placeholder": "Modell, Anbieter oder Sitzung…",+ "refresh": "Aktualisieren",+ "clear_filters": "Filter zurücksetzen",+ "load_error": "Die Kosten konnten nicht gelesen werden. Dieser Bereich liest die eigenen Datenbanken der App — wenn das bleibt, ist der Datenordner nicht erreichbar.",+ "stat_total": "Gesamtkosten",+ "stat_total_hint": "{perDay} pro Tag im Schnitt",+ "stat_tokens": "Tokens",+ "stat_tokens_hint": "{in} rein · {out} raus",+ "stat_top_provider": "Größter Posten",+ "stat_top_provider_hint": "{amount} · {share} der Gesamtkosten",+ "stat_none": "Noch nichts erfasst",+ "stat_gap": "Tokens ohne Preis",+ "stat_gap_hint": "{entries} Aufrufe zu einem Preis, den niemand veröffentlicht",+ "stat_gap_none": "Jeder Token ist bepreist",+ "trend_title": "Zeitlicher Verlauf",+ "trend_subtitle": "{from} → {to}",+ "metric_label": "Kennzahl",+ "metric_cost": "Kosten",+ "metric_tokens": "Tokens",+ "chart_empty": "In diesem Zeitraum wurde nichts ausgegeben.",+ "total": "Gesamt",+ "tokens_in": "Rein",+ "tokens_out": "Raus",+ "tokens_cached": "Cache",+ "breakdown_title": "Aufschlüsselung",+ "breakdown_subtitle": "Eine Zeile anklicken filtert den ganzen Bereich danach.",+ "breakdown_empty": "Zu diesen Filtern gibt es keine Kosten.",+ "dimension_label": "Gruppieren nach",+ "dim_provider": "Anbieter",+ "dim_model": "Modell",+ "dim_role": "Rolle",+ "dim_surface": "Bereich",+ "col_share": "Anteil",+ "col_cost": "Kosten",+ "col_calls": "Aufrufe",+ "col_when": "Wann",+ "col_what": "Was",+ "col_price_source": "Preis",+ "col_tokens": "Rein / Raus",+ "entries_title": "Einzelposten",+ "entries_subtitle": "{shown} von {total} sichtbar",+ "entries_empty": "Zu diesen Filtern gibt es keine Aufrufe.",+ "sort_label": "Sortierung",+ "sort_recent": "Neueste",+ "sort_cost": "Teuerste",+ "sort_tokens": "Meiste Tokens",+ "load_more": "{count} weitere anzeigen",+ "rates_title": "Preisliste",+ "rates_subtitle": "je Million Tokens",+ "rates_empty": "In diesem Zeitraum wurde kein Modell benutzt.",+ "rate_in": "Eingabe",+ "rate_out": "Ausgabe",+ "rate_audio": "Audio rein / raus",+ "rate_unknown": "kein Preis",+ "rate_from_config": "dein eingestellter Kurs",+ "rate_default": "Standardkurs",+ "footnote": "Gelesen aus {sources}. {estimated} der Summe wurden hier aus den Preistabellen berechnet, nicht vom Anbieter gemeldet. EUR umgerechnet mit {rate} ({rateSource}).",+ "role": {+ "realtime": "Echtzeit-Stimme",+ "tool": "Tool-Modell",+ "pipeline": "Pipeline-Gehirn",+ "agent": "Coding-Agent",+ "worker": "Missions-Worker"+ },+ "surface": {+ "voice": "Sprache",+ "agent_chat": "Agenten-Chat",+ "mission": "Mission"+ },+ "price_source": {+ "recorded": "Abgerechnet",+ "derived": "Geschätzt",+ "free": "Kostenlos",+ "unknown": "Ohne Preis"+ }}}diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.jsonindex 08c8883d7e..dc4bb1084d 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json@@ -80,6 +80,7 @@"tasks": "Tasks","sessions": "Transcription","run_inspector": "Run Inspector",+ "costs": "Spend","visualization": "Artifacts","clis": "CLIs","cli_test_hub": "CLI Test Hub",@@ -612,7 +613,12 @@"approval_denied": "Denied — the agent was told so.","tool_input": "Input","tool_output": "Output",- "tool_error": "Error"+ "tool_error": "Error",+ "thinking_for": "Thinking for {duration}",+ "tokens": "tokens",+ "tool_running": "Still running…",+ "interrupt_hint": "esc to interrupt",+ "status_words": "Thinking…, Working…, Digging…, Reasoning…, Pondering…, Wrangling…, Puzzling…, Noodling…, Assembling…, Untangling…, Cooking…, Vibing…"},"chats_view": {"title": "Chat",@@ -4938,5 +4944,90 @@"license": "Licence","seed_conflict": "A plugin of this name already ships with the app. Installing this one replaces it.","landed_open": "Show me"+ },+ "costs_view": {+ "title": "Spend & Tokens",+ "subtitle": "{entries} calls · {models} models · {providers} providers",+ "subtitle_loading": "Reading what every provider, model and role cost",+ "range_label": "Time range",+ "range_days": "{days}d",+ "range_all": "All",+ "currency_label": "Currency",+ "search": "Search",+ "search_placeholder": "Model, provider or session…",+ "refresh": "Refresh",+ "clear_filters": "Clear filters",+ "load_error": "Spend could not be read. This section reads the app's own databases — if it keeps failing, the data folder is unreachable.",+ "stat_total": "Total spend",+ "stat_total_hint": "{perDay} per day on average",+ "stat_tokens": "Tokens",+ "stat_tokens_hint": "{in} in · {out} out",+ "stat_top_provider": "Biggest spender",+ "stat_top_provider_hint": "{amount} · {share} of the total",+ "stat_none": "Nothing recorded yet",+ "stat_gap": "Unpriced tokens",+ "stat_gap_hint": "{entries} calls at a rate nobody publishes",+ "stat_gap_none": "Every token is priced",+ "trend_title": "Over time",+ "trend_subtitle": "{from} → {to}",+ "metric_label": "Metric",+ "metric_cost": "Cost",+ "metric_tokens": "Tokens",+ "chart_empty": "Nothing spent in this range.",+ "total": "Total",+ "tokens_in": "In",+ "tokens_out": "Out",+ "tokens_cached": "Cached",+ "breakdown_title": "Breakdown",+ "breakdown_subtitle": "Click a row to filter the whole section by it.",+ "breakdown_empty": "No spend matches these filters.",+ "dimension_label": "Group by",+ "dim_provider": "Provider",+ "dim_model": "Model",+ "dim_role": "Role",+ "dim_surface": "Surface",+ "col_share": "Share",+ "col_cost": "Cost",+ "col_calls": "Calls",+ "col_when": "When",+ "col_what": "What",+ "col_price_source": "Price",+ "col_tokens": "In / Out",+ "entries_title": "Line items",+ "entries_subtitle": "Showing {shown} of {total}",+ "entries_empty": "No calls match these filters.",+ "sort_label": "Sort",+ "sort_recent": "Newest",+ "sort_cost": "Most expensive",+ "sort_tokens": "Most tokens",+ "load_more": "Show {count} more",+ "rates_title": "Rate card",+ "rates_subtitle": "per million tokens",+ "rates_empty": "No models seen in this range.",+ "rate_in": "Input",+ "rate_out": "Output",+ "rate_audio": "Audio in / out",+ "rate_unknown": "no rate",+ "rate_from_config": "your configured rate",+ "rate_default": "default rate",+ "footnote": "Read from {sources}. {estimated} of the total was priced here from the rate tables rather than reported by the provider. EUR converted at {rate} ({rateSource}).",+ "role": {+ "realtime": "Realtime voice",+ "tool": "Tool model",+ "pipeline": "Pipeline brain",+ "agent": "Coding agent",+ "worker": "Mission worker"+ },+ "surface": {+ "voice": "Voice",+ "agent_chat": "Agent chat",+ "mission": "Mission"+ },+ "price_source": {+ "recorded": "Billed",+ "derived": "Estimated",+ "free": "Free",+ "unknown": "Unpriced"+ }}}diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.jsonindex 1b1d71f9b0..298132a5ea 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json@@ -80,6 +80,7 @@"tasks": "Tareas","sessions": "Transcripción","run_inspector": "Run Inspector",+ "costs": "Gastos","visualization": "Artefactos","clis": "CLIs","cli_test_hub": "CLI Test Hub",@@ -612,7 +613,12 @@"approval_denied": "Denegado: se informó al agente.","tool_input": "Entrada","tool_output": "Salida",- "tool_error": "Error"+ "tool_error": "Error",+ "thinking_for": "Pensando desde hace {duration}",+ "tokens": "tokens",+ "tool_running": "Sigue en marcha…",+ "interrupt_hint": "esc para interrumpir",+ "status_words": "Pensando…, Trabajando…, Excavando…, Razonando…, Cavilando…, Ordenando…, Descifrando…, Ideando…, Montando…, Desenredando…, Cocinando…, Fluyendo…"},"chats_view": {"title": "Chat",@@ -4938,5 +4944,90 @@"license": "Licencia","seed_conflict": "La app ya trae un plugin con este nombre. Instalar este lo sustituye.","landed_open": "Muéstramelo"+ },+ "costs_view": {+ "title": "Gastos y tokens",+ "subtitle": "{entries} llamadas · {models} modelos · {providers} proveedores",+ "subtitle_loading": "Leyendo lo que costó cada proveedor, modelo y función",+ "range_label": "Periodo",+ "range_days": "{days} d",+ "range_all": "Todo",+ "currency_label": "Moneda",+ "search": "Buscar",+ "search_placeholder": "Modelo, proveedor o sesión…",+ "refresh": "Actualizar",+ "clear_filters": "Quitar filtros",+ "load_error": "No se pudieron leer los gastos. Esta sección lee las bases de datos de la propia app; si sigue fallando, la carpeta de datos no es accesible.",+ "stat_total": "Gasto total",+ "stat_total_hint": "{perDay} al día de media",+ "stat_tokens": "Tokens",+ "stat_tokens_hint": "{in} entrada · {out} salida",+ "stat_top_provider": "Mayor gasto",+ "stat_top_provider_hint": "{amount} · {share} del total",+ "stat_none": "Todavía no hay datos",+ "stat_gap": "Tokens sin precio",+ "stat_gap_hint": "{entries} llamadas a una tarifa que nadie publica",+ "stat_gap_none": "Todos los tokens tienen precio",+ "trend_title": "Evolución",+ "trend_subtitle": "{from} → {to}",+ "metric_label": "Métrica",+ "metric_cost": "Coste",+ "metric_tokens": "Tokens",+ "chart_empty": "No hubo gasto en este periodo.",+ "total": "Total",+ "tokens_in": "Entrada",+ "tokens_out": "Salida",+ "tokens_cached": "Caché",+ "breakdown_title": "Desglose",+ "breakdown_subtitle": "Pulsa una fila para filtrar toda la sección por ella.",+ "breakdown_empty": "Ningún gasto coincide con estos filtros.",+ "dimension_label": "Agrupar por",+ "dim_provider": "Proveedor",+ "dim_model": "Modelo",+ "dim_role": "Función",+ "dim_surface": "Ámbito",+ "col_share": "Parte",+ "col_cost": "Coste",+ "col_calls": "Llamadas",+ "col_when": "Cuándo",+ "col_what": "Qué",+ "col_price_source": "Precio",+ "col_tokens": "Entrada / Salida",+ "entries_title": "Movimientos",+ "entries_subtitle": "Mostrando {shown} de {total}",+ "entries_empty": "Ninguna llamada coincide con estos filtros.",+ "sort_label": "Orden",+ "sort_recent": "Más recientes",+ "sort_cost": "Más caras",+ "sort_tokens": "Más tokens",+ "load_more": "Mostrar {count} más",+ "rates_title": "Tarifas",+ "rates_subtitle": "por millón de tokens",+ "rates_empty": "No se usó ningún modelo en este periodo.",+ "rate_in": "Entrada",+ "rate_out": "Salida",+ "rate_audio": "Audio entrada / salida",+ "rate_unknown": "sin tarifa",+ "rate_from_config": "tu tipo de cambio",+ "rate_default": "tipo por defecto",+ "footnote": "Leído de {sources}. {estimated} del total se calculó aquí con las tablas de tarifas, no lo informó el proveedor. EUR convertido a {rate} ({rateSource}).",+ "role": {+ "realtime": "Voz en tiempo real",+ "tool": "Modelo de herramientas",+ "pipeline": "Cerebro de la cadena",+ "agent": "Agente de código",+ "worker": "Trabajador de misión"+ },+ "surface": {+ "voice": "Voz",+ "agent_chat": "Chat de agentes",+ "mission": "Misión"+ },+ "price_source": {+ "recorded": "Facturado",+ "derived": "Estimado",+ "free": "Gratis",+ "unknown": "Sin precio"+ }}}diff --git a/jarvis/ui/web/frontend/src/store/events.ts b/jarvis/ui/web/frontend/src/store/events.tsindex 32f5a00428..2019e223ed 100644--- a/jarvis/ui/web/frontend/src/store/events.ts+++ b/jarvis/ui/web/frontend/src/store/events.ts@@ -61,6 +61,8 @@ export type SectionId =| "tasks"| "sessions"| "run_inspector"+ // Spend & Tokens — what every provider, model and role actually cost.+ | "costs"| "clis"| "cli-test-hub"| "board"@@ -112,6 +114,7 @@ export const SECTION_IDS = ["tasks","sessions","run_inspector",+ "costs","clis","cli-test-hub","board",@@ -199,6 +202,7 @@ export const SECTION_LABELS: Record<SectionId, string> = {tasks: "Tasks",sessions: "Transcription",run_inspector: "Run Inspector",+ costs: "Spend",clis: "CLIs","cli-test-hub": "CLI Test Hub",board: "Board",diff --git a/jarvis/ui/web/frontend/src/views/CostsView.tsx b/jarvis/ui/web/frontend/src/views/CostsView.tsxnew file mode 100644index 0000000000..14b8fc11f2--- /dev/null+++ b/jarvis/ui/web/frontend/src/views/CostsView.tsx@@ -0,0 +1,840 @@+/**+ * Spend & Tokens — where the money and the context window actually went.+ *+ * Same settings surface as Skills, Plugins, MCPs and CLIs: one quiet column of+ * panels built from `components/extensions/primitives`, so this section cannot+ * drift into a look of its own. What it adds on top is a drill-down: every+ * bar, every breakdown row and every line item is a filter. Clicking+ * "gemini-live" in the provider table narrows the totals, the chart, the+ * models table and the line items in one move, and the active filters sit as+ * removable chips under the header.+ *+ * The numbers come from `/api/costs` — a read model over the stores the app+ * already writes (voice sessions, missions, agent chats). Nothing here is a+ * separate ledger that could disagree with them.+ */+import { useMemo, useState } from "react";+import {+ AlertTriangle,+ ChevronDown,+ Coins,+ Hash,+ Layers,+ RefreshCw,+ Search,+ Sigma,+ Tag,+ X,+} from "lucide-react";+import { ScrollArea } from "@/components/ui/scroll-area";+import {+ Cell,+ Column,+ EmptyRow,+ IconButton,+ InlineSearch,+ Panel,+ PanelHeader,+ SegmentedFilter,+ StatusDot,+ Table,+ TableHead,+ TableRow,+} from "@/components/extensions/primitives";+import { CostTrendChart, type TrendMetric } from "@/components/costs/CostTrendChart";+import {+ formatBucketFull,+ formatExact,+ formatMoney,+ formatShare,+ formatTimestamp,+ formatTokens,+ keyColor,+ priceSourceLabelKey,+ priceSourceTone,+ roleColor,+ roleLabelKey,+ surfaceLabelKey,+} from "@/components/costs/costFormat";+import {+ EMPTY_FILTERS,+ hasActiveFilters,+ useCostEntries,+ useCostPricing,+ useCostSummary,+ type CostBucket,+ type CostFilters,+ type CostRole,+ type CostSurface,+} from "@/hooks/useCosts";+import { fill, useT } from "@/i18n";+import { cn } from "@/lib/utils";++type Dimension = "provider" | "model" | "role" | "surface";+type Currency = "usd" | "eur";+type EntrySort = "recent" | "cost" | "tokens";++const RANGES = [7, 30, 90, 0] as const;+const ENTRY_PAGE = 50;++export function CostsView() {+ const t = useT();+ const [filters, setFilters] = useState<CostFilters>(EMPTY_FILTERS);+ const [currency, setCurrency] = useState<Currency>("usd");+ const [metric, setMetric] = useState<TrendMetric>("cost");+ const [dimension, setDimension] = useState<Dimension>("provider");+ const [sort, setSort] = useState<EntrySort>("recent");+ const [visible, setVisible] = useState(ENTRY_PAGE);+ const [searchOpen, setSearchOpen] = useState(false);+ const [ratesOpen, setRatesOpen] = useState(false);++ const summary = useCostSummary(filters);+ const entries = useCostEntries(filters, sort, visible, 0);+ const pricing = useCostPricing(filters.days, ratesOpen);++ const data = summary.data;+ const eurPerUsd = data?.currency.eur_per_usd ?? 0.92;+ const totals = data?.totals;+ const money = (usd: number) => formatMoney(usd, eurPerUsd, currency);++ // One toggle for every filter dimension: clicking a row that is already+ // filtered removes it again, so a drill-down is never a one-way door.+ const toggle = (key: keyof CostFilters, value: string) => {+ setVisible(ENTRY_PAGE);+ setFilters((f) => {+ const list = f[key] as string[];+ const next = list.includes(value)+ ? list.filter((v) => v !== value)+ : [...list, value];+ return { ...f, [key]: next };+ });+ };++ const rows: CostBucket[] = useMemo(() => {+ if (!data) return [];+ switch (dimension) {+ case "model":+ return data.by_model;+ case "role":+ return data.by_role;+ case "surface":+ return data.by_surface;+ default:+ return data.by_provider;+ }+ }, [data, dimension]);++ const filterKeyFor = (d: Dimension): keyof CostFilters =>+ d === "provider" ? "providers" : d === "model" ? "models" : d === "role" ? "roles" : "surfaces";++ const activeFor = (d: Dimension): string[] => filters[filterKeyFor(d)] as string[];++ const topSpender = data?.by_provider[0];+ const rangeMs = Math.max(1, (data?.until_ms ?? 0) - (data?.since_ms ?? 0));+ const perDay = totals ? totals.cost_usd / Math.max(1, rangeMs / 86_400_000) : 0;++ return (+ <ScrollArea className="h-full">+ <div className="mx-auto flex max-w-[1180px] flex-col gap-4 px-6 py-6">+ <PanelHeader+ title={t("costs_view.title")}+ subtitle={+ data+ ? fill(t("costs_view.subtitle"), {+ entries: formatExact(totals?.entries ?? 0),+ models: String(data.models.length),+ // Both counts come from the FILTERED report — mixing in the+ // unfiltered facet count would claim eight providers next+ // to two models while a provider filter is on.+ providers: String(data.by_provider.length),+ })+ : t("costs_view.subtitle_loading")+ }+ actions={+ <>+ <SegmentedFilter<string>+ label={t("costs_view.range_label")}+ value={String(filters.days)}+ onChange={(v) => {+ setVisible(ENTRY_PAGE);+ setFilters((f) => ({ ...f, days: Number(v) }));+ }}+ options={RANGES.map((d) => ({+ id: String(d),+ label: d === 0 ? t("costs_view.range_all") : fill(t("costs_view.range_days"), { days: String(d) }),+ }))}+ />+ <span className="mx-1 h-4 w-px bg-border" aria-hidden />+ <SegmentedFilter<Currency>+ label={t("costs_view.currency_label")}+ value={currency}+ onChange={setCurrency}+ options={[+ { id: "usd", label: "USD" },+ { id: "eur", label: "EUR" },+ ]}+ />+ <IconButton+ label={t("costs_view.search")}+ active={searchOpen}+ onClick={() => setSearchOpen((v) => !v)}+ >+ <Search className="h-4 w-4" />+ </IconButton>+ <IconButton+ label={t("costs_view.refresh")}+ busy={summary.isFetching}+ onClick={() => void summary.refetch()}+ >+ <RefreshCw className="h-4 w-4" />+ </IconButton>+ </>+ }+ />++ {searchOpen ? (+ <div className="max-w-sm">+ <InlineSearch+ autoFocus+ value={filters.search}+ onChange={(v) => {+ setVisible(ENTRY_PAGE);+ setFilters((f) => ({ ...f, search: v }));+ }}+ placeholder={t("costs_view.search_placeholder")}+ />+ </div>+ ) : null}++ <ActiveFilterChips+ filters={filters}+ onRemove={(key, value) => toggle(key, value)}+ onClear={() => {+ setVisible(ENTRY_PAGE);+ setFilters((f) => ({ ...EMPTY_FILTERS, days: f.days }));+ }}+ />++ {summary.isError ? (+ <EmptyRow>{t("costs_view.load_error")}</EmptyRow>+ ) : null}++ {/* ---------------------------------------------------------------+ Headline numbers. Cost and tokens sit side by side on purpose:+ the cheapest provider is often the loudest token consumer, and+ one number without the other hides that.+ --------------------------------------------------------------- */}+ <div className="grid gap-3 sm:grid-cols-2 xl:grid-cols-4">+ <StatTile+ icon={<Coins className="h-4 w-4" />}+ label={t("costs_view.stat_total")}+ value={money(totals?.cost_usd ?? 0)}+ hint={fill(t("costs_view.stat_total_hint"), { perDay: money(perDay) })}+ loading={summary.isLoading}+ />+ <StatTile+ icon={<Sigma className="h-4 w-4" />}+ label={t("costs_view.stat_tokens")}+ value={formatTokens(totals?.tokens_total ?? 0)}+ hint={fill(t("costs_view.stat_tokens_hint"), {+ in: formatTokens(totals?.tokens_in ?? 0),+ out: formatTokens(totals?.tokens_out ?? 0),+ })}+ loading={summary.isLoading}+ />+ <StatTile+ icon={<Tag className="h-4 w-4" />}+ label={t("costs_view.stat_top_provider")}+ value={topSpender?.key ?? "—"}+ hint={+ topSpender+ ? fill(t("costs_view.stat_top_provider_hint"), {+ amount: money(topSpender.cost_usd),+ share: formatShare(topSpender.cost_share),+ })+ : t("costs_view.stat_none")+ }+ loading={summary.isLoading}+ />+ <StatTile+ icon={<AlertTriangle className="h-4 w-4" />}+ label={t("costs_view.stat_gap")}+ value={formatTokens(totals?.gap_tokens ?? 0)}+ hint={+ (totals?.gap_tokens ?? 0) > 0+ ? fill(t("costs_view.stat_gap_hint"), {+ entries: formatExact(totals?.gap_entries ?? 0),+ })+ : t("costs_view.stat_gap_none")+ }+ tone={(totals?.gap_tokens ?? 0) > 0 ? "warn" : "ok"}+ loading={summary.isLoading}+ />+ </div>++ {/* Trend ------------------------------------------------------- */}+ <Panel className="p-4">+ <PanelHeader+ title={t("costs_view.trend_title")}+ subtitle={+ data+ ? fill(t("costs_view.trend_subtitle"), {+ from: formatBucketFull(data.series[0]?.key ?? "", data.bucket),+ to: formatBucketFull(data.series[data.series.length - 1]?.key ?? "", data.bucket),+ })+ : ""+ }+ actions={+ <SegmentedFilter<TrendMetric>+ label={t("costs_view.metric_label")}+ value={metric}+ onChange={setMetric}+ options={[+ { id: "cost", label: t("costs_view.metric_cost") },+ { id: "tokens", label: t("costs_view.metric_tokens") },+ ]}+ />+ }+ />+ <div className="mt-3 h-[220px]">+ <CostTrendChart+ series={data?.series ?? []}+ bucket={data?.bucket ?? "day"}+ metric={metric}+ currency={currency}+ eurPerUsd={eurPerUsd}+ />+ </div>+ </Panel>++ {/* Breakdown --------------------------------------------------- */}+ <Panel>+ <div className="px-4 pt-4">+ <PanelHeader+ title={t("costs_view.breakdown_title")}+ subtitle={t("costs_view.breakdown_subtitle")}+ actions={+ <SegmentedFilter<Dimension>+ label={t("costs_view.dimension_label")}+ value={dimension}+ onChange={setDimension}+ options={[+ { id: "provider", label: t("costs_view.dim_provider") },+ { id: "model", label: t("costs_view.dim_model") },+ { id: "role", label: t("costs_view.dim_role") },+ { id: "surface", label: t("costs_view.dim_surface") },+ ]}+ />+ }+ />+ </div>+ <div className="mt-3">+ <BreakdownTable+ rows={rows}+ dimension={dimension}+ active={activeFor(dimension)}+ onToggle={(key) => toggle(filterKeyFor(dimension), key)}+ money={money}+ loading={summary.isLoading}+ />+ </div>+ </Panel>++ {/* Line items -------------------------------------------------- */}+ <Panel>+ <div className="px-4 pt-4">+ <PanelHeader+ title={t("costs_view.entries_title")}+ subtitle={fill(t("costs_view.entries_subtitle"), {+ shown: formatExact(Math.min(entries.data?.total ?? 0, visible)),+ total: formatExact(entries.data?.total ?? 0),+ })}+ actions={+ <SegmentedFilter<EntrySort>+ label={t("costs_view.sort_label")}+ value={sort}+ onChange={(v) => {+ setSort(v);+ setVisible(ENTRY_PAGE);+ }}+ options={[+ { id: "recent", label: t("costs_view.sort_recent") },+ { id: "cost", label: t("costs_view.sort_cost") },+ { id: "tokens", label: t("costs_view.sort_tokens") },+ ]}+ />+ }+ />+ </div>+ <div className="mt-3">+ <EntriesTable+ rows={entries.data?.items ?? []}+ money={money}+ loading={entries.isLoading}+ onFilterModel={(model) => toggle("models", model)}+ />+ </div>+ {(entries.data?.total ?? 0) > visible ? (+ <div className="border-t border-border px-4 py-3">+ <button+ type="button"+ onClick={() => setVisible((v) => v + ENTRY_PAGE)}+ className="text-sm font-medium text-foreground/80 transition-colors hover:text-foreground"+ >+ {fill(t("costs_view.load_more"), { count: String(ENTRY_PAGE) })}+ </button>+ </div>+ ) : null}+ </Panel>++ {/* Rate card --------------------------------------------------- */}+ <Panel>+ <button+ type="button"+ onClick={() => setRatesOpen((v) => !v)}+ aria-expanded={ratesOpen}+ className="flex w-full items-center gap-2 px-4 py-3 text-left transition-colors hover:bg-sheen/[0.04]"+ >+ <Layers className="h-4 w-4 text-muted-foreground" />+ <span className="text-sm font-medium text-foreground">{t("costs_view.rates_title")}</span>+ <span className="text-xs text-muted-foreground">{t("costs_view.rates_subtitle")}</span>+ <ChevronDown+ className={cn(+ "ml-auto h-4 w-4 text-muted-foreground transition-transform",+ ratesOpen && "rotate-180",+ )}+ />+ </button>+ {ratesOpen ? (+ <RatesTable+ rates={pricing.data?.rates ?? []}+ currency={currency}+ eurPerUsd={eurPerUsd}+ loading={pricing.isLoading}+ />+ ) : null}+ </Panel>++ <p className="px-1 pb-2 text-[11px] leading-relaxed text-muted-foreground">+ {fill(t("costs_view.footnote"), {+ sources: (data?.sources_present ?? []).join(", ") || "—",+ rate: eurPerUsd.toFixed(2),+ rateSource: t(+ data?.currency.source === "config"+ ? "costs_view.rate_from_config"+ : "costs_view.rate_default",+ ),+ estimated: money(totals?.estimated_usd ?? 0),+ })}+ </p>+ </div>+ </ScrollArea>+ );+}++// ---------------------------------------------------------------------------+// Stat tile+// ---------------------------------------------------------------------------++function StatTile({+ icon,+ label,+ value,+ hint,+ tone,+ loading,+}: {+ icon: React.ReactNode;+ label: string;+ value: string;+ hint: string;+ tone?: "ok" | "warn";+ loading?: boolean;+}) {+ return (+ <div className="rounded-xl border border-border bg-card/50 px-4 py-3.5">+ <div className="flex items-center gap-2 text-xs text-muted-foreground">+ <span className={cn(tone === "warn" && "text-amber-500")}>{icon}</span>+ <span className="truncate">{label}</span>+ </div>+ <div+ className={cn(+ "mt-1.5 truncate font-display text-[22px] font-semibold tabular-nums tracking-tight text-foreground",+ loading && "opacity-40",+ )}+ title={value}+ >+ {value}+ </div>+ <div className="mt-0.5 truncate text-[11px] text-muted-foreground" title={hint}>+ {hint}+ </div>+ </div>+ );+}++// ---------------------------------------------------------------------------+// Active filters+// ---------------------------------------------------------------------------++const CHIP_KEYS: { key: keyof CostFilters; labelKey: string }[] = [+ { key: "providers", labelKey: "costs_view.dim_provider" },+ { key: "models", labelKey: "costs_view.dim_model" },+ { key: "roles", labelKey: "costs_view.dim_role" },+ { key: "surfaces", labelKey: "costs_view.dim_surface" },+];++function ActiveFilterChips({+ filters,+ onRemove,+ onClear,+}: {+ filters: CostFilters;+ onRemove: (key: keyof CostFilters, value: string) => void;+ onClear: () => void;+}) {+ const t = useT();+ if (!hasActiveFilters(filters)) return null;+ return (+ <div className="flex flex-wrap items-center gap-1.5">+ {CHIP_KEYS.flatMap(({ key, labelKey }) =>+ (filters[key] as string[]).map((value) => (+ <button+ key={`${key}:${value}`}+ type="button"+ onClick={() => onRemove(key, value)}+ className="inline-flex h-7 items-center gap-1.5 rounded-md border border-border bg-card/60 px-2.5 text-xs text-foreground transition-colors hover:bg-sheen/[0.06]"+ >+ <span className="text-muted-foreground">{t(labelKey)}</span>+ <span className="font-medium">{value}</span>+ <X className="h-3 w-3 text-muted-foreground" />+ </button>+ )),+ )}+ {filters.search.trim() ? (+ <span className="inline-flex h-7 items-center gap-1.5 rounded-md border border-border bg-card/60 px-2.5 text-xs">+ <Search className="h-3 w-3 text-muted-foreground" />+ {filters.search}+ </span>+ ) : null}+ <button+ type="button"+ onClick={onClear}+ className="ml-1 text-xs text-muted-foreground transition-colors hover:text-foreground"+ >+ {t("costs_view.clear_filters")}+ </button>+ </div>+ );+}++// ---------------------------------------------------------------------------+// Breakdown table+// ---------------------------------------------------------------------------++function BreakdownTable({+ rows,+ dimension,+ active,+ onToggle,+ money,+ loading,+}: {+ rows: CostBucket[];+ dimension: Dimension;+ active: string[];+ onToggle: (key: string) => void;+ money: (usd: number) => string;+ loading?: boolean;+}) {+ const t = useT();+ const columns: Column[] = [+ { id: "name", label: t(`costs_view.dim_${dimension}`) },+ { id: "share", label: t("costs_view.col_share"), width: "170px" },+ { id: "cost", label: t("costs_view.col_cost"), width: "110px", align: "right" },+ { id: "in", label: t("costs_view.tokens_in"), width: "92px", align: "right" },+ { id: "out", label: t("costs_view.tokens_out"), width: "92px", align: "right" },+ { id: "calls", label: t("costs_view.col_calls"), width: "80px", align: "right" },+ ];++ if (!loading && rows.length === 0) {+ return (+ <div className="px-4 pb-4">+ <EmptyRow>{t("costs_view.breakdown_empty")}</EmptyRow>+ </div>+ );+ }++ return (+ <Table label={t("costs_view.breakdown_title")}>+ <TableHead columns={columns} />+ {rows.map((row) => {+ const isActive = active.includes(row.key);+ const color = dimension === "role" ? roleColor(row.key) : keyColor(row.key);+ return (+ <TableRow+ key={row.key}+ columns={columns}+ selected={isActive}+ onClick={() => onToggle(row.key)}+ ariaLabel={row.key}+ >+ <Cell>+ <div className="flex min-w-0 items-center gap-2.5">+ <span+ className="h-2.5 w-2.5 shrink-0 rounded-[3px]"+ style={{ background: color }}+ aria-hidden+ />+ <div className="min-w-0">+ <div className="truncate font-medium text-foreground">+ {dimension === "role"+ ? t(roleLabelKey(row.key))+ : dimension === "surface"+ ? t(surfaceLabelKey(row.key))+ : row.key}+ </div>+ {row.members.length > 0 ? (+ <div className="truncate text-xs text-muted-foreground">+ {row.members+ .map((m) =>+ dimension === "surface" || dimension === "provider"+ ? m in ROLE_KEYS+ ? t(roleLabelKey(m))+ : m+ : m,+ )+ .join(" · ")}+ </div>+ ) : null}+ </div>+ </div>+ </Cell>+ <Cell>+ <div className="flex items-center gap-2">+ <div className="h-1.5 w-full overflow-hidden rounded-full bg-sheen/[0.08]">+ <div+ className="h-full rounded-full"+ style={{+ width: `${Math.max(2, Math.round(row.cost_share * 100))}%`,+ background: color,+ }}+ />+ </div>+ <span className="w-10 shrink-0 text-right text-xs tabular-nums text-muted-foreground">+ {formatShare(row.cost_share)}+ </span>+ </div>+ </Cell>+ <Cell align="right">+ <span className="font-medium tabular-nums text-foreground">{money(row.cost_usd)}</span>+ </Cell>+ <Cell align="right" muted>+ <span className="tabular-nums" title={formatExact(row.tokens_in)}>+ {formatTokens(row.tokens_in)}+ </span>+ </Cell>+ <Cell align="right" muted>+ <span className="tabular-nums" title={formatExact(row.tokens_out)}>+ {formatTokens(row.tokens_out)}+ </span>+ </Cell>+ <Cell align="right" muted>+ <span className="tabular-nums">{formatExact(row.entries)}</span>+ </Cell>+ </TableRow>+ );+ })}+ </Table>+ );+}++/** Role ids as an object, so a member name can be checked without a cast. */+const ROLE_KEYS: Record<string, true> = {+ realtime: true,+ tool: true,+ pipeline: true,+ agent: true,+ worker: true,+};++// ---------------------------------------------------------------------------+// Line items+// ---------------------------------------------------------------------------++interface EntryRowShape {+ ts_ms: number;+ surface: CostSurface;+ role: CostRole;+ provider: string;+ model: string;+ tokens_in: number;+ tokens_out: number;+ tokens_cached: number;+ tokens_total: number;+ cost_usd: number;+ price_source: string;+ ref_id: string;+ label: string;+}++function EntriesTable({+ rows,+ money,+ loading,+ onFilterModel,+}: {+ rows: EntryRowShape[];+ money: (usd: number) => string;+ loading?: boolean;+ onFilterModel: (model: string) => void;+}) {+ const t = useT();+ const columns: Column[] = [+ { id: "when", label: t("costs_view.col_when"), width: "132px" },+ { id: "what", label: t("costs_view.col_what") },+ { id: "price", label: t("costs_view.col_price_source"), width: "128px" },+ { id: "tokens", label: t("costs_view.col_tokens"), width: "128px", align: "right" },+ { id: "cost", label: t("costs_view.col_cost"), width: "104px", align: "right" },+ ];++ if (!loading && rows.length === 0) {+ return (+ <div className="px-4 pb-4">+ <EmptyRow>{t("costs_view.entries_empty")}</EmptyRow>+ </div>+ );+ }++ return (+ <Table label={t("costs_view.entries_title")}>+ <TableHead columns={columns} />+ {rows.map((row, i) => (+ <TableRow+ key={`${row.ts_ms}-${row.ref_id}-${i}`}+ columns={columns}+ onClick={row.model ? () => onFilterModel(row.model) : undefined}+ ariaLabel={row.model || row.provider}+ >+ <Cell muted>+ <span className="tabular-nums">{formatTimestamp(row.ts_ms)}</span>+ </Cell>+ <Cell>+ <div className="flex min-w-0 items-center gap-2.5">+ <span+ className="h-2.5 w-2.5 shrink-0 rounded-[3px]"+ style={{ background: roleColor(row.role) }}+ aria-hidden+ />+ <div className="min-w-0">+ <div className="truncate font-medium text-foreground">+ {row.model || row.provider}+ </div>+ <div className="truncate text-xs text-muted-foreground">+ {t(roleLabelKey(row.role))} · {t(surfaceLabelKey(row.surface))}+ {row.label ? ` · ${row.label}` : ""}+ </div>+ </div>+ </div>+ </Cell>+ <Cell>+ <StatusDot+ tone={priceSourceTone(row.price_source as never)}+ label={t(priceSourceLabelKey(row.price_source))}+ />+ </Cell>+ <Cell align="right" muted>+ <span+ className="tabular-nums"+ title={`${formatExact(row.tokens_in)} in / ${formatExact(row.tokens_out)} out`}+ >+ {formatTokens(row.tokens_in)} / {formatTokens(row.tokens_out)}+ </span>+ </Cell>+ <Cell align="right">+ <span className="font-medium tabular-nums text-foreground">{money(row.cost_usd)}</span>+ </Cell>+ </TableRow>+ ))}+ </Table>+ );+}++// ---------------------------------------------------------------------------+// Rate card+// ---------------------------------------------------------------------------++interface RateRowShape {+ model: string;+ input_usd_per_mtok: number | null;+ output_usd_per_mtok: number | null;+ audio_input_usd_per_mtok: number | null;+ audio_output_usd_per_mtok: number | null;+ known: boolean;+}++function RatesTable({+ rates,+ currency,+ eurPerUsd,+ loading,+}: {+ rates: RateRowShape[];+ currency: Currency;+ eurPerUsd: number;+ loading?: boolean;+}) {+ const t = useT();+ const columns: Column[] = [+ { id: "model", label: t("costs_view.dim_model") },+ { id: "in", label: t("costs_view.rate_in"), width: "116px", align: "right" },+ { id: "out", label: t("costs_view.rate_out"), width: "116px", align: "right" },+ { id: "audio", label: t("costs_view.rate_audio"), width: "150px", align: "right" },+ ];+ const price = (v: number | null) =>+ v === null ? "—" : formatMoney(v, eurPerUsd, currency);++ if (!loading && rates.length === 0) {+ return (+ <div className="px-4 pb-4">+ <EmptyRow>{t("costs_view.rates_empty")}</EmptyRow>+ </div>+ );+ }++ return (+ <div className="border-t border-border">+ <Table label={t("costs_view.rates_title")}>+ <TableHead columns={columns} />+ {rates.map((rate) => (+ <TableRow key={rate.model} columns={columns}>+ <Cell>+ <div className="flex min-w-0 items-center gap-2">+ <Hash className="h-3.5 w-3.5 shrink-0 text-muted-foreground" />+ <span className="truncate text-foreground">{rate.model}</span>+ {!rate.known ? (+ <span className="shrink-0 rounded border border-amber-500/40 px-1.5 py-0.5 text-[10px] text-amber-500">+ {t("costs_view.rate_unknown")}+ </span>+ ) : null}+ </div>+ </Cell>+ <Cell align="right" muted>+ <span className="tabular-nums">{price(rate.input_usd_per_mtok)}</span>+ </Cell>+ <Cell align="right" muted>+ <span className="tabular-nums">{price(rate.output_usd_per_mtok)}</span>+ </Cell>+ <Cell align="right" muted>+ <span className="tabular-nums">+ {rate.audio_input_usd_per_mtok === null+ ? "—"+ : `${price(rate.audio_input_usd_per_mtok)} / ${price(rate.audio_output_usd_per_mtok)}`}+ </span>+ </Cell>+ </TableRow>+ ))}+ </Table>+ </div>+ );+}diff --git a/jarvis/ui/web/server.py b/jarvis/ui/web/server.pyindex 2514606dbb..982456fd99 100644--- a/jarvis/ui/web/server.py+++ b/jarvis/ui/web/server.py@@ -348,6 +348,7 @@ class WebServer:from .computer_use_routes import router as computer_use_routerfrom .contacts_routes import router as contacts_routerfrom .control_routes import router as control_router+ from .costs_routes import router as costs_routerfrom .deck_routes import router as deck_routerfrom .desktop_routes import router as desktop_routerfrom .diagnostics_routes import router as diagnostics_router@@ -446,6 +447,8 @@ class WebServer:app.include_router(skills_router)app.include_router(docs_router)app.include_router(cli_router)+ # Spend & Tokens — a read model over sessions/missions/agent-chat.+ app.include_router(costs_router)# Command Registry — the one machine-readable catalog of app commands# (consumed by the app-command brain tool, the UI, CLI, and docs gen).app.include_router(commands_router)diff --git a/tests/unit/costs/test_cost_read_model.py b/tests/unit/costs/test_cost_read_model.pynew file mode 100644index 0000000000..6ede987b0f--- /dev/null+++ b/tests/unit/costs/test_cost_read_model.py@@ -0,0 +1,395 @@+"""Tests for the Spend & Tokens read model (``jarvis/costs``).++The section makes four claims that are easy to get quietly wrong, so each has+a test of its own:++1. **No double counting.** A voice turn whose model calls are also in the+ event stream must be counted from the events OR from the turn row, never+ from both — the turn row is the fallback for pre-event history.+2. **The role split is real.** Inside one realtime turn, audio usage and the+ delegated tool model land on different roles; outside one, a brain call is+ the pipeline.+3. **Zero is not automatically free.** A recorded 0.0 with tokens on it is a+ pricing GAP for a metered provider, a genuine 0.0 for a local one, and a+ re-derived price when the rate tables know the model.+4. **Sources are optional.** A fresh install has none of these databases and+ the section must still answer.+"""+from __future__ import annotations++import json+import sqlite3+from pathlib import Path++import pytest++from jarvis.costs import CostSources, build_report, collect_entries+from jarvis.costs.aggregate import filter_entries+from jarvis.costs.model import price_entry++# ---------------------------------------------------------------------------+# Fixtures — minimal replicas of the real schemas+# ---------------------------------------------------------------------------++_SESSIONS_DDL = """+CREATE TABLE voice_turns (+ id TEXT PRIMARY KEY, session_id TEXT, idx INTEGER, started_ms INTEGER,+ ended_ms INTEGER, user_text TEXT, user_lang TEXT, jarvis_text TEXT,+ jarvis_lang TEXT, tier TEXT, provider TEXT, model TEXT,+ tokens_in INTEGER, tokens_out INTEGER, cost_usd REAL,+ latency_total_ms INTEGER+);+CREATE TABLE voice_events (+ seq INTEGER PRIMARY KEY AUTOINCREMENT, session_id TEXT, turn_id TEXT,+ ts_ms INTEGER, kind TEXT, payload_json TEXT+);+"""++_MISSIONS_DDL = """+CREATE TABLE missions (+ id TEXT PRIMARY KEY, prompt TEXT, state TEXT, created_ms INTEGER,+ cost_usd REAL+);+CREATE TABLE mission_events (+ seq INTEGER PRIMARY KEY AUTOINCREMENT, mission_id TEXT, worker_id TEXT,+ event_type TEXT, ts_ms INTEGER, payload_json TEXT+);+"""++_AGENT_CHAT_DDL = """+CREATE TABLE agent_chat_sessions (+ session_id TEXT PRIMARY KEY, title TEXT, provider TEXT, model TEXT,+ created_ms INTEGER, updated_ms INTEGER+);+CREATE TABLE agent_chat_events (+ session_id TEXT, seq INTEGER, ts_ms INTEGER, kind TEXT, payload TEXT+);+"""++T0 = 1_780_000_000_000+++def _sessions_db(path: Path) -> None:+ conn = sqlite3.connect(path)+ conn.executescript(_SESSIONS_DDL)+ # A realtime turn that delegated one tool call: two model calls, one turn.+ conn.execute(+ "INSERT INTO voice_turns (id, session_id, started_ms, tier, provider, model, "+ "tokens_in, tokens_out, cost_usd, user_text) VALUES (?,?,?,?,?,?,?,?,?,?)",+ ("turn-1", "sess-1", T0, "realtime", "gemini-live", "gemini-3.1-flash-live-preview",+ 50_000, 300, 0.4, "what is on my calendar"),+ )+ # A classic pipeline turn with no event rows — the fallback path.+ conn.execute(+ "INSERT INTO voice_turns (id, session_id, started_ms, tier, provider, model, "+ "tokens_in, tokens_out, cost_usd, user_text) VALUES (?,?,?,?,?,?,?,?,?,?)",+ ("turn-2", "sess-1", T0 + 60_000, "deep", "anthropic", "claude-opus-4-7-20251022",+ 1_000, 200, 0.05, "summarise the meeting"),+ )+ for turn_id, payload in (+ (+ "turn-1",+ {+ "provider": "gemini-live",+ "model": "gemini-3.1-flash-live-preview",+ "tokens_in": 50_000,+ "tokens_out": 300,+ "cost_usd": 0.4,+ "finish_reason": "realtime_usage",+ },+ ),+ (+ "turn-1",+ {+ "provider": "grok",+ "model": "grok-4.3",+ "tokens_in": 8_000,+ "tokens_out": 120,+ "cost_usd": 0.0,+ "finish_reason": "stop",+ },+ ),+ ):+ conn.execute(+ "INSERT INTO voice_events (session_id, turn_id, ts_ms, kind, payload_json) "+ "VALUES (?,?,?,?,?)",+ ("sess-1", turn_id, T0 + 1_000, "BrainTurnCompleted", json.dumps(payload)),+ )+ conn.commit()+ conn.close()+++def _missions_db(path: Path) -> None:+ conn = sqlite3.connect(path)+ conn.executescript(_MISSIONS_DDL)+ conn.execute(+ "INSERT INTO missions (id, prompt, state, created_ms, cost_usd) VALUES (?,?,?,?,?)",+ ("m-1", "refactor the parser", "done", T0, 0.0),+ )+ # A worker that reported its own price...+ conn.execute(+ "INSERT INTO mission_events (mission_id, worker_id, event_type, ts_ms, payload_json) "+ "VALUES (?,?,?,?,?)",+ ("m-1", "w-1", "WorkerDraftReady", T0 + 5_000,+ json.dumps({"tokens_used": 26_000, "cost_usd": 1.25})),+ )+ # ...and one that reported tokens but no price and no model, which is what+ # a CLI-driven worker actually emits. Those tokens are a real accounting+ # gap and must be visible as such.+ conn.execute(+ "INSERT INTO mission_events (mission_id, worker_id, event_type, ts_ms, payload_json) "+ "VALUES (?,?,?,?,?)",+ ("m-1", "w-2", "WorkerDraftReady", T0 + 6_000,+ json.dumps({"tokens_used": 33_000, "cost_usd": 0.0})),+ )+ conn.commit()+ conn.close()+++def _agent_chat_db(path: Path) -> None:+ conn = sqlite3.connect(path)+ conn.executescript(_AGENT_CHAT_DDL)+ conn.execute(+ "INSERT INTO agent_chat_sessions (session_id, title, provider, model, created_ms, "+ "updated_ms) VALUES (?,?,?,?,?,?)",+ ("chat-1", "Fix the build", "claude", "claude-opus-4-7-20251022", T0, T0),+ )+ conn.execute(+ "INSERT INTO agent_chat_events (session_id, seq, ts_ms, kind, payload) VALUES (?,?,?,?,?)",+ ("chat-1", 1, T0 + 10_000, "turn_finished", json.dumps({+ "status": "done",+ "cost_usd": 0.31,+ "usage": {+ "input_tokens": 4_000,+ "output_tokens": 900,+ "cache_read_input_tokens": 12_000,+ },+ })),+ )+ conn.commit()+ conn.close()+++def sources(tmp_path: Path) -> CostSources:+ sessions = tmp_path / "sessions.db"+ missions = tmp_path / "missions.db"+ agent_chat = tmp_path / "agent_chat.db"+ _sessions_db(sessions)+ _missions_db(missions)+ _agent_chat_db(agent_chat)+ return CostSources(sessions_db=sessions, missions_db=missions, agent_chat_db=agent_chat)+++# ---------------------------------------------------------------------------+# Collection+# ---------------------------------------------------------------------------+++def test_collects_every_source(sources: CostSources) -> None:+ entries = collect_entries(sources)+ surfaces = {e.surface for e in entries}+ assert surfaces == {"voice", "agent-chat", "mission"}+++def test_event_backed_turn_is_not_counted_twice(sources: CostSources) -> None:+ """turn-1 has two events; its own row must not add a third entry."""+ voice = [e for e in collect_entries(sources) if e.surface == "voice"]+ # 2 events for turn-1 + 1 fallback row for the event-less turn-2.+ assert len(voice) == 3+ realtime_cost = sum(e.cost_usd for e in voice if e.role == "realtime")+ assert realtime_cost == pytest.approx(0.4)+++def test_role_split_inside_one_realtime_turn(sources: CostSources) -> None:+ voice = [e for e in collect_entries(sources) if e.surface == "voice"]+ roles = {e.role: e for e in voice}+ assert roles["realtime"].provider == "gemini-live"+ # The delegated text model inside the realtime turn is the TOOL model...+ assert roles["tool"].model == "grok-4.3"+ # ...while a brain call in a non-realtime tier is the pipeline.+ assert roles["pipeline"].model == "claude-opus-4-7-20251022"+++def test_agent_chat_usage_is_bucketed_by_direction(sources: CostSources) -> None:+ entry = next(e for e in collect_entries(sources) if e.surface == "agent-chat")+ assert entry.role == "agent"+ assert entry.tokens_in == 4_000+ assert entry.tokens_out == 900+ # Cache reads are their own bucket — billed at a fraction of input.+ assert entry.tokens_cached == 12_000+ assert entry.cost_usd == pytest.approx(0.31)+++def test_missing_sources_are_skipped(tmp_path: Path) -> None:+ empty = CostSources(sessions_db=tmp_path / "nope.db")+ assert collect_entries(empty) == []+ report = build_report([], since_ms=0, until_ms=1)+ assert report.totals["cost_usd"] == 0.0+ assert report.by_provider == []+++def test_range_filter_excludes_older_rows(sources: CostSources) -> None:+ assert collect_entries(sources, since_ms=T0 + 100_000) == []+++# ---------------------------------------------------------------------------+# Pricing honesty+# ---------------------------------------------------------------------------+++def test_recorded_price_wins() -> None:+ cost, source = price_entry(+ provider="gemini-live", model="x", tokens_in=1, tokens_out=1, recorded_usd=0.5+ )+ assert (cost, source) == (0.5, "recorded")+++def test_local_provider_is_free_not_a_gap() -> None:+ cost, source = price_entry(+ provider="local-realtime", model="", tokens_in=9_000, tokens_out=10, recorded_usd=0.0+ )+ assert (cost, source) == (0.0, "free")+++def test_free_model_suffix_is_free() -> None:+ _, source = price_entry(+ provider="openrouter",+ model="nvidia/nemotron-3-ultra-550b-a55b:free",+ tokens_in=1_000,+ tokens_out=10,+ recorded_usd=0.0,+ )+ assert source == "free"+++def test_unknown_model_is_a_gap_not_a_zero_bill() -> None:+ cost, source = price_entry(+ provider="acme",+ model="totally-unknown-model-9000",+ tokens_in=500_000,+ tokens_out=1_000,+ recorded_usd=0.0,+ )+ assert (cost, source) == (0.0, "unknown")+++def test_known_model_is_re_derived() -> None:+ cost, source = price_entry(+ provider="anthropic",+ model="claude-opus-4-7-20251022",+ tokens_in=1_000_000,+ tokens_out=0,+ recorded_usd=0.0,+ )+ assert source == "derived"+ assert cost > 0+++def test_no_tokens_no_gap() -> None:+ """A 0.0 with nothing consumed is not a pricing hole."""+ assert price_entry(+ provider="acme", model="unknown", tokens_in=0, tokens_out=0, recorded_usd=0.0+ ) == (0.0, "recorded")+++# ---------------------------------------------------------------------------+# Aggregation+# ---------------------------------------------------------------------------+++def test_report_totals_and_breakdowns(sources: CostSources) -> None:+ entries = collect_entries(sources)+ report = build_report(entries, since_ms=T0 - 1, until_ms=T0 + 100_000)++ totals = report.totals+ assert totals["entries"] == len(entries)+ assert totals["cost_usd"] == pytest.approx(sum(e.cost_usd for e in entries))+ assert totals["tokens_total"] == sum(e.tokens_total for e in entries)++ # Every dimension sums back to the same money.+ for dimension in (report.by_provider, report.by_model, report.by_role, report.by_surface):+ assert sum(row["cost_usd"] for row in dimension) == pytest.approx(+ totals["cost_usd"], abs=1e-6+ )++ # Ranked by cost, so the top row is the biggest spender.+ costs = [row["cost_usd"] for row in report.by_provider]+ assert costs == sorted(costs, reverse=True)+++def test_gap_tokens_are_reported_not_hidden(sources: CostSources) -> None:+ entries = collect_entries(sources)+ report = build_report(entries, since_ms=0, until_ms=T0 + 100_000)+ # grok-4.3 IS in the price table; the gap is the model-less worker draft+ # that reported tokens without a price.+ gap = report.totals["gap_tokens"]+ assert gap == sum(e.tokens_total for e in entries if e.is_gap)+ assert gap == 33_000+ assert report.totals["gap_entries"] == 1+ # The gap is NOT quietly folded into the money as if it were free.+ assert report.totals["cost_usd"] == pytest.approx(sum(e.cost_usd for e in entries))+++def test_series_buckets_by_day_over_a_long_range(sources: CostSources) -> None:+ report = build_report(+ collect_entries(sources), since_ms=T0 - 30 * 86_400_000, until_ms=T0 + 86_400_000+ )+ assert report.bucket == "day"+ assert len(report.series) >= 1+ assert all(len(row["key"]) == len("2026-08-23") for row in report.series)+++def test_series_fills_quiet_days(sources: CostSources) -> None:+ """A day with no spend still gets a bucket, or the axis lies about time."""+ entries = collect_entries(sources)+ # Two entries a week apart: the days between them must appear as zeroes.+ spread = [+ *entries,+ ]+ far = entries[0]+ spread.append(+ type(far)(+ ts_ms=far.ts_ms + 7 * 86_400_000,+ surface=far.surface,+ role=far.role,+ provider=far.provider,+ model=far.model,+ tokens_in=10,+ tokens_out=1,+ tokens_cached=0,+ cost_usd=0.01,+ price_source="recorded",+ ref_id=far.ref_id,+ label=far.label,+ )+ )+ report = build_report(spread, since_ms=0, until_ms=far.ts_ms + 8 * 86_400_000)+ assert report.bucket == "day"+ assert len(report.series) == 8+ assert sum(1 for row in report.series if row["entries"] == 0) == 6+++def test_series_buckets_by_hour_over_a_short_range(sources: CostSources) -> None:+ report = build_report(collect_entries(sources), since_ms=T0, until_ms=T0 + 3_600_000)+ assert report.bucket == "hour"+++def test_breakdown_carries_the_second_dimension(sources: CostSources) -> None:+ report = build_report(collect_entries(sources), since_ms=0, until_ms=T0 + 100_000)+ day = report.series[0]+ assert set(day["breakdown"]).issubset({"realtime", "tool", "pipeline", "agent", "worker"})+++def test_filters_narrow_the_entries(sources: CostSources) -> None:+ entries = collect_entries(sources)+ assert all(e.role == "tool" for e in filter_entries(entries, roles={"tool"}))+ assert all(e.provider == "grok" for e in filter_entries(entries, providers={"grok"}))+ assert filter_entries(entries, search="nothing matches this") == []+ # Search reaches the label, not only the ids.+ assert filter_entries(entries, search="calendar")+++def test_empty_filters_keep_everything(sources: CostSources) -> None:+ entries = collect_entries(sources)+ assert filter_entries(entries) == entries