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; 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] }[]; modelDays: NonNullable; models?: Usage["providers_30d"]; }) { const { t, i18n } = useTranslation(); const { display, exact, compact, percent, seconds, date: formatDay } = usageFormats(i18n.language); const total = days.reduce((sum, day) => sum + (day.usage?.total_tokens ?? 0), 0); // 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(); 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(); const daily = new Map>(); for (const row of modelDays) { if (!dates.has(row.date) || row.total_tokens <= 0) continue; 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); type Bucket = { tokens: number; measured: number; generationMs: number; ttftMs: number; timed: number; cacheRead: number; cacheObserved: number }; const bucket = daily.get(row.date) ?? new Map(); 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)?.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))], stats: [...stats, { speed: null, ttft: null, hit: null }] }; }); const peak = Math.max(0, ...columns.map(column => column.total)); if (!peak || !series.length) return null; const labels = [...series.map(([, item]) => item.label), otherLabel]; 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
{columns.map(column => column.total === 0 ? ( ) : `${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"> {column.values.map((value, index) => value > 0 && )}
{column.date}
tok/s
TTFT
s
{t("settings.usage.cacheHitRate")}
tokens
{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
{labels[index]}
{speedValue}
{speedUnit}
{ttftValue}
{ttftUnit}
{hit == null ? "—" : percent(hit)}
{display(value)}
; })}
{t("settings.usage.totalTokens", { defaultValue: "Total tokens" })}
{display(column.total)}
{t("settings.usage.requests")}
{display(column.requests)}
)}
{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(model.cache_read_tokens / model.cache_read_observed_input_tokens) : "—"; const parts = [ [t("settings.usage.totalTokens"), `${display(tokens)} (${percent(tokens / total)})`], [t("settings.usage.cacheHitRate"), rate], ]; return `${name}: ${value}`).join(", ")}`} className="flex min-w-0 items-center gap-1.5 rounded-sm focus-visible:outline focus-visible:outline-2 focus-visible:outline-orange-500"> {label}

{label}

{parts.map(([name, value]) =>
{name}
{value}
)}
; })}
; }