Skip to content

armgit / kwant

Public Imported from GitHub
0

Your own team of AI bots in one self-hosted binary: spaces, every account you have, handoffs, approvals and routines. Open-source, self-hosted alternative to Grok Bot, Claude Duet and OpenAI dots. Rust + React.

Settings › Usage: 7/30-day trend and spend per model (#592)

Oleksandr Ivanchenkoe21f772b0cd8
diff --git a/frontend/src/components/DailyUsage.tsx b/frontend/src/components/DailyUsage.tsx
index 3e511f39..d325ee49 100644
--- a/frontend/src/components/DailyUsage.tsx
+++ b/frontend/src/components/DailyUsage.tsx
@@ -1,6 +1,8 @@
-import React, { useCallback, useEffect, useState } from 'react';
+import React, { useCallback, useEffect, useRef, useState } from 'react';
import { Loader2, RotateCcw } from 'lucide-react';
-import { DailyUsage, compactTokens, formatCost, freshOf, modelUsageApi } from '../modelUsage';
+import { DailyUsage, ModelTotals, compactTokens, formatCost, freshOf, modelUsageApi } from '../modelUsage';
+import { type EngineInfo, usageModelLabel } from '../engines';
+import { useEngines } from '../useEngines';
interface Day {
day: string;
@@ -38,6 +40,176 @@ export function dayLabel(day: string, now = new Date()): string {
: d.toLocaleDateString('en-GB', { weekday: 'short', day: 'numeric', month: 'short', timeZone: 'UTC' });
}
+/** The windows the switch offers. */
+export const RANGES = [7, 30] as const;
+export type Range = (typeof RANGES)[number];
+
+/** What the trend and the model shares measure: cost once any call in the window reported one, else fresh tokens. */
+export type Metric = 'cost' | 'tokens';
+
+export interface TrendDay {
+ day: string;
+ /** Cost or fresh tokens, by the window's metric; 0 on a day without use. */
+ value: number;
+ used: boolean;
+}
+
+const utcDay = (t: number) => new Date(t).toISOString().slice(0, 10);
+
+/** One entry per UTC day of the window, oldest first and today last, empty days included. */
+export function trendDays(rows: DailyUsage[], days: number, now = new Date()): { metric: Metric; days: TrendDay[]; total: number } {
+ const metric: Metric = rows.some((r) => r.cost_usd != null) ? 'cost' : 'tokens';
+ const by = new Map(groupDays(rows).map((d) => [d.day, d]));
+ const out: TrendDay[] = [];
+ for (let i = days - 1; i >= 0; i--) {
+ const day = utcDay(now.getTime() - i * 86_400_000);
+ const d = by.get(day);
+ out.push({ day, value: d ? (metric === 'cost' ? d.cost ?? 0 : d.fresh) : 0, used: !!d });
+ }
+ return { metric, days: out, total: out.reduce((n, d) => n + d.value, 0) };
+}
+
+/** "$0.42" or "1.2M tokens". */
+export function metricText(metric: Metric, v: number): string {
+ return metric === 'cost' ? formatCost(v) ?? '$0' : `${compactTokens(v)} tokens`;
+}
+
+/** Each model's share of the window, by the window's metric; models with none of it last. */
+export function modelShares(models: ModelTotals[], metric: Metric): Array<{ model: string; value: number; share: number; calls: number }> {
+ const val = (m: ModelTotals) => (metric === 'cost' ? m.cost_usd ?? 0 : freshOf(m));
+ const total = models.reduce((n, m) => n + val(m), 0);
+ return models
+ .map((m) => ({ model: m.model, value: val(m), share: total > 0 ? Math.round((val(m) / total) * 100) : 0, calls: m.calls }))
+ .sort((a, b) => b.value - a.value);
+}
+
+const focusRing = 'focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-400';
+
+const RangeSwitch: React.FC<{ range: Range; onRange?: (r: Range) => void }> = ({ range, onRange }) => (
+ <div role="group" aria-label="Show" className="flex gap-1.5">
+ {RANGES.map((r) => (
+ <button
+ key={r}
+ type="button"
+ aria-pressed={range === r}
+ disabled={!onRange}
+ onClick={() => onRange?.(r)}
+ data-usage-range={r}
+ className={`px-2.5 min-h-[36px] sm:min-h-[28px] rounded-full border text-[11px] ${focusRing} ${
+ range === r ? 'border-sky-500/60 bg-sky-500/15 text-sky-100' : 'border-zinc-700 text-zinc-400 hover:text-zinc-200'
+ }`}
+ >
+ {r} days
+ </button>
+ ))}
+ </div>
+);
+
+/** One bar per day, today on the right. Arrow keys move between days; the line under it names the day in focus. */
+const Trend: React.FC<{ days: TrendDay[]; metric: Metric; now?: Date }> = ({ days, metric, now }) => {
+ const [active, setActive] = useState(days.length - 1);
+ const [shown, setShown] = useState<number | null>(null);
+ const bars = useRef<Array<HTMLLIElement | null>>([]);
+ const max = Math.max(...days.map((d) => d.value), 0);
+ const label = (d: TrendDay) => `${dayLabel(d.day, now)}: ${d.used ? metricText(metric, d.value) : 'no AI use'}`;
+ const move = (i: number) => {
+ const j = Math.max(0, Math.min(days.length - 1, i));
+ setActive(j);
+ setShown(j);
+ bars.current[j]?.focus();
+ };
+ const at = shown == null ? null : days[shown];
+ return (
+ <div>
+ <ul
+ aria-label={`${metric === 'cost' ? 'Cost' : 'Fresh tokens'} per day`}
+ className={`flex items-end h-20 ${days.length > 14 ? 'gap-[2px]' : 'gap-1'}`}
+ onMouseLeave={() => setShown(null)}
+ data-usage-trend
+ >
+ {days.map((d, i) => {
+ const pct = max > 0 ? (d.value / max) * 100 : 0;
+ return (
+ <li
+ key={d.day}
+ ref={(el) => void (bars.current[i] = el)}
+ tabIndex={i === active ? 0 : -1}
+ aria-label={label(d)}
+ title={label(d)}
+ data-day={d.day}
+ data-used={d.used ? '' : undefined}
+ onMouseEnter={() => setShown(i)}
+ onFocus={() => (setActive(i), setShown(i))}
+ onBlur={() => setShown(null)}
+ onKeyDown={(e) => {
+ const step = { ArrowLeft: -1, ArrowRight: 1, Home: -days.length, End: days.length }[e.key];
+ if (step === undefined) return;
+ e.preventDefault();
+ move(i + step);
+ }}
+ className={`group relative flex-1 min-w-0 h-full flex items-end rounded-sm ${focusRing}`}
+ >
+ <span
+ aria-hidden="true"
+ className={`block w-full rounded-sm ${
+ !d.used || d.value === 0 ? 'h-px bg-zinc-700' : shown === i ? 'bg-sky-300' : 'bg-sky-500/70 group-hover:bg-sky-300'
+ }`}
+ style={d.used && d.value > 0 ? { height: `${Math.max(pct, 3)}%` } : undefined}
+ />
+ </li>
+ );
+ })}
+ </ul>
+ <div className="mt-1 flex items-center gap-2 text-[11px] text-zinc-500 tabular-nums" aria-hidden="true">
+ <span className="flex-1 truncate">{dayLabel(days[0].day, now)}</span>
+ <span className="text-zinc-300 truncate" data-usage-readout>
+ {at ? label(at) : ''}
+ </span>
+ <span className="flex-1 truncate text-right">Today</span>
+ </div>
+ </div>
+ );
+};
+
+const ByModel: React.FC<{ models: ModelTotals[]; metric: Metric; engines?: EngineInfo[] | null }> = ({ models, metric, engines }) => {
+ const rows = modelShares(models, metric);
+ if (!rows.length) return null;
+ return (
+ <div className="space-y-1.5">
+ <h4 className="text-[11px] font-medium text-zinc-400">By model</h4>
+ <ul className="space-y-1.5" aria-label="Use by model" data-usage-models>
+ {rows.map((r) => {
+ const name = usageModelLabel(r.model, engines ?? null);
+ return (
+ <li key={r.model} className="space-y-1" data-model={r.model}>
+ <div className="flex items-center gap-2">
+ <span className="flex-1 min-w-0 truncate text-[11px] text-zinc-300" title={r.model}>
+ {name}
+ </span>
+ {metric === 'cost' && r.value === 0 ? (
+ <span className="shrink-0 text-[11px] text-zinc-500">No cost reported</span>
+ ) : (
+ <span className="shrink-0 font-mono text-[11px] tabular-nums text-zinc-400">
+ {metricText(metric, r.value)}
+ <span className="text-zinc-600"> · </span>
+ <span className="text-zinc-200">{r.share}%</span>
+ </span>
+ )}
+ </div>
+ <span
+ aria-hidden="true"
+ className="relative block h-1 w-full overflow-hidden rounded-full bg-zinc-800"
+ >
+ <span className="absolute inset-y-0 left-0 rounded-full bg-sky-500/70" style={{ width: `${r.share}%` }} />
+ </span>
+ </li>
+ );
+ })}
+ </ul>
+ </div>
+ );
+};
+
const Numbers: React.FC<{ fresh: number; cached: number; cost: number | null; strong?: boolean }> = ({ fresh, cached, cost, strong }) => (
<span className={`shrink-0 font-mono text-[11px] tabular-nums ${strong ? 'text-zinc-200' : 'text-zinc-400'}`}>
<span title={`${fresh.toLocaleString('en-US')} fresh tokens`}>{compactTokens(fresh)}</span>
@@ -54,73 +226,129 @@ const Numbers: React.FC<{ fresh: number; cached: number; cost: number | null; st
</span>
);
-/** Settings → Usage: fresh and cached tokens and cost per day and bot. */
-export const DailyUsageView: React.FC<{ rows: DailyUsage[] | null; error?: string | null; onReload?: () => void; now?: Date }> = ({
- rows,
- error,
- onReload,
- now,
-}) => {
+/** Settings → Usage: the window's trend and spend per model, then fresh and cached tokens and cost per day and bot. */
+export const DailyUsageView: React.FC<{
+ rows: DailyUsage[] | null;
+ models?: ModelTotals[] | null;
+ range?: Range;
+ onRange?: (r: Range) => void;
+ engines?: EngineInfo[] | null;
+ error?: string | null;
+ onReload?: () => void;
+ now?: Date;
+}> = ({ rows, models, range = 7, onRange, engines, error, onReload, now }) => {
+ const head = (
+ <div className="flex flex-wrap items-center gap-2">
+ <h3 className="flex-1 text-[11px] font-semibold text-zinc-200">AI use</h3>
+ <RangeSwitch range={range} onRange={onRange} />
+ </div>
+ );
if (error)
return (
- <p role="alert" className="flex items-center gap-2 text-[11px] text-rose-300">
- <span className="flex-1">{error}</span>
- {onReload && (
- <button type="button" onClick={onReload} className="inline-flex items-center gap-1 text-zinc-300 hover:text-zinc-100 underline underline-offset-2">
- <RotateCcw size={11} aria-hidden="true" /> Retry
- </button>
- )}
- </p>
+ <div className="space-y-2" data-usage-history>
+ {head}
+ <p role="alert" className="flex items-center gap-2 text-[11px] text-rose-300">
+ <span className="flex-1">{error}</span>
+ {onReload && (
+ <button type="button" onClick={onReload} className="inline-flex items-center gap-1 text-zinc-300 hover:text-zinc-100 underline underline-offset-2">
+ <RotateCcw size={11} aria-hidden="true" /> Retry
+ </button>
+ )}
+ </p>
+ </div>
);
if (!rows)
return (
- <p className="flex items-center gap-2 text-[11px] text-zinc-500" role="status">
- <Loader2 size={12} className="animate-spin motion-reduce:animate-none" aria-hidden="true" /> Loading usage…
- </p>
+ <div className="space-y-2" data-usage-history>
+ {head}
+ <p className="flex items-center gap-2 text-[11px] text-zinc-500" role="status">
+ <Loader2 size={12} className="animate-spin motion-reduce:animate-none" aria-hidden="true" /> Loading usage…
+ </p>
+ </div>
+ );
+ if (!rows.length)
+ return (
+ <div className="space-y-2" data-usage-history>
+ {head}
+ <p className="text-[11px] text-zinc-500" data-usage-empty>
+ No AI use in the last {range} days.
+ </p>
+ </div>
);
- if (!rows.length) return <p className="text-[11px] text-zinc-500">No bot replies in the last two weeks.</p>;
+ const trend = trendDays(rows, range, now);
return (
- <div className="space-y-2">
- <p className="text-[11px] text-zinc-500">
- Fresh tokens · read from cache · cost where the engine reports it. Fresh is new input, cache writes and output: what makes a
- reply heavy.
- </p>
- <ul className="space-y-2" aria-label="Usage per day">
- {groupDays(rows).map((d) => (
- <li key={d.day} className="rounded-lg border border-zinc-800 bg-zinc-950/60">
- <div className="flex items-center gap-2 px-3 py-1.5 border-b border-zinc-800/80">
- <span className="flex-1 min-w-0 truncate text-[11px] font-medium text-zinc-200">{dayLabel(d.day, now)}</span>
- <Numbers fresh={d.fresh} cached={d.cached} cost={d.cost} strong />
- </div>
- <ul className="px-3 py-1">
- {d.bots.map((b) => (
- <li key={b.kwant_id} className="flex items-center gap-2 py-0.5">
- <span className="flex-1 min-w-0 truncate text-[11px] text-zinc-400">{b.kwant_name ?? 'Deleted bot'}</span>
- <Numbers fresh={freshOf(b)} cached={b.cache_read_tokens} cost={b.cost_usd ?? null} />
- </li>
- ))}
- </ul>
- </li>
- ))}
- </ul>
+ <div className="space-y-3" data-usage-history>
+ {head}
+ <div className="space-y-2">
+ <p className="text-[13px] text-zinc-100" data-usage-total>
+ <span className="font-medium tabular-nums">{metricText(trend.metric, trend.total)}</span>
+ <span className="text-zinc-400"> in the last {range} days</span>
+ </p>
+ <Trend key={`${range}-${trend.days[trend.days.length - 1].day}`} days={trend.days} metric={trend.metric} now={now} />
+ </div>
+ {models && <ByModel models={models} metric={trend.metric} engines={engines} />}
+ <div className="space-y-2">
+ <h4 className="text-[11px] font-medium text-zinc-400">By day</h4>
+ <p className="text-[11px] text-zinc-500">
+ Fresh tokens · read from cache · cost where the engine reports it. Fresh is new input, cache writes and output: what makes a
+ reply heavy.
+ </p>
+ <ul className="space-y-2" aria-label="Usage per day">
+ {groupDays(rows).map((d) => (
+ <li key={d.day} className="rounded-lg border border-zinc-800 bg-zinc-950/60">
+ <div className="flex items-center gap-2 px-3 py-1.5 border-b border-zinc-800/80">
+ <span className="flex-1 min-w-0 truncate text-[11px] font-medium text-zinc-200">{dayLabel(d.day, now)}</span>
+ <Numbers fresh={d.fresh} cached={d.cached} cost={d.cost} strong />
+ </div>
+ <ul className="px-3 py-1">
+ {d.bots.map((b) => (
+ <li key={b.kwant_id} className="flex items-center gap-2 py-0.5">
+ <span className="flex-1 min-w-0 truncate text-[11px] text-zinc-400">{b.kwant_name ?? 'Deleted bot'}</span>
+ <Numbers fresh={freshOf(b)} cached={b.cache_read_tokens} cost={b.cost_usd ?? null} />
+ </li>
+ ))}
+ </ul>
+ </li>
+ ))}
+ </ul>
+ </div>
</div>
);
};
-/** Loads the last two weeks while `open`. */
+/** Loads the last 7 or 30 days while `open`. */
export const DailyUsagePanel: React.FC<{ open: boolean }> = ({ open }) => {
+ const [range, setRange] = useState<Range>(7);
const [rows, setRows] = useState<DailyUsage[] | null>(null);
+ const [models, setModels] = useState<ModelTotals[] | null>(null);
const [error, setError] = useState<string | null>(null);
- const load = useCallback(() => {
+ const { engines } = useEngines(open);
+ const seq = useRef(0);
+ const load = useCallback((days: Range) => {
+ const n = ++seq.current;
setError(null);
setRows(null);
modelUsageApi
- .daily(14)
- .then((r) => setRows(r.rows))
- .catch((e) => setError(e instanceof Error ? e.message : 'Could not load usage.'));
+ .daily(days)
+ .then((r) => {
+ if (n !== seq.current) return;
+ setRows(r.rows);
+ setModels(r.models ?? null);
+ })
+ .catch((e) => n === seq.current && setError(e instanceof Error ? e.message : 'Could not load usage.'));
}, []);
useEffect(() => {
- if (open) load();
- }, [open, load]);
- return <DailyUsageView rows={rows} error={error} onReload={load} />;
+ if (open) load(range);
+ }, [open, range, load]);
+ return (
+ <DailyUsageView
+ rows={rows}
+ models={models}
+ range={range}
+ onRange={setRange}
+ engines={engines}
+ error={error}
+ onReload={() => load(range)}
+ />
+ );
};
diff --git a/frontend/src/engines.ts b/frontend/src/engines.ts
index 6e047ede..3b255ee1 100644
--- a/frontend/src/engines.ts
+++ b/frontend/src/engines.ts
@@ -305,6 +305,19 @@ export function ranOnLabel(meta: string | null | undefined, engines: EngineInfo[
}
}
+/** "Claude · Opus 5.5" for a model id from the usage log; the id as it is when no engine lists it. */
+export function usageModelLabel(model: string, engines: EngineInfo[] | null = null): string {
+ for (const e of engines ?? []) {
+ const m = e.models.find((x) => x.id === model);
+ if (!m) continue;
+ const name = familyLabel(FAMILY_OF[e.id] ?? 'custom').replace(/ \(.*\)$/, '');
+ return `${name} · ${shortModelLabel(m.label || m.id, name)}`;
+ }
+ // The CLI driver books "claude" when the turn reported no model.
+ const fam = FAMILIES.find((f) => f.id === model);
+ return fam ? fam.label.replace(/ \(.*\)$/, '') : model;
+}
+
/** "checked 3 min ago" style age, or null when never checked. */
export function checkedAgo(at: string | null, now = Date.now()): string | null {
if (!at) return null;
diff --git a/frontend/src/modelUsage.ts b/frontend/src/modelUsage.ts
index 75668a7f..b31b254d 100644
--- a/frontend/src/modelUsage.ts
+++ b/frontend/src/modelUsage.ts
@@ -74,10 +74,17 @@ export interface DailyUsage extends UsageSums {
kwant_name?: string | null;
}
+/** One model's totals over the same window (`model` is the id the call reported). */
+export interface ModelTotals extends UsageSums {
+ model: string;
+}
+
export interface DailyUsageResponse {
days: number;
/** Newest day first. */
rows: DailyUsage[];
+ /** Highest cost first; missing from servers before 0.9.9. */
+ models?: ModelTotals[];
}
/** Tokens the model had to take in or write new: everything but cache reads. */
diff --git a/frontend/tests/usageHistory.test.mjs b/frontend/tests/usageHistory.test.mjs
new file mode 100644
index 00000000..c6f24f96
--- /dev/null
+++ b/frontend/tests/usageHistory.test.mjs
@@ -0,0 +1,94 @@
+// Settings → Usage history (0.9.9): a 7/30-day trend with the window total, spend per model,
+// and the switch that loads the other window.
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { loadBundled } from './bundle.mjs';
+
+globalThis.localStorage ??= { getItem: () => null, setItem: () => {}, removeItem: () => {} };
+
+const m = await loadBundled(`
+ export { trendDays, modelShares, metricText } from './src/components/DailyUsage';
+ export { usageModelLabel } from './src/engines';
+ export { modelUsageApi } from './src/modelUsage';
+ import React from 'react';
+ import { renderToStaticMarkup } from 'react-dom/server.browser';
+ import { DailyUsageView } from './src/components/DailyUsage';
+ export const view = (props) => renderToStaticMarkup(React.createElement(DailyUsageView, props));
+`);
+
+const now = new Date('2026-11-13T15:00:00Z');
+const row = (day, kwant_id, o = {}) => ({
+ day, kwant_id, kwant_name: kwant_id.toUpperCase(), calls: 1, fresh_input_tokens: 0, cache_read_tokens: 0, cache_write_tokens: 0,
+ output_tokens: 0, tools_chars: 0, system_chars: 0, messages_chars: 0, cost_usd: null, ...o,
+});
+const model = (id, o = {}) => ({
+ model: id, calls: 1, fresh_input_tokens: 0, cache_read_tokens: 0, cache_write_tokens: 0, output_tokens: 0, tools_chars: 0,
+ system_chars: 0, messages_chars: 0, cost_usd: null, ...o,
+});
+const costRows = [
+ row('2026-11-13', 'a', { output_tokens: 1000, cost_usd: 1.5 }),
+ row('2026-11-13', 'b', { output_tokens: 9000 }),
+ row('2026-11-10', 'a', { output_tokens: 500, cost_usd: 0.25 }),
+];
+
+test('the trend has one day per slot, today last, empty days kept as gaps', () => {
+ const t = m.trendDays(costRows, 7, now);
+ assert.equal(t.metric, 'cost');
+ assert.deepEqual(t.days.map((d) => d.day), ['2026-11-07', '2026-11-08', '2026-11-09', '2026-11-10', '2026-11-11', '2026-11-12', '2026-11-13']);
+ assert.deepEqual(t.days.map((d) => d.value), [0, 0, 0, 0.25, 0, 0, 1.5]);
+ assert.deepEqual(t.days.map((d) => d.used), [false, false, false, true, false, false, true]);
+ assert.equal(t.total, 1.75);
+ assert.equal(m.trendDays(costRows, 30, now).days.length, 30);
+});
+
+test('without any reported cost the trend counts fresh tokens', () => {
+ const t = m.trendDays([row('2026-11-13', 'a', { fresh_input_tokens: 200_000, output_tokens: 1_000_000 })], 7, now);
+ assert.equal(t.metric, 'tokens');
+ assert.equal(m.metricText(t.metric, t.total), '1.2M tokens');
+});
+
+test('model shares follow the window metric, biggest first', () => {
+ const models = [model('gpt-5', { output_tokens: 9000 }), model('claude-opus-5-5', { output_tokens: 1500, cost_usd: 1.5 }), model('claude-haiku-5-5', { cost_usd: 0.5 })];
+ assert.deepEqual(m.modelShares(models, 'cost').map((r) => [r.model, r.share]), [['claude-opus-5-5', 75], ['claude-haiku-5-5', 25], ['gpt-5', 0]]);
+ assert.deepEqual(m.modelShares(models, 'tokens').map((r) => [r.model, r.share]), [['gpt-5', 86], ['claude-opus-5-5', 14], ['claude-haiku-5-5', 0]]);
+ assert.deepEqual(m.modelShares([], 'cost'), []);
+});
+
+test('model labels come from the engine list, else the id', () => {
+ const engines = [{ id: 'claude', models: [{ id: 'claude-opus-5-5', label: 'Claude Opus 5.5', default: true }] }, { id: 'openai_api', models: [{ id: 'gpt-5', label: 'GPT-5', default: true }] }];
+ assert.equal(m.usageModelLabel('claude-opus-5-5', engines), 'Claude · Opus 5.5');
+ assert.equal(m.usageModelLabel('gpt-5', engines), 'Codex · GPT-5');
+ assert.equal(m.usageModelLabel('claude', engines), 'Claude');
+ assert.equal(m.usageModelLabel('mystery-1', engines), 'mystery-1');
+ assert.equal(m.usageModelLabel('mystery-1'), 'mystery-1');
+});
+
+test('the panel shows the window total, a bar per day, models and the day list', () => {
+ const models = [model('claude-opus-5-5', { cost_usd: 1.75 }), model('gpt-5', { output_tokens: 9000 })];
+ const html = m.view({ rows: costRows, models, range: 7, onRange: () => {}, now });
+ assert.match(html, /\$1\.75<\/span><span[^>]*> in the last 7 days/);
+ assert.equal(html.match(/data-day="/g).length, 7);
+ assert.match(html, /aria-label="Today: \$1\.50"/);
+ assert.match(html, /aria-label="Wed 11 Nov: no AI use"/);
+ assert.match(html, /data-usage-readout="true"><\/span>/, "nothing named until a bar is hovered or focused");
+ // One tab stop for the bars: today's.
+ assert.equal(html.match(/<li tabindex="0"/g).length, 1);
+ assert.match(html, /aria-pressed="true"[^>]*data-usage-range="7"/);
+ assert.match(html, /By model.*claude-opus-5-5.*\$1\.75.*100%.*gpt-5.*No cost reported/s);
+ assert.doesNotMatch(html, /No cost reported<\/span>[^<]*·/, "no share after a model with no cost");
+ assert.match(html, /<span class="shrink-0 text-\[11px\] text-zinc-500">No cost reported<\/span><\/div>/, "plain words, no 0% share");
+ assert.match(html, /By day.*Today/s);
+ // An older server without `models`: no By model block, the rest works.
+ assert.doesNotMatch(m.view({ rows: costRows, now }), /By model/);
+});
+
+test('the switch asks the server for 7 or 30 days', async () => {
+ const seen = [];
+ globalThis.fetch = async (url) => {
+ seen.push(url);
+ return new Response(JSON.stringify({ days: 30, rows: [], models: [] }), { status: 200 });
+ };
+ await m.modelUsageApi.daily(7);
+ await m.modelUsageApi.daily(30);
+ assert.deepEqual(seen, ['/api/usage/daily?days=7', '/api/usage/daily?days=30']);
+});
diff --git a/frontend/tests/usageVisibility.test.mjs b/frontend/tests/usageVisibility.test.mjs
index 1e3ff4de..b06899a4 100644
--- a/frontend/tests/usageVisibility.test.mjs
+++ b/frontend/tests/usageVisibility.test.mjs
@@ -88,7 +88,8 @@ test('Settings → Usage groups days with fresh, cached and cost', () => {
test('Settings → Usage loading, empty and error states', () => {
assert.match(m.daily({ rows: null }), /Loading usage/);
- assert.match(m.daily({ rows: [] }), /No bot replies in the last two weeks/);
+ assert.match(m.daily({ rows: [] }), /No AI use in the last 7 days/);
+ assert.match(m.daily({ rows: [], range: 30 }), /No AI use in the last 30 days/);
assert.match(m.daily({ rows: null, error: 'Request failed (HTTP 500).', onReload: () => {} }), /role="alert".*HTTP 500.*Retry/s);
});
diff --git a/src/db/usage.rs b/src/db/usage.rs
index 41bf9bd0..0d40488e 100644
--- a/src/db/usage.rs
+++ b/src/db/usage.rs
@@ -94,6 +94,16 @@ pub struct DailyUsage {
pub totals: UsageTotals,
}
+/// One model's calls over a window, for Settings → Usage "By model".
+#[derive(Debug, Clone, Serialize, FromRow, PartialEq)]
+pub struct ModelTotals {
+ /// The model id the call reported, e.g. `claude-opus-5-5`.
+ pub model: String,
+ #[sqlx(flatten)]
+ #[serde(flatten)]
+ pub totals: UsageTotals,
+}
+
impl Database {
pub(super) async fn migrate_usage(&self) -> Result<(), DbError> {
for stmt in [
@@ -192,6 +202,17 @@ impl Database {
.fetch_all(&self.pool)
.await?)
}
+
+ /// Every bot's totals per model since `since`: highest cost first, then most fresh tokens.
+ pub async fn usage_by_model(&self, since: DateTime<Utc>) -> Result<Vec<ModelTotals>, DbError> {
+ Ok(sqlx::query_as(&format!(
+ "SELECT model, {SUMS} FROM model_usage WHERE created_at >= ? GROUP BY model \
+ ORDER BY COALESCE(SUM(cost_usd), -1) DESC, SUM(fresh_input) + SUM(cache_write) + SUM(output) DESC, model"
+ ))
+ .bind(since)
+ .fetch_all(&self.pool)
+ .await?)
+ }
}
#[cfg(test)]
@@ -237,4 +258,49 @@ mod tests {
assert_eq!(db.usage_totals("k1", Some(later)).await.unwrap().0, UsageTotals::default());
assert_eq!(db.usage_totals("nobody", None).await.unwrap().0.calls, 0);
}
+
+ #[tokio::test]
+ async fn usage_is_summed_per_model_over_the_window() {
+ let tmp = tempfile::tempdir().unwrap();
+ let db = Database::init(tmp.path()).await.unwrap();
+ let call = |model: &str, output, cost_usd| NewUsage {
+ kwant_id: "k1".into(),
+ context_id: "c".into(),
+ purpose: PURPOSE_REPLY,
+ model: model.into(),
+ fresh_input: 10,
+ output,
+ reported: true,
+ cost_usd,
+ ..Default::default()
+ };
+ db.record_usage(&call("gpt-5", 5000, None)).await.unwrap();
+ db.record_usage(&call("claude-opus-5-5", 100, Some(0.25))).await.unwrap();
+ db.record_usage(&call("claude-opus-5-5", 200, Some(0.5))).await.unwrap();
+ db.record_usage(&call("claude-haiku-5-5", 50, Some(0.01))).await.unwrap();
+ // Two days back: inside a 7-day window, outside one that starts today.
+ sqlx::query("UPDATE model_usage SET created_at = ? WHERE model = 'claude-haiku-5-5'")
+ .bind(Utc::now() - chrono::Duration::days(2))
+ .execute(&db.pool)
+ .await
+ .unwrap();
+
+ let week = db.usage_by_model(Utc::now() - chrono::Duration::days(7)).await.unwrap();
+ let got: Vec<_> = week.iter().map(|m| (m.model.as_str(), m.totals.calls, m.totals.output_tokens, m.totals.cost_usd)).collect();
+ assert_eq!(
+ got,
+ vec![
+ ("claude-opus-5-5", 2, 300, Some(0.75)),
+ ("claude-haiku-5-5", 1, 50, Some(0.01)),
+ ("gpt-5", 1, 5000, None),
+ ],
+ "highest cost first, models without a cost last"
+ );
+
+ let today = db.usage_by_model(Utc::now() - chrono::Duration::hours(1)).await.unwrap();
+ assert_eq!(today.iter().map(|m| m.model.as_str()).collect::<Vec<_>>(), vec!["claude-opus-5-5", "gpt-5"]);
+ // The per-day rows still cover both days.
+ assert_eq!(db.daily_usage(Utc::now() - chrono::Duration::days(7)).await.unwrap().len(), 2);
+ assert!(db.usage_by_model(Utc::now() + chrono::Duration::minutes(1)).await.unwrap().is_empty());
+ }
}
diff --git a/src/server/model_usage.rs b/src/server/model_usage.rs
index 4a1c902d..5c6cfa95 100644
--- a/src/server/model_usage.rs
+++ b/src/server/model_usage.rs
@@ -53,13 +53,14 @@ pub struct DailyQuery {
pub days: Option<i64>,
}
-/// `GET /api/usage/daily`: every bot's tokens and cost per UTC day, newest first, for
-/// Settings → Usage. Covers CLI and API-key bots alike.
+/// `GET /api/usage/daily`: every bot's tokens and cost per UTC day, newest first, and the same
+/// window's totals per model (`models`), for Settings → Usage. Covers CLI and API-key bots alike.
pub async fn get_daily(State(state): State<AppState>, Query(q): Query<DailyQuery>) -> Response {
let days = q.days.unwrap_or(14).clamp(1, 90);
let since = (Utc::now() - chrono::Duration::days(days - 1)).date_naive().and_hms_opt(0, 0, 0).map(|t| t.and_utc());
- match state.db.daily_usage(since.unwrap_or(DateTime::<Utc>::MIN_UTC)).await {
- Ok(rows) => Json(json!({ "days": days, "rows": rows })).into_response(),
- Err(_) => StatusCode::INTERNAL_SERVER_ERROR.into_response(),
+ let since = since.unwrap_or(DateTime::<Utc>::MIN_UTC);
+ match tokio::join!(state.db.daily_usage(since), state.db.usage_by_model(since)) {
+ (Ok(rows), Ok(models)) => Json(json!({ "days": days, "rows": rows, "models": models })).into_response(),
+ _ => StatusCode::INTERNAL_SERVER_ERROR.into_response(),
}
}