Skip to content

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.

feat(costs): one entry per day, and the day opens into the whole report

rubenluetke10-beep017ff6781400
diff --git a/jarvis/costs/sources.py b/jarvis/costs/sources.py
index 6d5c0f6b61..cb93231e3e 100644
--- a/jarvis/costs/sources.py
+++ b/jarvis/costs/sources.py
@@ -607,6 +607,10 @@ def _speech_label(stage: str, chars: int, audio_ms: float) -> str:
# Coding CLIs — the index, not the transcripts
# ---------------------------------------------------------------------------
+#: The finest grain the section ever draws. See :func:`_cli_entries`.
+_CLI_READ_BUCKET_MS = 60 * 60 * 1000
+
+
def _cli_entries(
data_dir: Path | None, since_ms: int, until_ms: int, bucket_ms: int
) -> Iterator[CostEntry]:
@@ -619,9 +623,19 @@ def _cli_entries(
A CLI on a monthly seat is quoted at what the same work would have cost
through the API and labelled ``subscription``; one on the user's own key
(OpenCode) carries the price it recorded, which is money that moved.
+
+ ``bucket_ms`` is an upper bound, never the grain itself. The report's own
+ grain must not decide how many rows a day HAS: read day-wide and a
+ session collapses into one row, read hour-wide and the same session
+ becomes several — so the daily ledger and the day report behind it
+ counted the same day differently (113 vs 204 calls, 2026-08-25). Reading
+ always at the finest grain the section ever draws keeps every count the
+ same number wherever it appears; rolling those rows up into days is what
+ :func:`jarvis.costs.aggregate.build_report` does anyway.
"""
if data_dir is None:
return
+ bucket_ms = min(int(bucket_ms), _CLI_READ_BUCKET_MS)
try:
from .cli_usage_index import rollups as indexed_rollups
except ImportError as exc: # pragma: no cover — the module ships with us
diff --git a/jarvis/ui/web/frontend/src/components/costs/costFormat.ts b/jarvis/ui/web/frontend/src/components/costs/costFormat.ts
index 21efc261ec..88ae356360 100644
--- a/jarvis/ui/web/frontend/src/components/costs/costFormat.ts
+++ b/jarvis/ui/web/frontend/src/components/costs/costFormat.ts
@@ -131,6 +131,57 @@ export function formatBucketFull(key: string, bucket: "day" | "hour"): string {
: d.toLocaleDateString(undefined, { weekday: "short", day: "numeric", month: "short" });
}
+/**
+ * `(start, end)` in epoch ms for a local `YYYY-MM-DD` day.
+ *
+ * Built from the local midnight of that date, not from UTC: the daily report
+ * has to draw the same day the person's own clock drew, and the backend cuts
+ * its days the same way (`jarvis/costs/aggregate.py:day_bounds_ms`).
+ */
+export function dayBoundsMs(date: string): [number, number] {
+ const start = new Date(`${date}T00:00:00`);
+ if (Number.isNaN(start.getTime())) return [0, 0];
+ const end = new Date(start);
+ end.setDate(end.getDate() + 1);
+ return [start.getTime(), end.getTime() - 1];
+}
+
+/** `today` / `yesterday` / `""` for a local `YYYY-MM-DD` day. */
+export function relativeDay(date: string): "today" | "yesterday" | "" {
+ const today = new Date();
+ const key = (d: Date) =>
+ `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;
+ if (key(today) === date) return "today";
+ const yesterday = new Date(today);
+ yesterday.setDate(yesterday.getDate() - 1);
+ return key(yesterday) === date ? "yesterday" : "";
+}
+
+/** "Tuesday, 25 August 2026" — the day report's own headline. */
+export function formatDayLong(date: string): string {
+ const d = new Date(`${date}T00:00:00`);
+ if (Number.isNaN(d.getTime())) return date;
+ return d.toLocaleDateString(undefined, {
+ weekday: "long",
+ day: "numeric",
+ month: "long",
+ year: "numeric",
+ });
+}
+
+/** "Tue, 25 Aug" — the ledger row's own label. */
+export function formatDayShort(date: string): string {
+ const d = new Date(`${date}T00:00:00`);
+ if (Number.isNaN(d.getTime())) return date;
+ return d.toLocaleDateString(undefined, { weekday: "short", day: "numeric", month: "short" });
+}
+
+/** "09:53" — a clock time, for the window a day's work actually ran in. */
+export function formatClock(ms: number): string {
+ if (!ms) return "—";
+ return new Date(ms).toLocaleTimeString(undefined, { hour: "2-digit", minute: "2-digit" });
+}
+
export function formatTimestamp(ms: number): string {
if (!ms) return "—";
return new Date(ms).toLocaleString(undefined, {
diff --git a/jarvis/ui/web/frontend/src/hooks/useCosts.ts b/jarvis/ui/web/frontend/src/hooks/useCosts.ts
index 996515f591..7c345fc1e8 100644
--- a/jarvis/ui/web/frontend/src/hooks/useCosts.ts
+++ b/jarvis/ui/web/frontend/src/hooks/useCosts.ts
@@ -127,6 +127,31 @@ export interface CostSummary {
sources_present: string[];
}
+/**
+ * One calendar day of spend, already broken down — the section's ledger row.
+ *
+ * Mirrors `DayRow` in costs_routes.py. A day, not a session, is the unit:
+ * a session row carries the timestamp of its FIRST call, so a long morning
+ * run sorts below a short one started later and reads as if it never
+ * happened.
+ */
+export interface CostDayRow {
+ /** Local `YYYY-MM-DD`. */
+ date: string;
+ since_ms: number;
+ until_ms: number;
+ totals: CostTotals;
+ by_model: CostBucket[];
+ by_provider: CostBucket[];
+ by_role: CostBucket[];
+ by_surface: CostBucket[];
+}
+
+export interface CostDailyLedger {
+ days: CostDayRow[];
+ currency: CostCurrency;
+}
+
export interface CostEntryRow {
ts_ms: number;
surface: CostSurface;
@@ -178,6 +203,14 @@ export interface CostFilters {
/** Session / mission ids — set by clicking a row in "Where it went". */
refs: string[];
search: string;
+ /**
+ * An explicit window, in epoch ms. When set it wins over `days` — the
+ * daily report drills into ONE day and everything it shows (the hourly
+ * curve, the breakdowns, the calls) is the same request the section
+ * already makes, just bounded to that day.
+ */
+ sinceMs?: number;
+ untilMs?: number;
}
export const EMPTY_FILTERS: CostFilters = {
@@ -205,6 +238,8 @@ export function hasActiveFilters(f: CostFilters): boolean {
function toParams(f: CostFilters): URLSearchParams {
const params = new URLSearchParams();
params.set("days", String(f.days));
+ if (f.sinceMs !== undefined) params.set("since_ms", String(Math.floor(f.sinceMs)));
+ if (f.untilMs !== undefined) params.set("until_ms", String(Math.floor(f.untilMs)));
// Repeated params rather than one comma-joined value: a model id may
// legitimately contain a comma-free but slash-heavy vendor prefix, and
// repeating keeps the split unambiguous on the backend.
@@ -239,6 +274,24 @@ export function useCostSummary(filters: CostFilters) {
});
}
+/**
+ * The daily ledger — one row per day for the whole selected range.
+ *
+ * Same filters as the summary, so a drill-down into a provider or a model
+ * narrows the days too rather than leaving a second, disagreeing list on
+ * screen.
+ */
+export function useCostDaily(filters: CostFilters) {
+ const params = toParams(filters);
+ return useQuery({
+ queryKey: ["costs", "daily", params.toString()],
+ queryFn: () => getJson<CostDailyLedger>(`/api/costs/daily?${params.toString()}`),
+ refetchInterval: 30_000,
+ staleTime: 10_000,
+ placeholderData: (prev) => prev,
+ });
+}
+
export function useCostEntries(
filters: CostFilters,
sort: "recent" | "cost" | "tokens",
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.json
index a96aa4bc86..e4c7bd941c 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json
@@ -5414,6 +5414,35 @@
"sort_cost": "Teuerste",
"sort_tokens": "Meiste Tokens",
"load_more": "{count} weitere anzeigen",
+ "daily_title": "Tagesreport",
+ "daily_subtitle": "Ein Eintrag pro Tag. Öffne einen Tag, um zu sehen, wohin Geld und Tokens gegangen sind.",
+ "daily_empty": "An keinem Tag in diesem Zeitraum wurde etwas ausgegeben.",
+ "daily_today": "Heute",
+ "daily_yesterday": "Gestern",
+ "daily_more_models": "+{count}",
+ "col_day": "Tag",
+ "col_models": "Benutzte Modelle",
+ "day_open": "{day} öffnen",
+ "day_back": "Alle Tage",
+ "day_byline": "{calls} Aufrufe · {models} Modelle · {providers} Anbieter",
+ "day_byline_window": "{from} bis {to}",
+ "day_share_of_range": "{share} des Zeitraums",
+ "day_stat_worth": "Wert des Tages",
+ "day_stat_worth_hint": "Jeder Aufruf zum Listenpreis des Anbieters",
+ "day_stat_billed": "Über API-Keys abgerechnet",
+ "day_stat_billed_hint": "Geld, das wirklich vom Konto gegangen ist",
+ "day_stat_seat": "Vom Abo gedeckt",
+ "day_stat_seat_hint": "Echte Rechnung auf echten Tokens — nur trägt sie keine Rechnung",
+ "day_stat_seat_none": "Heute lief nichts über ein Abo",
+ "day_hours_title": "Über den Tag",
+ "day_hours_subtitle": "Stunde für Stunde, gestapelt nach der Aufgabe des Modells",
+ "day_models_title": "Welche Modelle gearbeitet haben",
+ "day_models_subtitle": "Jedes Modell des Tages, das größte zuerst — von welchem Anbieter auch immer",
+ "day_tokens_title": "Wie die Tokens verbraucht wurden",
+ "day_tokens_subtitle": "Frische Eingabe, Cache-Lesungen und alles, was die Modelle zurückgeschrieben haben",
+ "day_split_title": "Wo in der App",
+ "day_split_subtitle": "Derselbe Tag, aufgeteilt nach Bereich und nach der Aufgabe des Modells",
+ "day_calls_title": "Jeder Aufruf des Tages",
"rates_title": "Preisliste",
"rates_subtitle": "je Million Tokens",
"rates_empty": "In diesem Zeitraum wurde kein Modell benutzt.",
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.json
index 63376b2784..9542c9fac1 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json
@@ -5414,6 +5414,35 @@
"sort_cost": "Most expensive",
"sort_tokens": "Most tokens",
"load_more": "Show {count} more",
+ "daily_title": "Daily report",
+ "daily_subtitle": "One entry per day. Open a day to see where the money and the tokens went.",
+ "daily_empty": "No day in this range spent anything.",
+ "daily_today": "Today",
+ "daily_yesterday": "Yesterday",
+ "daily_more_models": "+{count}",
+ "col_day": "Day",
+ "col_models": "Models used",
+ "day_open": "Open {day}",
+ "day_back": "All days",
+ "day_byline": "{calls} calls · {models} models · {providers} providers",
+ "day_byline_window": "{from} to {to}",
+ "day_share_of_range": "{share} of the range",
+ "day_stat_worth": "What the day was worth",
+ "day_stat_worth_hint": "Every call at the vendor's list price",
+ "day_stat_billed": "Billed to API keys",
+ "day_stat_billed_hint": "Money that actually left an account",
+ "day_stat_seat": "Covered by a seat",
+ "day_stat_seat_hint": "Real arithmetic on real tokens — no invoice carries it",
+ "day_stat_seat_none": "Nothing on a subscription today",
+ "day_hours_title": "Through the day",
+ "day_hours_subtitle": "Hour by hour, stacked by what the model was doing",
+ "day_models_title": "Which models did the work",
+ "day_models_subtitle": "Every model the day used, biggest first — whichever vendor it came from",
+ "day_tokens_title": "How the tokens were spent",
+ "day_tokens_subtitle": "Fresh input, cache reads, and everything the models wrote back",
+ "day_split_title": "Where in the app",
+ "day_split_subtitle": "The same day cut by area and by what the model was doing",
+ "day_calls_title": "Every call of the day",
"rates_title": "Rate card",
"rates_subtitle": "per million tokens",
"rates_empty": "No models seen in this range.",
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.json
index 155d69cdaa..52b4fbe51b 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json
@@ -5414,6 +5414,35 @@
"sort_cost": "Más caras",
"sort_tokens": "Más tokens",
"load_more": "Mostrar {count} más",
+ "daily_title": "Informe diario",
+ "daily_subtitle": "Una entrada por día. Abre un día para ver adónde fueron el dinero y los tokens.",
+ "daily_empty": "Ningún día de este periodo gastó nada.",
+ "daily_today": "Hoy",
+ "daily_yesterday": "Ayer",
+ "daily_more_models": "+{count}",
+ "col_day": "Día",
+ "col_models": "Modelos usados",
+ "day_open": "Abrir {day}",
+ "day_back": "Todos los días",
+ "day_byline": "{calls} llamadas · {models} modelos · {providers} proveedores",
+ "day_byline_window": "de {from} a {to}",
+ "day_share_of_range": "{share} del periodo",
+ "day_stat_worth": "Lo que valió el día",
+ "day_stat_worth_hint": "Cada llamada al precio de lista del proveedor",
+ "day_stat_billed": "Facturado a claves API",
+ "day_stat_billed_hint": "Dinero que salió de verdad de una cuenta",
+ "day_stat_seat": "Cubierto por una suscripción",
+ "day_stat_seat_hint": "Cálculo real sobre tokens reales — ninguna factura lo recoge",
+ "day_stat_seat_none": "Hoy no hubo nada por suscripción",
+ "day_hours_title": "A lo largo del día",
+ "day_hours_subtitle": "Hora a hora, apilado según lo que hacía el modelo",
+ "day_models_title": "Qué modelos hicieron el trabajo",
+ "day_models_subtitle": "Todos los modelos del día, el mayor primero — de cualquier proveedor",
+ "day_tokens_title": "Cómo se gastaron los tokens",
+ "day_tokens_subtitle": "Entrada nueva, lecturas de caché y todo lo que los modelos escribieron",
+ "day_split_title": "Dónde en la app",
+ "day_split_subtitle": "El mismo día repartido por área y por lo que hacía el modelo",
+ "day_calls_title": "Cada llamada del día",
"rates_title": "Tarifas",
"rates_subtitle": "por millón de tokens",
"rates_empty": "No se usó ningún modelo en este periodo.",
diff --git a/jarvis/ui/web/frontend/src/views/CostsView.tsx b/jarvis/ui/web/frontend/src/views/CostsView.tsx
index a81d177ef0..bfa07cda40 100644
--- a/jarvis/ui/web/frontend/src/views/CostsView.tsx
+++ b/jarvis/ui/web/frontend/src/views/CostsView.tsx
@@ -17,8 +17,11 @@ import { useMemo, useState } from "react";
import {
AlertTriangle,
AudioLines,
+ CalendarDays,
ChevronDown,
+ ChevronRight,
Coins,
+ CreditCard,
Hash,
Layers,
RefreshCw,
@@ -27,14 +30,17 @@ import {
Sparkles,
Tag,
Terminal,
+ Ticket,
Wallet,
X,
} from "lucide-react";
import { ScrollArea } from "@/components/ui/scroll-area";
import { ProviderLogo } from "@/components/providers/ProviderLogo";
import {
+ BackLink,
Cell,
Column,
+ DetailHeader,
EmptyRow,
IconButton,
InlineSearch,
@@ -49,7 +55,11 @@ import {
} from "@/components/extensions/primitives";
import { CostTrendChart, type TrendMetric } from "@/components/costs/CostTrendChart";
import {
+ dayBoundsMs,
formatBucketFull,
+ formatClock,
+ formatDayLong,
+ formatDayShort,
formatExact,
formatMoney,
formatShare,
@@ -59,6 +69,7 @@ import {
keyColor,
priceSourceLabelKey,
priceSourceTone,
+ relativeDay,
roleColor,
roleLabelKey,
SURFACE_GROUPS,
@@ -69,10 +80,12 @@ import {
import {
EMPTY_FILTERS,
hasActiveFilters,
+ useCostDaily,
useCostEntries,
useCostPricing,
useCostSummary,
type CostBucket,
+ type CostDayRow,
type CostFilters,
type CostRole,
type CostSurface,
@@ -93,13 +106,13 @@ export function CostsView() {
const [currency, setCurrency] = useState<Currency>("usd");
const [metric, setMetric] = useState<TrendMetric>("cost");
const [dimension, setDimension] = useState<Dimension>("provider");
- const [sort, setSort] = useState<EntrySort>("recent");
- const [visible, setVisible] = useState(ENTRY_PAGE);
const [searchOpen, setSearchOpen] = useState(false);
const [ratesOpen, setRatesOpen] = useState(false);
+ /** Which day's report is open, as a local `YYYY-MM-DD`. Null is the ledger. */
+ const [openDay, setOpenDay] = useState<string | null>(null);
const summary = useCostSummary(filters);
- const entries = useCostEntries(filters, sort, visible, 0);
+ const daily = useCostDaily(filters);
const pricing = useCostPricing(filters.days, ratesOpen);
const data = summary.data;
@@ -110,7 +123,6 @@ export function CostsView() {
// One toggle for every filter dimension: clicking a row that is already
// filtered removes it again, so a drill-down is never a one-way door.
const toggle = (key: keyof CostFilters, value: string) => {
- setVisible(ENTRY_PAGE);
setFilters((f) => {
const list = f[key] as string[];
const next = list.includes(value)
@@ -146,7 +158,6 @@ export function CostsView() {
const pickArea = (id: string) => {
const group = SURFACE_GROUPS.find((g) => g.id === id);
if (!group) return;
- setVisible(ENTRY_PAGE);
// Every row-level filter is cleared with the area, not just roles: a
// provider picked inside Agentic IDE ("claude-cli") carried over to the
// assistant's area, where no row can ever match it, and the tab showed
@@ -172,6 +183,21 @@ export function CostsView() {
const billed = Math.max(0, (totals?.cost_usd ?? 0) - seat);
const perDay = billed / Math.max(1, rangeMs / 86_400_000);
+ // A day report replaces the section rather than sitting inside it: it is
+ // the same question at a different grain, and two scrollers on one screen
+ // is how a reader loses track of which totals belong to what.
+ if (openDay) {
+ return (
+ <DayReport
+ date={openDay}
+ filters={filters}
+ currency={currency}
+ eurPerUsd={eurPerUsd}
+ onBack={() => setOpenDay(null)}
+ />
+ );
+ }
+
return (
<ScrollArea className="h-full">
<div className="mx-auto flex max-w-[1180px] flex-col gap-4 px-6 py-6">
@@ -194,10 +220,7 @@ export function CostsView() {
<SegmentedFilter<string>
label={t("costs_view.range_label")}
value={String(filters.days)}
- onChange={(v) => {
- setVisible(ENTRY_PAGE);
- setFilters((f) => ({ ...f, days: Number(v) }));
- }}
+ onChange={(v) => setFilters((f) => ({ ...f, days: Number(v) }))}
options={RANGES.map((d) => ({
id: String(d),
label: d === 0 ? t("costs_view.range_all") : fill(t("costs_view.range_days"), { days: String(d) }),
@@ -251,10 +274,7 @@ export function CostsView() {
<InlineSearch
autoFocus
value={filters.search}
- onChange={(v) => {
- setVisible(ENTRY_PAGE);
- setFilters((f) => ({ ...f, search: v }));
- }}
+ onChange={(v) => setFilters((f) => ({ ...f, search: v }))}
placeholder={t("costs_view.search_placeholder")}
/>
</div>
@@ -266,10 +286,7 @@ export function CostsView() {
data?.top_refs.find((r) => r.key === value)?.label || `${value.slice(0, 8)}…`
}
onRemove={(key, value) => toggle(key, value)}
- onClear={() => {
- setVisible(ENTRY_PAGE);
- setFilters((f) => ({ ...EMPTY_FILTERS, days: f.days }));
- }}
+ onClear={() => setFilters((f) => ({ ...EMPTY_FILTERS, days: f.days }))}
/>
{summary.isError ? (
@@ -503,51 +520,22 @@ export function CostsView() {
</div>
</Panel>
- {/* Line items -------------------------------------------------- */}
+ {/* The daily ledger -------------------------------------------- */}
<Panel>
<div className="px-4 pt-4">
<PanelHeader
- title={t("costs_view.entries_title")}
- subtitle={fill(t("costs_view.entries_subtitle"), {
- shown: formatExact(Math.min(entries.data?.total ?? 0, visible)),
- total: formatExact(entries.data?.total ?? 0),
- })}
- actions={
- <SegmentedFilter<EntrySort>
- label={t("costs_view.sort_label")}
- value={sort}
- onChange={(v) => {
- setSort(v);
- setVisible(ENTRY_PAGE);
- }}
- options={[
- { id: "recent", label: t("costs_view.sort_recent") },
- { id: "cost", label: t("costs_view.sort_cost") },
- { id: "tokens", label: t("costs_view.sort_tokens") },
- ]}
- />
- }
+ title={t("costs_view.daily_title")}
+ subtitle={t("costs_view.daily_subtitle")}
/>
</div>
<div className="mt-3">
- <EntriesTable
- rows={entries.data?.items ?? []}
+ <DailyTable
+ rows={daily.data?.days ?? []}
money={money}
- loading={entries.isLoading}
- onFilterModel={(model) => toggle("models", model)}
+ loading={daily.isLoading}
+ onOpen={setOpenDay}
/>
</div>
- {(entries.data?.total ?? 0) > visible ? (
- <div className="border-t border-border px-4 py-3">
- <button
- type="button"
- onClick={() => setVisible((v) => v + ENTRY_PAGE)}
- className="text-sm font-medium text-foreground/80 transition-colors hover:text-foreground"
- >
- {fill(t("costs_view.load_more"), { count: String(ENTRY_PAGE) })}
- </button>
- </div>
- ) : null}
</Panel>
{/* Rate card --------------------------------------------------- */}
@@ -1167,7 +1155,8 @@ function EntriesTable({
rows: EntryRowShape[];
money: (usd: number) => string;
loading?: boolean;
- onFilterModel: (model: string) => void;
+ /** Omitted inside a day report - there is nothing above it to filter. */
+ onFilterModel?: (model: string) => void;
}) {
const t = useT();
const columns: Column[] = [
@@ -1193,7 +1182,7 @@ function EntriesTable({
<TableRow
key={`${row.ts_ms}-${row.ref_id}-${i}`}
columns={columns}
- onClick={row.model ? () => onFilterModel(row.model) : undefined}
+ onClick={row.model && onFilterModel ? () => onFilterModel(row.model) : undefined}
ariaLabel={row.model || row.provider}
>
<Cell muted>
@@ -1318,3 +1307,656 @@ function RatesTable({
</div>
);
}
+
+// ---------------------------------------------------------------------------
+// The daily ledger — one row per day, and the report behind it
+// ---------------------------------------------------------------------------
+
+/**
+ * One row per calendar day.
+ *
+ * This replaced a flat list of every session: the section used to put five to
+ * fifteen rows on a single day, each one a session labelled with the model of
+ * that session, and the day's real composition was impossible to see. Worse,
+ * a session row carries the timestamp of its FIRST call, so "newest first"
+ * buried a long morning run under a short one started later — a day of one
+ * model's work read as a day of something else entirely (maintainer,
+ * 2026-08-25).
+ *
+ * A day has no such ambiguity. It names every model it saw, biggest first,
+ * whichever vendor they came from, and opens into the full report.
+ */
+function DailyTable({
+ rows,
+ money,
+ loading,
+ onOpen,
+}: {
+ rows: CostDayRow[];
+ money: (usd: number) => string;
+ loading?: boolean;
+ onOpen: (date: string) => void;
+}) {
+ const t = useT();
+ const columns: Column[] = [
+ { id: "day", label: t("costs_view.col_day"), width: "196px" },
+ { id: "models", label: t("costs_view.col_models") },
+ { id: "calls", label: t("costs_view.col_calls"), width: "80px", align: "right" },
+ { id: "tokens", label: t("costs_view.stat_tokens"), width: "116px", align: "right" },
+ { id: "cost", label: t("costs_view.col_cost"), width: "132px", align: "right" },
+ { id: "open", label: "", width: "32px", align: "right" },
+ ];
+
+ if (!loading && rows.length === 0) {
+ return (
+ <div className="px-4 pb-4">
+ <EmptyRow>{t("costs_view.daily_empty")}</EmptyRow>
+ </div>
+ );
+ }
+
+ return (
+ <Table label={t("costs_view.daily_title")}>
+ <TableHead columns={columns} />
+ {rows.map((row) => {
+ const rel = relativeDay(row.date);
+ const seat = row.totals.subscription_usd;
+ const billed = Math.max(0, row.totals.cost_usd - seat);
+ // A day where nothing was billed still ranks its models — by tokens,
+ // because a share of zero dollars tells nobody anything.
+ const priced = row.totals.cost_usd > 0;
+ const shown = row.by_model.slice(0, 3);
+ const rest = row.by_model.length - shown.length;
+ return (
+ <TableRow
+ key={row.date}
+ columns={columns}
+ onClick={() => onOpen(row.date)}
+ ariaLabel={fill(t("costs_view.day_open"), { day: row.date })}
+ >
+ <Cell>
+ <div className="flex min-w-0 items-center gap-2.5">
+ <CalendarDays className="h-4 w-4 shrink-0 text-muted-foreground" aria-hidden />
+ <div className="min-w-0">
+ <div className="truncate font-medium text-foreground">
+ {rel ? t(`costs_view.daily_${rel}`) : formatDayShort(row.date)}
+ </div>
+ <div className="truncate text-xs text-muted-foreground">
+ {rel
+ ? formatDayShort(row.date)
+ : fill(t("costs_view.day_byline_window"), {
+ from: formatClock(row.totals.first_ts_ms),
+ to: formatClock(row.totals.last_ts_ms),
+ })}
+ </div>
+ </div>
+ </div>
+ </Cell>
+ <Cell>
+ <div className="flex min-w-0 flex-wrap items-center gap-1.5">
+ {shown.map((m) => (
+ <span
+ key={m.key}
+ className="inline-flex max-w-[210px] items-center gap-1.5 rounded-md border border-border bg-card/60 px-1.5 py-0.5 text-xs"
+ title={m.key}
+ >
+ <span
+ className="h-2 w-2 shrink-0 rounded-[2px]"
+ style={{ background: keyColor(m.key) }}
+ aria-hidden
+ />
+ <span className="truncate text-foreground/90">{m.key}</span>
+ <span className="shrink-0 tabular-nums text-muted-foreground">
+ {formatShare(priced ? m.cost_share : m.token_share)}
+ </span>
+ </span>
+ ))}
+ {rest > 0 ? (
+ <span className="text-xs text-muted-foreground">
+ {fill(t("costs_view.daily_more_models"), { count: String(rest) })}
+ </span>
+ ) : null}
+ </div>
+ </Cell>
+ <Cell align="right" muted>
+ <span className="tabular-nums">{formatExact(row.totals.entries)}</span>
+ </Cell>
+ <Cell align="right" muted>
+ <span className="tabular-nums" title={formatExact(row.totals.tokens_total)}>
+ {formatTokensOrNone(row.totals.tokens_total)}
+ </span>
+ </Cell>
+ <Cell align="right">
+ <div>
+ <div className="font-medium tabular-nums text-foreground">
+ {money(row.totals.cost_usd)}
+ </div>
+ {seat > 0 ? (
+ <div
+ className="text-[11px] tabular-nums text-muted-foreground"
+ title={t("costs_view.day_stat_billed")}
+ >
+ {money(billed)}
+ </div>
+ ) : null}
+ </div>
+ </Cell>
+ <Cell align="right" muted>
+ <ChevronRight className="h-4 w-4" aria-hidden />
+ </Cell>
+ </TableRow>
+ );
+ })}
+ </Table>
+ );
+}
+
+/**
+ * One day, in full — the answer to "where did today's money and tokens go".
+ *
+ * Everything on this page is the SAME request the section above makes, only
+ * bounded to one local day (`since_ms`/`until_ms`), so a day can never
+ * disagree with the range it belongs to. Nothing is vendor-specific: whatever
+ * models, providers and areas the day actually saw are what it names.
+ */
+function DayReport({
+ date,
+ filters,
+ currency,
+ eurPerUsd,
+ onBack,
+}: {
+ date: string;
+ filters: CostFilters;
+ currency: Currency;
+ eurPerUsd: number;
+ onBack: () => void;
+}) {
+ const t = useT();
+ const [metric, setMetric] = useState<TrendMetric>("cost");
+ const [sort, setSort] = useState<EntrySort>("cost");
+ const [visible, setVisible] = useState(ENTRY_PAGE);
+
+ const [sinceMs, untilMs] = dayBoundsMs(date);
+ // The row filters carry over — drilling into a day from a filtered section
+ // must not silently widen back out to everything.
+ const dayFilters = useMemo(
+ () => ({ ...filters, sinceMs, untilMs }),
+ [filters, sinceMs, untilMs],
+ );
+ const summary = useCostSummary(dayFilters);
+ const entries = useCostEntries(dayFilters, sort, visible, 0);
+
+ const data = summary.data;
+ const totals = data?.totals;
+ const money = (usd: number) => formatMoney(usd, eurPerUsd, currency);
+ const seat = totals?.subscription_usd ?? 0;
+ const billed = Math.max(0, (totals?.cost_usd ?? 0) - seat);
+ const priced = (totals?.cost_usd ?? 0) > 0;
+ const rel = relativeDay(date);
+ const long = formatDayLong(date);
+
+ return (
+ <ScrollArea className="h-full">
+ <div className="mx-auto flex max-w-[1180px] flex-col gap-4 px-6 py-6">
+ <BackLink label={t("costs_view.day_back")} onClick={onBack} />
+
+ <DetailHeader
+ leading={
+ <div className="rounded-xl border border-border bg-card/50 p-2.5">
+ <CalendarDays className="h-5 w-5 text-muted-foreground" aria-hidden />
+ </div>
+ }
+ title={rel ? t(`costs_view.daily_${rel}`) : long}
+ titleAccessory={
+ rel ? <span className="text-sm text-muted-foreground">{long}</span> : null
+ }
+ byline={
+ data
+ ? `${fill(t("costs_view.day_byline"), {
+ calls: formatExact(totals?.entries ?? 0),
+ models: String(data.by_model.length),
+ providers: String(data.by_provider.length),
+ })} · ${fill(t("costs_view.day_byline_window"), {
+ from: formatClock(totals?.first_ts_ms ?? 0),
+ to: formatClock(totals?.last_ts_ms ?? 0),
+ })}`
+ : t("costs_view.subtitle_loading")
+ }
+ actions={
+ <IconButton
+ label={t("costs_view.refresh")}
+ busy={summary.isFetching}
+ onClick={() => void summary.refetch()}
+ >
+ <RefreshCw className="h-4 w-4" />
+ </IconButton>
+ }
+ />
+
+ {summary.isError ? <EmptyRow>{t("costs_view.load_error")}</EmptyRow> : null}
+
+ {/* ---------------------------------------------------------------
+ Three money numbers, deliberately kept apart: what the day was
+ WORTH at list price, what an API key was actually charged, and
+ what a monthly seat already covered. Folding the third into the
+ first is how a dashboard starts reading like a bill nobody got.
+ --------------------------------------------------------------- */}
+ <div className="grid gap-3 sm:grid-cols-2 xl:grid-cols-4">
+ <StatTile
+ icon={<Coins className="h-4 w-4" />}
+ label={t("costs_view.day_stat_worth")}
+ value={money(totals?.cost_usd ?? 0)}
+ hint={t("costs_view.day_stat_worth_hint")}
+ loading={summary.isLoading}
+ />
+ <StatTile
+ icon={<CreditCard className="h-4 w-4" />}
+ label={t("costs_view.day_stat_billed")}
+ value={money(billed)}
+ hint={t("costs_view.day_stat_billed_hint")}
+ tone={billed > 0 ? "primary" : "ok"}
+ loading={summary.isLoading}
+ />
+ <StatTile
+ icon={<Ticket className="h-4 w-4" />}
+ label={t("costs_view.day_stat_seat")}
+ value={seat > 0 ? money(seat) : "—"}
+ hint={seat > 0 ? t("costs_view.day_stat_seat_hint") : t("costs_view.day_stat_seat_none")}
+ loading={summary.isLoading}
+ />
+ <StatTile
+ icon={<Sigma className="h-4 w-4" />}
+ label={t("costs_view.stat_tokens")}
+ value={formatTokens(totals?.tokens_total ?? 0)}
+ hint={fill(
+ t(
+ (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}
+ />
+ </div>
+
+ {/* Hour by hour ------------------------------------------------- */}
+ <Panel className="p-4">
+ <PanelHeader
+ title={t("costs_view.day_hours_title")}
+ subtitle={t("costs_view.day_hours_subtitle")}
+ actions={
+ <SegmentedFilter<TrendMetric>
+ label={t("costs_view.metric_label")}
+ value={metric}
+ onChange={setMetric}
+ options={[
+ { id: "cost", label: t("costs_view.metric_cost") },
+ { id: "tokens", label: t("costs_view.metric_tokens") },
+ ]}
+ />
+ }
+ />
+ <div className="mt-3 h-[220px]">
+ <CostTrendChart
+ series={data?.series ?? []}
+ bucket="hour"
+ metric={metric}
+ currency={currency}
+ eurPerUsd={eurPerUsd}
+ />
+ </div>
+ </Panel>
+
+ {/* Which models ------------------------------------------------ */}
+ <Panel>
+ <div className="px-4 pt-4">
+ <PanelHeader
+ title={t("costs_view.day_models_title")}
+ subtitle={t("costs_view.day_models_subtitle")}
+ />
+ </div>
+ <div className="mt-3">
+ <DayModelsTable
+ rows={data?.by_model ?? []}
+ priced={priced}
+ money={money}
+ loading={summary.isLoading}
+ />
+ </div>
+ </Panel>
+
+ {/* Token composition ------------------------------------------- */}
+ <Panel className="p-4">
+ <PanelHeader
+ title={t("costs_view.day_tokens_title")}
+ subtitle={t("costs_view.day_tokens_subtitle")}
+ />
+ <TokenSplitBar
+ tokensIn={totals?.tokens_in ?? 0}
+ tokensCached={totals?.tokens_cached ?? 0}
+ tokensOut={totals?.tokens_out ?? 0}
+ />
+ </Panel>
+
+ {/* Where in the app -------------------------------------------- */}
+ <Panel className="p-4">
+ <PanelHeader
+ title={t("costs_view.day_split_title")}
+ subtitle={t("costs_view.day_split_subtitle")}
+ />
+ <div className="mt-4 grid gap-6 md:grid-cols-2">
+ <ShareBars
+ rows={data?.by_surface ?? []}
+ labelOf={(key) => t(surfaceLabelKey(key))}
+ colorOf={(key) => keyColor(key)}
+ priced={priced}
+ money={money}
+ empty={t("costs_view.breakdown_empty")}
+ />
+ <ShareBars
+ rows={data?.by_role ?? []}
+ labelOf={(key) => t(roleLabelKey(key))}
+ colorOf={(key) => roleColor(key)}
+ priced={priced}
+ money={money}
+ empty={t("costs_view.breakdown_empty")}
+ />
+ </div>
+ </Panel>
+
+ {/* Which sessions ---------------------------------------------- */}
+ <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={[]}
+ onToggle={() => undefined}
+ money={money}
+ loading={summary.isLoading}
+ />
+ </div>
+ </Panel>
+
+ {/* Every call --------------------------------------------------- */}
+ <Panel>
+ <div className="px-4 pt-4">
+ <PanelHeader
+ title={t("costs_view.day_calls_title")}
+ subtitle={fill(t("costs_view.entries_subtitle"), {
+ shown: formatExact(Math.min(entries.data?.total ?? 0, visible)),
+ total: formatExact(entries.data?.total ?? 0),
+ })}
+ actions={
+ <SegmentedFilter<EntrySort>
+ label={t("costs_view.sort_label")}
+ value={sort}
+ onChange={(v) => {
+ setSort(v);
+ setVisible(ENTRY_PAGE);
+ }}
+ options={[
+ { id: "cost", label: t("costs_view.sort_cost") },
+ { id: "tokens", label: t("costs_view.sort_tokens") },
+ { id: "recent", label: t("costs_view.sort_recent") },
+ ]}
+ />
+ }
+ />
+ </div>
+ <div className="mt-3">
+ <EntriesTable
+ rows={entries.data?.items ?? []}
+ money={money}
+ loading={entries.isLoading}
+ />
+ </div>
+ {(entries.data?.total ?? 0) > visible ? (
+ <div className="border-t border-border px-4 py-3">
+ <button
+ type="button"
+ onClick={() => setVisible((v) => v + ENTRY_PAGE)}
+ className="text-sm font-medium text-foreground/80 transition-colors hover:text-foreground"
+ >
+ {fill(t("costs_view.load_more"), { count: String(ENTRY_PAGE) })}
+ </button>
+ </div>
+ ) : null}
+ </Panel>
+ </div>
+ </ScrollArea>
+ );
+}
+
+/** Every model of one day: how much of it, how many tokens, what it cost. */
+function DayModelsTable({
+ rows,
+ priced,
+ money,
+ loading,
+}: {
+ rows: CostBucket[];
+ /** Did the day cost anything? If not, the bar ranks by tokens instead. */
+ priced: boolean;
+ money: (usd: number) => string;
+ loading?: boolean;
+}) {
+ const t = useT();
+ const columns: Column[] = [
+ { id: "model", label: t("costs_view.dim_model") },
+ { id: "share", label: t("costs_view.col_share"), width: "150px" },
+ { id: "calls", label: t("costs_view.col_calls"), width: "76px", align: "right" },
+ { id: "in", label: t("costs_view.tokens_in"), width: "92px", align: "right" },
+ { id: "cached", label: t("costs_view.tokens_cached"), width: "92px", align: "right" },
+ { id: "out", label: t("costs_view.tokens_out"), width: "92px", align: "right" },
+ { id: "cost", label: t("costs_view.col_cost"), width: "112px", align: "right" },
+ ];
+
+ if (!loading && rows.length === 0) {
+ return (
+ <div className="px-4 pb-4">
+ <EmptyRow>{t("costs_view.breakdown_empty")}</EmptyRow>
+ </div>
+ );
+ }
+
+ return (
+ <Table label={t("costs_view.day_models_title")}>
+ <TableHead columns={columns} />
+ {rows.map((row) => {
+ const share = priced ? row.cost_share : row.token_share;
+ const provider = row.members[0] ?? "";
+ return (
+ <TableRow key={row.key} columns={columns} ariaLabel={row.key}>
+ <Cell>
+ <div className="flex min-w-0 items-center gap-2.5">
+ {provider ? (
+ <ProviderLogo providerId={provider} label={row.key} size="sm" />
+ ) : (
+ <span
+ className="h-2.5 w-2.5 shrink-0 rounded-[3px]"
+ style={{ background: keyColor(row.key) }}
+ aria-hidden
+ />
+ )}
+ <div className="min-w-0">
+ <div className="truncate font-medium text-foreground">{row.key}</div>
+ {provider ? (
+ <div className="truncate text-xs text-muted-foreground">{provider}</div>
+ ) : null}
+ </div>
+ </div>
+ </Cell>
+ <Cell>
+ <div className="flex items-center gap-2">
+ <div className="h-1.5 w-full overflow-hidden rounded-full bg-sheen/[0.08]">
+ <div
+ className="h-full rounded-full"
+ style={{
+ width: `${Math.max(2, Math.round(share * 100))}%`,
+ background: keyColor(row.key),
+ }}
+ />
+ </div>
+ <span className="w-10 shrink-0 text-right text-xs tabular-nums text-muted-foreground">
+ {formatShare(share)}
+ </span>
+ </div>
+ </Cell>
+ <Cell align="right" muted>
+ <span className="tabular-nums">{formatExact(row.entries)}</span>
+ </Cell>
+ <Cell align="right" muted>
+ <span className="tabular-nums" title={formatExact(row.tokens_in)}>
+ {formatTokensOrNone(row.tokens_in)}
+ </span>
+ </Cell>
+ <Cell align="right" muted>
+ <span className="tabular-nums" title={formatExact(row.tokens_cached)}>
+ {formatTokensOrNone(row.tokens_cached)}
+ </span>
+ </Cell>
+ <Cell align="right" muted>
+ <span className="tabular-nums" title={formatExact(row.tokens_out)}>
+ {formatTokensOrNone(row.tokens_out)}
+ </span>
+ </Cell>
+ <Cell align="right">
+ <span className="font-medium tabular-nums text-foreground">
+ {money(row.cost_usd)}
+ </span>
+ </Cell>
+ </TableRow>
+ );
+ })}
+ </Table>
+ );
+}
+
+/**
+ * The day's tokens as one bar: fresh input, cache reads, output.
+ *
+ * The three bill at three different rates, and the cheapest of them is
+ * usually the largest — a single "tokens" number hides exactly the thing
+ * that explains the bill.
+ */
+function TokenSplitBar({
+ tokensIn,
+ tokensCached,
+ tokensOut,
+}: {
+ tokensIn: number;
+ tokensCached: number;
+ tokensOut: number;
+}) {
+ const t = useT();
+ const parts = [
+ { id: "tokens_in", value: tokensIn, color: "hsl(199 90% 62%)" },
+ { id: "tokens_cached", value: tokensCached, color: "hsl(268 72% 68%)" },
+ { id: "tokens_out", value: tokensOut, color: "hsl(50 100% 52%)" },
+ ];
+ const total = parts.reduce((sum, p) => sum + p.value, 0);
+
+ if (total <= 0) {
+ return (
+ <div className="mt-4">
+ <EmptyRow>{t("costs_view.chart_empty")}</EmptyRow>
+ </div>
+ );
+ }
+
+ return (
+ <div className="mt-4">
+ <div className="flex h-3 w-full overflow-hidden rounded-full bg-sheen/[0.08]">
+ {parts
+ .filter((p) => p.value > 0)
+ .map((p) => (
+ <div
+ key={p.id}
+ style={{ width: `${(p.value / total) * 100}%`, background: p.color }}
+ title={`${t(`costs_view.${p.id}`)} · ${formatExact(p.value)}`}
+ />
+ ))}
+ </div>
+ <div className="mt-3 flex flex-wrap gap-x-6 gap-y-2">
+ {parts.map((p) => (
+ <div key={p.id} className="flex items-center gap-2">
+ <span
+ className="h-2.5 w-2.5 shrink-0 rounded-[3px]"
+ style={{ background: p.color }}
+ aria-hidden
+ />
+ <span className="text-sm text-muted-foreground">{t(`costs_view.${p.id}`)}</span>
+ <span
+ className="text-sm font-medium tabular-nums text-foreground"
+ title={formatExact(p.value)}
+ >
+ {formatTokensOrNone(p.value)}
+ </span>
+ <span className="text-xs tabular-nums text-muted-foreground">
+ {formatShare(p.value / total)}
+ </span>
+ </div>
+ ))}
+ </div>
+ </div>
+ );
+}
+
+/** A small ranked bar list — the day cut by area, or by what a model did. */
+function ShareBars({
+ rows,
+ labelOf,
+ colorOf,
+ priced,
+ money,
+ empty,
+}: {
+ rows: CostBucket[];
+ labelOf: (key: string) => string;
+ colorOf: (key: string) => string;
+ priced: boolean;
+ money: (usd: number) => string;
+ empty: string;
+}) {
+ if (rows.length === 0) {
+ return <EmptyRow>{empty}</EmptyRow>;
+ }
+ return (
+ <div className="flex flex-col gap-3">
+ {rows.map((row) => {
+ const share = priced ? row.cost_share : row.token_share;
+ return (
+ <div key={row.key}>
+ <div className="flex items-baseline justify-between gap-3 text-sm">
+ <span className="truncate text-foreground">{labelOf(row.key)}</span>
+ <span className="shrink-0 tabular-nums text-muted-foreground">
+ {money(row.cost_usd)} · {formatShare(share)}
+ </span>
+ </div>
+ <div className="mt-1.5 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(share * 100))}%`,
+ background: colorOf(row.key),
+ }}
+ />
+ </div>
+ </div>
+ );
+ })}
+ </div>
+ );
+}
diff --git a/tests/unit/costs/test_cost_read_model.py b/tests/unit/costs/test_cost_read_model.py
index d30ac4c0b1..e42dc65f80 100644
--- a/tests/unit/costs/test_cost_read_model.py
+++ b/tests/unit/costs/test_cost_read_model.py
@@ -673,3 +673,58 @@ def test_a_bring_your_own_key_cli_row_is_billed_at_its_recorded_price(tmp_path:
assert entries["gpt-5.5"].price_source == "recorded"
assert entries["gpt-5.5"].cost_usd == pytest.approx(0.0123)
assert entries["nemotron:free"].price_source == "free"
+# ---------------------------------------------------------------------------
+# The coding-CLI source reads at ONE grain, whatever the report draws at
+# ---------------------------------------------------------------------------
+
+
+def _claude_transcript(home: Path, *, hours: list[int]) -> None:
+ """A Claude Code session with one response in each of the given hours."""
+ path = home / ".claude" / "projects" / "-work-jarvis" / "sess-1.jsonl"
+ path.parent.mkdir(parents=True, exist_ok=True)
+ lines = [
+ json.dumps(
+ {
+ "type": "assistant",
+ "uuid": f"u{hour}",
+ "sessionId": "sess-1",
+ "timestamp": f"2026-08-23T{hour:02d}:30:00.000Z",
+ "cwd": "/work/jarvis",
+ "message": {
+ "id": f"msg_{hour}",
+ "model": "claude-opus-5",
+ "usage": {"input_tokens": 100, "output_tokens": 20},
+ },
+ }
+ )
+ for hour in hours
+ ]
+ path.write_bytes(("\n".join(lines) + "\n").encode("utf-8"))
+
+
+def test_a_session_counts_the_same_whatever_grain_the_report_draws_at(
+ tmp_path: Path,
+) -> None:
+ """A day must not gain rows just because a chart asked for hours.
+
+ The coding-CLI index pre-aggregates before the read model ever sees it,
+ so it has to be told a grain. When that grain was the report's own, one
+ session spanning three hours of a day collapsed into a single row for a
+ 30-day view and into three for a one-day view — and the daily ledger and
+ the day report behind it then counted the same day differently (113 vs
+ 204 calls, 2026-08-25). It now always reads at the finest grain the
+ section ever draws, and rolls up from there.
+ """
+ from jarvis.costs.cli_usage_index import refresh
+
+ data = tmp_path / "data"
+ _claude_transcript(tmp_path, hours=[9, 10, 11])
+ refresh(data_dir=data, home=tmp_path)
+
+ sources = CostSources(cli_index_dir=data)
+ hourly = collect_entries(sources, bucket_ms=60 * 60 * 1000)
+ daily = collect_entries(sources, bucket_ms=24 * 60 * 60 * 1000)
+
+ assert len(hourly) == 3
+ assert len(daily) == len(hourly)
+ assert sum(e.tokens_total for e in daily) == sum(e.tokens_total for e in hourly)
diff --git a/tests/unit/ui/web/test_costs_routes.py b/tests/unit/ui/web/test_costs_routes.py
index 563262c0e1..1bea8ab455 100644
--- a/tests/unit/ui/web/test_costs_routes.py
+++ b/tests/unit/ui/web/test_costs_routes.py
@@ -12,6 +12,7 @@ from __future__ import annotations
import sqlite3
import time
+from datetime import datetime, timedelta
from pathlib import Path
from types import SimpleNamespace
@@ -136,3 +137,104 @@ 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"}
+
+
+# ---------------------------------------------------------------------------
+# The daily ledger — one row per day, and the drill-down behind it
+# ---------------------------------------------------------------------------
+
+def _seed_two_days(data_dir: Path) -> None:
+ """Two calendar days, two models on the busier one.
+
+ Both days are in the PAST and both are anchored to local noon. Seeding
+ "today at noon" would put half the rows in the future whenever the suite
+ runs in the morning, and seeding "now minus a day" would straddle
+ midnight — either way the test would pass or fail by the hour it ran.
+ """
+ data_dir.mkdir(parents=True, exist_ok=True)
+ noon = datetime.now().replace(hour=12, minute=0, second=0, microsecond=0)
+ busy = int((noon - timedelta(days=1)).timestamp() * 1000)
+ quiet = int((noon - timedelta(days=2)).timestamp() * 1000)
+ conn = sqlite3.connect(data_dir / "sessions.db")
+ conn.executescript(_SCHEMA)
+ rows = [
+ # The busy day: the expensive model ran early, the cheap one an hour
+ # later. A ledger that sorted by "newest" would put the cheap one on
+ # top and read as if the day had been spent on it.
+ ("d1", "sess-a", busy, "deep", "anthropic",
+ "claude-opus-4-7-20251022", 200_000, 20_000, 6.00, "the long morning run"),
+ ("d2", "sess-b", busy + 3_600_000, "fast", "anthropic",
+ "claude-haiku-4-5-20251001", 5_000, 500, 0.01, "a quick question"),
+ ("d3", "sess-c", quiet, "realtime", "gemini-live",
+ "gemini-3.1-flash-live-preview", 40_000, 200, 0.40, "the day before"),
+ ]
+ 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 two_day_client(tmp_path: Path) -> TestClient:
+ _seed_two_days(tmp_path / "data")
+ return _client(tmp_path / "data")
+
+
+def test_daily_is_one_row_per_day_newest_first(two_day_client: TestClient) -> None:
+ body = two_day_client.get("/api/costs/daily?days=30").json()
+ dates = [d["date"] for d in body["days"]]
+ assert len(dates) == 2
+ assert dates == sorted(dates, reverse=True)
+
+
+def test_daily_names_every_model_the_day_used(two_day_client: TestClient) -> None:
+ """The regression this replaced: a day read as if one model did it all.
+
+ Three sessions on one day used to be three rows, each labelled with its
+ own model, ordered by the timestamp of their FIRST call — so the day's
+ biggest spender sank below a later, smaller one.
+ """
+ body = two_day_client.get("/api/costs/daily?days=30").json()
+ busy = body["days"][0]
+ models = [m["key"] for m in busy["by_model"]]
+ assert models == ["claude-opus-4-7-20251022", "claude-haiku-4-5-20251001"]
+ assert busy["by_model"][0]["cost_share"] > 0.9
+
+
+def test_daily_totals_add_up_to_the_range(two_day_client: TestClient) -> None:
+ daily = two_day_client.get("/api/costs/daily?days=30").json()
+ summary = two_day_client.get("/api/costs/summary?days=30").json()
+ assert sum(d["totals"]["entries"] for d in daily["days"]) == summary["totals"]["entries"]
+ assert (
+ pytest.approx(sum(d["totals"]["cost_usd"] for d in daily["days"]), rel=1e-6)
+ == summary["totals"]["cost_usd"]
+ )
+
+
+def test_a_day_row_opens_into_exactly_that_day(two_day_client: TestClient) -> None:
+ """The drill-down contract: a row's bounds reproduce the row."""
+ row = two_day_client.get("/api/costs/daily?days=30").json()["days"][0]
+ detail = two_day_client.get(
+ f"/api/costs/summary?since_ms={row['since_ms']}&until_ms={row['until_ms']}"
+ ).json()
+ assert detail["totals"]["entries"] == row["totals"]["entries"]
+ assert pytest.approx(detail["totals"]["cost_usd"]) == row["totals"]["cost_usd"]
+ # A one-day window is short enough to be drawn hour by hour.
+ assert detail["bucket"] == "hour"
+
+
+def test_daily_narrows_with_the_same_filters(two_day_client: TestClient) -> None:
+ body = two_day_client.get("/api/costs/daily?days=30&provider=gemini-live").json()
+ assert len(body["days"]) == 1
+ assert [m["key"] for m in body["days"][0]["by_model"]] == [
+ "gemini-3.1-flash-live-preview"
+ ]
+
+
+def test_daily_on_an_empty_install_is_an_empty_ledger(tmp_path: Path) -> None:
+ body = _client(tmp_path / "nothing").get("/api/costs/daily?days=30").json()
+ assert body["days"] == []
+ assert body["currency"]["eur_per_usd"] > 0