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 seat is not a bill, a cache read is not an input, and every provider wears its own mark
rubenluetke10-beepbff0b7576c10
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/components/extensions/primitives.tsx b/jarvis/ui/web/frontend/src/components/extensions/primitives.tsxindex 0e910cf220..c2a2e119b8 100644--- a/jarvis/ui/web/frontend/src/components/extensions/primitives.tsx+++ b/jarvis/ui/web/frontend/src/components/extensions/primitives.tsx@@ -648,3 +648,80 @@ export function SegmentedFilter<T extends string>({</div>);}++// ---------------------------------------------------------------------------+// Stat tile — the headline numbers above a table+// ---------------------------------------------------------------------------++/**+ * One number with a label above it and a line of context below.+ *+ * Lives here rather than next to its first caller because two sections now+ * open with a row of these (Spend and the agent board) and a second copy is+ * exactly the drift this file exists to prevent. Four per row on a wide pane,+ * two on a narrow one — the caller supplies the grid.+ *+ * `tone` colours only the icon; the value itself always stays `foreground` so+ * a row of tiles reads as one block of numbers rather than a traffic light.+ */+export function StatTile({+ icon,+ label,+ value,+ hint,+ tone = "ok",+ loading,+}: {+ icon?: ReactNode;+ label: string;+ value: ReactNode;+ hint?: ReactNode;+ tone?: "ok" | "warn" | "danger" | "primary" | "success";+ loading?: boolean;+}) {+ return (+ // A named group, so a screen reader announces "Failed, 0, nothing broke"+ // as one figure rather than three loose numbers in a row of five tiles.+ <div+ role="group"+ aria-label={label}+ 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">+ {icon ? (+ <span+ className={cn(+ tone === "warn" && "text-amber-500",+ tone === "danger" && "text-destructive",+ tone === "primary" && "text-primary",+ // Emerald carries a meaning the token set has no name for+ // ("finished cleanly") and needs its own value per theme: the+ // 400 shade glows on charcoal and drops to ~2:1 on paper.+ tone === "success" && "text-emerald-600 dark:text-emerald-400",+ )}+ >+ {icon}+ </span>+ ) : null}+ <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={typeof value === "string" ? value : undefined}+ >+ {value}+ </div>+ {hint ? (+ <div+ className="mt-0.5 truncate text-[11px] text-muted-foreground"+ title={typeof hint === "string" ? hint : undefined}+ >+ {hint}+ </div>+ ) : null}+ </div>+ );+}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 681366f0f0..2cc0d16361 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json@@ -688,25 +688,56 @@},"subagents_view": {"title": "{name}-Agents",+ "subtitle": "{active} laufen · {total} insgesamt","explicit_spawn_hint": "{name}-Agents starten nur, wenn du ausdrücklich danach fragst — sag z. B. „Spawne einen Agenten dafür“ oder „Mach einen Deep Dive mit einem Agenten“.",- "stat_active": "aktiv",- "stat_total": "gesamt","clear": "Leeren","clear_tooltip": "Tafel leeren",- "board_title": "Abfahrtstafel",- "active_label": "Aktiv",+ "stat_agents_hint": "in dieser Sitzung gestartet",+ "stat_active_label": "Laufend",+ "stat_active_hint": "{tools} Tool-Aufrufe unterwegs",+ "stat_active_hint_idle": "nichts unterwegs",+ "stat_done_label": "Fertig",+ "stat_done_hint": "abgeschlossen und zurückgemeldet",+ "stat_failed_label": "Fehlgeschlagen",+ "stat_failed_hint": "siehe Spalte Ergebnis",+ "stat_failed_hint_none": "nichts ist schiefgegangen",+ "stat_tools_label": "Tool-Aufrufe",+ "stat_tools_hint": "über alle Agents",+ "board_title": "Einsatzübersicht",+ "board_subtitle": "Live aus der Backend-Registry und dem Mission-WebSocket.",+ "live_label": "Live","standby_label": "Standby",+ "col_expand": "Zeile ausklappen","col_agent": "{name}-Agent",- "col_target": "Ziel",+ "col_task": "Aufgabe / Projekt","col_status": "Status",- "col_cost": "Kosten",- "agents_traveling": "{name}-Agent(s) unterwegs",- "last_departure": "letzte Abfahrt",- "last_departure_ago": "letzte Abfahrt vor {0}",+ "col_tools": "Tools",+ "col_runtime": "Laufzeit",+ "col_result": "Ergebnis",+ "role_worker": "Worker",+ "role_worker_hint": "Worker-Prozess",+ "role_agent_hint": "Hintergrund-Agent",+ "task_none": "Keine Aufgabe erfasst",+ "result_done": "Fertig",+ "result_running": "Läuft",+ "empty_title": "Gerade laufen keine {agents}.",+ "empty_body": "Sobald {name} einen echten {agent} startet, erscheint er hier mit Aufgabe, Status, Tool-Aufrufen, Laufzeit und Ergebnis.",+ "snapshot_error": "Die Tafel konnte nicht geladen werden: {detail}",+ "drill_tools": "Tool-Aufrufe",+ "drill_tools_empty": "Keine Tool-Aufrufe erfasst.",+ "drill_details": "{agent} – Details",+ "drill_trace": "Trace {trace}",+ "tool_unnamed": "Tool",+ "tool_status": {+ "running": "Läuft",+ "completed": "Fertig",+ "failed": "Fehlgeschlagen"+ },"status": {- "running": "fährt",- "completed": "ankunft",- "failed": "störung"+ "running": "Läuft",+ "completed": "Fertig",+ "failed": "Fehlgeschlagen",+ "cancelled": "Abgebrochen"},"health_degraded": "Subagent-Anbieter beeinträchtigt","health_error": "Kein Subagent-Anbieter erreichbar",@@ -4968,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",@@ -4978,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",@@ -5039,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": {@@ -5076,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 26359d5ee4..22befdde3f 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json@@ -688,25 +688,56 @@},"subagents_view": {"title": "{name}-Agents",+ "subtitle": "{active} running · {total} in total","explicit_spawn_hint": "{name}-Agents start only when you explicitly ask for one — say e.g. “Spawn an agent for this” or “Do a deep dive with an agent”.",- "stat_active": "active",- "stat_total": "total","clear": "Clear","clear_tooltip": "Clear board",- "board_title": "Departure Board",- "active_label": "Active",+ "stat_agents_hint": "started in this session",+ "stat_active_label": "Running",+ "stat_active_hint": "{tools} tool calls in flight",+ "stat_active_hint_idle": "nothing in flight",+ "stat_done_label": "Done",+ "stat_done_hint": "finished and reported back",+ "stat_failed_label": "Failed",+ "stat_failed_hint": "see the result column",+ "stat_failed_hint_none": "nothing broke",+ "stat_tools_label": "Tool calls",+ "stat_tools_hint": "across every agent",+ "board_title": "Operations board",+ "board_subtitle": "Live from the backend registry and the mission WebSocket.",+ "live_label": "Live","standby_label": "Standby",+ "col_expand": "Expand row","col_agent": "{name}-Agent",- "col_target": "Goal",+ "col_task": "Task / project","col_status": "Status",- "col_cost": "Cost",- "agents_traveling": "{name}-Agent(s) traveling",- "last_departure": "last departure",- "last_departure_ago": "last departure {0} ago",+ "col_tools": "Tools",+ "col_runtime": "Runtime",+ "col_result": "Result",+ "role_worker": "Worker",+ "role_worker_hint": "worker process",+ "role_agent_hint": "background agent",+ "task_none": "No task recorded",+ "result_done": "Done",+ "result_running": "In progress",+ "empty_title": "No {agents} are running right now.",+ "empty_body": "When {name} starts a real {agent}, it appears here with its task, status, tool calls, runtime and result.",+ "snapshot_error": "The board could not be loaded: {detail}",+ "drill_tools": "Tool calls",+ "drill_tools_empty": "No tool calls recorded.",+ "drill_details": "{agent} details",+ "drill_trace": "trace {trace}",+ "tool_unnamed": "tool",+ "tool_status": {+ "running": "Running",+ "completed": "Done",+ "failed": "Failed"+ },"status": {- "running": "running",- "completed": "arrived",- "failed": "failed"+ "running": "Running",+ "completed": "Done",+ "failed": "Failed",+ "cancelled": "Cancelled"},"health_degraded": "Subagent provider degraded","health_error": "No subagent provider reachable",@@ -4968,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",@@ -4978,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",@@ -5039,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": {@@ -5076,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 dd57445c5d..5df9b64e2d 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json@@ -688,25 +688,56 @@},"subagents_view": {"title": "{name}-Agents",+ "subtitle": "{active} en marcha · {total} en total","explicit_spawn_hint": "Los {name}-Agents solo arrancan cuando lo pides explícitamente — di p. ej. «Spawn un agente para esto» o «Haz un deep dive con un agente».",- "stat_active": "activos",- "stat_total": "total","clear": "Limpiar","clear_tooltip": "Limpiar tablero",- "board_title": "Tablero de Salidas",- "active_label": "Activo",+ "stat_agents_hint": "iniciados en esta sesión",+ "stat_active_label": "En marcha",+ "stat_active_hint": "{tools} llamadas a herramientas en curso",+ "stat_active_hint_idle": "nada en curso",+ "stat_done_label": "Terminados",+ "stat_done_hint": "terminados y reportados",+ "stat_failed_label": "Fallidos",+ "stat_failed_hint": "mira la columna Resultado",+ "stat_failed_hint_none": "no falló nada",+ "stat_tools_label": "Llamadas a herramientas",+ "stat_tools_hint": "en todos los agentes",+ "board_title": "Panel de operaciones",+ "board_subtitle": "En vivo desde el registro del backend y el WebSocket de misiones.",+ "live_label": "En vivo","standby_label": "En espera",+ "col_expand": "Desplegar fila","col_agent": "{name}-Agent",- "col_target": "Destino",+ "col_task": "Tarea / proyecto","col_status": "Estado",- "col_cost": "Coste",- "agents_traveling": "{name}-Agent(s) en camino",- "last_departure": "última salida",- "last_departure_ago": "última salida hace {0}",+ "col_tools": "Herramientas",+ "col_runtime": "Duración",+ "col_result": "Resultado",+ "role_worker": "Worker",+ "role_worker_hint": "proceso worker",+ "role_agent_hint": "agente en segundo plano",+ "task_none": "Sin tarea registrada",+ "result_done": "Terminado",+ "result_running": "En curso",+ "empty_title": "Ahora mismo no hay {agents} en marcha.",+ "empty_body": "Cuando {name} inicie un {agent} real, aparecerá aquí con su tarea, estado, llamadas a herramientas, duración y resultado.",+ "snapshot_error": "No se pudo cargar el panel: {detail}",+ "drill_tools": "Llamadas a herramientas",+ "drill_tools_empty": "No se registraron llamadas a herramientas.",+ "drill_details": "Detalles de {agent}",+ "drill_trace": "traza {trace}",+ "tool_unnamed": "herramienta",+ "tool_status": {+ "running": "En curso",+ "completed": "Terminado",+ "failed": "Fallido"+ },"status": {- "running": "en marcha",- "completed": "llegado",- "failed": "fallo"+ "running": "En marcha",+ "completed": "Terminado",+ "failed": "Fallido",+ "cancelled": "Cancelado"},"health_degraded": "Proveedor de subagentes degradado","health_error": "Ningún proveedor de subagentes accesible",@@ -4968,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",@@ -4978,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",@@ -5039,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": {@@ -5076,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 2015113840..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,@@ -36,6 +41,7 @@ import {Panel,PanelHeader,SegmentedFilter,+ StatTile,StatusDot,Table,TableHead,@@ -54,6 +60,9 @@ import {priceSourceTone,roleColor,roleLabelKey,+ SURFACE_GROUPS,+ surfaceGroupFor,+ surfaceGroupLabelKey,surfaceLabelKey,} from "@/components/costs/costFormat";import {@@ -129,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;@@ -192,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@@ -228,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,42 +519,131 @@ export function CostsView() {}// ----------------------------------------------------------------------------// Stat tile+// Which area of the app — and which kind of model inside it// ----------------------------------------------------------------------------function StatTile({- icon,- label,+/** 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,- hint,- tone,- loading,+ onChange,}: {- icon: React.ReactNode;- label: string;- value: string;- hint: string;- tone?: "ok" | "warn";- loading?: boolean;+ value: string | null;+ onChange: (id: string) => void;}) {+ const t = useT();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+ 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>);}@@ -599,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}@@ -609,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"