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.

fix(spend): filter coding costs from trend charts

rubenluetke10-beepff33e7a923e3
diff --git a/jarvis/ui/web/frontend/src/components/costs/CostTrendChart.tsx b/jarvis/ui/web/frontend/src/components/costs/CostTrendChart.tsx
index 0d9268fb0d..6dc83249ad 100644
--- a/jarvis/ui/web/frontend/src/components/costs/CostTrendChart.tsx
+++ b/jarvis/ui/web/frontend/src/components/costs/CostTrendChart.tsx
@@ -85,7 +85,11 @@ export function CostTrendChart({
// entry in Recharts, and a legend full of zeroes reads as missing data.
const roles = useMemo(() => {
const present = new Set<string>();
- for (const b of series) for (const k of Object.keys(b.breakdown ?? {})) present.add(k);
+ for (const b of series) {
+ for (const [role, cost] of Object.entries(b.breakdown ?? {})) {
+ if (cost > 0) present.add(role);
+ }
+ }
return ROLE_ORDER.filter((r) => present.has(r));
}, [series]);
@@ -248,7 +252,10 @@ function TrendTooltip(props: {
}) {
const { active, payload, label, bucket, metric, currency, eurPerUsd, stacks, t } = props;
if (!active || !payload || payload.length === 0) return null;
- const total = payload.reduce((sum, p) => sum + (p.value ?? 0), 0);
+ const total = stacks.reduce(
+ (sum, stack) => sum + (payload.find((p) => p.dataKey === stack.dataKey)?.value ?? 0),
+ 0,
+ );
const fmt = (v: number) =>
metric === "cost" ? formatMoney(v, eurPerUsd, currency) : formatTokens(v);
diff --git a/jarvis/ui/web/frontend/src/components/costs/CostTrendPanel.test.tsx b/jarvis/ui/web/frontend/src/components/costs/CostTrendPanel.test.tsx
new file mode 100644
index 0000000000..82baca925f
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/costs/CostTrendPanel.test.tsx
@@ -0,0 +1,182 @@
+import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { EMPTY_FILTERS, type CostBucket, type CostFilters, type CostSummary } from "@/hooks/useCosts";
+import { useI18nStore } from "@/i18n";
+import { CostTrendPanel } from "./CostTrendPanel";
+import { roleColor } from "./costFormat";
+import { CostsView } from "@/views/CostsView";
+
+class ChartResizeObserver {
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+}
+
+const clients: QueryClient[] = [];
+
+beforeEach(() => {
+ useI18nStore.getState().setUi("en", { push: false });
+ vi.stubGlobal("ResizeObserver", ChartResizeObserver);
+ vi.spyOn(HTMLElement.prototype, "getBoundingClientRect").mockReturnValue({
+ width: 640, height: 200, x: 0, y: 0, top: 0, left: 0, right: 640, bottom: 200,
+ toJSON: () => ({}),
+ });
+});
+
+afterEach(() => {
+ cleanup();
+ for (const client of clients.splice(0)) client.clear();
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+});
+
+function bucket(breakdown: Record<string, number>, tokens = 100): CostBucket {
+ return {
+ key: "2026-09-07", breakdown,
+ cost_usd: Object.values(breakdown).reduce((sum, cost) => sum + cost, 0),
+ tokens_in: tokens, tokens_out: 20, tokens_cached: 10, tokens_total: tokens + 30,
+ entries: 3, gap_tokens: 0, subscription_usd: 0, chars: 0, audio_ms: 0,
+ price_sources: ["recorded"], last_ts_ms: 0, cost_share: 1, token_share: 1, members: [],
+ };
+}
+
+function summary(point: CostBucket): CostSummary {
+ return {
+ since_ms: 1, until_ms: 2, bucket: "day",
+ totals: {
+ ...point, gap_entries: 0, free_tokens: 0, estimated_usd: 0, first_ts_ms: 1,
+ },
+ series: [point], by_provider: [], by_model: [], by_role: [], by_surface: [],
+ top_refs: [], models: [], refs_total: 0, sources_present: [],
+ currency: { eur_per_usd: 0.9, source: "default" },
+ facets: {
+ providers: [], models: [], roles: ["agent", "worker", "tts"],
+ surfaces: ["agentic-ide", "agent-chat", "mission", "jarvis-voice"],
+ },
+ };
+}
+
+function mount(data: CostSummary, filters: CostFilters = EMPTY_FILTERS) {
+ const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+ clients.push(client);
+ return render(
+ <QueryClientProvider client={client}>
+ <CostTrendPanel filters={filters} summary={data} loading={false}
+ title="Over time" subtitle="September" currency="usd" eurPerUsd={0.9} />
+ </QueryClientProvider>,
+ );
+}
+
+function maxAxisTick(container: HTMLElement) {
+ const ticks = container.querySelectorAll('.recharts-cartesian-axis-tick-value[orientation="left"]');
+ if (!ticks.length) return NaN;
+ return Math.max(...Array.from(ticks, (tick) => {
+ const text = tick.textContent ?? "";
+ const multiplier = text.endsWith("M") ? 1_000_000 : text.endsWith("k") ? 1000 : 1;
+ return parseFloat(text.replace(/[$,]/g, "")) * multiplier;
+ }));
+}
+
+describe("CostTrendPanel", () => {
+ it("excludes IDE surfaces, rescales by orders of magnitude, and restores original totals", async () => {
+ const all = summary(bucket({ agent: 100_000, worker: 20_000, tts: 0.5 }, 1_000_000));
+ const filtered = summary(bucket({ agent: 0.2, worker: 0.1, tts: 0.5 }));
+ const original = JSON.stringify(all);
+ const fetcher = vi.fn().mockResolvedValue({ ok: true, json: async () => filtered });
+ vi.stubGlobal("fetch", fetcher);
+ const { container } = mount(all, { ...EMPTY_FILTERS, providers: ["example"], billing: "billed" });
+ await waitFor(() => expect(maxAxisTick(container)).toBeGreaterThan(100_000));
+ expect(fetcher).not.toHaveBeenCalled();
+
+ fireEvent.click(screen.getByRole("checkbox", { name: "Include Agentic IDE" }));
+ await waitFor(() => expect(maxAxisTick(container)).toBeLessThan(2));
+ const params = new URL(String(fetcher.mock.calls[0][0]), "http://localhost").searchParams;
+ expect(params.getAll("surface")).toEqual(["agent-chat", "mission", "jarvis-voice"]);
+ expect(params.getAll("provider")).toEqual(["example"]);
+ expect(params.get("billing")).toBe("billed");
+ // Non-IDE agent/worker spend survives and keeps the same palette.
+ expect(container.querySelector(`path[fill="${roleColor("agent")}"]`)).not.toBeNull();
+ expect(container.querySelector(`path[fill="${roleColor("worker")}"]`)).not.toBeNull();
+ expect(JSON.stringify(all)).toBe(original);
+ fireEvent.keyDown(screen.getByRole("application"), { key: "ArrowRight" });
+ await waitFor(() => expect(container.querySelector(".recharts-tooltip-wrapper")?.textContent).toContain("Total$0.80"));
+ expect(screen.queryByText("$100,000")).toBeNull();
+
+ fireEvent.click(screen.getByRole("tab", { name: "Tokens" }));
+ await waitFor(() => expect(maxAxisTick(container)).toBeLessThan(1000));
+ fireEvent.click(screen.getByRole("checkbox", { name: "Include Agentic IDE" }));
+ await waitFor(() => expect(maxAxisTick(container)).toBeGreaterThanOrEqual(1_000_000));
+ expect(JSON.stringify(all)).toBe(original);
+ });
+
+ it("never widens an IDE-only area to all surfaces", () => {
+ const fetcher = vi.fn();
+ vi.stubGlobal("fetch", fetcher);
+ mount(summary(bucket({ agent: 100_000 })), { ...EMPTY_FILTERS, surfaces: ["agentic-ide"] });
+ fireEvent.click(screen.getByRole("checkbox", { name: "Include Agentic IDE" }));
+ expect(screen.getByText("Nothing spent in this range.")).toBeTruthy();
+ expect(fetcher).not.toHaveBeenCalled();
+ });
+
+ it("keeps hour, provider and explicit surface filters and drops absent legend entries", async () => {
+ const data = summary(bucket({ agent: 100_000, tts: 0.5 }));
+ const filtered = summary(bucket({ tts: 0.5, agent: 0 }));
+ filtered.bucket = "hour";
+ filtered.series[0].key = "2026-09-07T12:00";
+ const fetcher = vi.fn().mockResolvedValue({ ok: true, json: async () => filtered });
+ vi.stubGlobal("fetch", fetcher);
+ const { container } = mount(data, {
+ ...EMPTY_FILTERS, surfaces: ["agentic-ide", "jarvis-voice"],
+ sinceMs: 1000, untilMs: 2000, providers: ["example"],
+ });
+ fireEvent.click(screen.getByRole("checkbox", { name: "Include Agentic IDE" }));
+ await waitFor(() => expect(screen.getByText("Text to speech")).toBeTruthy());
+ expect(screen.queryByText("Coding agent")).toBeNull();
+ const params = new URL(String(fetcher.mock.calls[0][0]), "http://localhost").searchParams;
+ expect(params.getAll("surface")).toEqual(["jarvis-voice"]);
+ expect(params.getAll("provider")).toEqual(["example"]);
+ expect(params.get("since_ms")).toBe("1000");
+ expect(params.get("until_ms")).toBe("2000");
+ fireEvent.keyDown(screen.getByRole("application"), { key: "ArrowRight" });
+ await waitFor(() => expect(container.querySelector(".recharts-tooltip-wrapper")?.textContent).toContain("Total$0.50"));
+ });
+
+ it("shows loading and errors instead of old coding spend under an active filter", async () => {
+ let reject!: (error: Error) => void;
+ vi.stubGlobal("fetch", vi.fn().mockReturnValue(new Promise((_resolve, fail) => { reject = fail; })));
+ const { container } = mount(summary(bucket({ agent: 100_000 })));
+ fireEvent.click(screen.getByRole("checkbox", { name: "Include Agentic IDE" }));
+ expect(screen.getByRole("status")).toBeTruthy();
+ expect(container.querySelector(".recharts-bar")).toBeNull();
+ reject(new Error("offline"));
+ await waitFor(() => expect(screen.getByRole("alert")).toBeTruthy());
+ expect(container.querySelector(".recharts-bar")).toBeNull();
+ });
+
+ it("refreshes the active filtered chart from the Spend view refresh button", async () => {
+ const all = summary(bucket({ agent: 100_000, tts: 0.5 }));
+ let filtered = summary(bucket({ tts: 0.5 }));
+ let filteredReads = 0;
+ vi.stubGlobal("fetch", vi.fn(async (input: string) => {
+ const url = new URL(input, "http://localhost");
+ let data: unknown = { days: [], currency: all.currency };
+ if (url.pathname.endsWith("/summary")) {
+ const excludesIde = url.searchParams.has("surface");
+ if (excludesIde) filteredReads += 1;
+ data = excludesIde ? filtered : all;
+ }
+ return { ok: true, json: async () => data };
+ }));
+ const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+ clients.push(client);
+ const { container } = render(<QueryClientProvider client={client}><CostsView /></QueryClientProvider>);
+ await waitFor(() => expect(maxAxisTick(container)).toBeGreaterThan(100_000));
+ fireEvent.click(screen.getByRole("checkbox", { name: "Include Agentic IDE" }));
+ await waitFor(() => expect(maxAxisTick(container)).toBeLessThan(2));
+ filtered = summary(bucket({ tts: 50 }));
+ fireEvent.click(screen.getByRole("button", { name: "Refresh" }));
+ await waitFor(() => expect(maxAxisTick(container)).toBeGreaterThanOrEqual(50));
+ expect(filteredReads).toBe(2);
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/components/costs/CostTrendPanel.tsx b/jarvis/ui/web/frontend/src/components/costs/CostTrendPanel.tsx
new file mode 100644
index 0000000000..214cbf39d5
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/costs/CostTrendPanel.tsx
@@ -0,0 +1,97 @@
+import { useState } from "react";
+import { useQuery } from "@tanstack/react-query";
+import { Panel, PanelHeader, SegmentedFilter } from "@/components/extensions/primitives";
+import { costSummaryQueryOptions, type CostFilters, type CostSummary } from "@/hooks/useCosts";
+import { useT } from "@/i18n";
+import { CostTrendChart, type TrendMetric } from "./CostTrendChart";
+
+/** Chart-only filtering leaves the surrounding ledger and its totals intact. */
+export function CostTrendPanel({
+ filters,
+ summary,
+ loading,
+ title,
+ subtitle,
+ currency,
+ eurPerUsd,
+ bucket = "day",
+}: {
+ filters: CostFilters;
+ summary?: CostSummary;
+ loading: boolean;
+ title: string;
+ subtitle: string;
+ currency: "usd" | "eur";
+ eurPerUsd: number;
+ bucket?: "day" | "hour";
+}) {
+ const t = useT();
+ const [metric, setMetric] = useState<TrendMetric>("cost");
+ const [includeIde, setIncludeIde] = useState(true);
+ // Roles overlap: both agent chats and coding sessions can use "agent".
+ // Filter the actual surfaces reported by the backend, including new ones.
+ const surfaces = (filters.surfaces.length ? filters.surfaces : summary?.facets.surfaces ?? [])
+ .filter((surface) => surface !== "agentic-ide");
+ const chartQuery = useQuery({
+ ...costSummaryQueryOptions({ ...filters, surfaces }),
+ enabled: !includeIde && !!summary && surfaces.length > 0,
+ refetchInterval: 120_000,
+ // No placeholder from the previous filter: it would briefly claim the
+ // dominant coding spend was already excluded while still plotting it.
+ });
+ // An empty surface list means "all" to the API, so an IDE-only selection
+ // must render empty locally instead of accidentally requesting everything.
+ const chartData = includeIde ? summary : surfaces.length ? chartQuery.data : undefined;
+ const chartLoading = includeIde
+ ? loading
+ : loading || (surfaces.length > 0 && chartQuery.isPending);
+ const chartError = !includeIde && surfaces.length > 0 && chartQuery.isError;
+
+ return (
+ <Panel className="p-4">
+ <PanelHeader
+ className="flex-wrap [&>div]:max-w-full"
+ title={title}
+ subtitle={subtitle}
+ actions={
+ <div className="flex min-w-0 flex-wrap items-center gap-x-5 gap-y-2">
+ <label className="flex cursor-pointer items-center gap-2 text-xs text-muted-foreground">
+ <input
+ type="checkbox"
+ checked={includeIde}
+ onChange={(event) => setIncludeIde(event.target.checked)}
+ className="h-4 w-4 accent-accent focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
+ />
+ {t("costs_view.chart_include_ide")}
+ </label>
+ <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>
+ }
+ />
+ <div className="mt-3 h-[220px]">
+ {chartError ? (
+ <div role="alert" className="flex h-full items-center justify-center text-xs text-muted-foreground">
+ {t("costs_view.load_error")}
+ </div>
+ ) : (
+ <CostTrendChart
+ series={chartData?.series ?? []}
+ bucket={chartData?.bucket ?? bucket}
+ metric={metric}
+ currency={currency}
+ eurPerUsd={eurPerUsd}
+ loading={chartLoading}
+ />
+ )}
+ </div>
+ </Panel>
+ );
+}
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.json
index bc4cf54a44..c073d5dceb 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json
@@ -4901,6 +4901,7 @@
"stat_gap_none": "Jeder Token ist bepreist",
"trend_title": "Zeitlicher Verlauf",
"trend_subtitle": "{from} → {to}",
+ "chart_include_ide": "Agentic IDE einbeziehen",
"metric_label": "Kennzahl",
"metric_cost": "Kosten",
"metric_tokens": "Tokens",
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.json
index 402a7e52b6..1b8d062162 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json
@@ -4934,6 +4934,7 @@
"stat_gap_none": "Every token is priced",
"trend_title": "Over time",
"trend_subtitle": "{from} → {to}",
+ "chart_include_ide": "Include Agentic IDE",
"metric_label": "Metric",
"metric_cost": "Cost",
"metric_tokens": "Tokens",
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.json
index be9a44ce84..3bb7b25536 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json
@@ -4901,6 +4901,7 @@
"stat_gap_none": "Todos los tokens tienen precio",
"trend_title": "Evolución",
"trend_subtitle": "{from} → {to}",
+ "chart_include_ide": "Incluir Agentic IDE",
"metric_label": "Métrica",
"metric_cost": "Coste",
"metric_tokens": "Tokens",
diff --git a/jarvis/ui/web/frontend/src/views/CostsView.tsx b/jarvis/ui/web/frontend/src/views/CostsView.tsx
index 4d46d8c69a..24023e2918 100644
--- a/jarvis/ui/web/frontend/src/views/CostsView.tsx
+++ b/jarvis/ui/web/frontend/src/views/CostsView.tsx
@@ -14,6 +14,7 @@
* separate ledger that could disagree with them.
*/
import { useMemo, useState } from "react";
+import { useQueryClient } from "@tanstack/react-query";
import {
AlertTriangle,
AudioLines,
@@ -53,7 +54,7 @@ import {
TableHead,
TableRow,
} from "@/components/extensions/primitives";
-import { CostTrendChart, type TrendMetric } from "@/components/costs/CostTrendChart";
+import { CostTrendPanel } from "@/components/costs/CostTrendPanel";
import {
dayBoundsMs,
formatBucketFull,
@@ -103,9 +104,9 @@ const ENTRY_PAGE = 50;
export function CostsView() {
const t = useT();
+ const queryClient = useQueryClient();
const [filters, setFilters] = useState<CostFilters>(EMPTY_FILTERS);
const [currency, setCurrency] = useState<Currency>("usd");
- const [metric, setMetric] = useState<TrendMetric>("cost");
const [dimension, setDimension] = useState<Dimension>("provider");
const [searchOpen, setSearchOpen] = useState(false);
const [ratesOpen, setRatesOpen] = useState(false);
@@ -247,7 +248,7 @@ export function CostsView() {
<IconButton
label={t("costs_view.refresh")}
busy={summary.isFetching}
- onClick={() => void summary.refetch()}
+ onClick={() => void queryClient.refetchQueries({ queryKey: ["costs", "summary"], type: "active" })}
>
<RefreshCw className="h-4 w-4" />
</IconButton>
@@ -440,40 +441,22 @@ export function CostsView() {
</div>
{/* Trend ------------------------------------------------------- */}
- <Panel className="p-4">
- <PanelHeader
- title={t("costs_view.trend_title")}
- subtitle={
- data
- ? fill(t("costs_view.trend_subtitle"), {
- from: formatBucketFull(data.series[0]?.key ?? "", data.bucket),
- to: formatBucketFull(data.series[data.series.length - 1]?.key ?? "", data.bucket),
- })
- : ""
- }
- actions={
- <SegmentedFilter<TrendMetric>
- label={t("costs_view.metric_label")}
- value={metric}
- onChange={setMetric}
- options={[
- { id: "cost", label: t("costs_view.metric_cost") },
- { id: "tokens", label: t("costs_view.metric_tokens") },
- ]}
- />
- }
- />
- <div className="mt-3 h-[220px]">
- <CostTrendChart
- series={data?.series ?? []}
- bucket={data?.bucket ?? "day"}
- metric={metric}
- currency={currency}
- eurPerUsd={eurPerUsd}
- loading={summary.isLoading}
- />
- </div>
- </Panel>
+ <CostTrendPanel
+ filters={filters}
+ summary={data}
+ loading={summary.isLoading}
+ title={t("costs_view.trend_title")}
+ subtitle={
+ data
+ ? fill(t("costs_view.trend_subtitle"), {
+ from: formatBucketFull(data.series[0]?.key ?? "", data.bucket),
+ to: formatBucketFull(data.series[data.series.length - 1]?.key ?? "", data.bucket),
+ })
+ : ""
+ }
+ currency={currency}
+ eurPerUsd={eurPerUsd}
+ />
{/* Breakdown --------------------------------------------------- */}
<Panel>
@@ -1520,7 +1503,7 @@ function DayReport({
onBack: () => void;
}) {
const t = useT();
- const [metric, setMetric] = useState<TrendMetric>("cost");
+ const queryClient = useQueryClient();
const [sort, setSort] = useState<EntrySort>("cost");
const [visible, setVisible] = useState(ENTRY_PAGE);
@@ -1574,7 +1557,7 @@ function DayReport({
<IconButton
label={t("costs_view.refresh")}
busy={summary.isFetching}
- onClick={() => void summary.refetch()}
+ onClick={() => void queryClient.refetchQueries({ queryKey: ["costs", "summary"], type: "active" })}
>
<RefreshCw className="h-4 w-4" />
</IconButton>
@@ -1633,33 +1616,16 @@ function DayReport({
</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}
- loading={summary.isLoading}
- />
- </div>
- </Panel>
+ <CostTrendPanel
+ filters={dayFilters}
+ summary={data}
+ loading={summary.isLoading}
+ title={t("costs_view.day_hours_title")}
+ subtitle={t("costs_view.day_hours_subtitle")}
+ currency={currency}
+ eurPerUsd={eurPerUsd}
+ bucket="hour"
+ />
{/* Which models ------------------------------------------------ */}
<Panel>