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
fix(costs): restore the seat-accounting work my previous commit rolled back
rubenluetke10-beep3a1524d5bfb9
diff --git a/jarvis/costs/aggregate.py b/jarvis/costs/aggregate.pyindex 5999645fac..c7765184e7 100644--- a/jarvis/costs/aggregate.py+++ b/jarvis/costs/aggregate.py@@ -39,6 +39,8 @@ class Bucket:tokens_cached: int = 0entries: int = 0gap_tokens: int = 0+ #: Of ``cost_usd``, how much a monthly seat covered rather than an invoice.+ subscription_usd: float = 0.0last_ts_ms: int = 0#: Secondary dimension — which providers/models/roles fed this bucket.members: dict[str, float] = field(default_factory=lambda: defaultdict(float))@@ -51,6 +53,8 @@ class Bucket:self.entries += 1if entry.is_gap:self.gap_tokens += entry.tokens_total+ if entry.price_source == "subscription":+ self.subscription_usd += entry.cost_usdself.last_ts_ms = max(self.last_ts_ms, entry.ts_ms)if member:self.members[member] += entry.cost_usd@@ -67,6 +71,7 @@ class Bucket:"tokens_total": tokens,"entries": self.entries,"gap_tokens": self.gap_tokens,+ "subscription_usd": round(self.subscription_usd, 6),"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,@@ -166,6 +171,7 @@ def build_report(gap_tokens = gap_entries = 0free_tokens = 0derived_cost = 0.0+ subscription_cost = 0.0hourly = (until_ms - since_ms) <= _HOURLY_RANGE_MSbucket_kind = "hour" if hourly else "day"@@ -182,6 +188,8 @@ def build_report(free_tokens += e.tokens_totalif e.price_source == "derived":derived_cost += e.cost_usd+ if e.price_source == "subscription":+ subscription_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)@@ -215,6 +223,10 @@ def build_report("gap_entries": gap_entries,"free_tokens": free_tokens,"estimated_usd": round(derived_cost, 6),+ # Part of ``cost_usd``, not beside it: the work was done and is worth+ # this much, a seat just already paid for it. Subtracting it here would+ # make the section disagree with itself the moment anyone filtered.+ "subscription_usd": round(subscription_cost, 6),"first_ts_ms": entries[0].ts_ms if entries else 0,"last_ts_ms": entries[-1].ts_ms if entries else 0,}diff --git a/jarvis/costs/model.py b/jarvis/costs/model.pyindex b79c59f651..542010570f 100644--- a/jarvis/costs/model.py+++ b/jarvis/costs/model.py@@ -16,9 +16,13 @@ four very different things, and the UI must be able to tell them apart:``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+``subscription`` a seat paid monthly — the amount is what the same work+ would have cost through the API, not money that movedOnly ``unknown`` is a hole in the accounting, and it is reported as tokens,-never quietly folded into the total as if it were free.+never quietly folded into the total as if it were free. ``subscription`` is+the opposite kind of honesty: the number is real arithmetic on real tokens,+but no invoice carries it, so it is named rather than mixed in silently."""from __future__ import annotations@@ -51,7 +55,7 @@ ROLE_WORKER = "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"]+PriceSource = Literal["recorded", "derived", "free", "unknown", "subscription"]# 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.@@ -65,6 +69,8 @@ LOCAL_PROVIDERS: frozenset[str] = frozenset("lmstudio","vllm","whisper-local",+ # Any OpenAI-compatible server the user points at themselves.+ "local-openai",})@@ -78,6 +84,20 @@ SUBSCRIPTION_PROVIDERS: frozenset[str] = frozenset(})+# The other half of the same question, and the reliable one. A provider id+# cannot answer it: ``claude-api`` is one row for two billing worlds — the+# Claude Code CLI on a Max seat when it is installed, the Anthropic API+# otherwise (:mod:`jarvis.agent_chat.catalog`). Only the runner that actually+# answered the turn knows, and it is recorded on every ``turn_started``.+SUBSCRIPTION_RUNNERS: frozenset[str] = frozenset(+ {+ "claude-cli",+ "codex-cli",+ "agy-cli",+ "grok-cli",+ }+)+@dataclass(frozen=True, slots=True)class CostEntry:@@ -137,6 +157,7 @@ def price_entry(tokens_in: int,tokens_out: int,recorded_usd: float,+ subscription: bool = False,) -> tuple[float, PriceSource]:"""Settle what a call actually cost and how confident that number is.@@ -144,11 +165,29 @@ def price_entry(modality (audio vs text) and we do not. Everything else is re-derived fromthe shared rate tables so a model the price table gained later stopsshowing up as free.++ ``subscription`` says a monthly seat answered the turn. The amount is still+ the API-equivalent — a seat that reports one (Claude Code does) is quoting+ exactly that, and a seat that reports nothing gets the rate tables applied+ like any other call. What changes is the label, so a report can show the+ worth of the work without claiming the money moved. A seat whose model has+ no rate anywhere is still a gap: the tokens are real and unpriced."""+ tokens = max(0, tokens_in) + max(0, tokens_out)+ if subscription and tokens > 0:+ if recorded_usd > 0:+ return float(recorded_usd), "subscription"+ # Lazy, like the branch below: a report of nothing but priced seats+ # never has to load the catalogue.+ from jarvis.brain.cost import calculate_cost_usd, resolve_rates++ if model and resolve_rates(model) is not None:+ return calculate_cost_usd(model, tokens_in, tokens_out), "subscription"+ return 0.0, "unknown"+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"diff --git a/jarvis/costs/sources.py b/jarvis/costs/sources.pyindex 9e8e87eecf..7c909838ad 100644--- a/jarvis/costs/sources.py+++ b/jarvis/costs/sources.py@@ -23,6 +23,7 @@ from .model import (ROLE_REALTIME,ROLE_TOOL,ROLE_WORKER,+ SUBSCRIPTION_RUNNERS,SURFACE_AGENT_CHAT,SURFACE_MISSION,SURFACE_VOICE,@@ -281,13 +282,21 @@ _AGENT_IN_KEYS = ("cache_creation_input_tokens","cache_write_input_tokens",)-_AGENT_OUT_KEYS = (- "output_tokens",- "completion_tokens",- "reasoning_output_tokens",- "thinking_tokens",+_AGENT_OUT_KEYS = ("output_tokens", "completion_tokens")++# Reasoning is a BREAKDOWN of the output count, not a sibling of it — both+# Anthropic and OpenAI report it inside ``output_tokens_details``. Summing it+# alongside counted those tokens twice. It stands in only when a runner reports+# no primary output count at all.+_AGENT_OUT_DETAIL_KEYS = ("reasoning_output_tokens", "thinking_tokens")++_AGENT_CACHED_KEYS = (+ "cache_read_input_tokens",+ "cached_input_tokens",+ "cache_read_tokens",+ # What the in-process API runner and the brain plugins call it.+ "cache_hit_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]:@@ -305,6 +314,33 @@ def _agent_chat_entries(path: Path | None, since_ms: int, until_ms: int) -> Iter):sessions[str(row["session_id"])] = row+ # ``turn_started`` is where the runner is named, and it is the only+ # place that says whether a monthly seat or an API key answered: the+ # ``claude-api`` row means either, decided at call time. It also holds+ # the model AS IT WAS, which the session row does not — that one moves+ # with the picker and would re-label every past turn.+ #+ # Unfiltered by time on purpose: a turn that started before the window+ # and finished inside it still needs its own runner.+ starts: dict[str, dict[str, str]] = {}+ for row in conn.execute(+ "SELECT payload FROM agent_chat_events WHERE kind = 'turn_started'"+ ):+ try:+ started = json.loads(row["payload"] or "{}")+ except (TypeError, ValueError) as exc:+ log.debug("cost read model: unparsable turn_started (%s)", exc)+ continue+ if not isinstance(started, dict):+ continue+ turn_id = str(started.get("turn_id") or "")+ if turn_id:+ starts[turn_id] = {+ "runner": str(started.get("runner") or ""),+ "provider": str(started.get("provider") or ""),+ "model": str(started.get("model") or ""),+ }+for row in conn.execute("SELECT session_id, ts_ms, payload FROM agent_chat_events ""WHERE kind = 'turn_finished' AND ts_ms BETWEEN ? AND ?",@@ -321,19 +357,24 @@ def _agent_chat_entries(path: Path | None, since_ms: int, until_ms: int) -> Iterusage = 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)+ if tokens_out <= 0:+ tokens_out = sum(_int(usage.get(k)) for k in _AGENT_OUT_DETAIL_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:continuesession = 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 "")+ start = starts.get(str(payload.get("turn_id") or ""), {})+ session_provider = str(session["provider"] if session is not None else "")+ provider = start.get("provider") or session_provider or "agent-cli"+ model = start.get("model") or 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,+ subscription=start.get("runner", "") in SUBSCRIPTION_RUNNERS,)yield CostEntry(ts_ms=_int(row["ts_ms"]),diff --git a/jarvis/ui/web/costs_routes.py b/jarvis/ui/web/costs_routes.pyindex d0c0c29321..713b54be71 100644--- a/jarvis/ui/web/costs_routes.py+++ b/jarvis/ui/web/costs_routes.py@@ -58,6 +58,7 @@ class Bucket(BaseModel):tokens_total: intentries: intgap_tokens: int+ subscription_usd: float = 0.0last_ts_ms: intcost_share: floattoken_share: float@@ -82,6 +83,9 @@ class Totals(BaseModel):"""Tokens spent at a rate no price table knows — the accounting hole."""gap_entries: intfree_tokens: int+ #: Of ``cost_usd``, the share a monthly seat covered — priced as the API+ #: would have, but no invoice carries it.+ subscription_usd: float = 0.0"""Tokens on local engines, subscription seats or ``:free`` models."""estimated_usd: float"""Share of ``cost_usd`` this section re-derived rather than read back."""diff --git a/jarvis/ui/web/frontend/src/components/costs/costFormat.ts b/jarvis/ui/web/frontend/src/components/costs/costFormat.tsindex d8c9b6c7a2..cd597c106b 100644--- a/jarvis/ui/web/frontend/src/components/costs/costFormat.ts+++ b/jarvis/ui/web/frontend/src/components/costs/costFormat.ts@@ -15,9 +15,19 @@ export const ROLE_COLORS: Record<CostRole, string> = {pipeline: "hsl(268 72% 68%)", // violet — the classic brain pathagent: "hsl(152 58% 52%)", // green — coding agentsworker: "hsl(18 88% 62%)", // orange — autonomous missions+ stt: "hsl(340 75% 65%)", // rose — the ear+ tts: "hsl(30 90% 60%)", // amber — the voice};-export const ROLE_ORDER: CostRole[] = ["realtime", "tool", "pipeline", "agent", "worker"];+export const ROLE_ORDER: CostRole[] = [+ "realtime",+ "tool",+ "pipeline",+ "agent",+ "worker",+ "stt",+ "tts",+];/** Fallback for a bucket key that is not a role (provider, model, day). */export const NEUTRAL_COLOR = "hsl(0 0% 62%)";@@ -139,9 +149,57 @@ export function priceSourceTone(source: PriceSource): "ok" | "warn" | "off" | "ereturn "warn";case "free":return "off";+ case "subscription":+ // Not a warning and not a gap: the number is sound, it just is not a+ // bill. It reads as its own thing rather than borrowing another's tone.+ return "ok";default:return "error";}}-export const ALL_SURFACES: CostSurface[] = ["voice", "agent-chat", "mission"];+export const ALL_SURFACES: CostSurface[] = [+ "voice",+ "agent-chat",+ "mission",+ "agentic-ide",+ "jarvis-voice",+];++/**+ * The top-level areas the section can be read as, and which surfaces each one+ * covers.+ *+ * Surfaces are how the read model records a line item; these are how a person+ * thinks about the app. The two are not the same shape — "Jarvis" is three+ * surfaces at once — so the grouping lives here rather than being inferred.+ * `surfaces: []` means no filter at all, which is what "Overall" is.+ */+export interface SurfaceGroup {+ id: string;+ surfaces: CostSurface[];+ /** Roles that can occur in this area, in the order they should be offered. */+ roles: CostRole[];+}++export const SURFACE_GROUPS: SurfaceGroup[] = [+ { id: "all", surfaces: [], roles: ROLE_ORDER },+ {+ id: "jarvis",+ surfaces: ["voice", "agent-chat", "mission"],+ roles: ["realtime", "tool", "pipeline", "agent", "worker"],+ },+ { id: "agentic-ide", surfaces: ["agentic-ide"], roles: ["agent", "worker"] },+ { id: "jarvis-voice", surfaces: ["jarvis-voice"], roles: ["stt", "tts"] },+];++/** The group whose surfaces are exactly the ones selected, if any. */+export function surfaceGroupFor(surfaces: readonly string[]): SurfaceGroup | null {+ const want = [...surfaces].sort().join(",");+ if (!want) return SURFACE_GROUPS[0];+ return SURFACE_GROUPS.find((g) => g.surfaces.length > 0 && [...g.surfaces].sort().join(",") === want) ?? null;+}++export function surfaceGroupLabelKey(id: string): string {+ return `costs_view.area.${id.replace(/-/g, "_")}`;+}diff --git a/jarvis/ui/web/frontend/src/hooks/useCosts.ts b/jarvis/ui/web/frontend/src/hooks/useCosts.tsindex 0ad91c6d64..a9121215da 100644--- a/jarvis/ui/web/frontend/src/hooks/useCosts.ts+++ b/jarvis/ui/web/frontend/src/hooks/useCosts.ts@@ -12,10 +12,24 @@ import { useQuery } from "@tanstack/react-query";// ---------------------------------------------------------------------------/** Which model in a turn spent this. */-export type CostRole = "realtime" | "tool" | "pipeline" | "agent" | "worker";+export type CostRole =+ | "realtime"+ | "tool"+ | "pipeline"+ | "agent"+ | "worker"+ // The speech layer bills by audio second and by character, not by token —+ // its own two roles rather than a shape forced onto the token vocabulary.+ | "stt"+ | "tts";/** Which part of the app it was spent in. */-export type CostSurface = "voice" | "agent-chat" | "mission";+export type CostSurface =+ | "voice"+ | "agent-chat"+ | "mission"+ | "agentic-ide"+ | "jarvis-voice";/*** How confident the price is.@@ -23,8 +37,10 @@ export type CostSurface = "voice" | "agent-chat" | "mission";* - `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+ * - `subscription` a monthly seat did the work; the amount is what the same+ * call would have cost through the API, not money that moved*/-export type PriceSource = "recorded" | "derived" | "free" | "unknown";+export type PriceSource = "recorded" | "derived" | "free" | "unknown" | "subscription";export interface CostBucket {key: string;@@ -35,6 +51,8 @@ export interface CostBucket {tokens_total: number;entries: number;gap_tokens: number;+ /** Of `cost_usd`, the part a monthly seat already paid for. */+ subscription_usd: number;last_ts_ms: number;cost_share: number;token_share: number;@@ -62,6 +80,8 @@ export interface CostTotals {gap_entries: number;free_tokens: number;estimated_usd: number;+ /** Of `cost_usd`, the part covered by a subscription rather than invoiced. */+ subscription_usd: number;first_ts_ms: number;last_ts_ms: number;}diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.jsonindex cbb8acddc2..2cc0d16361 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json@@ -4283,7 +4283,7 @@"setup_label": "Arbeitsbereich einrichten","reading_mode": "Darstellung","reading_mode_label": "Darstellung des Arbeitsbereichs",- "view_hint": "Es geht nichts verloren: Die Terminals arbeiten hinter dem Chat weiter, und der Schalter in der Workspace-Leiste wechselt jederzeit zwischen beiden.",+ "view_hint": "Nur die Darstellung ändert sich — Agents, Fenster und Unterhaltungen bleiben gleich, und die Toolbar kann jederzeit wechseln.","selected": "Ausgewählt","workspace": "Arbeitsbereich","opens_as": "Wird geöffnet als",@@ -4294,12 +4294,12 @@"folder": { "label": "Ordner", "title": "Projektordner auswählen", "hint": "Alles, was die Agents tun, bleibt in diesem Ordner." },"layout": { "label": "Layout", "title": "Arbeitsbereich aufteilen", "hint": "Lege fest, wie viele unabhängige Terminal-Fenster geöffnet werden." },"agents": { "label": "Agents" },- "view": { "label": "Ansicht", "title": "Darstellung des Arbeitsbereichs auswählen", "hint": "Danach ist beides einen Klick entfernt — der Schalter sitzt in der Workspace-Leiste." },+ "view": { "label": "Ansicht", "title": "Darstellung des Arbeitsbereichs auswählen", "hint": "Die Agents bleiben gleich — die Toolbar kann jederzeit umschalten." },"review": { "label": "Prüfen", "title": "Vor dem Öffnen prüfen", "hint": "Nichts startet, bevor du den Arbeitsbereich öffnest." }},"views": {"grid": { "title": "Terminal-Raster", "description": "Alle Fenster gleichzeitig nebeneinander — die vollständige Terminal-Wand." },- "chat": { "title": "Chat", "description": "Der Agenten-Chat, im Ordner dieses Workspaces — schreiben statt Terminals zuschauen." }+ "chat": { "title": "Chat-Ansicht", "description": "Ein Agent im Mittelpunkt, die anderen in einer Leiste — lesbar wie eine Unterhaltung." }}},"crowded": {@@ -4999,6 +4999,14 @@"subtitle": "{entries} Aufrufe · {models} Modelle · {providers} Anbieter","subtitle_loading": "Liest, was jeder Anbieter, jedes Modell und jede Rolle gekostet hat","range_label": "Zeitraum",+ "area": {+ "all": "Gesamt",+ "jarvis": "{name}",+ "agentic_ide": "Agentic IDE",+ "jarvis_voice": "{name} Voice"+ },+ "area_label": "Welchen Bereich der App anzeigen",+ "role_filter_label": "Nach der Aufgabe des Modells filtern","range_days": "{days} T","range_all": "Alles","currency_label": "Währung",@@ -5009,8 +5017,10 @@"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_total_hint_seat": "{perDay}/Tag · {seat} über ein Abo","stat_tokens": "Tokens","stat_tokens_hint": "{in} rein · {out} raus",+ "stat_tokens_hint_cached": "{in} rein · {cached} Cache · {out} raus","stat_top_provider": "Größter Posten","stat_top_provider_hint": "{amount} · {share} der Gesamtkosten","stat_none": "Noch nichts erfasst",@@ -5070,18 +5080,23 @@"tool": "Tool-Modell","pipeline": "Pipeline-Gehirn","agent": "Coding-Agent",- "worker": "Missions-Worker"+ "worker": "Missions-Worker",+ "stt": "Sprache zu Text",+ "tts": "Text zu Sprache"},"surface": {"voice": "Sprache","agent_chat": "Agenten-Chat",- "mission": "Mission"+ "mission": "Mission",+ "agentic_ide": "Agentic IDE",+ "jarvis_voice": "{name} Voice"},"price_source": {"recorded": "Abgerechnet","derived": "Geschätzt","free": "Kostenlos",- "unknown": "Ohne Preis"+ "unknown": "Ohne Preis",+ "subscription": "Abo"}},"all_chats": {@@ -5107,4 +5122,4 @@"read_only": "Eine gesprochene Unterhaltung. Sprich weiter, um sie fortzusetzen.","continue": "Per Sprache fortsetzen"}-}\ No newline at end of file+}diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.jsonindex f94a4fc2dd..22befdde3f 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json@@ -4283,7 +4283,7 @@"setup_label": "Workspace setup","reading_mode": "Reading mode","reading_mode_label": "How the workspace opens",- "view_hint": "Nothing is given up either way: the terminals keep working behind the chat, and the switch in the workspace bar moves between the two at any time.",+ "view_hint": "Only how the workspace is read changes — the agents, panes and conversations stay the same, and the toolbar can switch at any time.","selected": "Selected","workspace": "Workspace","opens_as": "Opens as",@@ -4294,12 +4294,12 @@"folder": { "label": "Folder", "title": "Choose the project folder", "hint": "Everything the agents do stays inside this folder." },"layout": { "label": "Layout", "title": "Shape the workspace", "hint": "Choose how many independent terminal panes should open." },"agents": { "label": "Agents" },- "view": { "label": "View", "title": "Choose how to read the workspace", "hint": "Both are one click apart afterwards — the switch is in the workspace bar." },+ "view": { "label": "View", "title": "Choose how to read the workspace", "hint": "The same agents either way — the toolbar can switch at any time." },"review": { "label": "Review", "title": "Review before opening", "hint": "Nothing starts until you open the workspace." }},"views": {"grid": { "title": "Terminal grid", "description": "Every pane on screen at once, side by side — the full wall of terminals." },- "chat": { "title": "Chat", "description": "The agent chat, running in this workspace's folder — type instead of watching terminals." }+ "chat": { "title": "Chat view", "description": "One agent at a time on a calm stage, the rest on a rail — read like a conversation." }}},"crowded": {@@ -4999,6 +4999,14 @@"subtitle": "{entries} calls · {models} models · {providers} providers","subtitle_loading": "Reading what every provider, model and role cost","range_label": "Time range",+ "area": {+ "all": "Overall",+ "jarvis": "{name}",+ "agentic_ide": "Agentic IDE",+ "jarvis_voice": "{name} Voice"+ },+ "area_label": "Which part of the app to show",+ "role_filter_label": "Filter by what the model was doing","range_days": "{days}d","range_all": "All","currency_label": "Currency",@@ -5009,8 +5017,10 @@"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_total_hint_seat": "{perDay}/day · {seat} on a subscription","stat_tokens": "Tokens","stat_tokens_hint": "{in} in · {out} out",+ "stat_tokens_hint_cached": "{in} in · {cached} cached · {out} out","stat_top_provider": "Biggest spender","stat_top_provider_hint": "{amount} · {share} of the total","stat_none": "Nothing recorded yet",@@ -5070,18 +5080,23 @@"tool": "Tool model","pipeline": "Pipeline brain","agent": "Coding agent",- "worker": "Mission worker"+ "worker": "Mission worker",+ "stt": "Speech to text",+ "tts": "Text to speech"},"surface": {"voice": "Voice","agent_chat": "Agent chat",- "mission": "Mission"+ "mission": "Mission",+ "agentic_ide": "Agentic IDE",+ "jarvis_voice": "{name} Voice"},"price_source": {"recorded": "Billed","derived": "Estimated","free": "Free",- "unknown": "Unpriced"+ "unknown": "Unpriced",+ "subscription": "Subscription"}},"all_chats": {@@ -5107,4 +5122,4 @@"read_only": "A spoken conversation. Continue it by talking.","continue": "Continue by voice"}-}\ No newline at end of file+}diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.jsonindex c0a7b2dac7..5df9b64e2d 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json@@ -4283,7 +4283,7 @@"setup_label": "Configurar espacio de trabajo","reading_mode": "Modo de lectura","reading_mode_label": "Cómo se abre el espacio de trabajo",- "view_hint": "No se pierde nada: las terminales siguen trabajando detrás del chat y el conmutador de la barra cambia entre ambas en cualquier momento.",+ "view_hint": "Solo cambia la presentación: los agentes, paneles y conversaciones siguen iguales, y la barra permite cambiar en cualquier momento.","selected": "Seleccionado","workspace": "Espacio de trabajo","opens_as": "Se abre como",@@ -4294,12 +4294,12 @@"folder": { "label": "Carpeta", "title": "Elige la carpeta del proyecto", "hint": "Todo lo que hagan los agentes permanece dentro de esta carpeta." },"layout": { "label": "Diseño", "title": "Diseña el espacio de trabajo", "hint": "Elige cuántos paneles de terminal independientes deben abrirse." },"agents": { "label": "Agentes" },- "view": { "label": "Vista", "title": "Elige cómo leer el espacio", "hint": "Después ambas quedan a un clic: el conmutador está en la barra del espacio de trabajo." },+ "view": { "label": "Vista", "title": "Elige cómo leer el espacio", "hint": "Los agentes son los mismos y la barra permite cambiar en cualquier momento." },"review": { "label": "Revisar", "title": "Revisa antes de abrir", "hint": "Nada empieza hasta que abras el espacio de trabajo." }},"views": {"grid": { "title": "Cuadrícula de terminales", "description": "Todos los paneles a la vez, uno junto a otro: la pared completa de terminales." },- "chat": { "title": "Chat", "description": "El chat de agentes, en la carpeta de este espacio de trabajo: escribe en lugar de mirar terminales." }+ "chat": { "title": "Vista de chat", "description": "Un agente en el centro y los demás en una barra, como una conversación." }}},"crowded": {@@ -4999,6 +4999,14 @@"subtitle": "{entries} llamadas · {models} modelos · {providers} proveedores","subtitle_loading": "Leyendo lo que costó cada proveedor, modelo y función","range_label": "Periodo",+ "area": {+ "all": "Total",+ "jarvis": "{name}",+ "agentic_ide": "Agentic IDE",+ "jarvis_voice": "{name} Voice"+ },+ "area_label": "Qué parte de la aplicación mostrar",+ "role_filter_label": "Filtrar por la tarea del modelo","range_days": "{days} d","range_all": "Todo","currency_label": "Moneda",@@ -5009,8 +5017,10 @@"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_total_hint_seat": "{perDay}/día · {seat} con una suscripción","stat_tokens": "Tokens","stat_tokens_hint": "{in} entrada · {out} salida",+ "stat_tokens_hint_cached": "{in} entrada · {cached} caché · {out} salida","stat_top_provider": "Mayor gasto","stat_top_provider_hint": "{amount} · {share} del total","stat_none": "Todavía no hay datos",@@ -5070,18 +5080,23 @@"tool": "Modelo de herramientas","pipeline": "Cerebro de la cadena","agent": "Agente de código",- "worker": "Trabajador de misión"+ "worker": "Trabajador de misión",+ "stt": "Voz a texto",+ "tts": "Texto a voz"},"surface": {"voice": "Voz","agent_chat": "Chat de agentes",- "mission": "Misión"+ "mission": "Misión",+ "agentic_ide": "Agentic IDE",+ "jarvis_voice": "{name} Voice"},"price_source": {"recorded": "Facturado","derived": "Estimado","free": "Gratis",- "unknown": "Sin precio"+ "unknown": "Sin precio",+ "subscription": "Suscripción"}},"all_chats": {@@ -5107,4 +5122,4 @@"read_only": "Una conversación hablada. Continúala hablando.","continue": "Continuar por voz"}-}\ No newline at end of file+}diff --git a/jarvis/ui/web/frontend/src/views/CostsView.tsx b/jarvis/ui/web/frontend/src/views/CostsView.tsxindex c4c554295f..db28d04a55 100644--- a/jarvis/ui/web/frontend/src/views/CostsView.tsx+++ b/jarvis/ui/web/frontend/src/views/CostsView.tsx@@ -16,6 +16,7 @@import { useMemo, useState } from "react";import {AlertTriangle,+ AudioLines,ChevronDown,Coins,Hash,@@ -23,10 +24,14 @@ import {RefreshCw,Search,Sigma,+ Sparkles,Tag,+ Terminal,+ Wallet,X,} from "lucide-react";import { ScrollArea } from "@/components/ui/scroll-area";+import { ProviderLogo } from "@/components/providers/ProviderLogo";import {Cell,Column,@@ -55,6 +60,9 @@ import {priceSourceTone,roleColor,roleLabelKey,+ SURFACE_GROUPS,+ surfaceGroupFor,+ surfaceGroupLabelKey,surfaceLabelKey,} from "@/components/costs/costFormat";import {@@ -130,6 +138,20 @@ export function CostsView() {const activeFor = (d: Dimension): string[] => filters[filterKeyFor(d)] as string[];+ // The switch is not extra state: it reads the surface filter and writes it.+ // Anything else would let a row click and the switch disagree about which+ // area is on screen.+ const area = surfaceGroupFor(filters.surfaces);+ const pickArea = (id: string) => {+ const group = SURFACE_GROUPS.find((g) => g.id === id);+ if (!group) return;+ setVisible(ENTRY_PAGE);+ // Roles are cleared with the area: "pipeline brain" means nothing once you+ // are looking at the speech layer, and a stale role filter would silently+ // empty the new area.+ setFilters((f) => ({ ...f, surfaces: [...group.surfaces], roles: [] }));+ };+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;@@ -193,6 +215,21 @@ export function CostsView() {}/>+ {/* ---------------------------------------------------------------+ Which part of the app you are looking at. Roles answer "what kind+ of model"; this answers "where" — and the two together are the+ question people actually ask ("what does the coding agent cost me").+ --------------------------------------------------------------- */}+ <div className="flex flex-wrap items-center gap-x-2 gap-y-2">+ <AreaSwitch value={area?.id ?? null} onChange={pickArea} />+ <RoleFilters+ roles={(area ?? SURFACE_GROUPS[0]).roles}+ available={data?.facets.roles ?? []}+ active={filters.roles}+ onToggle={(role) => toggle("roles", role)}+ />+ </div>+{searchOpen ? (<div className="max-w-sm"><InlineSearch@@ -229,21 +266,47 @@ export function CostsView() {one number without the other hides that.--------------------------------------------------------------- */}<div className="grid gap-3 sm:grid-cols-2 xl:grid-cols-4">+ {/*+ The headline is everything the work was worth. A subscription seat+ did some of it, and that part is named rather than netted out —+ hiding it would make the total disagree with every breakdown below.+ */}<StatTileicon={<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) })}+ hint={+ (totals?.subscription_usd ?? 0) > 0+ ? fill(t("costs_view.stat_total_hint_seat"), {+ perDay: money(perDay),+ seat: money(totals?.subscription_usd ?? 0),+ })+ : fill(t("costs_view.stat_total_hint"), { perDay: money(perDay) })+ }loading={summary.isLoading}/>+ {/*+ The headline is in + cached + out. Cache reads bill at their own+ rate, so the read model keeps them out of `tokens_in` — naming only+ two of the three buckets made the tile look like it could not add+ up. The cached term appears only when there is cache to report.+ */}<StatTileicon={<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),- })}+ hint={fill(+ t(+ (totals?.tokens_cached ?? 0) > 0+ ? "costs_view.stat_tokens_hint_cached"+ : "costs_view.stat_tokens_hint",+ ),+ {+ in: formatTokens(totals?.tokens_in ?? 0),+ cached: formatTokens(totals?.tokens_cached ?? 0),+ out: formatTokens(totals?.tokens_out ?? 0),+ },+ )}loading={summary.isLoading}/><StatTile@@ -455,6 +518,136 @@ export function CostsView() {);}+// ---------------------------------------------------------------------------+// Which area of the app — and which kind of model inside it+// ---------------------------------------------------------------------------++/** One lucide mark per area, so the switch reads without its labels too. */+const AREA_ICONS = {+ all: Wallet,+ jarvis: Sparkles,+ "agentic-ide": Terminal,+ "jarvis-voice": AudioLines,+} as const;++/**+ * Overall · Jarvis · Agentic IDE · Jarvis Voice.+ *+ * The same pill the front page uses for Voice/Chat (`home/SurfaceSwitch`) —+ * one shape for "which area am I in", wherever the question appears.+ *+ * `value` is null when a breakdown row produced a surface selection no area+ * matches. Nothing is lit then, which is the honest state: the chips under+ * the header say what is actually filtered.+ */+function AreaSwitch({+ value,+ onChange,+}: {+ value: string | null;+ onChange: (id: string) => void;+}) {+ const t = useT();+ return (+ <div+ role="tablist"+ aria-label={t("costs_view.area_label")}+ data-testid="costs-area-switch"+ // Hugs its labels on a real window and only goes full width when+ // there is no room to sit beside itself — a control stretched across+ // 1400px reads as a header bar, not as a choice between four things.+ className={cn(+ "flex w-full flex-wrap items-center gap-0.5 rounded-xl border border-border bg-secondary p-0.5",+ "sm:w-auto sm:flex-nowrap sm:self-start",+ )}+ >+ {SURFACE_GROUPS.map((group) => {+ const active = group.id === value;+ const Icon = AREA_ICONS[group.id as keyof typeof AREA_ICONS] ?? Wallet;+ return (+ <button+ key={group.id}+ type="button"+ role="tab"+ aria-selected={active}+ data-testid={`costs-area-${group.id}`}+ onClick={() => onChange(group.id)}+ className={cn(+ "flex flex-1 items-center justify-center gap-1.5 rounded-[10px] px-3 py-1.5 text-xs font-medium transition-colors sm:flex-none",+ "focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring",+ active+ ? "bg-card text-foreground shadow-sm"+ : "text-muted-foreground hover:text-foreground",+ )}+ >+ <Icon aria-hidden className="h-3.5 w-3.5" />+ <span className="truncate">{t(surfaceGroupLabelKey(group.id))}</span>+ </button>+ );+ })}+ </div>+ );+}++/**+ * The roles that can occur in the chosen area, as toggles.+ *+ * Only roles the data has actually seen are offered — an area that has never+ * run shows no chips rather than a row of dead buttons. A single possible+ * role is not a choice, so the row hides itself entirely.+ */+function RoleFilters({+ roles,+ available,+ active,+ onToggle,+}: {+ roles: CostRole[];+ available: CostRole[];+ active: CostRole[];+ onToggle: (role: CostRole) => void;+}) {+ const t = useT();+ const shown = roles.filter((r) => available.includes(r));+ if (shown.length < 2) return null;+ return (+ <div+ role="group"+ aria-label={t("costs_view.role_filter_label")}+ data-testid="costs-role-filters"+ className="flex flex-wrap items-center gap-1"+ >+ <span className="mr-1 hidden h-4 w-px shrink-0 bg-border sm:block" aria-hidden />+ {shown.map((role) => {+ const on = active.includes(role);+ return (+ <button+ key={role}+ type="button"+ aria-pressed={on}+ data-testid={`costs-role-${role}`}+ onClick={() => onToggle(role)}+ className={cn(+ "inline-flex h-7 items-center gap-1.5 rounded-md px-2.5 text-xs transition-colors",+ "focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring",+ on+ ? "bg-sheen/[0.08] font-medium text-foreground"+ : "text-muted-foreground hover:text-foreground",+ )}+ >+ <span+ className="h-2 w-2 shrink-0 rounded-[3px]"+ style={{ background: roleColor(role) }}+ aria-hidden+ />+ {t(roleLabelKey(role))}+ </button>+ );+ })}+ </div>+ );+}+// ---------------------------------------------------------------------------// Active filters// ---------------------------------------------------------------------------@@ -559,6 +752,15 @@ function BreakdownTable({{rows.map((row) => {const isActive = active.includes(row.key);const color = dimension === "role" ? roleColor(row.key) : keyColor(row.key);+ // A provider row IS its vendor; a model row belongs to one. Roles and+ // surfaces are ours, not a vendor's — they keep the colour chip that+ // ties the row to its stack in the chart above.+ const logoId =+ dimension === "provider"+ ? row.key+ : dimension === "model"+ ? (row.members[0] ?? row.key)+ : null;return (<TableRowkey={row.key}@@ -569,11 +771,15 @@ function BreakdownTable({><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- />+ {logoId ? (+ <ProviderLogo providerId={logoId} label={row.key} size="sm" />+ ) : (+ <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"