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

@@ -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;