import { useTranslation } from "react-i18next"; import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip"; import type { SettingsPayload } from "@/lib/types"; import { cn } from "@/lib/utils"; import { TokenUsageDetails } from "@/components/settings/TokenUsageDetails"; import { SettingsHint } from "@/components/settings/shared/SettingsHint"; type Usage = NonNullable; 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-neutral-200 dark:bg-neutral-700", "bg-orange-500 dark:bg-orange-400", "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]; 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)]; } function todayInTimeZone(timeZone?: string): string { const now = new Date(); if (timeZone) { try { const parts = new Intl.DateTimeFormat("en", { calendar: "gregory", numberingSystem: "latn", timeZone, year: "numeric", month: "2-digit", day: "2-digit", }).formatToParts(now); const values = Object.fromEntries(parts.map(({ type, value }) => [type, value])); return `${values.year}-${values.month}-${values.day}`; } catch { // Unrecognized configured timezones fall back to UTC. } } return now.toISOString().slice(0, 10); } export function TokenUsageCard({ usage, timeZone }: { usage?: Usage; timeZone?: string }) { const { t, i18n } = useTranslation(); const today = todayInTimeZone(timeZone); const byDate = new Map(usage?.days.map(day => [day.date, day])); const days = Array.from({ length: 30 }, (_, index) => { const date = new Date(`${today}T00:00:00Z`); date.setUTCDate(date.getUTCDate() - 29 + index); const key = date.toISOString().slice(0, 10); 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 segmentLabels = [ t("settings.usage.cachedInput", { defaultValue: "Cached input" }), 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 sourceLabels: Record = { user: t("settings.usage.sources.user", { defaultValue: "Chat" }), api: t("settings.usage.sources.api", { defaultValue: "API" }), cron: t("settings.usage.sources.cron", { defaultValue: "Automations" }), dream: t("settings.usage.sources.dream", { defaultValue: "Memory" }), system: t("settings.usage.sources.system", { defaultValue: "Auxiliary calls" }), other: t("settings.usage.unclassified", { defaultValue: "Unclassified" }), }; const sources = new Map(); for (const day of days) { let classified = 0; for (const [source, value] of Object.entries(day.usage?.sources ?? {})) { const key = SOURCE_KEYS.some(known => known === source) ? source : "other"; sources.set(key, (sources.get(key) ?? 0) + value.total_tokens); classified += value.total_tokens; } const remainder = Math.max(0, (day.usage?.total_tokens ?? 0) - classified); sources.set("other", (sources.get("other") ?? 0) + remainder); } const breakdown = [...sources].filter(([, tokens]) => tokens > 0).sort((a, b) => b[1] - a[1]); return (

{t("settings.usage.shortTitle", { defaultValue: "Token usage" })}

{usage ? compact.format(total) : "—"}

{usage && }
{!usage || total === 0 ? (

{!usage ? t("settings.usage.unavailable", { defaultValue: "Usage data is unavailable." }) : t("settings.usage.noActivity", { defaultValue: "No token usage in the last 30 days." })}

) : ( <>
{compact.format(peak)}
{[0, 1, 2].map(line =>
)}
{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 ; return ( `${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"> {segments.map((value, index) => value > 0 && )}
{day.date}{exact.format(tokens)}
{segments.map((value, index) => (index < 4 || value > 0) &&
{segmentLabels[index]}
{exact.format(value)}
)}
{t("settings.usage.cacheHitRate", { defaultValue: "Cache hit rate" })}
{day.usage?.cache_read_observed_input_tokens ? percent.format(day.usage.cache_read_tokens / day.usage.cache_read_observed_input_tokens) : "—"}
); })}
{formatDate(days[0].date)} {formatDate(days[14].date)} {formatDate(today)}
{segmentLabels.map((label, index) => (index < 4 || hasOtherTokens) && {label})}
{breakdown.map(([source, tokens]) => (
{source === "system" ? ( {sourceLabels[source]} ) : sourceLabels[source]}
{new Intl.NumberFormat(i18n.language, { style: "percent", maximumFractionDigits: 1 }).format(tokens / total)}
))}
)}
); }