feat(webui): show the full token-usage picture in settings (#6638)

This commit is contained in:
chengyongru authored and GitHub committed 2026-11-12 18:13:06 +08:00
1 parent b49218b6a3
commit e6b23c7356
42 files changed
+1116 -342

No files matched your search

+10 -3
View File
@@ -942,6 +942,9 @@ function Shell({
const { skills, loading: skillsLoading, error: skillsError } = useSkills(getToken);
const [settingsSnapshot, setSettingsSnapshot] = useState<SettingsPayload | null>(null);
const [settingsLoading, setSettingsLoading] = useState(true);
const settingsSnapshotRef = useRef(settingsSnapshot);
settingsSnapshotRef.current = settingsSnapshot;
const settingsOwnsSnapshot = view !== "chat" && view !== "remote";
const settingsRefreshGenerationRef = useRef(0);
const [pendingAutomationMessage, setPendingAutomationMessage] = useState<{
id: string;
@@ -1082,10 +1085,14 @@ function Shell({
}, [client]);
useEffect(() => {
if (settingsOwnsSnapshot || settingsSnapshotRef.current !== null) {
setSettingsLoading(false);
return;
}
let cancelled = false;
const requestGeneration = settingsRefreshGenerationRef.current;
setSettingsLoading(true);
fetchSettings(getToken())
fetchSettings(getToken(), "", client)
.then((payload) => {
if (!cancelled && requestGeneration === settingsRefreshGenerationRef.current) {
setSettingsSnapshot(payload);
@@ -1102,7 +1109,7 @@ function Shell({
return () => {
cancelled = true;
};
}, [getToken]);
}, [client, getToken, settingsOwnsSnapshot]);
useEffect(() => {
try {
@@ -1925,7 +1932,7 @@ function Shell({
let cancelled = false;
let retryTimer: number | undefined;
const refreshSettings = (generation: number, attempt = 0): void => {
void fetchSettings(getToken())
void fetchSettings(getToken(), "", client)
.then((payload) => {
if (!cancelled && generation === settingsRefreshGenerationRef.current) {
setSettingsSnapshot(payload);
@@ -25,6 +25,7 @@ import {
} from "@/components/settings/models/ProviderSettings";
import { providerFormFromRow } from "@/components/settings/models/providerForm";
import { AboutSettings, AppearanceSettings, OverviewSettings } from "@/components/settings/overview/OverviewSettings";
import { TokenUsageOverview } from "@/components/settings/TokenUsageOverview";
import { NotificationSettings } from "@/components/settings/notifications/NotificationSettings";
import { SettingsSidebar, standaloneSectionTitle } from "@/components/settings/SettingsSidebar";
import {
@@ -270,6 +271,7 @@ export function SettingsPage({
settings={settings}
showBrandLogos={localPrefs.brandLogos}
onSelectSection={selectSection}
usageCard={<TokenUsageOverview initialUsage={settings.usage} timeZone={settings.agent.timezone} />}
/>
);
case "about":
@@ -2,27 +2,33 @@ import { useTranslation } from "react-i18next";
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";
import type { SettingsPayload } from "@/lib/types";
import { usageFormats } from "@/lib/usage-number";
import { cn } from "@/lib/utils";
import { TokenUsageDetails } from "@/components/settings/TokenUsageDetails";
import { UsageAxis, UsageDateAxis, usageAxisTicks, usagePeakCenter } from "@/components/settings/usage-chart";
import { SettingsHint } from "@/components/settings/shared/SettingsHint";
type Usage = NonNullable<SettingsPayload["usage"]>;
const SOURCE_KEYS = ["user", "api", "cron", "dream", "system"] as const;
const SEGMENT_CLASSES = [
"bg-orange-100 text-orange-500 dark:bg-orange-400/15 dark:text-orange-400",
"bg-neutral-300 dark:bg-neutral-500",
"bg-orange-300 dark:bg-orange-400/40",
"bg-neutral-400 dark:bg-neutral-500",
"bg-neutral-200 dark:bg-neutral-700",
"bg-orange-500 dark:bg-orange-400",
"bg-neutral-700 dark:bg-neutral-200",
"bg-neutral-500 dark:bg-neutral-300",
];
const CACHE_PATTERN = { backgroundImage: "repeating-linear-gradient(135deg, transparent, transparent 3px, currentColor 3px, currentColor 4px)" };
function tokenSegments(day?: Usage["days"][number]): number[] {
if (!day) return [0, 0, 0, 0, 0];
if (!day) return [0, 0, 0, 0, 0, 0];
const observed = day.cache_read_observed_input_tokens;
return [day.cache_read_tokens, observed - day.cache_read_tokens,
day.input_tokens - observed,
day.output_tokens, Math.max(0, day.total_tokens - day.input_tokens - day.output_tokens)];
// Older backends cannot locate writes within the read-observed and unknown pools.
const input = day.cache_miss_tokens !== undefined && day.cache_unknown_tokens !== undefined
? [day.cache_read_tokens, day.cache_write_tokens, day.cache_miss_tokens, day.cache_unknown_tokens]
: [day.cache_read_tokens, 0, observed - day.cache_read_tokens, day.input_tokens - observed];
return [...input, day.output_tokens,
Math.max(0, day.total_tokens - day.input_tokens - day.output_tokens)];
}
function todayInTimeZone(timeZone?: string): string {
@@ -42,7 +48,12 @@ function todayInTimeZone(timeZone?: string): string {
return now.toISOString().slice(0, 10);
}
export function TokenUsageCard({ usage, timeZone }: { usage?: Usage; timeZone?: string }) {
export function TokenUsageCard({ usage, timeZone, onDetailsOpenChange, detailsLoading }: {
usage?: Usage;
timeZone?: string;
detailsLoading?: boolean;
onDetailsOpenChange?: (open: boolean) => void;
}) {
const { t, i18n } = useTranslation();
const today = todayInTimeZone(timeZone);
const byDate = new Map(usage?.days.map(day => [day.date, day]));
@@ -53,20 +64,29 @@ export function TokenUsageCard({ usage, timeZone }: { usage?: Usage; timeZone?:
return { date: key, usage: byDate.get(key) };
});
const total = days.reduce((sum, day) => sum + (day.usage?.total_tokens ?? 0), 0);
const peak = Math.max(0, ...days.map(day => day.usage?.total_tokens ?? 0));
const compact = new Intl.NumberFormat(i18n.language, { notation: "compact", maximumFractionDigits: 1 });
const exact = new Intl.NumberFormat(i18n.language);
const percent = new Intl.NumberFormat(i18n.language, { style: "percent", maximumFractionDigits: 1 });
const dateFormat = new Intl.DateTimeFormat(i18n.language, { month: "short", day: "numeric", timeZone: "UTC" });
const formatDate = (date: string) => dateFormat.format(new Date(`${date}T00:00:00Z`));
const values = days.map(day => day.usage?.total_tokens ?? 0);
const average = total / values.length;
const peak = Math.max(0, ...values);
const peakDay = days.reduce<(typeof days)[number] | undefined>(
(best, day) => ((day.usage?.total_tokens ?? 0) > (best?.usage?.total_tokens ?? 0) ? day : best),
undefined,
);
const peakIndex = peak > 0 ? values.indexOf(peak) : -1;
const peakCenter = usagePeakCenter(values.length, peakIndex);
const ticks = usageAxisTicks(peak, average);
const { display, exact, compact, percent, date: formatDate } = usageFormats(i18n.language);
const segmentLabels = [
t("settings.usage.cachedInput", { defaultValue: "Cached input" }),
t("settings.usage.cacheWrite", { defaultValue: "Cache write" }),
t("settings.usage.cacheMiss", { defaultValue: "Cache miss" }),
t("settings.usage.cacheUnknown", { defaultValue: "Cache status unknown" }),
t("settings.usage.outputTokens", { defaultValue: "Output" }),
t("settings.usage.otherTokens", { defaultValue: "Other tokens" }),
];
const hasOtherTokens = days.some(day => tokenSegments(day.usage)[4] > 0);
const segmentTotals = days.reduce<number[]>(
(sums, day) => tokenSegments(day.usage).map((value, index) => sums[index] + value),
[0, 0, 0, 0, 0, 0],
);
const sourceLabels: Record<string, string> = {
user: t("settings.usage.sources.user", { defaultValue: "Chat" }),
api: t("settings.usage.sources.api", { defaultValue: "API" }),
@@ -92,12 +112,15 @@ export function TokenUsageCard({ usage, timeZone }: { usage?: Usage; timeZone?:
<div className="min-w-0 space-y-5">
<div className="flex items-start justify-between gap-4">
<div>
<h3 className="text-sm font-medium">{t("settings.usage.shortTitle", { defaultValue: "Token usage" })}</h3>
<p className="mt-2 text-3xl font-semibold tracking-tight tabular-nums" aria-label={usage ? `${exact.format(total)} tokens` : undefined}>
{usage ? compact.format(total) : "—"}
<h3 className="flex items-baseline gap-2 text-sm font-medium">
{t("settings.usage.shortTitle", { defaultValue: "Token usage" })}
{usage && <span className="text-[11px] font-normal leading-none text-muted-foreground">{t("settings.usage.last30Days", { defaultValue: "Last 30 days" })}</span>}
</h3>
<p className="mt-2 text-3xl font-semibold tracking-tight tabular-nums" aria-label={usage ? `${exact(total)} tokens in the last 30 days` : undefined}>
{usage ? compact(total) : "—"}
</p>
</div>
{usage && <TokenUsageDetails days={days} models={usage.providers_30d} modelDays={usage.model_days_30d} />}
{usage && <TokenUsageDetails days={days} models={usage.providers_30d} modelDays={usage.model_days_30d} onOpenChange={onDetailsOpenChange} loading={detailsLoading} />}
</div>
{!usage || total === 0 ? (
@@ -109,61 +132,63 @@ export function TokenUsageCard({ usage, timeZone }: { usage?: Usage; timeZone?:
) : (
<>
<div>
<div className="mb-2 text-right text-[11px] tabular-nums text-muted-foreground" aria-hidden>{compact.format(peak)}</div>
<div className="relative">
<div className="pointer-events-none absolute inset-0 flex flex-col justify-between" aria-hidden>
{[0, 1, 2].map(line => <div key={line} className="border-t border-border/40" />)}
</div>
<div className="relative grid h-28 grid-cols-[repeat(30,minmax(0,1fr))] gap-1" role="group" aria-label={t("settings.usage.dailyTrend", { defaultValue: "Daily token usage" })}>
<TooltipProvider>
{days.map(day => {
const tokens = day.usage?.total_tokens ?? 0;
const segments = tokenSegments(day.usage);
const label = t("settings.usage.cellTitle", {
defaultValue: "{{date}}: {{tokens}} tokens, {{requests}} requests",
date: day.date, tokens: exact.format(tokens), requests: day.usage?.requests ?? 0,
});
if (tokens === 0) return <span key={day.date} role="img" aria-label={label} />;
return (
<Tooltip key={day.date}>
<TooltipTrigger asChild>
<span tabIndex={0} role="img" aria-label={`${label}; ${segments.map((value, index) => `${segmentLabels[index]}: ${exact.format(value)}`).join(", ")}`} className="group flex h-full min-w-0 items-end rounded-sm focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-orange-600 dark:focus-visible:outline-orange-400">
<span className="flex w-full flex-col-reverse overflow-hidden rounded-t-sm group-hover:brightness-95" style={{ height: `${tokens / peak * 100}%` }}>
{segments.map((value, index) => value > 0 && <span key={index} className={cn("w-full shrink-0", SEGMENT_CLASSES[index])} style={{ height: `${value / tokens * 100}%`, ...(index === 0 ? CACHE_PATTERN : {}) }} />)}
</span>
</span>
</TooltipTrigger>
<TooltipContent className="min-w-56 p-3">
<div className="mb-2 flex justify-between gap-6 font-medium tabular-nums"><span>{day.date}</span><span>{exact.format(tokens)}</span></div>
<dl className="space-y-1.5">
{segments.map((value, index) => (index < 4 || value > 0) && <div key={index} className="flex items-center justify-between gap-6">
<dt className="flex items-center text-muted-foreground"><span aria-hidden className={cn("size-2.5 rounded-sm", SEGMENT_CLASSES[index])} style={index === 0 ? CACHE_PATTERN : undefined} /><span className="sr-only">{segmentLabels[index]}</span></dt>
<dd className="tabular-nums">{exact.format(value)}</dd>
</div>)}
<div className="flex justify-between gap-6 border-t border-border/50 pt-2">
<dt className="text-muted-foreground">{t("settings.usage.cacheHitRate", { defaultValue: "Cache hit rate" })}</dt>
<dd className="tabular-nums">{day.usage?.cache_read_observed_input_tokens ? percent.format(day.usage.cache_read_tokens / day.usage.cache_read_observed_input_tokens) : "—"}</dd>
</div>
</dl>
</TooltipContent>
</Tooltip>
);
})}
</TooltipProvider>
</div>
</div>
<div className="mt-2 flex justify-between text-[11px] text-muted-foreground" aria-hidden>
<span>{formatDate(days[0].date)}</span>
<span>{formatDate(days[14].date)}</span>
<span>{formatDate(today)}</span>
<div className="relative pl-11">
<div className="relative h-28">
<UsageAxis ticks={ticks} format={compact} gridlineAttribute="data-usage-gridline" />
<div className="relative grid h-full grid-cols-[repeat(30,minmax(0,1fr))]" role="group" aria-label={t("settings.usage.dailyTrend", { defaultValue: "Daily token usage" })}>
<TooltipProvider delayDuration={0} disableHoverableContent>
{days.map(day => {
const tokens = day.usage?.total_tokens ?? 0;
const segments = tokenSegments(day.usage);
const label = t("settings.usage.cellTitle", {
defaultValue: "{{date}}: {{tokens}} tokens, {{requests}} requests",
date: day.date, tokens: exact(tokens), requests: day.usage?.requests ?? 0,
});
if (tokens === 0) return <span key={day.date} role="img" aria-label={label} />;
return (
<Tooltip key={day.date}>
<TooltipTrigger asChild>
<span tabIndex={0} role="img" aria-label={`${label}; ${segments.map((value, index) => `${segmentLabels[index]}: ${exact(value)}`).join(", ")}`} className="group flex h-full min-w-0 items-end pr-1 rounded-sm focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-orange-600 dark:focus-visible:outline-orange-400">
<span className="flex w-full flex-col-reverse overflow-hidden rounded-t-sm group-hover:brightness-95" style={{ height: `${tokens / peak * 100}%` }}>
{segments.map((value, index) => value > 0 && <span key={index} className={cn("w-full shrink-0", SEGMENT_CLASSES[index])} style={{ height: `${value / tokens * 100}%`, ...(index === 0 ? CACHE_PATTERN : {}) }} />)}
</span>
</span>
</TooltipTrigger>
<TooltipContent className="min-w-56 p-3">
<div className="mb-2 flex justify-between gap-6 font-medium tabular-nums"><span>{day.date}</span><span title={exact(tokens)}>{display(tokens)}</span></div>
<dl className="space-y-1.5">
{segments.map((value, index) => (index < 5 || value > 0) && <div key={index} className="flex items-center justify-between gap-6">
<dt className="flex items-center gap-2 text-muted-foreground"><span aria-hidden className={cn("size-2.5 shrink-0 rounded-sm", SEGMENT_CLASSES[index])} style={index === 0 ? CACHE_PATTERN : undefined} /><span>{segmentLabels[index]}</span></dt>
<dd className="tabular-nums" title={exact(value)}>{display(value)}</dd>
</div>)}
<div className="flex justify-between gap-6 border-t border-border/50 pt-2">
<dt className="text-muted-foreground">{t("settings.usage.cacheHitRate", { defaultValue: "Cache hit rate" })}</dt>
<dd className="tabular-nums">{day.usage?.cache_read_observed_input_tokens ? percent(day.usage.cache_read_tokens / day.usage.cache_read_observed_input_tokens) : "—"}</dd>
</div>
<div className="flex justify-between gap-6">
<dt className="text-muted-foreground">{t("settings.usage.requests", { defaultValue: "Requests" })}</dt>
<dd className="tabular-nums">
{display(day.usage?.requests ?? 0)}
{(day.usage?.failed_requests ?? 0) > 0 && <span className="text-muted-foreground"> ({t("settings.usage.failedRequests", { defaultValue: "{{count}} failed", count: display(day.usage?.failed_requests ?? 0) })})</span>}
</dd>
</div>
</dl>
</TooltipContent>
</Tooltip>
);
})}
</TooltipProvider>
</div>
</div>
<UsageDateAxis start={days[0].date} end={today} peak={peakDay?.date ?? days[0].date} peakCenter={peakCenter} format={formatDate} />
</div>
<div className="mt-3 flex flex-wrap gap-x-4 gap-y-2 text-[11px] text-muted-foreground">
{segmentLabels.map((label, index) => (index < 4 || hasOtherTokens) && <span key={label} className="flex items-center gap-1.5"><span aria-hidden className={cn("size-2.5 rounded-sm", SEGMENT_CLASSES[index])} style={index === 0 ? CACHE_PATTERN : undefined} />{label}</span>)}
{segmentLabels.map((label, index) => segmentTotals[index] > 0 && <span key={label} className="flex items-center gap-1.5"><span aria-hidden className={cn("size-2.5 rounded-sm", SEGMENT_CLASSES[index])} style={index === 0 ? CACHE_PATTERN : undefined} />{label}</span>)}
</div>
</div>
<dl className="grid grid-cols-1 gap-x-6 gap-y-2 text-xs sm:grid-cols-3" aria-label={t("settings.usage.bySource", { defaultValue: "Usage by source" })}>
<dl className="flex flex-wrap gap-x-8 gap-y-2 text-xs" aria-label={t("settings.usage.bySource", { defaultValue: "Usage by source" })}>
{breakdown.map(([source, tokens]) => (
<div key={source} className="flex min-w-0 items-center justify-between gap-2">
<div key={source} className="flex min-w-0 items-baseline gap-2">
<dt className="min-w-0 break-words text-muted-foreground">
{source === "system" ? (
<SettingsHint description={t("settings.usage.systemHelp", {
@@ -171,7 +196,7 @@ export function TokenUsageCard({ usage, timeZone }: { usage?: Usage; timeZone?:
})}>{sourceLabels[source]}</SettingsHint>
) : sourceLabels[source]}
</dt>
<dd className="shrink-0 tabular-nums" title={`${exact.format(tokens)} tokens`}>{new Intl.NumberFormat(i18n.language, { style: "percent", maximumFractionDigits: 1 }).format(tokens / total)}</dd>
<dd className="shrink-0 tabular-nums" title={`${exact(tokens)} tokens`}>{tokens / total < 0.001 ? `<${percent(0.001)}` : percent(tokens / total)}</dd>
</div>
))}
</dl>
@@ -2,44 +2,48 @@ import { ChevronRight } from "lucide-react";
import { useTranslation } from "react-i18next";
import { Dialog, DialogContent, DialogLayoutContext, DialogTitle, DialogTrigger } from "@/components/ui/dialog";
import type { SettingsPayload } from "@/lib/types";
import { usageFormats } from "@/lib/usage-number";
import { TokenUsageModelTrend } from "@/components/settings/TokenUsageModelTrend";
type Usage = NonNullable<SettingsPayload["usage"]>;
type DayTotal = NonNullable<Usage["days"][number]>;
export function TokenUsageDetails({ days, models, modelDays }: {
days: { date: string; usage?: Usage["days"][number] }[];
export function TokenUsageDetails({ days, models, modelDays, onOpenChange, loading }: {
days: { date: string; usage?: DayTotal }[];
models?: Usage["providers_30d"];
modelDays?: Usage["model_days_30d"];
onOpenChange?: (open: boolean) => void;
loading?: boolean;
}) {
const { t, i18n } = useTranslation();
const number = new Intl.NumberFormat(i18n.language, { maximumFractionDigits: 0 });
const percent = new Intl.NumberFormat(i18n.language, { style: "percent", maximumFractionDigits: 1 });
const sum = (key: "total_tokens" | "requests" | "cache_read_tokens" | "cache_read_observed_input_tokens") =>
const percent = usageFormats(i18n.language).percent;
const sum = (key: "total_tokens" | "estimated_tokens") =>
days.reduce((total, day) => total + (day.usage?.[key] ?? 0), 0);
const total = sum("total_tokens");
const observed = sum("cache_read_observed_input_tokens");
const metrics = [
[t("settings.usage.totalTokens"), number.format(total)],
[t("settings.usage.requests"), number.format(sum("requests"))],
[t("settings.usage.cacheHitRate"), observed ? percent.format(sum("cache_read_tokens") / observed) : "—"],
];
const estimated = sum("estimated_tokens");
return (
<DialogLayoutContext.Provider value={null}>
<Dialog>
<Dialog onOpenChange={onOpenChange}>
<DialogTrigger asChild>
<button type="button" className="settings-hover flex shrink-0 items-center gap-1 rounded-full px-2 py-1 text-xs text-muted-foreground focus-visible:outline focus-visible:outline-2 focus-visible:outline-ring">
<button type="button" className="settings-hover flex shrink-0 items-center gap-1 rounded-full px-2 py-1 text-xs text-muted-foreground focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring">
{t("settings.usage.viewDetails")}<ChevronRight className="size-3.5" aria-hidden />
</button>
</DialogTrigger>
<DialogContent className="w-[min(1100px,calc(100vw-32px))] max-w-none gap-5 p-5 pt-10 sm:p-7 sm:pt-10" aria-describedby={undefined}>
<DialogTitle className="sr-only">{t("settings.usage.shortTitle")}</DialogTitle>
<dl className="grid grid-cols-3 gap-3">
{metrics.map(([label, value], index) => <div key={label} title={index === 2 ? t("settings.usage.cacheRateHelp") : undefined}>
<dt className="text-xs text-muted-foreground">{label}</dt>
<dd className="mt-1 text-lg font-medium tabular-nums sm:text-2xl">{value}</dd>
</div>)}
</dl>
{modelDays?.length ? <TokenUsageModelTrend days={days} modelDays={modelDays} models={models} /> : <p className="text-sm text-muted-foreground">{t("settings.usage.modelsUnavailable")}</p>}
<div className="flex items-baseline justify-between gap-4 pr-8">
<DialogTitle className="text-sm font-medium">{t("settings.usage.shortTitle")}</DialogTitle>
<span className="text-[11px] text-muted-foreground">{t("settings.usage.last30Days", { defaultValue: "Last 30 days" })}</span>
</div>
{estimated > 0 && total > 0 && (
<p className="text-[11px] text-muted-foreground">
{t("settings.usage.estimatedShare", {
defaultValue: "{{percent}} of tokens are estimated",
percent: percent(estimated / total),
})}
</p>
)}
{modelDays?.length ? <TokenUsageModelTrend days={days} modelDays={modelDays} models={models} /> : <p className="text-sm text-muted-foreground">{t(loading ? "common.loading" : "settings.usage.modelsUnavailable")}</p>}
</DialogContent>
</Dialog>
</DialogLayoutContext.Provider>
@@ -1,10 +1,14 @@
import { Fragment } from "react";
import { useTranslation } from "react-i18next";
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";
import type { SettingsPayload } from "@/lib/types";
import { usageFormats, usageSpeed } from "@/lib/usage-number";
import { normalizeUsageModel } from "@/lib/usage-model";
import { cn } from "@/lib/utils";
import { UsageAxis, UsageDateAxis, usageAxisTicks, usagePeakCenter } from "@/components/settings/usage-chart";
type Usage = NonNullable<SettingsPayload["usage"]>;
const COLORS = ["bg-orange-500", "bg-amber-500", "bg-stone-500", "bg-orange-300", "bg-zinc-400", "bg-neutral-200 dark:bg-neutral-600"];
const COLORS = ["bg-orange-600 dark:bg-orange-500", "bg-amber-300 dark:bg-amber-300", "bg-stone-700 dark:bg-stone-300", "bg-orange-300 dark:bg-orange-200", "bg-zinc-500 dark:bg-neutral-500", "bg-neutral-400 dark:bg-neutral-600"];
export function TokenUsageModelTrend({ days, modelDays, models }: {
days: { date: string; usage?: Usage["days"][number] }[];
@@ -12,31 +16,57 @@ export function TokenUsageModelTrend({ days, modelDays, models }: {
models?: Usage["providers_30d"];
}) {
const { t, i18n } = useTranslation();
const number = new Intl.NumberFormat(i18n.language);
const percent = new Intl.NumberFormat(i18n.language, { style: "percent", maximumFractionDigits: 1 });
const { display, exact, compact, percent, seconds, date: formatDay } = usageFormats(i18n.language);
const total = days.reduce((sum, day) => sum + (day.usage?.total_tokens ?? 0), 0);
const modelUsage = new Map((models ?? []).map(model => [JSON.stringify([model.provider, model.model]), model]));
const compact = new Intl.NumberFormat(i18n.language, { notation: "compact", maximumFractionDigits: 1 });
// Group by provider and normalized model, so one model is never split across
// `openai-codex/…` and bare ids.
const modelKey = (provider: string, model: string) => JSON.stringify([provider, normalizeUsageModel(provider, model)]);
const modelUsage = new Map<string, { cache_read_tokens: number; cache_read_observed_input_tokens: number }>();
for (const model of models ?? []) {
const key = modelKey(model.provider, model.model);
const entry = modelUsage.get(key) ?? { cache_read_tokens: 0, cache_read_observed_input_tokens: 0 };
entry.cache_read_tokens += model.cache_read_tokens ?? 0;
entry.cache_read_observed_input_tokens += model.cache_read_observed_input_tokens ?? 0;
modelUsage.set(key, entry);
}
const dates = new Set(days.map(day => day.date));
const totals = new Map<string, { label: string; total: number }>();
const daily = new Map<string, Map<string, number>>();
const daily = new Map<string, Map<string, { tokens: number; measured: number; generationMs: number; ttftMs: number; timed: number; cacheRead: number; cacheObserved: number }>>();
for (const row of modelDays) {
if (!dates.has(row.date) || row.total_tokens <= 0) continue;
const key = JSON.stringify([row.provider, row.model]);
const item = totals.get(key) ?? { label: row.model, total: 0 };
const label = normalizeUsageModel(row.provider, row.model);
const key = JSON.stringify([row.provider, label]);
const item = totals.get(key) ?? { label, total: 0 };
item.total += row.total_tokens;
totals.set(key, item);
const bucket = daily.get(row.date) ?? new Map<string, number>();
bucket.set(key, (bucket.get(key) ?? 0) + row.total_tokens);
type Bucket = { tokens: number; measured: number; generationMs: number; ttftMs: number; timed: number; cacheRead: number; cacheObserved: number };
const bucket = daily.get(row.date) ?? new Map<string, Bucket>();
const entry = bucket.get(key) ?? { tokens: 0, measured: 0, generationMs: 0, ttftMs: 0, timed: 0, cacheRead: 0, cacheObserved: 0 };
entry.tokens += row.total_tokens;
entry.measured += row.measured_output_tokens ?? 0;
entry.generationMs += row.generation_ms ?? 0;
entry.ttftMs += row.ttft_ms ?? 0;
entry.timed += row.timed_requests ?? 0;
entry.cacheRead += row.cache_read_tokens ?? 0;
entry.cacheObserved += row.cache_read_observed_input_tokens ?? 0;
bucket.set(key, entry);
daily.set(row.date, bucket);
}
const series = [...totals].sort((a, b) => b[1].total - a[1].total).slice(0, 5);
const otherLabel = t("settings.usage.otherModels", { defaultValue: "Other / unattributed" });
const columns = days.map(day => {
const bucket = daily.get(day.date);
const values = series.map(([key]) => bucket?.get(key) ?? 0);
const values = series.map(([key]) => bucket?.get(key)?.tokens ?? 0);
const stats = series.map(([key]) => {
const entry = bucket?.get(key);
return {
speed: entry ? usageSpeed(entry.measured, entry.generationMs) : null,
ttft: entry && entry.timed > 0 ? entry.ttftMs / entry.timed : null,
hit: entry && entry.cacheObserved > 0 ? entry.cacheRead / entry.cacheObserved : null,
};
});
const total = day.usage?.total_tokens ?? 0;
return { date: day.date, total, requests: day.usage?.requests ?? 0, values: [...values, Math.max(0, total - values.reduce((a, b) => a + b, 0))] };
return { date: day.date, total, requests: day.usage?.requests ?? 0, values: [...values, Math.max(0, total - values.reduce((a, b) => a + b, 0))], stats: [...stats, { speed: null, ttft: null, hit: null }] };
});
const peak = Math.max(0, ...columns.map(column => column.total));
if (!peak || !series.length) return null;
@@ -44,53 +74,70 @@ export function TokenUsageModelTrend({ days, modelDays, models }: {
const color = (index: number) => index === series.length ? COLORS[5] : COLORS[index];
const hasOther = columns.some(column => column.values[series.length] > 0);
const title = t("settings.usage.modelTrend", { defaultValue: "Model usage over time" });
const average = total / columns.length;
const peakIndex = columns.findIndex(column => column.total === peak);
const peakCenter = usagePeakCenter(columns.length, peakIndex);
const ticks = usageAxisTicks(peak, average);
// Missing telemetry reads as `—`; 0 tok/s would look like a stall. Value and
// unit stay in separate columns so both line up down the tooltip.
const speed = (value: number | null): [string, string] =>
value == null ? ["—", ""] : [display(Math.round(value)), "tok/s"];
const firstToken = (value: number | null): [string, string] =>
value == null ? ["—", ""] : [seconds(value), "s"];
const spoken = (stats: { speed: number | null; ttft: number | null; hit: number | null }) =>
`${stats.speed == null ? "" : `, ${Math.round(stats.speed)} tok/s`}${stats.ttft == null ? "" : `, ${seconds(stats.ttft)}s to first token`}${stats.hit == null ? "" : `, ${percent(stats.hit)} cache hit`}`;
return <section className="mt-2">
<h3 className="mb-4 text-sm font-medium">{title}</h3>
<div className="relative pl-9">
<div className="relative pl-11">
<div className="relative h-[clamp(144px,30vh,280px)]" data-model-usage-plot>
<div className="pointer-events-none absolute inset-y-0 -left-9 right-0" aria-hidden>
{[peak, peak / 2, 0].map((value, index) => <div key={index} className="absolute inset-x-0 flex items-center gap-2" style={{ top: `${index * 50}%` }}>
<span className="absolute top-0 w-7 -translate-y-1/2 text-right text-[10px] tabular-nums text-muted-foreground">{compact.format(value)}</span>
<span className="ml-9 flex-1 border-t border-border/40" data-model-usage-gridline={index} />
</div>)}
</div>
<div role="group" aria-label={title} className="relative grid h-full grid-cols-[repeat(30,minmax(0,1fr))] gap-px">
<TooltipProvider>
<UsageAxis ticks={ticks} format={compact} gridlineAttribute="data-model-usage-gridline" />
<div role="group" aria-label={title} className="relative grid h-full grid-cols-[repeat(30,minmax(0,1fr))]">
<TooltipProvider delayDuration={0} disableHoverableContent>
{columns.map(column => column.total === 0 ? (
<span key={column.date} role="img" aria-label={`${column.date}: ${number.format(0)} tokens`} />
<span key={column.date} role="img" aria-label={`${column.date}: ${exact(0)} tokens`} />
) : <Tooltip key={column.date}>
<TooltipTrigger asChild>
<span role="img" tabIndex={0} aria-label={`${column.date}: ${number.format(column.total)} tokens; ${column.values.map((value, index) => `${labels[index]}: ${number.format(value)}`).join(", ")}`} className="flex min-w-0 items-end focus-visible:outline focus-visible:outline-2 focus-visible:outline-orange-500">
<span className="flex w-full flex-col-reverse" style={{ height: `${column.total / peak * 100}%` }}>
<span role="img" tabIndex={0} aria-label={`${column.date}: ${exact(column.total)} tokens; ${column.values.map((value, index) => `${labels[index]}: ${exact(value)}${spoken(column.stats[index])}`).join(", ")}`} className="flex min-w-0 items-end pr-1 focus-visible:outline focus-visible:outline-2 focus-visible:outline-orange-500">
<span className="flex w-full flex-col-reverse overflow-hidden rounded-t-sm" style={{ height: `${column.total / peak * 100}%` }}>
{column.values.map((value, index) => value > 0 && <span key={index} className={cn("w-full shrink-0", color(index))} style={{ height: `${value / column.total * 100}%` }} />)}
</span>
</span>
</TooltipTrigger>
<TooltipContent className="w-72 max-w-[85vw] p-3">
<p className="mb-2 text-xs font-medium">{column.date}</p>
<dl className="space-y-2">
{column.values.map((value, index) => ({ value, index })).filter(item => item.value > 0).sort((a, b) => b.value - a.value).map(({ value, index }) => <div key={index} className="flex items-start justify-between gap-3 text-xs">
<dt className="flex min-w-0 items-start gap-2"><span aria-hidden className={cn("mt-0.5 h-3 w-1 shrink-0 rounded-full", color(index))} /><span className="break-words">{labels[index]}</span></dt><dd className="shrink-0 tabular-nums">{number.format(value)}</dd>
</div>)}
<div className="flex justify-between border-t border-border/50 pt-2 text-xs font-medium"><dt>{t("settings.usage.totalTokens", { defaultValue: "Total tokens" })}</dt><dd className="tabular-nums">{number.format(column.total)}</dd></div>
<div className="flex justify-between text-xs text-muted-foreground"><dt>{t("settings.usage.requests")}</dt><dd className="tabular-nums">{number.format(column.requests)}</dd></div>
<TooltipContent className="w-[27rem] max-w-[90vw] p-3">
<dl className="grid grid-cols-[minmax(0,1fr)_auto_auto_auto_auto_auto_auto] items-baseline gap-x-2 gap-y-2 text-xs">
<dt className="whitespace-nowrap text-xs font-medium">{column.date}</dt>
<dd />
<dd className="text-[11px] text-muted-foreground">tok/s</dd>
<dd className="text-right text-[11px] text-muted-foreground">TTFT</dd>
<dd className="text-[11px] text-muted-foreground">s</dd>
<dd className="text-right text-[11px] text-muted-foreground">{t("settings.usage.cacheHitRate")}</dd>
<dd className="text-right text-[11px] text-muted-foreground">tokens</dd>
{column.values.map((value, index) => ({ value, index })).filter(item => item.value > 0).sort((a, b) => b.value - a.value).map(({ value, index }) => {
const [speedValue, speedUnit] = speed(column.stats[index].speed);
const [ttftValue, ttftUnit] = firstToken(column.stats[index].ttft);
const hit = column.stats[index].hit;
return <Fragment key={index}>
<dt className="flex min-w-0 items-start gap-2"><span aria-hidden className={cn("mt-0.5 h-3 w-1 shrink-0 rounded-full", color(index))} /><span className="break-words">{labels[index]}</span></dt><dd className="text-right tabular-nums">{speedValue}</dd><dd className="w-8 tabular-nums">{speedUnit}</dd><dd className="text-right tabular-nums">{ttftValue}</dd><dd className="w-2 tabular-nums">{ttftUnit}</dd><dd className="text-right tabular-nums">{hit == null ? "—" : percent(hit)}</dd><dd className="text-right tabular-nums">{display(value)}</dd>
</Fragment>;
})}
<dt className="col-span-6 border-t border-border/50 pt-2 font-medium">{t("settings.usage.totalTokens", { defaultValue: "Total tokens" })}</dt><dd className="border-t border-border/50 pt-2 text-right font-medium tabular-nums">{display(column.total)}</dd>
<dt className="col-span-6 text-muted-foreground">{t("settings.usage.requests")}</dt><dd className="text-right tabular-nums text-muted-foreground">{display(column.requests)}</dd>
</dl>
</TooltipContent>
</Tooltip>)}
</TooltipProvider>
</div>
</div>
<div className="relative mt-2 flex justify-between text-[10px] tabular-nums text-muted-foreground"><span>{days[0].date.slice(5)}</span><span>{days[14].date.slice(5)}</span><span>{days[days.length - 1].date.slice(5)}</span></div>
<UsageDateAxis start={days[0].date} end={days[days.length - 1].date} peak={days[peakIndex].date} peakCenter={peakCenter} format={formatDay} />
</div>
<TooltipProvider>
<TooltipProvider delayDuration={0} disableHoverableContent>
<div className="mt-4 grid grid-cols-2 gap-x-4 gap-y-2 text-[11px] text-muted-foreground sm:grid-cols-3">
{labels.map((label, index) => {
if (index === series.length && !hasOther) return null;
const model = index < series.length ? modelUsage.get(series[index][0]) : undefined;
const tokens = columns.reduce((sum, column) => sum + column.values[index], 0);
const rate = model?.cache_read_observed_input_tokens ? percent.format(model.cache_read_tokens / model.cache_read_observed_input_tokens) : "—";
const rate = model?.cache_read_observed_input_tokens ? percent(model.cache_read_tokens / model.cache_read_observed_input_tokens) : "—";
const parts = [
[t("settings.usage.totalTokens"), `${number.format(tokens)} (${percent.format(tokens / total)})`],
[t("settings.usage.totalTokens"), `${display(tokens)} (${percent(tokens / total)})`],
[t("settings.usage.cacheHitRate"), rate],
];
return <Tooltip key={index}>
@@ -0,0 +1,56 @@
import { useEffect, useMemo, useRef, useState } from "react";
import { TokenUsageCard } from "@/components/settings/TokenUsageCard";
import { usePageVisibility } from "@/hooks/usePageVisibility";
import { fetchSettingsUsage } from "@/lib/api";
import type { SettingsPayload } from "@/lib/types";
import { useClient } from "@/providers/ClientProvider";
type Usage = NonNullable<SettingsPayload["usage"]>;
export function TokenUsageOverview({ initialUsage, timeZone }: { initialUsage?: Usage; timeZone?: string }) {
const { client, getToken } = useClient();
const pageVisible = usePageVisibility();
const [details, setDetails] = useState(false);
const [usage, setUsage] = useState(initialUsage);
const [modelsLoading, setModelsLoading] = useState(false);
const cache = useMemo<{ overview?: Usage; models?: Usage }>(() => ({ overview: initialUsage }), [client, initialUsage, timeZone]);
const previousDetails = useRef(false);
useEffect(() => setUsage(cache.overview), [cache]);
useEffect(() => {
const closingDetails = previousDetails.current && !details;
previousDetails.current = details;
if (!pageVisible) return;
if (details && cache.models) setUsage(cache.models);
const controller = new AbortController();
let refreshing = false;
const refresh = async () => {
if (refreshing) return;
refreshing = true;
const key = details ? "models" : "overview";
if (details) setModelsLoading(!cache.models);
try {
const next = await fetchSettingsUsage(getToken(), { details, cached: cache[key], signal: controller.signal });
if (!controller.signal.aborted) {
cache[key] = next;
setUsage(next);
}
} catch {
// Keep the last telemetry snapshot during transient failures.
} finally {
if (!controller.signal.aborted) setModelsLoading(false);
refreshing = false;
}
};
if (!closingDetails) void refresh();
const interval = window.setInterval(() => void refresh(), 5000);
window.addEventListener("focus", refresh);
return () => {
controller.abort();
window.clearInterval(interval);
window.removeEventListener("focus", refresh);
};
}, [cache, details, getToken, pageVisible]);
return <TokenUsageCard usage={usage} timeZone={timeZone} detailsLoading={modelsLoading} onDetailsOpenChange={setDetails} />;
}
@@ -4,7 +4,7 @@ import {
ImageGenerationIcon,
VoiceIcon,
} from "@/components/icons/product-icons";
import { useContext, useEffect, type Dispatch, type SetStateAction } from "react";
import { useContext, useEffect, type Dispatch, type ReactNode, type SetStateAction } from "react";
import {
ChevronRight,
type LucideIcon,
@@ -39,10 +39,12 @@ export function OverviewSettings({
settings,
onSelectSection,
showBrandLogos,
usageCard,
}: {
settings: SettingsPayload;
onSelectSection: (section: SettingsSectionKey) => void;
showBrandLogos: boolean;
usageCard?: ReactNode;
}) {
const { t } = useTranslation();
const tx = (key: string, fallback: string) => t(key, { defaultValue: fallback });
@@ -76,7 +78,7 @@ export function OverviewSettings({
return (
<div className="settings-stack">
<section className="rounded-panel bg-settings-surface p-6">
<TokenUsageCard usage={settings.usage} timeZone={settings.agent.timezone} />
{usageCard ?? <TokenUsageCard usage={settings.usage} timeZone={settings.agent.timezone} />}
</section>
<section>
@@ -0,0 +1,67 @@
/**
* Shared chrome for the two usage charts: the peak/average axis and the date
* axis below the bars. Both charts draw 30 columns over the same window, so
* they must not drift apart in scale, ticks, or labels.
*/
export interface UsageAxisTick {
value: number;
top: number;
/** Stable identity for `data-*-gridline`, independent of which ticks render. */
gridline: 0 | 1 | 2;
}
/** Peak at the top, daily average as the reference line, zero as the baseline. */
export function usageAxisTicks(peak: number, average: number): UsageAxisTick[] {
if (peak <= 0) return [];
const meanTop = Math.min(100, (1 - average / peak) * 100);
const ticks: UsageAxisTick[] = [{ value: peak, top: 0, gridline: 0 }];
// A mean hugging the peak would print two labels on top of each other.
if (meanTop >= 12) ticks.push({ value: average, top: meanTop, gridline: 1 });
ticks.push({ value: 0, top: 100, gridline: 2 });
return ticks;
}
/** Horizontal center of the peak column, in percent of the plot width. */
export function usagePeakCenter(columns: number, peakIndex: number): number {
return columns ? ((peakIndex + 0.5) / columns) * 100 : 0;
}
export function UsageAxis({ ticks, format, gridlineAttribute }: {
ticks: UsageAxisTick[];
format: (value: number) => string;
gridlineAttribute: "data-usage-gridline" | "data-model-usage-gridline";
}) {
return (
<div className="pointer-events-none absolute inset-y-0 -left-11 right-0" aria-hidden>
{ticks.map(tick => (
<div key={tick.gridline} className="absolute inset-x-0 flex items-center gap-2" style={{ top: `${tick.top}%` }}>
{tick.value > 0 && <span className="absolute top-0 w-9 -translate-y-1/2 whitespace-nowrap text-right text-[10px] tabular-nums text-muted-foreground">{format(tick.value)}</span>}
<span className="ml-11 flex-1 border-t border-border/40" {...{ [gridlineAttribute]: tick.gridline }} />
</div>
))}
</div>
);
}
export function UsageDateAxis({ start, peak, end, peakCenter, format }: {
start: string;
peak: string;
end: string;
peakCenter: number;
format: (date: string) => string;
}) {
// Keep the peak label inside the plot instead of letting it hang off an edge.
const peakStyle = peakCenter < 17
? { left: 0 }
: peakCenter > 83
? { left: "100%", transform: "translateX(-100%)" }
: { left: `${peakCenter}%`, transform: "translateX(-50%)" };
return (
<div className="relative mt-2 h-4 text-[10px] tabular-nums text-muted-foreground" aria-hidden>
{peakCenter > 20 && <span className="absolute left-0 top-0">{format(start)}</span>}
{peakCenter < 80 && <span className="absolute right-0 top-0">{format(end)}</span>}
<span className="absolute top-0 whitespace-nowrap text-orange-500 dark:text-orange-400" style={peakStyle}>{format(peak)}</span>
</div>
);
}
@@ -36,7 +36,7 @@ import { useSystemSettingsState } from "@/components/settings/system/useSystemSe
import { getToolsCatalog } from "@/lib/tools-catalog-cache";
import { usePageVisibility } from "@/hooks/usePageVisibility";
import { useEditCompletion } from "@/components/settings/shared/useEditCompletion";
import { cancelProviderOAuth, fetchSettings, fetchSettingsUsage } from "@/lib/api";
import { cancelProviderOAuth, fetchSettings } from "@/lib/api";
import {
LOCAL_PREFS_CHANGED_EVENT,
readLocalPreferences,
@@ -204,7 +204,7 @@ export function useSettingsController({
const requestInitialSettings = latestInitialSettingsRef.current;
const requestDrafts = draftsRef.current;
if (showLoading) setLoading(true);
fetchSettings(getToken())
fetchSettings(getToken(), "", client)
.then((payload) => {
if (!cancelled && latestInitialSettingsRef.current === requestInitialSettings) {
const current = draftsRef.current;
@@ -228,37 +228,8 @@ export function useSettingsController({
return () => {
cancelled = true;
};
}, [applyPayload, getToken]);
}, [applyPayload, client, getToken]);
const hasSettings = settings !== null;
useEffect(() => {
if (activeSection !== "overview" || !hasSettings || !pageVisible) return;
let cancelled = false;
let refreshing = false;
const refresh = async () => {
if (refreshing) return;
refreshing = true;
try {
const usage = await fetchSettingsUsage(getToken());
if (!cancelled) {
setSettings((current) => (current ? { ...current, usage } : current));
}
} catch {
// Usage is best-effort telemetry; the settings snapshot remains usable.
} finally {
refreshing = false;
}
};
void refresh();
const interval = window.setInterval(() => void refresh(), 5000);
const onFocus = () => void refresh();
window.addEventListener("focus", onFocus);
return () => {
cancelled = true;
window.clearInterval(interval);
window.removeEventListener("focus", onFocus);
};
}, [activeSection, getToken, hasSettings, pageVisible]);
const { refreshAutomations } = useSystemSettingsEffects({
state: systemState,
activeSection,
@@ -363,7 +334,7 @@ export function useSettingsController({
const requestDrafts = draftsRef.current;
try {
const nextToken = await onNativeEngineRestart();
const payload = await fetchSettings(nextToken);
const payload = await fetchSettings(nextToken, "", client);
const current = draftsRef.current;
applyPayload(payload, {
preserveAgentForm: current.form !== requestDrafts.form,
@@ -399,7 +370,7 @@ export function useSettingsController({
setHostEngineApplying(true);
try {
const nextToken = await onNativeEngineRestart();
const refreshed = await fetchSettings(nextToken);
const refreshed = await fetchSettings(nextToken, "", client);
applyPayload(refreshed, { preserveAgentForm: true, preserveCapabilityForms: true });
setPendingRestartSections(EMPTY_PENDING_RESTART_SECTIONS);
setError(null);
@@ -4,8 +4,11 @@ import * as TooltipPrimitive from "@radix-ui/react-tooltip";
import { floatingSurfaceElevationClassName } from "@/components/ui/floating-surface";
import { cn } from "@/lib/utils";
function TooltipProvider(props: Omit<React.ComponentPropsWithoutRef<typeof TooltipPrimitive.Provider>, "delayDuration" | "skipDelayDuration">) {
return <TooltipPrimitive.Provider {...props} delayDuration={500} skipDelayDuration={0} />;
function TooltipProvider({
delayDuration = 500,
...props
}: Omit<React.ComponentPropsWithoutRef<typeof TooltipPrimitive.Provider>, "delayDuration" | "skipDelayDuration"> & { delayDuration?: number }) {
return <TooltipPrimitive.Provider {...props} delayDuration={delayDuration} skipDelayDuration={0} />;
}
const Tooltip = TooltipPrimitive.Root;
const TooltipTrigger = TooltipPrimitive.Trigger;
+9 -4
View File
@@ -220,10 +220,15 @@ const usage: Usage = (() => {
return { days, total_tokens: total, total_tokens_30d: total, total_tokens_365d: total,
peak_day_tokens: Math.max(...days.map((day) => day.total_tokens)), current_streak_days: 3, longest_streak_days: 6,
active_days_30d: days.filter((day) => day.total_tokens > 0).length, requests_30d: days.reduce((sum, day) => sum + day.requests, 0),
model_days_30d: days.flatMap((day) => [
{ date: day.date, provider: "openai", model: "gpt-5.4", total_tokens: day.total_tokens * 0.6 },
{ date: day.date, provider: "anthropic", model: "claude-sonnet-4", total_tokens: day.total_tokens * 0.4 },
]) };
model_days_30d: days.flatMap((day, index) => [
{ provider: "openai", model: "gpt-5.4", share: 0.6, speed: 48 + index % 7 },
{ provider: "anthropic", model: "claude-sonnet-4", share: 0.4, speed: 33 + index % 5 },
].map(({ provider, model, share, speed }) => {
const totalTokens = day.total_tokens * share;
const measured = Math.round(totalTokens * 0.4);
const generationMs = Math.round(measured / speed * 1000);
return { date: day.date, provider, model, total_tokens: totalTokens, measured_output_tokens: measured, generation_ms: generationMs, ttft_ms: Math.round(generationMs * 0.6), timed_requests: 1, cache_read_tokens: Math.round(totalTokens * 0.5), cache_read_observed_input_tokens: Math.round(totalTokens * 0.8) };
})) };
})();
function UsagePreview() {
+6 -3
View File
@@ -1323,17 +1323,18 @@
"shortTitle": "Token usage",
"viewDetails": "View details",
"cacheHitRate": "Cache hit rate",
"cacheRateHelp": "Cache hit rate excludes input with unknown cache status.",
"dailyTrend": "Daily tokens",
"bySource": "Usage by source",
"modelTrend": "Model trends",
"modelsUnavailable": "No model breakdown available.",
"otherModels": "Other / unattributed",
"otherModels": "Other models",
"unclassified": "Unclassified",
"unavailable": "Usage data is unavailable.",
"noActivity": "No token usage in the last 30 days.",
"last30Days": "Last 30 days",
"cachedInput": "Cached input",
"cacheMiss": "Cache miss",
"cacheWrite": "Cache write",
"cacheUnknown": "Unknown status",
"outputTokens": "Output",
"otherTokens": "Other tokens",
@@ -1347,7 +1348,9 @@
"dream": "Memory",
"system": "Auxiliary calls"
},
"systemHelp": "Includes internal tasks and calls without a recorded source."
"systemHelp": "Includes internal tasks and calls without a recorded source.",
"failedRequests": "{{count}} failed",
"estimatedShare": "{{percent}} of tokens are estimated"
},
"providers": {
"manageProviders": "Manage providers",
+6 -3
View File
@@ -935,18 +935,19 @@
"shortTitle": "Uso de tokens",
"viewDetails": "Ver detalles",
"cacheHitRate": "Tasa de aciertos de caché",
"cacheRateHelp": "La tasa excluye las entradas cuyo estado de caché se desconoce.",
"dailyTrend": "Tokens diarios",
"systemHelp": "Incluye tareas internas y llamadas sin origen registrado.",
"bySource": "Uso por origen",
"modelTrend": "Tendencias por modelo",
"modelsUnavailable": "Sin desglose por modelo.",
"otherModels": "Otros / sin atribuir",
"otherModels": "Otros modelos",
"unclassified": "Sin clasificar",
"unavailable": "Los datos de uso no están disponibles.",
"noActivity": "Sin uso de tokens en los últimos 30 días.",
"last30Days": "Últimos 30 días",
"cachedInput": "Entrada en caché",
"cacheMiss": "Fallo de caché",
"cacheWrite": "Escritura de caché",
"cacheUnknown": "Estado desconocido",
"outputTokens": "Salida",
"otherTokens": "Otros tokens",
@@ -959,7 +960,9 @@
"cron": "Automatizaciones",
"dream": "Consolidación de memoria",
"system": "Llamadas auxiliares"
}
},
"failedRequests": "{{count}} fallidas",
"estimatedShare": "El {{percent}} de los tokens es estimado"
},
"providers": {
"manageProviders": "Gestionar proveedores",
+6 -3
View File
@@ -935,18 +935,19 @@
"shortTitle": "Utilisation des tokens",
"viewDetails": "Voir les détails",
"cacheHitRate": "Taux de réussite du cache",
"cacheRateHelp": "Le taux exclut les entrées dont l’état du cache est inconnu.",
"dailyTrend": "Tokens quotidiens",
"systemHelp": "Inclut les tâches internes et les appels sans source enregistrée.",
"bySource": "Utilisation par source",
"modelTrend": "Tendances des modèles",
"modelsUnavailable": "Aucune ventilation par modèle disponible.",
"otherModels": "Autres / non attribués",
"otherModels": "Autres modèles",
"unclassified": "Non classé",
"unavailable": "Les données d’utilisation sont indisponibles.",
"noActivity": "Aucun token utilisé au cours des 30 derniers jours.",
"last30Days": "30 derniers jours",
"cachedInput": "Entrée en cache",
"cacheMiss": "Cache manqué",
"cacheWrite": "Écriture de cache",
"cacheUnknown": "État inconnu",
"outputTokens": "Sortie",
"otherTokens": "Autres tokens",
@@ -959,7 +960,9 @@
"cron": "Automatisations",
"dream": "Consolidation de la mémoire",
"system": "Appels auxiliaires"
}
},
"failedRequests": "{{count}} échecs",
"estimatedShare": "{{percent}} des tokens sont estimés"
},
"providers": {
"manageProviders": "Gérer les fournisseurs",
+6 -3
View File
@@ -935,18 +935,19 @@
"shortTitle": "Penggunaan token",
"viewDetails": "Lihat detail",
"cacheHitRate": "Rasio cache hit",
"cacheRateHelp": "Rasio tidak mencakup input dengan status cache yang tidak diketahui.",
"dailyTrend": "Token harian",
"systemHelp": "Termasuk tugas internal dan panggilan tanpa sumber tercatat.",
"bySource": "Penggunaan berdasarkan sumber",
"modelTrend": "Tren model",
"modelsUnavailable": "Rincian per model tidak tersedia.",
"otherModels": "Lainnya / belum dikategorikan",
"otherModels": "Model lain",
"unclassified": "Tidak dikategorikan",
"unavailable": "Data penggunaan tidak tersedia.",
"noActivity": "Tidak ada penggunaan token dalam 30 hari terakhir.",
"last30Days": "30 hari terakhir",
"cachedInput": "Input tersedia di cache",
"cacheMiss": "Cache tidak ditemukan",
"cacheWrite": "Penulisan cache",
"cacheUnknown": "Status tidak diketahui",
"outputTokens": "Output",
"otherTokens": "Token lainnya",
@@ -959,7 +960,9 @@
"cron": "Otomasi",
"dream": "Penataan memori",
"system": "Panggilan pendukung"
}
},
"failedRequests": "{{count}} gagal",
"estimatedShare": "{{percent}} token diperkirakan"
},
"providers": {
"manageProviders": "Kelola penyedia",
+6 -3
View File
@@ -935,18 +935,19 @@
"shortTitle": "トークン使用量",
"viewDetails": "詳細を見る",
"cacheHitRate": "キャッシュヒット率",
"cacheRateHelp": "キャッシュ状態が不明な入力はヒット率の計算から除外します。",
"dailyTrend": "毎日の Token",
"systemHelp": "内部タスクと記録された送信元がない呼び出しを含みます。",
"bySource": "利用元別の使用量",
"modelTrend": "モデルの推移",
"modelsUnavailable": "モデル別の内訳はありません。",
"otherModels": "その他 / 未分類",
"otherModels": "その他のモデル",
"unclassified": "未分類",
"unavailable": "使用量データを取得できません。",
"noActivity": "過去30日間のトークン使用はありません。",
"last30Days": "過去 30 日間",
"cachedInput": "キャッシュヒット",
"cacheMiss": "キャッシュ未使用",
"cacheWrite": "キャッシュ書き込み",
"cacheUnknown": "状態不明",
"outputTokens": "出力",
"otherTokens": "その他のトークン",
@@ -959,7 +960,9 @@
"cron": "自動タスク",
"dream": "メモリ整理",
"system": "補助処理"
}
},
"failedRequests": "失敗 {{count}} 件",
"estimatedShare": "トークンの {{percent}} は推定値"
},
"providers": {
"manageProviders": "プロバイダーを管理",
+6 -3
View File
@@ -935,18 +935,19 @@
"shortTitle": "토큰 사용량",
"viewDetails": "자세히 보기",
"cacheHitRate": "캐시 적중률",
"cacheRateHelp": "캐시 상태가 알려진 입력만 적중률 계산에 포함됩니다.",
"dailyTrend": "일일 Token",
"systemHelp": "내부 작업과 출처가 기록되지 않은 호출을 포함합니다.",
"bySource": "출처별 사용량",
"modelTrend": "모델 추이",
"modelsUnavailable": "모델별 내역이 없습니다.",
"otherModels": "기타 / 미분류",
"otherModels": "기타 모델",
"unclassified": "미분류",
"unavailable": "사용량 데이터를 사용할 수 없습니다.",
"noActivity": "최근 30일 동안 토큰 사용량이 없습니다.",
"last30Days": "최근 30일",
"cachedInput": "캐시 적중",
"cacheMiss": "캐시 미스",
"cacheWrite": "캐시 쓰기",
"cacheUnknown": "상태 알 수 없음",
"outputTokens": "출력",
"otherTokens": "기타 토큰",
@@ -959,7 +960,9 @@
"cron": "자동화",
"dream": "기억 정리",
"system": "보조 호출"
}
},
"failedRequests": "실패 {{count}}회",
"estimatedShare": "토큰의 {{percent}}가 추정치"
},
"providers": {
"manageProviders": "제공업체 관리",
+6 -3
View File
@@ -1143,18 +1143,19 @@
"shortTitle": "Uso de tokens",
"viewDetails": "Ver detalhes",
"cacheHitRate": "Taxa de acertos de cache",
"cacheRateHelp": "A taxa exclui entradas com estado de cache desconhecido.",
"dailyTrend": "Tokens diários",
"systemHelp": "Inclui tarefas internas e chamadas sem origem registrada.",
"bySource": "Uso por origem",
"modelTrend": "Tendências dos modelos",
"modelsUnavailable": "Sem detalhamento por modelo.",
"otherModels": "Outros / não atribuídos",
"otherModels": "Outros modelos",
"unclassified": "Não classificado",
"unavailable": "Os dados de uso estão indisponíveis.",
"noActivity": "Nenhum token usado nos últimos 30 dias.",
"last30Days": "Últimos 30 dias",
"cachedInput": "Entrada em cache",
"cacheMiss": "Falha de cache",
"cacheWrite": "Gravação de cache",
"cacheUnknown": "Status desconhecido",
"outputTokens": "Saída",
"otherTokens": "Outros tokens",
@@ -1167,7 +1168,9 @@
"cron": "Automações",
"dream": "Consolidação de memória",
"system": "Chamadas auxiliares"
}
},
"failedRequests": "{{count}} falhas",
"estimatedShare": "{{percent}} dos tokens são estimados"
},
"providers": {
"manageProviders": "Gerenciar provedores",
+6 -3
View File
@@ -935,18 +935,19 @@
"shortTitle": "Mức dùng token",
"viewDetails": "Xem chi tiết",
"cacheHitRate": "Tỷ lệ trúng bộ nhớ đệm",
"cacheRateHelp": "Tỷ lệ không tính đầu vào có trạng thái bộ nhớ đệm không rõ.",
"dailyTrend": "Token mỗi ngày",
"systemHelp": "Gồm tác vụ nội bộ và lệnh gọi chưa ghi nguồn.",
"bySource": "Mức dùng theo nguồn",
"modelTrend": "Xu hướng mô hình",
"modelsUnavailable": "Chưa có chi tiết theo mô hình.",
"otherModels": "Khác / chưa phân loại",
"otherModels": "Mô hình khác",
"unclassified": "Chưa phân loại",
"unavailable": "Không có dữ liệu sử dụng.",
"noActivity": "Không có token nào được sử dụng trong 30 ngày qua.",
"last30Days": "30 ngày qua",
"cachedInput": "Đầu vào có trong bộ nhớ đệm",
"cacheMiss": "Không khớp cache",
"cacheWrite": "Ghi bộ nhớ đệm",
"cacheUnknown": "Trạng thái chưa rõ",
"outputTokens": "Đầu ra",
"otherTokens": "Token khác",
@@ -959,7 +960,9 @@
"cron": "Tự động hóa",
"dream": "Sắp xếp bộ nhớ",
"system": "Lượt gọi phụ trợ"
}
},
"failedRequests": "{{count}} lần lỗi",
"estimatedShare": "{{percent}} token là ước tính"
},
"providers": {
"manageProviders": "Quản lý nhà cung cấp",
+6 -3
View File
@@ -1323,17 +1323,18 @@
"shortTitle": "Token 用量",
"viewDetails": "查看详情",
"cacheHitRate": "缓存命中率",
"cacheRateHelp": "缓存命中率仅统计缓存状态已知的输入。",
"dailyTrend": "每日 Token",
"bySource": "用量来源",
"modelTrend": "模型趋势",
"modelsUnavailable": "暂无模型用量明细。",
"otherModels": "其他模型 / 未分类",
"otherModels": "其他模型",
"unclassified": "未分类",
"unavailable": "暂时无法获取用量数据。",
"noActivity": "近 30 天暂无 Token 用量。",
"last30Days": "近 30 天",
"cachedInput": "缓存命中",
"cacheMiss": "未命中",
"cacheWrite": "缓存写入",
"cacheUnknown": "状态未知",
"outputTokens": "输出",
"otherTokens": "其他 Token",
@@ -1347,7 +1348,9 @@
"dream": "记忆整理",
"system": "辅助调用"
},
"systemHelp": "包括内部任务和未标注来源的调用"
"systemHelp": "包括内部任务和未标注来源的调用",
"failedRequests": "{{count}} 次失败",
"estimatedShare": "{{percent}} 的 Token 为本地估算"
},
"providers": {
"manageProviders": "管理提供商",
+6 -3
View File
@@ -935,18 +935,19 @@
"shortTitle": "Token 用量",
"viewDetails": "查看詳情",
"cacheHitRate": "快取命中率",
"cacheRateHelp": "快取命中率僅統計快取狀態已知的輸入。",
"dailyTrend": "每日 Token",
"systemHelp": "包括內部任務和未標註來源的呼叫",
"bySource": "用量來源",
"modelTrend": "模型趨勢",
"modelsUnavailable": "暫無模型用量明細。",
"otherModels": "其他模型 / 未歸類",
"otherModels": "其他模型",
"unclassified": "未分類",
"unavailable": "暫時無法取得用量資料。",
"noActivity": "近 30 天暫無 Token 用量。",
"last30Days": "近 30 天",
"cachedInput": "快取命中",
"cacheMiss": "未命中",
"cacheWrite": "快取寫入",
"cacheUnknown": "狀態未知",
"outputTokens": "輸出",
"otherTokens": "其他 Token",
@@ -959,7 +960,9 @@
"cron": "自動任務",
"dream": "記憶整理",
"system": "輔助呼叫"
}
},
"failedRequests": "{{count}} 次失敗",
"estimatedShare": "{{percent}} 的 Token 為本地估算"
},
"providers": {
"manageProviders": "管理提供商",
+26 -14
View File
@@ -842,28 +842,40 @@ export async function deleteSession(
);
}
export async function fetchSettings(
const settingsReads = new WeakMap<WebUIMutationTransport, Map<string, Promise<SettingsPayload>>>();
export function fetchSettings(
token: string,
base: string = "",
scope?: WebUIMutationTransport,
): Promise<SettingsPayload> {
return request<SettingsPayload>(
`${base}/api/settings`,
token,
undefined,
API_READ_TIMEOUT_MS,
);
const load = () => request<SettingsPayload>(`${base}/api/settings`, token, undefined, API_READ_TIMEOUT_MS);
if (!scope) return load();
let reads = settingsReads.get(scope);
if (!reads) {
reads = new Map();
settingsReads.set(scope, reads);
}
const key = JSON.stringify([base, token]);
const pending = reads.get(key);
if (pending) return pending;
const read = load().finally(() => reads.delete(key));
reads.set(key, read);
return read;
}
export async function fetchSettingsUsage(
token: string,
base: string = "",
options: { details?: boolean; cached?: NonNullable<SettingsPayload["usage"]>; signal?: AbortSignal } = {},
): Promise<NonNullable<SettingsPayload["usage"]>> {
return request<NonNullable<SettingsPayload["usage"]>>(
`${base}/api/settings/usage`,
token,
undefined,
API_READ_TIMEOUT_MS,
);
const headers: Record<string, string> = { Authorization: `Bearer ${token}` };
if (options.cached?.revision) headers["If-None-Match"] = `W/"${options.cached.revision}"`;
const response = await fetchWithTimeout(`/api/settings/usage${options.details ? "?details=true" : ""}`, {
headers, credentials: "same-origin", cache: "no-store", signal: options.signal,
}, API_READ_TIMEOUT_MS);
if (response.status === 304 && options.cached) return options.cached;
if (!response.ok) throw new ApiError(response.status, `HTTP ${response.status}`);
return await response.json() as NonNullable<SettingsPayload["usage"]>;
}
export type UpdateChannel = "stable" | "preview";
+23 -8
View File
@@ -918,6 +918,8 @@ export interface SettingsPayload {
cache_write_tokens: number;
cache_read_observed_input_tokens: number;
cache_write_observed_input_tokens: number;
cache_miss_tokens?: number;
cache_unknown_tokens?: number;
total_tokens: number;
reported_tokens?: number;
estimated_tokens?: number;
@@ -940,6 +942,8 @@ export interface SettingsPayload {
cache_write_tokens: number;
cache_read_observed_input_tokens: number;
cache_write_observed_input_tokens: number;
cache_miss_tokens?: number;
cache_unknown_tokens?: number;
total_tokens: number;
reported_tokens?: number;
estimated_tokens?: number;
@@ -956,14 +960,17 @@ export interface SettingsPayload {
}
>;
}>;
total_tokens: number;
total_tokens_30d: number;
total_tokens_365d: number;
peak_day_tokens: number;
current_streak_days: number;
longest_streak_days: number;
active_days_30d: number;
requests_30d: number;
revision?: string;
range_start?: string;
range_end?: string;
total_tokens?: number;
total_tokens_30d?: number;
total_tokens_365d?: number;
peak_day_tokens?: number;
current_streak_days?: number;
longest_streak_days?: number;
active_days_30d?: number;
requests_30d?: number;
failed_requests_30d?: number;
reported_tokens_30d?: number;
estimated_tokens_30d?: number;
@@ -979,6 +986,8 @@ export interface SettingsPayload {
cache_write_tokens: number;
cache_read_observed_input_tokens: number;
cache_write_observed_input_tokens: number;
cache_miss_tokens?: number;
cache_unknown_tokens?: number;
total_tokens: number;
reported_tokens: number;
estimated_tokens: number;
@@ -998,6 +1007,12 @@ export interface SettingsPayload {
provider: string;
model: string;
total_tokens: number;
measured_output_tokens?: number;
generation_ms?: number;
ttft_ms?: number;
timed_requests?: number;
cache_read_tokens?: number;
cache_read_observed_input_tokens?: number;
}>;
updated_at?: string | null;
};
+21
View File
@@ -0,0 +1,21 @@
/**
* Providers report the same model under different ids: the Codex backend
* answers with `openai-codex/gpt-6.1-sol` while other calls record the bare
* `gpt-6-astra`. Grouping stays per provider, but the model name has to be
* normalized first, otherwise one model shows up as several cards.
*/
const SEPARATORS = /[^a-z0-9]/g;
function identity(value: string): string {
return value.toLowerCase().replace(SEPARATORS, "");
}
export function normalizeUsageModel(provider: string, model: string): string {
const separator = model.indexOf("/");
if (separator <= 0) return model;
const prefix = identity(model.slice(0, separator));
const owner = identity(provider);
// Only strip a prefix that names the provider itself; `qwen/…` under a
// custom provider is part of the model name.
return prefix && owner.startsWith(prefix) ? model.slice(separator + 1) : model;
}
+55
View File
@@ -0,0 +1,55 @@
/**
* Usage counters are routinely eight to eleven digits. Reading them requires
* locale units (`100.5亿`, `10B`), but the exact value still has to stay
* available for titles, accessible labels, and diagnostics.
*/
const COMPACT_THRESHOLD = 10_000;
export interface UsageNumberFormats {
/** Locale units for five-digit and larger values, exact digits below that. */
display: (value: number) => string;
/** Grouped exact digits. */
exact: (value: number) => string;
}
export interface UsageFormats extends UsageNumberFormats {
/** Locale units regardless of magnitude. */
compact: (value: number) => string;
/** Percentage with one fraction digit. */
percent: (value: number) => string;
/** Milliseconds as seconds with one fraction digit. */
seconds: (value: number) => string;
/** Short month and day for a `YYYY-MM-DD` key, in UTC. */
date: (date: string) => string;
}
const formatsByLocale = new Map<string, UsageFormats>();
/**
* `Intl` constructors are comparatively expensive and the usage panels
* re-render on every hover, so each locale's formatters are built once.
*/
export function usageFormats(locale: string): UsageFormats {
const cached = formatsByLocale.get(locale);
if (cached) return cached;
const compact = new Intl.NumberFormat(locale, { notation: "compact", maximumFractionDigits: 1 });
const exact = new Intl.NumberFormat(locale, { maximumFractionDigits: 0 });
const percent = new Intl.NumberFormat(locale, { style: "percent", maximumFractionDigits: 1 });
const seconds = new Intl.NumberFormat(locale, { minimumFractionDigits: 1, maximumFractionDigits: 1 });
const date = new Intl.DateTimeFormat(locale, { month: "short", day: "numeric", timeZone: "UTC" });
const formats: UsageFormats = {
display: (value) => (Math.abs(value) >= COMPACT_THRESHOLD ? compact.format(value) : exact.format(value)),
exact: (value) => exact.format(value),
compact: (value) => compact.format(value),
percent: (value) => percent.format(value),
seconds: (value) => seconds.format(value / 1000),
date: (value) => date.format(new Date(`${value}T00:00:00Z`)),
};
formatsByLocale.set(locale, formats);
return formats;
}
/** Output tokens per second, or `null` when no generation time was measured. */
export function usageSpeed(measuredOutputTokens: number, generationMs: number): number | null {
return generationMs > 0 ? measuredOutputTokens / (generationMs / 1000) : null;
}
+28
View File
@@ -707,6 +707,34 @@ describe("webui API helpers", () => {
);
});
it("shares only pending settings reads within the same client", async () => {
const pending: ((response: Response) => void)[] = [];
vi.mocked(fetch).mockImplementation(() => new Promise<Response>((resolve) => pending.push(resolve)));
const first = fetchSettings("tok", "", mutationTransport);
expect(fetchSettings("tok", "", mutationTransport)).toBe(first);
const other = fetchSettings("tok", "", { requestMutation });
expect(fetch).toHaveBeenCalledTimes(2);
pending[0]({ ok: true, json: async () => ({ version: { current: "first" } }) } as Response);
pending[1]({ ok: true, json: async () => ({ version: { current: "other" } }) } as Response);
expect((await first).version?.current).toBe("first");
expect((await other).version?.current).toBe("other");
const refreshed = fetchSettings("tok", "", mutationTransport);
expect(fetch).toHaveBeenCalledTimes(3);
pending[2]({ ok: true, json: async () => ({ version: { current: "refreshed" } }) } as Response);
expect((await refreshed).version?.current).toBe("refreshed");
});
it("reuses unchanged usage and requests model details explicitly", async () => {
const cached = { days: [], revision: "models" };
const json = vi.fn();
vi.mocked(fetch).mockResolvedValue({ status: 304, json } as unknown as Response);
expect(await fetchSettingsUsage("tok", { details: true, cached })).toBe(cached);
expect(fetch).toHaveBeenCalledWith("/api/settings/usage?details=true", expect.objectContaining({
headers: { Authorization: "Bearer tok", "If-None-Match": 'W/"models"' },
}));
expect(json).not.toHaveBeenCalled();
});
it("serializes model configuration creation", async () => {
await createModelConfiguration(mutationTransport, {
name: "Fast writing",
+14
View File
@@ -662,6 +662,20 @@ describe("App layout", () => {
expect(asideClassNames.some((cls) => cls.includes("lg:block"))).toBe(true);
});
it("loads settings once when opening the overview directly", async () => {
window.location.hash = "#/settings";
mockFetchRoutes({ "/api/settings": baseSettingsPayload(), "/api/settings/usage": { days: [] } });
render(<App />);
await act(async () => { await import("@/components/settings/SettingsView"); });
expect(await screen.findByRole("navigation", { name: "Settings sections" })).toBeInTheDocument();
expect(await screen.findByText("Token usage")).toBeInTheDocument();
const reads = () => vi.mocked(fetch).mock.calls.filter(([url]) => String(url) === "/api/settings");
expect(reads()).toHaveLength(1);
fireEvent.click(screen.getByRole("button", { name: "Back to chat" }));
await screen.findByRole("navigation", { name: "Sidebar navigation" });
expect(reads()).toHaveLength(1);
});
it("uses one main landmark and a page heading in desktop settings", async () => {
mockFetchRoutes({ "/api/settings": baseSettingsPayload() });
const { container } = render(<App />);
@@ -569,13 +569,14 @@ describe("Settings capabilities", () => {
requestMutationMock.mockResolvedValueOnce(saved);
let refreshParent!: (snapshot: SettingsPayload) => void;
let parentSnapshot: SettingsPayload = payload;
const client = { requestMutation: requestMutationMock, status: "open",
onStatus: (handler: (status: "open") => void) => { handler("open"); return () => {}; },
} as never;
function Parent() {
const [snapshot, setSnapshot] = useState<SettingsPayload>(payload);
parentSnapshot = snapshot;
refreshParent = setSnapshot;
return <ClientProvider client={{ requestMutation: requestMutationMock, status: "open",
onStatus: (handler: (status: "open") => void) => { handler("open"); return () => {}; },
} as never} token="tok">
return <ClientProvider client={client} token="tok">
<SettingsView themePreference="light" initialSection="voice" initialSettings={snapshot}
onSettingsChange={setSnapshot} onNativeEngineRestart={restart}
onChangeTheme={() => {}} onBackToChat={() => {}} onModelNameChange={() => {}} />
+2 -1
View File
@@ -386,6 +386,7 @@ describe("Settings overview and appearance", () => {
vi.fn(async (input: RequestInfo | URL) => {
const url = String(input);
if (url === "/api/settings") return jsonResponse(payload);
if (url === "/api/settings/usage") return jsonResponse(payload.usage);
if (url === "/api/settings/cli-apps") {
return jsonResponse({ apps: [], installed_count: 0 });
}
@@ -398,7 +399,7 @@ describe("Settings overview and appearance", () => {
renderSettingsView({ initialSection: "overview" });
expect(await screen.findByLabelText("1,500 tokens")).toBeInTheDocument();
expect(await screen.findByLabelText("1,500 tokens in the last 30 days")).toBeInTheDocument();
expect(screen.getByText("Token usage")).toBeInTheDocument();
});
+89 -13
View File
@@ -11,7 +11,7 @@ function day(date: string, tokens: number): Usage["days"][number] {
cache_write_observed_input_tokens: 0, requests: 1 };
}
function usage(days: Usage["days"]): Usage {
return { days, total_tokens: 999999, total_tokens_30d: 999999, total_tokens_365d: 999999,
return { days, total_tokens: 999999, total_tokens_30d: 999999, total_tokens_365d: 1_500_000,
peak_day_tokens: 999999, current_streak_days: 0, longest_streak_days: 0,
active_days_30d: 0, requests_30d: 0, updated_at: "2026-09-09T00:00:00Z" };
}
@@ -33,7 +33,7 @@ describe("Token usage card", () => {
const baseline = container.querySelector<HTMLElement>('[data-model-usage-gridline="2"]')!;
expect(plot).toContainElement(baseline);
expect(baseline.parentElement).toHaveStyle({ top: "100%" });
expect(plot).not.toContainElement(screen.getByText("09-01"));
expect(plot).not.toContainElement(screen.getByText("Sep 1"));
expect(bars[0].firstElementChild).toHaveStyle({ height: "100%" });
expect(bars[0].firstElementChild?.children).toHaveLength(2);
expect(bars[1].firstElementChild).toHaveStyle({ height: `${1 / 30_000_000 * 100}%` });
@@ -46,17 +46,17 @@ describe("Token usage card", () => {
afterEach(() => vi.useRealTimers());
it("uses one 30-day window for the total, chart and source percentages", () => {
const today = { ...day("2026-09-09", 300), input_tokens: 240, output_tokens: 60, cache_read_tokens: 120, cache_read_observed_input_tokens: 180, estimated_tokens: 100,
const today = { ...day("2026-09-09", 300), input_tokens: 240, output_tokens: 60, cache_read_tokens: 120, cache_read_observed_input_tokens: 180, cache_miss_tokens: 60, cache_unknown_tokens: 60, estimated_tokens: 100,
sources: { user: day("2026-09-09", 200) } };
render(<TokenUsageCard timeZone="UTC" usage={usage([
day("2026-08-10", 9000), day("2026-08-11", 100), today, day("2026-09-10", 9000),
])} />);
expect(screen.getByLabelText("400 tokens")).toBeInTheDocument();
expect(screen.getByLabelText("400 tokens in the last 30 days")).toBeInTheDocument();
const bars = within(screen.getByRole("group", { name: "Daily tokens" })).getAllByRole("img");
expect(bars).toHaveLength(30);
expect(bars.filter((bar) => bar.tabIndex === 0)).toEqual([bars[0], bars[29]]);
expect(bars[0]).toHaveAccessibleName(/2026-08-11: 100 tokens, 1 requests/);
expect(bars[29]).toHaveAccessibleName(/Cached input: 120, Cache miss: 60, Unknown status: 60, Output: 60/);
expect(bars[29]).toHaveAccessibleName(/Cached input: 120, Cache write: 0, Cache miss: 60, Unknown status: 60, Output: 60/);
const segments = bars[29].firstElementChild?.children;
expect(segments).toHaveLength(4);
expect(segments?.[0]).toHaveStyle({ height: "40%" });
@@ -66,6 +66,43 @@ describe("Token usage card", () => {
expect(bars[0]).toHaveAccessibleName(/Cache miss: 0, Unknown status: 100/);
expect(screen.getAllByText("50%")).toHaveLength(2);
expect(screen.getByText("Unclassified")).toBeInTheDocument();
expect(screen.getByText("13.3")).toBeInTheDocument();
expect(screen.getByText(/Sep 9/)).toBeInTheDocument();
});
it.each([0, 100])("partitions cache writes without overlap when cached input is %i", (read) => {
const output = read === 0 ? 20 : 40;
const total = read + 100 + output;
const today = { ...day("2026-09-09", total), input_tokens: read + 100, output_tokens: output,
cache_read_tokens: read, cache_write_tokens: 100,
cache_read_observed_input_tokens: read, cache_write_observed_input_tokens: read + 100,
cache_miss_tokens: 0, cache_unknown_tokens: 0 };
render(<TokenUsageCard usage={usage([today])} />);
const bar = within(screen.getByRole("group", { name: "Daily tokens" })).getAllByRole("img")[29];
expect(bar).toHaveAccessibleName(new RegExp(`Cached input: ${read}, Cache write: 100, Cache miss: 0, Unknown status: 0, Output: ${output}`));
const segments = Array.from(bar.firstElementChild!.children);
const values = [read, 100, output].filter(value => value > 0);
expect(segments).toHaveLength(values.length);
segments.forEach((segment, index) => expect(segment).toHaveStyle({ height: `${values[index] / total * 100}%` }));
});
it("keeps the read-only breakdown for older backends without per-call partitions", () => {
render(<TokenUsageCard usage={usage([{ ...day("2026-09-09", 240), input_tokens: 200, output_tokens: 40,
cache_read_tokens: 100, cache_write_tokens: 100,
cache_read_observed_input_tokens: 100, cache_write_observed_input_tokens: 200 }])} />);
const bar = within(screen.getByRole("group", { name: "Daily tokens" })).getAllByRole("img")[29];
expect(bar).toHaveAccessibleName(/Cached input: 100, Cache write: 0, Cache miss: 0, Unknown status: 100, Output: 40/);
expect(bar.firstElementChild?.children).toHaveLength(3);
expect(bar.firstElementChild?.children[1]).toHaveStyle({ height: `${100 / 240 * 100}%` });
});
it("hides a legend entry when that segment stays empty across the window", () => {
const today = { ...day("2026-09-09", 1000), cache_read_tokens: 200, cache_read_observed_input_tokens: 400 };
const { rerender } = render(<TokenUsageCard usage={usage([today])} />);
expect(screen.getByText("Cached input")).toBeInTheDocument();
expect(screen.queryByText("Cache write")).not.toBeInTheDocument();
rerender(<TokenUsageCard usage={usage([{ ...today, cache_write_tokens: 150, cache_write_observed_input_tokens: 400, cache_miss_tokens: 50, cache_unknown_tokens: 600 }])} />);
expect(screen.getByText("Cache write")).toBeInTheDocument();
});
it("shows an empty state for zero usage", () => {
@@ -73,15 +110,11 @@ describe("Token usage card", () => {
expect(screen.getByRole("status")).toHaveTextContent("No token usage in the last 30 days.");
});
it("opens details and computes the weighted cache rate from observed input only", () => {
render(<TokenUsageCard usage={usage([
{ ...day("2026-09-08", 100), cache_read_tokens: 80, cache_read_observed_input_tokens: 100 },
{ ...day("2026-09-09", 900), cache_read_tokens: 20, cache_read_observed_input_tokens: 300 },
])} />);
it("flags the share of tokens that were estimated locally", () => {
render(<TokenUsageCard usage={usage([{ ...day("2026-09-09", 1000), estimated_tokens: 250 }])} />);
fireEvent.click(screen.getByRole("button", { name: "View details" }));
const details = screen.getByRole("dialog", { name: "Token usage" });
expect(within(details).getByText("25%")).toBeInTheDocument();
expect(within(details).getByTitle("Cache hit rate excludes input with unknown cache status.")).toBeInTheDocument();
expect(within(details).getByText("25% of tokens are estimated")).toBeInTheDocument();
});
it("does not misrepresent unavailable usage as zero", () => {
@@ -90,6 +123,49 @@ describe("Token usage card", () => {
expect(screen.getByText("—")).toBeInTheDocument();
});
it("merges one model recorded under a provider prefix and a bare id", () => {
const days = Array.from({ length: 30 }, (_, index) => {
const date = new Date("2026-09-09T00:00:00Z");
date.setUTCDate(date.getUTCDate() - 29 + index);
const key = date.toISOString().slice(0, 10);
return { date: key, usage: day(key, index === 29 ? 1000 : 0) };
});
render(<TokenUsageModelTrend days={days} models={[
{ ...day("2026-09-09", 600), provider: "openai_codex", model: "openai-codex/gpt-6",
cache_read_tokens: 100, cache_read_observed_input_tokens: 200,
reported_tokens: 600, estimated_tokens: 0, successful_requests: 1, failed_requests: 0,
reported_requests: 1, estimated_requests: 0, generation_ms: 0, measured_output_tokens: 0,
ttft_ms: 0, timed_requests: 0, duration_ms: 0 },
{ ...day("2026-09-09", 400), provider: "openai_codex", model: "gpt-6",
cache_read_tokens: 50, cache_read_observed_input_tokens: 100,
reported_tokens: 400, estimated_tokens: 0, successful_requests: 1, failed_requests: 0,
reported_requests: 1, estimated_requests: 0, generation_ms: 0, measured_output_tokens: 0,
ttft_ms: 0, timed_requests: 0, duration_ms: 0 },
]} modelDays={[
{ date: "2026-09-09", provider: "openai_codex", model: "openai-codex/gpt-6", total_tokens: 600 },
{ date: "2026-09-09", provider: "openai_codex", model: "gpt-6", total_tokens: 400 },
]} />);
expect(screen.getAllByText("gpt-6")).toHaveLength(1);
expect(screen.getByLabelText("gpt-6: Total tokens: 1,000 (100%), Cache hit rate: 50%")).toBeInTheDocument();
});
it("reports per-model speed, first-token wait and cache hit rate where measured", () => {
const days = Array.from({ length: 30 }, (_, index) => {
const date = new Date("2026-09-09T00:00:00Z");
date.setUTCDate(date.getUTCDate() - 29 + index);
const key = date.toISOString().slice(0, 10);
return { date: key, usage: day(key, index === 29 ? 1500 : 0) };
});
render(<TokenUsageModelTrend days={days} modelDays={[
{ date: "2026-09-09", provider: "openai", model: "fast", total_tokens: 1000, measured_output_tokens: 400, generation_ms: 8000, ttft_ms: 3200, timed_requests: 1, cache_read_tokens: 700, cache_read_observed_input_tokens: 1000 },
{ date: "2026-09-09", provider: "openai", model: "legacy", total_tokens: 500 },
]} />);
const column = screen.getAllByRole("img")[29];
const label = column.getAttribute("aria-label") ?? "";
expect(label).toContain("fast: 1,000, 50 tok/s, 3.2s to first token, 70% cache hit");
expect(label).toContain("legacy: 500, Other models");
});
it("keeps the five leading model series and reconciles the rest to the daily total", () => {
const days = Array.from({ length: 30 }, (_, index) => {
const date = new Date("2026-09-09T00:00:00Z");
@@ -108,7 +184,7 @@ describe("Token usage card", () => {
expect(screen.getAllByRole("img").filter((bar) => bar.tabIndex === 0)).toEqual([column]);
expect(column).toHaveAccessibleName(/2026-09-09: 2,200 tokens/);
expect(column).toHaveAccessibleName(/model-5: 600/);
expect(column).toHaveAccessibleName(/Other \/ unattributed: 200/);
expect(column).toHaveAccessibleName(/Other models: 200/);
const legend = screen.getByLabelText("model-5: Total tokens: 600 (27.3%), Cache hit rate: 80%");
expect(legend).toHaveAttribute("tabindex", "0");
});
@@ -0,0 +1,90 @@
import { act, cleanup, fireEvent, render, screen } from "@testing-library/react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { TokenUsageOverview } from "@/components/settings/TokenUsageOverview";
const client = {};
const getToken = () => "tok";
vi.mock("@/providers/ClientProvider", () => ({ useClient: () => ({ client, getToken }) }));
const overview = { days: [], revision: "overview" };
const models = { ...overview, revision: "models", providers_30d: [], model_days_30d: [] };
const json = (value: unknown) => ({ ok: true, status: 200, json: async () => value }) as Response;
async function settle() {
await act(async () => {});
}
describe("Token usage loading", () => {
beforeEach(() => {
vi.useFakeTimers();
vi.setSystemTime(new Date("2026-09-09T12:00:00Z"));
});
afterEach(() => {
cleanup();
vi.useRealTimers();
vi.unstubAllGlobals();
vi.restoreAllMocks();
});
it("polls conditionally and loads models only while details are open", async () => {
const fetchMock = vi.fn(async (_input: RequestInfo | URL, init?: RequestInit) => {
if ((init?.headers as Record<string, string>)["If-None-Match"]) {
return { status: 304 } as Response;
}
return json(String(_input).includes("details=true") ? models : overview);
});
vi.stubGlobal("fetch", fetchMock);
const { unmount } = render(<TokenUsageOverview />);
await settle();
expect(fetchMock.mock.calls.map(([url]) => url)).toEqual(["/api/settings/usage"]);
await act(async () => vi.advanceTimersByTimeAsync(5000));
expect(fetchMock).toHaveBeenLastCalledWith("/api/settings/usage", expect.objectContaining({
headers: { Authorization: "Bearer tok", "If-None-Match": 'W/"overview"' },
}));
fireEvent.click(screen.getByRole("button", { name: "View details" }));
await settle();
expect(fetchMock).toHaveBeenLastCalledWith("/api/settings/usage?details=true", expect.anything());
await act(async () => vi.advanceTimersByTimeAsync(5000));
expect(fetchMock).toHaveBeenLastCalledWith("/api/settings/usage?details=true", expect.objectContaining({
headers: { Authorization: "Bearer tok", "If-None-Match": 'W/"models"' },
}));
const beforeClose = fetchMock.mock.calls.length;
fireEvent.keyDown(screen.getByRole("dialog"), { key: "Escape" });
await settle();
expect(fetchMock).toHaveBeenCalledTimes(beforeClose);
await act(async () => vi.advanceTimersByTimeAsync(5000));
expect(fetchMock).toHaveBeenLastCalledWith("/api/settings/usage", expect.anything());
const beforeLeave = fetchMock.mock.calls.length;
unmount();
await act(async () => vi.advanceTimersByTimeAsync(10000));
fireEvent(window, new Event("focus"));
expect(fetchMock).toHaveBeenCalledTimes(beforeLeave);
});
it("aborts a pending request when hidden and refreshes once when visible again", async () => {
let visibility = "visible";
vi.spyOn(document, "visibilityState", "get").mockImplementation(() => visibility as DocumentVisibilityState);
const signals: AbortSignal[] = [];
const fetchMock = vi.fn((_input: RequestInfo | URL, init?: RequestInit) => new Promise<Response>((_resolve, reject) => {
const signal = init!.signal!;
signals.push(signal);
signal.addEventListener("abort", () => reject(new DOMException("Aborted", "AbortError")), { once: true });
}));
vi.stubGlobal("fetch", fetchMock);
render(<TokenUsageOverview />);
await settle();
fireEvent(window, new Event("focus"));
await act(async () => vi.advanceTimersByTimeAsync(5000));
expect(fetchMock).toHaveBeenCalledTimes(1);
visibility = "hidden";
fireEvent(document, new Event("visibilitychange"));
await settle();
expect(signals[0].aborted).toBe(true);
await act(async () => vi.advanceTimersByTimeAsync(10000));
expect(fetchMock).toHaveBeenCalledTimes(1);
visibility = "visible";
fireEvent(document, new Event("visibilitychange"));
await settle();
expect(fetchMock).toHaveBeenCalledTimes(2);
});
});
+17
View File
@@ -0,0 +1,17 @@
import { describe, expect, it } from "vitest";
import { normalizeUsageModel } from "@/lib/usage-model";
describe("usage model names", () => {
it("strips a prefix that repeats the provider", () => {
expect(normalizeUsageModel("openai_codex", "openai-codex/gpt-6.1-sol")).toBe("gpt-6.1-sol");
expect(normalizeUsageModel("openai_codex", "openai/gpt-6-astra")).toBe("gpt-6-astra");
expect(normalizeUsageModel("custom-ffsa", "custom/model")).toBe("model");
});
it("keeps prefixes that belong to the model name", () => {
expect(normalizeUsageModel("custom-ffsa", "qwen/qwen3.8-27b")).toBe("qwen/qwen3.8-27b");
expect(normalizeUsageModel("zhipu", "glm-5.3-flash")).toBe("glm-5.3-flash");
expect(normalizeUsageModel("openai_codex", "gpt-6-astra")).toBe("gpt-6-astra");
expect(normalizeUsageModel("acme", "/leading-slash")).toBe("/leading-slash");
});
});
+28
View File
@@ -0,0 +1,28 @@
import { describe, expect, it } from "vitest";
import { usageFormats } from "@/lib/usage-number";
describe("usage number formats", () => {
it("switches to locale units once a count reaches five digits", () => {
const en = usageFormats("en");
const zh = usageFormats("zh-CN");
expect(en.display(10_046_620_708)).toBe("10B");
expect(en.display(69_134)).toBe("69.1K");
expect(en.display(3039)).toBe("3,039");
expect(zh.display(10_046_620_708)).toBe("100.5亿");
expect(zh.display(10_324)).toBe("1万");
expect(zh.display(3039)).toBe("3,039");
});
it("keeps exact digits for titles and accessible labels", () => {
const en = usageFormats("en");
expect(en.exact(10_046_620_708)).toBe("10,046,620,708");
expect(en.exact(0)).toBe("0");
});
it("builds one formatter set per locale", () => {
expect(usageFormats("en")).toBe(usageFormats("en"));
expect(usageFormats("en")).not.toBe(usageFormats("zh-CN"));
expect(usageFormats("en").percent(0.5)).toBe("50%");
expect(usageFormats("en").date("2026-10-27")).toBe("Oct 27");
});
});