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): "Where it went" — the most expensive conversations, and a filter to match
rubenluetke10-beep79f96afb66e2
diff --git a/jarvis/costs/aggregate.py b/jarvis/costs/aggregate.pyindex 7e395628d9..5999645fac 100644--- a/jarvis/costs/aggregate.py+++ b/jarvis/costs/aggregate.py@@ -119,6 +119,7 @@ def filter_entries(models: set[str] | None = None,roles: set[str] | None = None,surfaces: set[str] | None = None,+ refs: set[str] | None = None,search: str = "",) -> list[CostEntry]:"""Narrow the line items. An empty filter set means "everything"."""@@ -133,6 +134,8 @@ def filter_entries(return Falseif surfaces and e.surface not in surfaces:return False+ if refs and e.ref_id not in refs:+ return Falseif needle and needle not in f"{e.model} {e.provider} {e.label}".casefold():return Falsereturn Truediff --git a/jarvis/ui/web/costs_routes.py b/jarvis/ui/web/costs_routes.pyindex 07343a7126..d0c0c29321 100644--- a/jarvis/ui/web/costs_routes.py+++ b/jarvis/ui/web/costs_routes.py@@ -297,6 +297,7 @@ async def get_summary(model: Annotated[list[str] | None, Query()] = None,role: Annotated[list[str] | None, Query()] = None,surface: Annotated[list[str] | None, Query()] = None,+ ref: Annotated[list[str] | None, Query()] = None,search: str = "",top: Annotated[int, Query(ge=1, le=100)] = 12,) -> CostSummary:@@ -314,6 +315,7 @@ async def get_summary(models=_split(model),roles=_split(role),surfaces=_split(surface),+ refs=_split(ref),search=search,)report = build_report(selected, since_ms=start, until_ms=end, top_n=top)@@ -334,6 +336,7 @@ async def get_entries(model: Annotated[list[str] | None, Query()] = None,role: Annotated[list[str] | None, Query()] = None,surface: Annotated[list[str] | None, Query()] = None,+ ref: 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,@@ -348,6 +351,7 @@ async def get_entries(models=_split(model),roles=_split(role),surfaces=_split(surface),+ refs=_split(ref),search=search,)if sort == "cost":diff --git a/jarvis/ui/web/frontend/src/hooks/useCosts.ts b/jarvis/ui/web/frontend/src/hooks/useCosts.tsindex 525cba0d5c..0ad91c6d64 100644--- a/jarvis/ui/web/frontend/src/hooks/useCosts.ts+++ b/jarvis/ui/web/frontend/src/hooks/useCosts.ts@@ -150,6 +150,8 @@ export interface CostFilters {models: string[];roles: CostRole[];surfaces: CostSurface[];+ /** Session / mission ids — set by clicking a row in "Where it went". */+ refs: string[];search: string;}@@ -159,6 +161,7 @@ export const EMPTY_FILTERS: CostFilters = {models: [],roles: [],surfaces: [],+ refs: [],search: "",};@@ -169,6 +172,7 @@ export function hasActiveFilters(f: CostFilters): boolean {f.models.length > 0 ||f.roles.length > 0 ||f.surfaces.length > 0 ||+ f.refs.length > 0 ||f.search.trim().length > 0);}@@ -183,6 +187,7 @@ function toParams(f: CostFilters): URLSearchParams {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);+ for (const r of f.refs) params.append("ref", r);if (f.search.trim()) params.set("search", f.search.trim());return params;}diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.jsonindex 8483414274..9c2d4a1b12 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json@@ -4993,6 +4993,11 @@"col_what": "Was","col_price_source": "Preis","col_tokens": "Rein / Raus",+ "top_refs_title": "Wofür es ausgegeben wurde",+ "top_refs_subtitle": "Die teuersten Gespräche, Chats und Missionen. Eins anklicken filtert danach.",+ "top_refs_empty": "In diesem Zeitraum noch nichts.",+ "col_session": "Gespräch",+ "dim_ref": "Gespräch","entries_title": "Einzelposten","entries_subtitle": "{shown} von {total} sichtbar","entries_empty": "Zu diesen Filtern gibt es keine Aufrufe.",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.jsonindex dc4bb1084d..bec1a2ccd3 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json@@ -4993,6 +4993,11 @@"col_what": "What","col_price_source": "Price","col_tokens": "In / Out",+ "top_refs_title": "Where it went",+ "top_refs_subtitle": "The most expensive conversations, chats and missions. Click one to filter by it.",+ "top_refs_empty": "Nothing in this range yet.",+ "col_session": "Conversation",+ "dim_ref": "Conversation","entries_title": "Line items","entries_subtitle": "Showing {shown} of {total}","entries_empty": "No calls match these filters.",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.jsonindex 298132a5ea..b0de5d47e9 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json@@ -4993,6 +4993,11 @@"col_what": "Qué","col_price_source": "Precio","col_tokens": "Entrada / Salida",+ "top_refs_title": "A dónde fue",+ "top_refs_subtitle": "Las conversaciones, chats y misiones más caras. Pulsa una para filtrar por ella.",+ "top_refs_empty": "Todavía no hay nada en este periodo.",+ "col_session": "Conversación",+ "dim_ref": "Conversación","entries_title": "Movimientos","entries_subtitle": "Mostrando {shown} de {total}","entries_empty": "Ninguna llamada coincide con estos filtros.",diff --git a/jarvis/ui/web/frontend/src/views/CostsView.tsx b/jarvis/ui/web/frontend/src/views/CostsView.tsxindex 14b8fc11f2..2015113840 100644--- a/jarvis/ui/web/frontend/src/views/CostsView.tsx+++ b/jarvis/ui/web/frontend/src/views/CostsView.tsx@@ -208,6 +208,9 @@ export function CostsView() {<ActiveFilterChipsfilters={filters}+ labelFor={(value) =>+ data?.top_refs.find((r) => r.key === value)?.label || `${value.slice(0, 8)}…`+ }onRemove={(key, value) => toggle(key, value)}onClear={() => {setVisible(ENTRY_PAGE);@@ -340,6 +343,25 @@ export function CostsView() {</div></Panel>+ {/* Where it went ----------------------------------------------- */}+ <Panel>+ <div className="px-4 pt-4">+ <PanelHeader+ title={t("costs_view.top_refs_title")}+ subtitle={t("costs_view.top_refs_subtitle")}+ />+ </div>+ <div className="mt-3">+ <TopRefsTable+ rows={data?.top_refs ?? []}+ active={filters.refs}+ onToggle={(key) => toggle("refs", key)}+ money={money}+ loading={summary.isLoading}+ />+ </div>+ </Panel>+{/* Line items -------------------------------------------------- */}<Panel><div className="px-4 pt-4">@@ -482,16 +504,20 @@ const CHIP_KEYS: { key: keyof CostFilters; labelKey: string }[] = [{ key: "models", labelKey: "costs_view.dim_model" },{ key: "roles", labelKey: "costs_view.dim_role" },{ key: "surfaces", labelKey: "costs_view.dim_surface" },+ { key: "refs", labelKey: "costs_view.dim_ref" },];function ActiveFilterChips({filters,onRemove,onClear,+ labelFor,}: {filters: CostFilters;onRemove: (key: keyof CostFilters, value: string) => void;onClear: () => void;+ /** Renders an opaque id (a session) as the words the user recognises. */+ labelFor?: (value: string) => string;}) {const t = useT();if (!hasActiveFilters(filters)) return null;@@ -506,7 +532,9 @@ function ActiveFilterChips({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>+ <span className="font-medium">+ {key === "refs" && labelFor ? labelFor(value) : value}+ </span><X className="h-3 w-3 text-muted-foreground" /></button>)),@@ -658,6 +686,110 @@ const ROLE_KEYS: Record<string, true> = {worker: true,};+// ---------------------------------------------------------------------------+// Where it went — the most expensive conversations, missions and agent runs+// ---------------------------------------------------------------------------++interface RefRowShape extends CostBucket {+ label: string;+ surface: string;+}++/**+ * The breakdown answers "which model"; this one answers "which conversation".+ *+ * A session id means nothing to a person, so each row leads with what was+ * actually said (or asked of a mission) and keeps the id only as the filter+ * value behind the click.+ */+function TopRefsTable({+ rows,+ active,+ onToggle,+ money,+ loading,+}: {+ rows: RefRowShape[];+ active: string[];+ onToggle: (key: string) => void;+ money: (usd: number) => string;+ loading?: boolean;+}) {+ const t = useT();+ const columns: Column[] = [+ { id: "what", label: t("costs_view.col_session") },+ { id: "share", label: t("costs_view.col_share"), width: "150px" },+ { id: "cost", label: t("costs_view.col_cost"), width: "110px", align: "right" },+ { id: "tokens", label: t("costs_view.stat_tokens"), width: "96px", align: "right" },+ { id: "when", label: t("costs_view.col_when"), width: "132px", align: "right" },+ ];++ if (!loading && rows.length === 0) {+ return (+ <div className="px-4 pb-4">+ <EmptyRow>{t("costs_view.top_refs_empty")}</EmptyRow>+ </div>+ );+ }++ return (+ <Table label={t("costs_view.top_refs_title")}>+ <TableHead columns={columns} />+ {rows.map((row) => {+ const isActive = active.includes(row.key);+ return (+ <TableRow+ key={row.key}+ columns={columns}+ selected={isActive}+ onClick={() => onToggle(row.key)}+ ariaLabel={row.label || row.key}+ >+ <Cell>+ <div className="min-w-0">+ <div className="truncate font-medium text-foreground">+ {row.label || `${row.key.slice(0, 8)}…`}+ </div>+ <div className="truncate text-xs text-muted-foreground">+ {t(surfaceLabelKey(row.surface))}+ {row.members.length > 0 ? ` · ${row.members.join(" · ")}` : ""}+ </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: keyColor(row.surface),+ }}+ />+ </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_total)}>+ {formatTokens(row.tokens_total)}+ </span>+ </Cell>+ <Cell align="right" muted>+ <span className="tabular-nums">{formatTimestamp(row.last_ts_ms)}</span>+ </Cell>+ </TableRow>+ );+ })}+ </Table>+ );+}+// ---------------------------------------------------------------------------// Line items// ---------------------------------------------------------------------------diff --git a/tests/unit/ui/web/test_costs_routes.py b/tests/unit/ui/web/test_costs_routes.pynew file mode 100644index 0000000000..563262c0e1--- /dev/null+++ b/tests/unit/ui/web/test_costs_routes.py@@ -0,0 +1,138 @@+"""Tests for the Spend & Tokens REST surface (``/api/costs``).++The read model itself is covered in ``tests/unit/costs``; what matters here is+the contract the section depends on:++- the filters actually narrow the report, and every dimension is filterable,+- the filter OPTIONS stay complete while a filter is on (a picker that removes+ its own options is a dead end),+- an install with no databases yet still answers 200 with zeroes.+"""+from __future__ import annotations++import sqlite3+import time+from pathlib import Path+from types import SimpleNamespace++import pytest+from fastapi import FastAPI+from fastapi.testclient import TestClient++_SCHEMA = """+CREATE TABLE voice_turns (+ id TEXT PRIMARY KEY, session_id TEXT, started_ms INTEGER, tier TEXT,+ provider TEXT, model TEXT, tokens_in INTEGER, tokens_out INTEGER,+ cost_usd REAL, user_text TEXT+);+"""++NOW_MS = int(time.time() * 1000)+++def _seed(data_dir: Path) -> None:+ data_dir.mkdir(parents=True, exist_ok=True)+ conn = sqlite3.connect(data_dir / "sessions.db")+ conn.executescript(_SCHEMA)+ rows = [+ ("t1", "sess-a", NOW_MS - 3_600_000, "realtime", "gemini-live",+ "gemini-3.1-flash-live-preview", 40_000, 200, 0.40, "what is on my calendar"),+ ("t2", "sess-b", NOW_MS - 7_200_000, "deep", "anthropic",+ "claude-opus-4-7-20251022", 2_000, 400, 0.09, "summarise the meeting"),+ ]+ conn.executemany(+ "INSERT INTO voice_turns (id, session_id, started_ms, tier, provider, model, "+ "tokens_in, tokens_out, cost_usd, user_text) VALUES (?,?,?,?,?,?,?,?,?,?)",+ rows,+ )+ conn.commit()+ conn.close()+++def _client(data_dir: Path) -> TestClient:+ from jarvis.ui.web.costs_routes import router++ app = FastAPI()+ app.include_router(router)+ # The routes resolve their stores from the instance's data dir, so a test+ # sandbox is a config object with nothing else on it.+ app.state.config = SimpleNamespace(memory=SimpleNamespace(data_dir=str(data_dir)))+ return TestClient(app)+++def client(tmp_path: Path) -> TestClient:+ _seed(tmp_path / "data")+ return _client(tmp_path / "data")+++def test_summary_totals_every_source(client: TestClient) -> None:+ body = client.get("/api/costs/summary?days=30").json()+ assert body["totals"]["cost_usd"] == pytest.approx(0.49)+ assert body["totals"]["entries"] == 2+ assert {row["key"] for row in body["by_provider"]} == {"gemini-live", "anthropic"}+ assert {row["key"] for row in body["by_role"]} == {"realtime", "pipeline"}+ assert body["sources_present"] == ["sessions.db"]+++def test_filters_narrow_the_totals(client: TestClient) -> None:+ body = client.get("/api/costs/summary?days=30&provider=anthropic").json()+ assert body["totals"]["entries"] == 1+ assert body["totals"]["cost_usd"] == pytest.approx(0.09)+++def test_facets_stay_complete_while_filtering(client: TestClient) -> None:+ """Picking a provider must not delete the other providers from the picker."""+ body = client.get("/api/costs/summary?days=30&provider=anthropic").json()+ assert set(body["facets"]["providers"]) == {"gemini-live", "anthropic"}+++def test_role_filter_matches_the_read_model(client: TestClient) -> None:+ body = client.get("/api/costs/summary?days=30&role=realtime").json()+ assert [row["key"] for row in body["by_provider"]] == ["gemini-live"]+++def test_ref_filter_isolates_one_session(client: TestClient) -> None:+ body = client.get("/api/costs/summary?days=30&ref=sess-b").json()+ assert body["totals"]["entries"] == 1+ assert body["top_refs"][0]["key"] == "sess-b"+++def test_comma_separated_filters_are_accepted(client: TestClient) -> None:+ body = client.get("/api/costs/summary?days=30&provider=anthropic,gemini-live").json()+ assert body["totals"]["entries"] == 2+++def test_entries_sort_and_paginate(client: TestClient) -> None:+ page = client.get("/api/costs/entries?days=30&sort=cost&limit=1").json()+ assert page["total"] == 2+ assert len(page["items"]) == 1+ assert page["items"][0]["provider"] == "gemini-live"++ second = client.get("/api/costs/entries?days=30&sort=cost&limit=1&offset=1").json()+ assert second["items"][0]["provider"] == "anthropic"+++def test_pricing_lists_every_seen_model(client: TestClient) -> None:+ body = client.get("/api/costs/pricing?days=30").json()+ models = {row["model"] for row in body["rates"]}+ assert models == {"gemini-3.1-flash-live-preview", "claude-opus-4-7-20251022"}+ live = next(r for r in body["rates"] if r["model"] == "gemini-3.1-flash-live-preview")+ # The realtime model's audio rates are the whole point of the rate card.+ assert live["audio_input_usd_per_mtok"] is not None+ assert live["known"] is True+++def test_empty_install_answers_with_zeroes(tmp_path: Path) -> None:+ """No databases yet — the section must open, not 500."""+ client = _client(tmp_path / "nothing")+ body = client.get("/api/costs/summary?days=30").json()+ assert body["totals"]["cost_usd"] == 0.0+ assert body["by_provider"] == []+ assert body["sources_present"] == []+++def test_currency_is_labelled_as_a_conversion(client: TestClient) -> None:+ body = client.get("/api/costs/summary?days=30").json()+ assert body["currency"]["eur_per_usd"] > 0+ assert body["currency"]["source"] in {"config", "default"}diff --git a/tests/unit/ui/web/test_section_id_parity.py b/tests/unit/ui/web/test_section_id_parity.pyindex a4057687b8..ca3282410a 100644--- a/tests/unit/ui/web/test_section_id_parity.py+++ b/tests/unit/ui/web/test_section_id_parity.py@@ -33,7 +33,10 @@ _REPO_ROOT = Path(__file__).resolve().parents[4]_FRONTEND = _REPO_ROOT / "jarvis" / "ui" / "web" / "frontend" / "src"_EVENTS_TS = _FRONTEND / "store" / "events.ts"_MAIN_VIEW_TSX = _FRONTEND / "components" / "layout" / "MainView.tsx"-_SIDEBAR_TSX = _FRONTEND / "components" / "layout" / "Sidebar.tsx"+# The nav rows moved out of Sidebar.tsx into navGroups.ts (the mission deck+# needs the same list without the sidebar's dependency tree). The guard+# follows the list, not the file that happens to render it.+_NAV_GROUPS_TS = _FRONTEND / "components" / "layout" / "navGroups.ts"_VOICE_HUB_TSX = _FRONTEND / "views" / "VoiceHubView.tsx"_LOCALES = _FRONTEND / "i18n" / "locales"@@ -118,12 +121,12 @@ def _voice_hub_routed_ids() -> set[str]:def _sidebar_voice_match_ids() -> set[str]:- """The ``matchIds`` of the single sidebar row labelled ``nav.voice``."""+ """The ``matchIds`` of the single nav row labelled ``nav.voice``."""body = re.search(r'labelKey:\s*"nav\.voice"\s*,[\s\S]{0,400}?matchIds:\s*\[([^\]]*)\]',- _read(_SIDEBAR_TSX),+ _read(_NAV_GROUPS_TS),)- assert body is not None, "voice NavItem with matchIds not found in Sidebar.tsx"+ assert body is not None, "voice NavItem with matchIds not found in navGroups.ts"return set(re.findall(r'"([a-z0-9_-]+)"', body.group(1)))