Open History to see the last commit
1import { ChatGptUsageButton } from "../settings/ChatGptUsageButton";
2import { usesChatGptSharing } from "@t3tools/shared/usageLimits";
3import { RefreshIcon } from "~/components/ui/refresh-icon";
4import { useAtomValue } from "@effect/atom-react";
5import { Atom } from "effect/reactivity";
6import {
7 USAGE_CONTRACT_VERSION,
8 type EnvironmentId,
9 type UsageProviderKind,
10 type UsageSummaryInput,
11} from "@t3tools/contracts";
12import { CircleAlertIcon, ChevronDownIcon, InfoIcon, SlidersHorizontalIcon } from "lucide-react";
13import { useEffect, useEffectEvent, useRef, useState } from "react";
14import { settlePromise } from "@t3tools/client-runtime/state/runtime";
15import * as AsyncResult from "effect/reactivity/AsyncResult";
16import * as Cause from "effect/Cause";
17import { refreshUsageLimits } from "@t3tools/client-runtime/state/usage";
18import {
19 updatingProvidersLabel,
20 usageEnvironmentProgress,
21 usageLoadingState,
22} from "@t3tools/client-runtime/state/usage-progress";
23
24import {
25 isCompatibleUsageContractVersion,
26 isModelCostUnknown,
27 type DailyTotals,
28 type HourlyTotals,
29 type MergedUsage,
30} from "@t3tools/shared/usageMerge";
31
32import { cn } from "../../lib/utils";
33import { usePrimarySettings } from "../../hooks/useSettings";
34import { resolveHour12 } from "../../timestampFormat";
35import { appAtomRegistry } from "~/rpc/atomRegistry";
36import { environmentPresentations } from "../../state/presentation";
37import { primaryServerKeybindingsAtom, serverEnvironment } from "../../state/server";
38import { isCommandPaletteOpen } from "../../commandPaletteBus";
39import { isModelPickerOpen } from "../../modelPickerVisibility";
40import { shortcutLabelForCommand } from "../../keybindings";
41import { useUsage, type EnvironmentUsageStatus } from "../../state/usage";
42import { useAtomCommand } from "../../state/use-atom-command";
43import {
44 enumerateDays,
45 enumerateHourStarts,
46 formatCount,
47 formatDateTimeShort,
48 formatDayShort,
49 formatHourShort,
50 formatPercent,
51 formatTokens,
52 formatUsageContractMismatch,
53 formatUsd,
54 makeWindow,
55 usageSourceMessages,
56} from "@t3tools/shared/usageFormat";
57import { Button, InlineButton } from "../ui/button";
58import { ProviderInstanceIcon } from "../chat/ProviderInstanceIcon";
59import {
60 Menu,
61 MenuCheckboxItem,
62 MenuItem,
63 MenuPopup,
64 MenuSeparator,
65 MenuTrigger,
66} from "../ui/menu";
67import { ScrollArea } from "../ui/scroll-area";
68import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select";
69import { AppRouteModal, AppRouteModalClose } from "../AppRouteModal";
70import { Skeleton } from "../ui/skeleton";
71import { Toggle, ToggleGroup } from "../ui/toggle-group";
72import { Popover, PopoverPopup, PopoverTrigger } from "../ui/popover";
73import {
74 WorkspaceBreadcrumb,
75 WorkspaceBreadcrumbItem,
76 WorkspaceBreadcrumbSeparator,
77 WorkspaceBreadcrumbText,
78} from "../WorkspaceBreadcrumb";
79import { WorkspacePageContainer } from "../WorkspacePageContainer";
80import { UsageLimitsSection } from "./UsageLimits";
81import { UsagePriceOverrides } from "./UsagePriceOverrides";
82import { UsageProviderChart } from "./UsageProviderChart";
83import { SpeedPremium, UsageModelDialog } from "./UsageModelDialog";
84import { UsageShareBar } from "./UsageShareBar";
85import {
86 costTypeSegments,
87 modelShare,
88 sortModelsByTokens,
89 speedCostSegments,
90 tokenTypeSegments,
91} from "./usageBreakdown";
92import {
93 METRIC_OPTIONS,
94 WINDOW_OPTIONS,
95 resolveUsageShortcut,
96 type UsageMetric,
97} from "./usageShortcuts";
98import {
99 PROVIDER_ORDER,
100 PROVIDER_PRESENTATION,
101 providersWithUsage,
102 rankProvidersByMetric,
103} from "./usageProviders";
104import {
105 readUsagePagePreferences,
106 saveUsagePagePreferences,
107 type UsagePagePreferences,
108} from "./usagePagePreferences";
109
110function isUsageMetric(value: string | null | undefined): value is UsageMetric {
111 return METRIC_OPTIONS.some((option) => option.value === value);
112}
113
114function isUsageWindowDays(value: number): value is UsagePagePreferences["windowDays"] {
115 return WINDOW_OPTIONS.some((option) => option.days === value);
116}
117
118const providerLabel = (provider: UsageProviderKind) => PROVIDER_PRESENTATION[provider].label;
119
120function usageLoading(
121 showingKept: boolean,
122 selectedEnvironments: Parameters<typeof usageLoadingState>[0],
123 refreshingUsage: boolean,
124 hiddenProviders: ReadonlySet<UsageProviderKind>,
125) {
126 if (showingKept) {
127 return { partial: true, everyProvider: true, providers: new Set<UsageProviderKind>() };
128 }
129 const state = usageLoadingState(selectedEnvironments, refreshingUsage);
130 const providers = new Set([...state.providers].filter((p) => !hiddenProviders.has(p)));
131 return {
132 partial: state.everyProvider || providers.size > 0,
133 everyProvider: state.everyProvider,
134 providers,
135 };
136}
137
138/** Keep dialog selection outside UsagePage so opening/closing rerenders only its host. */
139const selectedUsageModelKeyAtom = Atom.make<string | null>(null).pipe(
140 Atom.keepAlive,
141 Atom.withLabel("usage:selected-model-key"),
142);
143
144function selectUsageModel(key: string | null): void {
145 appAtomRegistry.set(selectedUsageModelKeyAtom, key);
146}
147
148function UsageModelDialogHost({
149 models,
150 onSetPrice,
151 ...dialogProps
152}: Omit<Parameters<typeof UsageModelDialog>[0], "model" | "onSetPrice" | "onClose"> & {
153 readonly models: MergedUsage["models"];
154 readonly onSetPrice: (model: string) => void;
155}) {
156 const selectedKey = useAtomValue(selectedUsageModelKeyAtom);
157 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- clears the shared selected-model atom on unmount
158 useEffect(() => () => selectUsageModel(null), []);
159 const model =
160 selectedKey === null
161 ? undefined
162 : models.find((candidate) => `${candidate.provider}:${candidate.model}` === selectedKey);
163 if (model === undefined) return null;
164 return (
165 <UsageModelDialog
166 {...dialogProps}
167 model={model}
168 onSetPrice={() => {
169 selectUsageModel(null);
170 onSetPrice(model.model);
171 }}
172 onClose={() => selectUsageModel(null)}
173 />
174 );
175}
176
177export function UsagePage() {
178 const [preferences, setPreferences] = useState(readUsagePagePreferences);
179 const keybindings = useAtomValue(primaryServerKeybindingsAtom);
180 const hour12 = usePrimarySettings((settings) => resolveHour12(settings.timestampFormat));
181 const shortcutTitle = (
182 option: (typeof METRIC_OPTIONS)[number] | (typeof WINDOW_OPTIONS)[number],
183 ) => {
184 const shortcut = shortcutLabelForCommand(keybindings, option.command, {
185 context: { usagePageOpen: true },
186 });
187 return shortcut ? `${option.label} (${shortcut})` : option.label;
188 };
189 const [windowSelection, setWindowSelection] = useState(() => ({
190 days: preferences.windowDays,
191 window: makeWindow(
192 preferences.windowDays,
193 undefined,
194 preferences.windowDays === 1 ? "hour" : "day",
195 ),
196 }));
197 const metric = preferences.metric;
198 const showingLimits = metric === "limits";
199 const [isRefreshing, setIsRefreshing] = useState(false);
200 const [limitsNow, setLimitsNow] = useState(() => Date.now());
201 const refreshingRef = useRef(false);
202 const [priceDialog, setPriceDialog] = useState<{ readonly model?: string } | null>(null);
203 const [selectedEnvironmentIds, setSelectedEnvironmentIds] =
204 useState<ReadonlySet<EnvironmentId> | null>(null);
205 const hiddenProviders = new Set(preferences.hiddenProviders);
206 const { days: windowDays, window } = windowSelection;
207 const isPast24Hours = windowDays === 1;
208 const {
209 merged: answeredUsage,
210 environments,
211 selectedEnvironments,
212 shown,
213 isPartial,
214 refresh,
215 } = useUsage(window, selectedEnvironmentIds, hiddenProviders);
216 const merged = shown?.merged ?? answeredUsage;
217 const shownWindow = shown?.window ?? window;
218 const shownHourly = shownWindow.resolution === "hour";
219 const refreshingUsage = isRefreshing && !showingLimits;
220 const showingKept = shown !== null && shown.window !== window;
221 const presentations = useAtomValue(environmentPresentations.presentationsAtom);
222 const presentationsWithProviders = useAtomValue(
223 environmentPresentations.presentationsWithProvidersAtom,
224 );
225 const refreshProviders = useAtomCommand(serverEnvironment.refreshProviders, {
226 reportFailure: false,
227 });
228
229 const canReadDiagnostics = selectedEnvironments.some(
230 (environment) => environment.canReadDiagnostics,
231 );
232
233 const updatePreferences = (patch: Partial<UsagePagePreferences>) => {
234 const nextPreferences = { ...preferences, ...patch };
235 setPreferences(nextPreferences);
236 saveUsagePagePreferences(nextPreferences);
237 };
238 const selectWindow = (days: number) => {
239 if (!isUsageWindowDays(days)) return;
240 updatePreferences({ windowDays: days });
241 setWindowSelection({
242 days,
243 window: makeWindow(days, undefined, days === 1 ? "hour" : "day"),
244 });
245 };
246 const selectMetric = (nextMetric: UsageMetric) => {
247 if (nextMetric === "limits") setLimitsNow(Date.now());
248 updatePreferences({ metric: nextMetric });
249 };
250 const refreshLimits = (automatic = false) =>
251 // Settled so the timestamp still advances when a refresh throws.
252 settlePromise(() =>
253 Promise.all(
254 Array.from(presentations, ([environmentId, presentation]) => {
255 if (selectedEnvironmentIds !== null && !selectedEnvironmentIds.has(environmentId)) return;
256 if (presentation.connection.phase === "connected" && presentation.serverConfig !== null) {
257 return refreshUsageLimits(
258 environmentId,
259 () => refreshProviders({ environmentId, input: {} }),
260 automatic,
261 );
262 }
263 }),
264 ),
265 ).then((result) => {
266 setLimitsNow(Date.now());
267 if (!AsyncResult.isSuccess(result)) throw Cause.squash(result.cause);
268 });
269 const onUsageKeyDown = useEffectEvent((event: KeyboardEvent) => {
270 if (
271 event.defaultPrevented ||
272 event.repeat ||
273 event.isComposing ||
274 isCommandPaletteOpen() ||
275 isModelPickerOpen()
276 )
277 return;
278
279 const command = resolveUsageShortcut(event, keybindings);
280 const metricOption = METRIC_OPTIONS.find((option) => option.command === command);
281 const periodOption = WINDOW_OPTIONS.find((option) => option.command === command);
282 if (!metricOption && !periodOption) return;
283
284 event.preventDefault();
285 event.stopPropagation();
286 if (metricOption) selectMetric(metricOption.value);
287 if (periodOption && !showingLimits) selectWindow(periodOption.days);
288 });
289
290 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- window capture keydown listener for usage metric and period shortcuts
291 useEffect(() => {
292 globalThis.window.addEventListener("keydown", onUsageKeyDown, true);
293 return () => globalThis.window.removeEventListener("keydown", onUsageKeyDown, true);
294 }, []);
295
296 const refreshWindow = () => {
297 if (refreshingRef.current) return;
298
299 if (showingLimits) {
300 refreshingRef.current = true;
301 setIsRefreshing(true);
302 void refreshLimits().finally(() => {
303 refreshingRef.current = false;
304 setIsRefreshing(false);
305 });
306 return;
307 }
308 const nextWindow = makeWindow(windowDays, undefined, isPast24Hours ? "hour" : "day");
309 if (
310 nextWindow.sinceDay !== window.sinceDay ||
311 nextWindow.untilDay !== window.untilDay ||
312 nextWindow.sinceTime !== window.sinceTime ||
313 nextWindow.untilTime !== window.untilTime
314 ) {
315 setWindowSelection({ days: windowDays, window: nextWindow });
316 }
317 refreshingRef.current = true;
318 setIsRefreshing(true);
319 void refresh(nextWindow).finally(() => {
320 refreshingRef.current = false;
321 setIsRefreshing(false);
322 });
323 };
324 const connectedLimitsEnvironments = [...presentations]
325 .filter(
326 ([environmentId, presentation]) =>
327 presentation.connection.phase === "connected" &&
328 presentation.serverConfig !== null &&
329 (selectedEnvironmentIds === null || selectedEnvironmentIds.has(environmentId)),
330 )
331 .map(([environmentId]) => environmentId)
332 .sort()
333 .join(",");
334 const autoRefreshLimits = useEffectEvent(() => {
335 void refreshLimits(true);
336 });
337 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- refreshes provider limits from the server when the connected environment set changes
338 useEffect(() => {
339 if (showingLimits && connectedLimitsEnvironments) autoRefreshLimits();
340 }, [showingLimits, connectedLimitsEnvironments]);
341
342 const days = enumerateDays(shownWindow.sinceDay, shownWindow.untilDay);
343 const hours =
344 shownWindow.sinceTime === undefined || shownWindow.untilTime === undefined
345 ? []
346 : enumerateHourStarts(shownWindow.sinceTime, shownWindow.untilTime);
347 const showChatGptSharing =
348 !hiddenProviders.has("codex") &&
349 [...presentationsWithProviders].some(
350 ([id, presentation]) =>
351 (selectedEnvironmentIds === null || selectedEnvironmentIds.has(id)) &&
352 (presentation.serverConfig?.providers ?? []).some(usesChatGptSharing),
353 );
354
355 const windowLabel =
356 shownHourly && shownWindow.sinceTime !== undefined && shownWindow.untilTime !== undefined
357 ? `${formatDateTimeShort(shownWindow.sinceTime, shownWindow.timeZone, hour12)} to ${formatDateTimeShort(shownWindow.untilTime, shownWindow.timeZone, hour12)}`
358 : `${formatDayShort(shownWindow.sinceDay)} to ${formatDayShort(shownWindow.untilDay)}`;
359 const topbarContent = (
360 <div className="grid w-full min-w-0 grid-cols-[minmax(0,1fr)_auto] items-center gap-x-3 py-2 @4xl/usage-header:flex">
361 <WorkspaceBreadcrumb ariaLabel="Usage breadcrumb" className="min-w-0">
362 <WorkspaceBreadcrumbItem>
363 <h1>Usage</h1>
364 </WorkspaceBreadcrumbItem>
365 <WorkspaceBreadcrumbSeparator />
366 <WorkspaceBreadcrumbItem className="min-w-10 shrink">
367 <UsageEnvironmentFilter
368 environments={environments}
369 selectedEnvironments={selectedEnvironments}
370 selectedEnvironmentIds={selectedEnvironmentIds}
371 onSelectionChange={setSelectedEnvironmentIds}
372 showUsageStatus={!showingLimits}
373 refreshing={refreshingUsage}
374 isPartial={isPartial}
375 duplicateSources={merged.duplicateSources}
376 contractMismatches={merged.contractMismatches}
377 onOpenModelPrices={() => setPriceDialog({})}
378 />
379 </WorkspaceBreadcrumbItem>
380 <WorkspaceBreadcrumbSeparator />
381 <WorkspaceBreadcrumbItem current className="min-w-10">
382 <UsageProviderFilter
383 hiddenProviders={hiddenProviders}
384 onChange={(next) => updatePreferences({ hiddenProviders: next })}
385 />
386 </WorkspaceBreadcrumbItem>
387 </WorkspaceBreadcrumb>
388 {!showingLimits ? (
389 <span className="hidden min-w-0 truncate text-xs text-muted-foreground @7xl/usage-header:block">
390 {windowLabel}
391 </span>
392 ) : null}
393 <div className="ms-auto hidden shrink-0 items-center justify-end gap-2 @4xl/usage-header:flex">
394 {/* Limits are always current, so they have no period. The period sits before the metric
395 tabs so dropping it never moves them. */}
396 {showingLimits ? null : (
397 <ToggleGroup
398 aria-label="Usage period"
399 variant="segmented"
400 value={[String(windowDays)]}
401 onValueChange={(next) => {
402 const value = next[0];
403 if (value) selectWindow(Number(value));
404 }}
405 >
406 {WINDOW_OPTIONS.map((option) => (
407 <Toggle key={option.days} value={String(option.days)} title={shortcutTitle(option)}>
408 {option.label}
409 </Toggle>
410 ))}
411 </ToggleGroup>
412 )}
413 <ToggleGroup
414 aria-label="Usage metric"
415 variant="segmented"
416 value={[metric]}
417 onValueChange={(next) => {
418 const value = next[0];
419 if (isUsageMetric(value)) selectMetric(value);
420 }}
421 >
422 {METRIC_OPTIONS.map((option) => (
423 <Toggle key={option.value} value={option.value} title={shortcutTitle(option)}>
424 {option.label}
425 </Toggle>
426 ))}
427 </ToggleGroup>
428 <Button
429 onClick={refreshWindow}
430 aria-label={showingLimits ? "Refresh limits" : "Refresh usage"}
431 aria-busy={isRefreshing}
432 disabled={isRefreshing || (!showingLimits && !canReadDiagnostics)}
433 size="icon-sm"
434 variant="ghost"
435 >
436 <RefreshIcon size="sm" refreshing={isRefreshing} />
437 </Button>
438 </div>
439 <div className="ms-auto flex shrink-0 items-center justify-end gap-1 @4xl/usage-header:hidden">
440 {showingLimits ? null : (
441 <Select value={String(windowDays)} onValueChange={(value) => selectWindow(Number(value))}>
442 <SelectTrigger
443 aria-label="Usage period"
444 size="compact"
445 variant="ghost"
446 className="w-auto min-w-0"
447 >
448 <SelectValue>
449 {WINDOW_OPTIONS.find((option) => option.days === windowDays)?.label}
450 </SelectValue>
451 </SelectTrigger>
452 <SelectPopup align="end" alignItemWithTrigger={false}>
453 {WINDOW_OPTIONS.map((option) => (
454 <SelectItem
455 key={option.days}
456 value={String(option.days)}
457 title={shortcutTitle(option)}
458 >
459 {option.label}
460 </SelectItem>
461 ))}
462 </SelectPopup>
463 </Select>
464 )}
465 <Select
466 value={metric}
467 onValueChange={(value) => {
468 if (isUsageMetric(value)) selectMetric(value);
469 }}
470 >
471 <SelectTrigger
472 aria-label="Usage metric"
473 size="compact"
474 variant="ghost"
475 className="w-auto min-w-0"
476 >
477 <SelectValue>
478 {METRIC_OPTIONS.find((option) => option.value === metric)?.label}
479 </SelectValue>
480 </SelectTrigger>
481 <SelectPopup align="end" alignItemWithTrigger={false}>
482 {METRIC_OPTIONS.map((option) => (
483 <SelectItem key={option.value} value={option.value} title={shortcutTitle(option)}>
484 {option.label}
485 </SelectItem>
486 ))}
487 </SelectPopup>
488 </Select>
489 <Button
490 onClick={refreshWindow}
491 aria-label={showingLimits ? "Refresh limits" : "Refresh usage"}
492 aria-busy={isRefreshing}
493 disabled={isRefreshing || (!showingLimits && !canReadDiagnostics)}
494 size="icon-sm"
495 variant="ghost"
496 >
497 <RefreshIcon size="sm" refreshing={isRefreshing} />
498 </Button>
499 </div>
500 </div>
501 );
502
503 return (
504 <AppRouteModal label="Usage">
505 <div className="flex min-h-0 min-w-0 flex-1 flex-col">
506 <header className="@container/usage-header flex min-h-12 shrink-0 items-center gap-1 border-b ps-5 pe-2">
507 {topbarContent}
508 <AppRouteModalClose />
509 </header>
510
511 <ScrollArea className="min-h-0 flex-1">
512 <WorkspacePageContainer width="wide">
513 {selectedEnvironments.length === 0 ? (
514 <p className="text-sm text-muted-foreground">
515 {environments.length === 0
516 ? `Connect an environment to see ${showingLimits ? "limits" : "usage"}.`
517 : `Select an environment to see ${showingLimits ? "limits" : "usage"}.`}
518 </p>
519 ) : showingLimits ? (
520 <UsageLimitsSection
521 selectedEnvironmentIds={selectedEnvironmentIds}
522 hiddenProviders={hiddenProviders}
523 now={limitsNow}
524 />
525 ) : shown === null ? (
526 <UsageSkeleton />
527 ) : !canReadDiagnostics ? (
528 <div className="space-y-2 py-12 text-center text-sm text-muted-foreground">
529 {selectedEnvironments.map((environment) => (
530 <p key={environment.environmentId}>
531 {selectedEnvironments.length > 1 ? `${environment.label}: ` : null}
532 {environment.error}
533 </p>
534 ))}
535 </div>
536 ) : (
537 <UsageOverview
538 merged={merged}
539 shownWindow={shownWindow}
540 hour12={hour12}
541 days={days}
542 hours={hours}
543 showingKept={showingKept}
544 metric={metric === "tokens" ? "tokens" : "cost"}
545 selectedEnvironments={selectedEnvironments}
546 hiddenProviders={hiddenProviders}
547 refreshingUsage={refreshingUsage}
548 showChatGptSharing={showChatGptSharing}
549 onSelectModel={selectUsageModel}
550 />
551 )}
552 </WorkspacePageContainer>
553 </ScrollArea>
554 </div>
555 {showingLimits ? null : (
556 <UsageModelDialogHost
557 models={merged.models}
558 environments={selectedEnvironments}
559 metric={metric === "tokens" ? "tokens" : "cost"}
560 chartWindow={{
561 days,
562 hours,
563 resolution: shownHourly ? "hour" : "day",
564 timeZone: shownWindow.timeZone,
565 referenceTime: shownWindow.untilTime,
566 hour12,
567 }}
568 onSetPrice={(model) => setPriceDialog({ model })}
569 />
570 )}
571 {priceDialog ? (
572 <UsagePriceOverrides
573 usage={environments}
574 initialSelectedEnvironmentIds={selectedEnvironmentIds}
575 initialModel={priceDialog.model}
576 onOpenChange={(open) => {
577 if (!open) setPriceDialog(null);
578 }}
579 />
580 ) : null}
581 </AppRouteModal>
582 );
583}
584
585function UsageOverview({
586 merged,
587 shownWindow,
588 hour12,
589 days,
590 hours,
591 showingKept,
592 metric,
593 selectedEnvironments,
594 hiddenProviders,
595 refreshingUsage,
596 showChatGptSharing,
597 onSelectModel,
598}: {
599 readonly merged: MergedUsage;
600 readonly shownWindow: UsageSummaryInput;
601 readonly hour12: boolean;
602 readonly days: readonly string[];
603 readonly hours: readonly string[];
604 readonly showingKept: boolean;
605 readonly metric: "tokens" | "cost";
606 readonly selectedEnvironments: readonly EnvironmentUsageStatus[];
607 readonly hiddenProviders: ReadonlySet<UsageProviderKind>;
608 readonly refreshingUsage: boolean;
609 readonly showChatGptSharing: boolean;
610 readonly onSelectModel: (key: string) => void;
611}) {
612 const [breakdown, setBreakdown] = useState<"model" | "time">("model");
613 const shownHourly = shownWindow.resolution === "hour";
614 const loading = usageLoading(showingKept, selectedEnvironments, refreshingUsage, hiddenProviders);
615 // Copy the primitive; JSX reads of loading.partial would merge all derivations into one compiler cache
616 // scope.
617 const loadingPartial = loading.partial === true;
618 const loadingProviders = new Set(
619 PROVIDER_ORDER.filter((provider) => loading.everyProvider || loading.providers.has(provider)),
620 );
621 const providersWithData = new Set(providersWithUsage(merged.providers));
622 // Only loading.providers excludes hidden providers without data. Filter a fresh array so the compiler can
623 // cache independently.
624 const activeProviders = [...PROVIDER_ORDER].filter(
625 (provider) => providersWithData.has(provider) || loading.providers.has(provider),
626 );
627 const chartLoadingProviders = new Set(
628 activeProviders.filter((provider) => loadingProviders.has(provider)),
629 );
630 const sourceMessages = usageSourceMessages(
631 selectedEnvironments.flatMap(
632 (environment) =>
633 environment.summary?.sources.filter(
634 (source) => !hiddenProviders.has(source.fingerprint.provider),
635 ) ?? [],
636 ),
637 );
638 const breakdownPeriods: readonly (DailyTotals | HourlyTotals)[] = (
639 shownHourly ? merged.hourly : merged.daily
640 ).toReversed();
641 const breakdownModels =
642 breakdown === "model" && metric === "tokens"
643 ? sortModelsByTokens(merged.models)
644 : merged.models;
645 const breakdownPeak = breakdownModels.reduce(
646 (peak, model) => Math.max(peak, metric === "tokens" ? model.totalTokens : model.costUsd),
647 0,
648 );
649 const rankedProviders = rankProvidersByMetric(activeProviders, merged.providers, metric);
650
651 return (
652 <div aria-busy={loadingPartial} className="flex flex-col gap-6">
653 {sourceMessages.map((message) => (
654 <p key={message} className="mb-4 text-sm text-muted-foreground">
655 {message}
656 </p>
657 ))}
658 <section className="grid gap-6 lg:grid-cols-[minmax(0,18rem)_minmax(0,1fr)]">
659 <div className="flex min-w-0 flex-col gap-5">
660 <div className="flex flex-col gap-1">
661 <span
662 className={cn(
663 "text-4xl font-semibold text-foreground tabular-nums",
664 figureClass(loadingPartial),
665 )}
666 >
667 {metric === "cost" ? formatUsd(merged.costUsd) : formatTokens(merged.totalTokens)}
668 </span>
669 <span className="inline-flex items-center gap-1 text-xs text-muted-foreground">
670 <span>
671 <span className={figureClass(loadingPartial)}>
672 {formatCount(merged.sessions)} sessions
673 </span>
674 {metric === "cost" && " · API estimate"}
675 </span>
676 {metric === "cost" && merged.costQuality.unpricedShare > 0 && (
677 <Popover>
678 <PopoverTrigger
679 openOnHover
680 render={<InlineButton tone="muted" />}
681 aria-label="Unpriced usage details"
682 >
683 <InfoIcon className="size-3" aria-hidden />
684 </PopoverTrigger>
685 <PopoverPopup side="top" tooltipStyle>
686 API estimate excludes {formatPercent(merged.costQuality.unpricedShare)} unpriced
687 records.
688 </PopoverPopup>
689 </Popover>
690 )}
691 </span>
692 </div>
693
694 {showChatGptSharing ? (
695 <div className="flex items-center justify-between gap-2 text-xs text-muted-foreground">
696 <span>ChatGPT shared usage</span>
697 <ChatGptUsageButton size="xs" />
698 </div>
699 ) : null}
700
701 {rankedProviders.map((provider) => {
702 const totals = merged.providers.find((entry) => entry.provider === provider);
703 const share = metric === "cost" ? (totals?.costShare ?? 0) : (totals?.tokenShare ?? 0);
704 const providerSessions = totals?.sessions ?? 0;
705 const sessionLabel = `${formatCount(providerSessions)} ${
706 providerSessions === 1 ? "session" : "sessions"
707 }`;
708 const providerLoading = loadingProviders.has(provider);
709 const awaitingData = providerLoading && !providersWithData.has(provider);
710 return (
711 <div key={provider} className="flex flex-col gap-1">
712 <div className="flex items-baseline justify-between gap-4">
713 <span className="flex min-w-0 items-center gap-2 text-sm text-foreground">
714 <span
715 aria-hidden
716 className="size-2 shrink-0 rounded-full"
717 style={{
718 backgroundColor: PROVIDER_PRESENTATION[provider].color,
719 }}
720 />
721 <ProviderMark provider={provider} className="size-4" />
722 <span className="flex min-w-0 items-baseline gap-1.5">
723 <span className="truncate">{PROVIDER_PRESENTATION[provider].label}</span>
724 <span
725 className={cn(
726 "shrink-0 whitespace-nowrap text-2xs text-muted-foreground tabular-nums",
727 figureClass(providerLoading),
728 awaitingData && "invisible",
729 )}
730 >
731 {sessionLabel}
732 </span>
733 </span>
734 </span>
735 <span
736 className={cn(
737 "shrink-0 text-sm font-medium text-foreground tabular-nums",
738 figureClass(providerLoading),
739 )}
740 >
741 {awaitingData
742 ? "-"
743 : metric === "cost"
744 ? formatUsd(totals?.costUsd ?? 0)
745 : formatTokens(totals?.totalTokens ?? 0)}
746 </span>
747 </div>
748 <span
749 className={cn(
750 "text-xs text-muted-foreground",
751 figureClass(providerLoading),
752 awaitingData && "invisible",
753 )}
754 >
755 {metric === "cost"
756 ? `${formatPercent(share)} of cost · ${formatTokens(totals?.totalTokens ?? 0)} tokens`
757 : `${formatPercent(share)} of tokens · ${formatUsd(totals?.costUsd ?? 0)}`}
758 </span>
759 </div>
760 );
761 })}
762 </div>
763
764 <div className="flex min-w-0 flex-col gap-3">
765 <h2 className="text-sm font-medium text-foreground">
766 {shownHourly ? "Hourly" : "Daily"} {metric === "tokens" ? "processed tokens" : "cost"}
767 </h2>
768 <UsageProviderChart
769 providers={activeProviders}
770 loadingProviders={chartLoadingProviders}
771 days={days}
772 daily={merged.daily}
773 hours={hours}
774 hourly={merged.hourly}
775 metric={metric}
776 referenceTime={shownWindow.untilTime}
777 resolution={shownHourly ? "hour" : "day"}
778 timeZone={shownWindow.timeZone}
779 hour12={hour12}
780 />
781 </div>
782 </section>
783
784 <section className="flex flex-col gap-2">
785 <h2 className="text-sm font-medium text-foreground">Totals</h2>
786 <div className="grid grid-cols-2 gap-x-6 gap-y-4 py-1 md:grid-cols-5">
787 <Metric
788 loading={loadingPartial}
789 label="Processed tokens"
790 value={formatTokens(merged.totalTokens)}
791 />
792 <Metric
793 loading={loadingPartial}
794 label="Cached input"
795 value={formatTokens(merged.cachedInputTokens)}
796 />
797 <Metric
798 loading={loadingPartial}
799 label="Uncached input"
800 value={formatTokens(merged.uncachedInputTokens)}
801 />
802 <Metric
803 loading={loadingPartial}
804 label="Output"
805 value={formatTokens(merged.outputTokens)}
806 />
807 <Metric
808 loading={loadingPartial}
809 label="Cache savings"
810 value={formatUsd(merged.costQuality.cacheSavingsUsd)}
811 />
812 </div>
813 </section>
814
815 {merged.totalTokens > 0 ? (
816 <section
817 className={cn("grid gap-x-12 gap-y-8 lg:grid-cols-2", figureClass(loadingPartial))}
818 >
819 {metric === "tokens" ? (
820 <UsageShareBar
821 label="Tokens by type"
822 segments={tokenTypeSegments(merged)}
823 format={formatTokens}
824 />
825 ) : (
826 <>
827 <UsageShareBar
828 label="Cost by type"
829 segments={costTypeSegments(merged.categoryCost)}
830 format={formatUsd}
831 />
832 {merged.speedCost.fast + merged.speedCost.ultrafast > 0 ? (
833 <UsageShareBar
834 label="Cost by speed"
835 segments={speedCostSegments(merged.speedCost)}
836 format={formatUsd}
837 aside={<SpeedPremium premiumUsd={merged.speedCost.premium} />}
838 />
839 ) : null}
840 </>
841 )}
842 </section>
843 ) : null}
844
845 <section className="flex flex-col gap-3">
846 <div className="flex items-center justify-between gap-3">
847 <h2 className="text-sm font-medium text-foreground">Breakdown</h2>
848 <ToggleGroup
849 aria-label="Usage breakdown"
850 variant="segmented"
851 value={[breakdown]}
852 onValueChange={(next) => {
853 const value = next[0];
854 if (value === "model" || value === "time") setBreakdown(value);
855 }}
856 >
857 {(
858 [
859 { value: "model", label: "Model" },
860 { value: "time", label: shownHourly ? "Hour" : "Day" },
861 ] as const
862 ).map((option) => (
863 <Toggle key={option.value} value={option.value}>
864 {option.label}
865 </Toggle>
866 ))}
867 </ToggleGroup>
868 </div>
869
870 {breakdown === "model" ? (
871 <table className="w-full text-sm">
872 <thead>
873 <tr className="border-b border-border text-right text-xs text-muted-foreground">
874 <th className="py-2 pr-3 pl-2 text-left font-normal">#</th>
875 <th className="w-full py-2 text-left font-normal">Model</th>
876 <th className="py-2 pl-6 font-normal">Cost</th>
877 <th className="hidden py-2 pl-6 font-normal sm:table-cell">Share</th>
878 <th className="py-2 pr-2 pl-6 font-normal">Tokens</th>
879 </tr>
880 </thead>
881 <tbody>
882 {breakdownModels.length === 0 ? (
883 <tr>
884 <td colSpan={5} className="py-6 text-center text-muted-foreground">
885 No activity in this window.
886 </td>
887 </tr>
888 ) : (
889 breakdownModels.map((model, index) => {
890 const key = `${model.provider}:${model.model}`;
891 const value = metric === "tokens" ? model.totalTokens : model.costUsd;
892 const hasBar = value > 0 && breakdownPeak > 0;
893 const share = modelShare(model, metric === "tokens" ? "tokens" : "cost");
894 const rowFigures = figureClass(loadingProviders.has(model.provider));
895 return (
896 <tr
897 key={key}
898 className="relative border-b border-border/50 text-right whitespace-nowrap text-muted-foreground tabular-nums transition-colors hover:bg-muted/50 has-focus-visible:bg-muted/50"
899 >
900 <td className="py-2.5 pr-3 pl-2 text-left text-xs">{index + 1}</td>
901 <td className="py-2.5 text-left whitespace-normal">
902 <button
903 type="button"
904 onClick={() => onSelectModel(key)}
905 className={cn(
906 "flex items-center gap-2 text-left text-foreground outline-none after:absolute after:inset-0",
907 !hasBar && "py-1",
908 )}
909 >
910 <ProviderMark provider={model.provider} className="size-3.5" />
911 {model.model}
912 </button>
913 {hasBar ? (
914 <div aria-hidden className={cn("mt-1.5 h-0.5 max-w-48", rowFigures)}>
915 <div
916 className="h-full rounded-full"
917 style={{
918 width: `max(0.5rem, ${(value / breakdownPeak) * 100}%)`,
919 backgroundColor: PROVIDER_PRESENTATION[model.provider].color,
920 }}
921 />
922 </div>
923 ) : null}
924 </td>
925 <td className={cn("py-2.5 pl-6 text-foreground", rowFigures)}>
926 {isModelCostUnknown(model) ? (
927 <span className="text-muted-foreground">Unpriced</span>
928 ) : (
929 formatUsd(model.costUsd)
930 )}
931 </td>
932 <td className={cn("hidden py-2.5 pl-6 sm:table-cell", rowFigures)}>
933 {share === null ? "" : formatPercent(share)}
934 </td>
935 <td className={cn("py-2.5 pr-2 pl-6", rowFigures)}>
936 {formatTokens(model.totalTokens)}
937 </td>
938 </tr>
939 );
940 })
941 )}
942 </tbody>
943 </table>
944 ) : (
945 <div
946 className="overflow-x-auto outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring"
947 role="region"
948 aria-label="Usage breakdown by time"
949 tabIndex={0}
950 >
951 <table className="w-full text-sm whitespace-nowrap">
952 <colgroup>
953 <col className="w-2/5" />
954 </colgroup>
955 <thead>
956 <tr className="border-b border-border text-left text-xs text-muted-foreground">
957 <th className="py-2 pl-2 font-normal">{shownHourly ? "Hour" : "Day"}</th>
958 {activeProviders.map((provider) => (
959 <th key={provider} className="py-2 pl-4 text-right font-normal">
960 {PROVIDER_PRESENTATION[provider].label}
961 </th>
962 ))}
963 <th className="py-2 pl-4 text-right font-normal">Total</th>
964 <th className="py-2 pr-2 pl-4 text-right font-normal">Tokens</th>
965 </tr>
966 </thead>
967 <tbody>
968 {breakdownPeriods.length === 0 ? (
969 <tr>
970 <td
971 colSpan={activeProviders.length + 3}
972 className="py-6 text-center text-muted-foreground"
973 >
974 No activity in this window.
975 </td>
976 </tr>
977 ) : (
978 breakdownPeriods.map((period) => (
979 <tr
980 key={"hourStart" in period ? period.hourStart : period.day}
981 className="border-b border-border/50 transition-colors hover:bg-muted/50"
982 >
983 <td className="py-2 pl-2 text-foreground">
984 {"hourStart" in period
985 ? formatHourShort(period.hourStart, shownWindow.timeZone, hour12)
986 : formatDayShort(period.day)}
987 </td>
988 {activeProviders.map((provider) => (
989 <td
990 key={provider}
991 className={cn(
992 "py-2 pl-4 text-right text-muted-foreground tabular-nums",
993 figureClass(loadingProviders.has(provider)),
994 )}
995 >
996 {formatUsd(period.byProvider.get(provider)?.costUsd ?? 0)}
997 </td>
998 ))}
999 <td
1000 className={cn(
1001 "py-2 pl-4 text-right text-foreground tabular-nums",
1002 figureClass(loadingPartial),
1003 )}
1004 >
1005 {formatUsd(period.costUsd)}
1006 </td>
1007 <td
1008 className={cn(
1009 "py-2 pr-2 pl-4 text-right text-muted-foreground tabular-nums",
1010 figureClass(loadingPartial),
1011 )}
1012 >
1013 {formatTokens(period.totalTokens)}
1014 </td>
1015 </tr>
1016 ))
1017 )}
1018 </tbody>
1019 </table>
1020 </div>
1021 )}
1022 </section>
1023 </div>
1024 );
1025}
1026
1027function ProviderMark({
1028 provider,
1029 className,
1030}: {
1031 readonly provider: UsageProviderKind;
1032 readonly className: string;
1033}) {
1034 const presentation = PROVIDER_PRESENTATION[provider];
1035 return (
1036 <ProviderInstanceIcon
1037 driverKind={presentation.driverKind}
1038 displayName={presentation.label}
1039 iconClassName={className}
1040 />
1041 );
1042}
1043
1044function figureClass(loading: boolean) {
1045 return cn("transition-opacity", loading && "opacity-40 delay-150");
1046}
1047
1048function Metric({
1049 label,
1050 value,
1051 loading,
1052}: {
1053 readonly label: string;
1054 readonly value: string;
1055 readonly loading: boolean;
1056}) {
1057 return (
1058 <div className="flex min-w-0 flex-col gap-0.5">
1059 <span className="text-xs text-muted-foreground">{label}</span>
1060 <span
1061 className={cn("text-base font-medium text-foreground tabular-nums", figureClass(loading))}
1062 >
1063 {value}
1064 </span>
1065 </div>
1066 );
1067}
1068
1069function UsageCoverageNotice({
1070 environments,
1071 duplicateSources,
1072 contractMismatches,
1073}: {
1074 readonly environments: readonly EnvironmentUsageStatus[];
1075 readonly duplicateSources: readonly string[];
1076 readonly contractMismatches: MergedUsage["contractMismatches"];
1077}) {
1078 const failed = environments.filter((environment) => environment.error !== null);
1079 const mismatchByEnvironment = new Map(
1080 contractMismatches.map((mismatch) => [mismatch.environmentId, mismatch]),
1081 );
1082 const incompatible = environments.flatMap((environment) => {
1083 const mismatch = mismatchByEnvironment.get(environment.environmentId);
1084 return mismatch === undefined ? [] : [{ environment, mismatch }];
1085 });
1086 if (failed.length === 0 && incompatible.length === 0 && duplicateSources.length === 0) {
1087 return null;
1088 }
1089
1090 return (
1091 <div className="flex flex-col gap-1 border-t border-border px-2 py-2 text-xs text-muted-foreground">
1092 {failed.map((environment) => (
1093 <span key={environment.label}>
1094 {environment.label}: {environment.error}
1095 </span>
1096 ))}
1097 {incompatible.map(({ environment, mismatch }) => (
1098 <span key={environment.environmentId}>
1099 {formatUsageContractMismatch(environment.label, mismatch)}
1100 </span>
1101 ))}
1102 {duplicateSources.length > 0 ? (
1103 <span>
1104 Counted once across environments sharing a transcript directory:{" "}
1105 {duplicateSources.join(", ")}
1106 </span>
1107 ) : null}
1108 </div>
1109 );
1110}
1111
1112function UsageEnvironmentFilter({
1113 environments,
1114 selectedEnvironments,
1115 selectedEnvironmentIds,
1116 onSelectionChange,
1117 showUsageStatus,
1118 refreshing,
1119 isPartial,
1120 duplicateSources,
1121 contractMismatches,
1122 onOpenModelPrices,
1123}: {
1124 readonly environments: readonly EnvironmentUsageStatus[];
1125 readonly selectedEnvironments: readonly EnvironmentUsageStatus[];
1126 readonly selectedEnvironmentIds: ReadonlySet<EnvironmentId> | null;
1127 readonly onSelectionChange: (ids: ReadonlySet<EnvironmentId> | null) => void;
1128 readonly showUsageStatus: boolean;
1129 readonly refreshing: boolean;
1130 readonly isPartial: boolean;
1131 readonly duplicateSources: readonly string[];
1132 readonly contractMismatches: MergedUsage["contractMismatches"];
1133 readonly onOpenModelPrices: () => void;
1134}) {
1135 const allSelected = selectedEnvironmentIds === null;
1136 const label = allSelected
1137 ? "All environments"
1138 : selectedEnvironments.length === 1
1139 ? selectedEnvironments[0]!.label
1140 : `${selectedEnvironments.length} environments`;
1141 const hasIssue =
1142 selectedEnvironments.some((environment) => environment.error !== null) ||
1143 contractMismatches.length > 0;
1144
1145 return (
1146 <Menu>
1147 <MenuTrigger render={<InlineButton />} className="group/usage-environment min-w-0 max-w-full">
1148 <WorkspaceBreadcrumbText>{label}</WorkspaceBreadcrumbText>
1149 <span className="flex size-3.5 shrink-0 items-center justify-center text-muted-foreground">
1150 {showUsageStatus && hasIssue ? (
1151 <CircleAlertIcon
1152 className="size-3.5 text-warning-foreground"
1153 aria-label="Some environments could not report usage"
1154 />
1155 ) : (
1156 <ChevronDownIcon
1157 className="size-3.5 opacity-60 transition-opacity group-hover/usage-environment:opacity-100 group-focus-visible/usage-environment:opacity-100 group-data-popup-open/usage-environment:opacity-100"
1158 aria-hidden
1159 />
1160 )}
1161 </span>
1162 </MenuTrigger>
1163 <MenuPopup align="start">
1164 <MenuCheckboxItem
1165 checked={allSelected}
1166 closeOnClick={false}
1167 onCheckedChange={(checked) => onSelectionChange(checked ? null : new Set())}
1168 >
1169 All environments
1170 </MenuCheckboxItem>
1171 <MenuSeparator />
1172 {environments.map((environment) => {
1173 const checked =
1174 selectedEnvironmentIds === null ||
1175 selectedEnvironmentIds.has(environment.environmentId);
1176 const progress = usageEnvironmentProgress(environment, refreshing);
1177 const status =
1178 environment.error !== null
1179 ? "Unavailable"
1180 : environment.summary !== null &&
1181 !isCompatibleUsageContractVersion(
1182 environment.summary.contractVersion,
1183 USAGE_CONTRACT_VERSION,
1184 )
1185 ? "Update required"
1186 : !environment.isConnected
1187 ? "Connecting…"
1188 : progress.phase === "loading"
1189 ? "Scanning…"
1190 : progress.phase === "stale"
1191 ? "Refreshing…"
1192 : progress.phase === "partway"
1193 ? updatingProvidersLabel(progress.providers, providerLabel)
1194 : "Ready";
1195 return (
1196 <MenuCheckboxItem
1197 key={environment.environmentId}
1198 checked={checked}
1199 closeOnClick={false}
1200 onCheckedChange={(nextChecked) => {
1201 const next = new Set(selectedEnvironments.map((entry) => entry.environmentId));
1202 if (nextChecked) next.add(environment.environmentId);
1203 else next.delete(environment.environmentId);
1204 onSelectionChange(next.size === environments.length ? null : next);
1205 }}
1206 >
1207 <span className="flex min-w-0 items-center gap-3">
1208 <span className="min-w-0 flex-1 truncate">{environment.label}</span>
1209 {showUsageStatus ? (
1210 <span
1211 className={cn(
1212 "shrink-0 text-xs text-muted-foreground",
1213 environment.error !== null && "text-destructive",
1214 )}
1215 >
1216 {status}
1217 </span>
1218 ) : null}
1219 </span>
1220 </MenuCheckboxItem>
1221 );
1222 })}
1223 {environments.length === 0 ? (
1224 <p className="px-2 py-2 text-xs text-muted-foreground">No environments connected.</p>
1225 ) : null}
1226 {showUsageStatus && isPartial ? (
1227 <p className="px-2 py-2 text-xs text-muted-foreground">
1228 Totals are partial while selected environments scan.
1229 </p>
1230 ) : null}
1231 {showUsageStatus ? (
1232 <UsageCoverageNotice
1233 environments={selectedEnvironments}
1234 duplicateSources={duplicateSources}
1235 contractMismatches={contractMismatches}
1236 />
1237 ) : null}
1238 <MenuSeparator />
1239 <MenuItem onClick={onOpenModelPrices}>
1240 <SlidersHorizontalIcon aria-hidden />
1241 Model prices
1242 </MenuItem>
1243 </MenuPopup>
1244 </Menu>
1245 );
1246}
1247
1248function UsageProviderFilter({
1249 hiddenProviders,
1250 onChange,
1251}: {
1252 readonly hiddenProviders: ReadonlySet<UsageProviderKind>;
1253 readonly onChange: (hiddenProviders: readonly UsageProviderKind[]) => void;
1254}) {
1255 const visible = PROVIDER_ORDER.filter((provider) => !hiddenProviders.has(provider));
1256 const label =
1257 visible.length === PROVIDER_ORDER.length
1258 ? "All providers"
1259 : visible.length === 0
1260 ? "No providers"
1261 : visible.length === 1
1262 ? PROVIDER_PRESENTATION[visible[0]!].label
1263 : `${visible.length} providers`;
1264
1265 return (
1266 <Menu>
1267 <MenuTrigger render={<InlineButton />} className="group/usage-provider min-w-0 max-w-full">
1268 <span className="min-w-0 truncate">{label}</span>
1269 <ChevronDownIcon
1270 className="size-3.5 shrink-0 text-muted-foreground opacity-60 transition-opacity group-hover/usage-provider:opacity-100 group-focus-visible/usage-provider:opacity-100 group-data-popup-open/usage-provider:opacity-100"
1271 aria-hidden
1272 />
1273 </MenuTrigger>
1274 <MenuPopup align="start">
1275 <MenuCheckboxItem
1276 checked={hiddenProviders.size === 0}
1277 closeOnClick={false}
1278 onCheckedChange={(checked) => onChange(checked ? [] : PROVIDER_ORDER)}
1279 >
1280 All providers
1281 </MenuCheckboxItem>
1282 <MenuSeparator />
1283 {PROVIDER_ORDER.map((provider) => (
1284 <MenuCheckboxItem
1285 key={provider}
1286 checked={!hiddenProviders.has(provider)}
1287 closeOnClick={false}
1288 onCheckedChange={(checked) =>
1289 onChange(
1290 PROVIDER_ORDER.filter((entry) =>
1291 entry === provider ? !checked : hiddenProviders.has(entry),
1292 ),
1293 )
1294 }
1295 >
1296 <span className="flex min-w-0 items-center gap-2">
1297 <ProviderMark provider={provider} className="size-3.5" />
1298 <span className="truncate">{PROVIDER_PRESENTATION[provider].label}</span>
1299 </span>
1300 </MenuCheckboxItem>
1301 ))}
1302 </MenuPopup>
1303 </Menu>
1304 );
1305}
1306
1307function UsageSkeleton() {
1308 return (
1309 <>
1310 <section className="grid gap-6 lg:grid-cols-[minmax(0,18rem)_minmax(0,1fr)]">
1311 <div className="flex flex-col gap-5">
1312 <div className="flex flex-col gap-1">
1313 <Skeleton className="h-10 w-36" />
1314 <Skeleton className="h-4 w-32" />
1315 </div>
1316 {PROVIDER_ORDER.map((provider) => (
1317 <div key={provider} className="flex flex-col gap-1">
1318 <div className="flex min-h-5 items-center justify-between gap-4">
1319 <span className="flex items-center gap-2">
1320 <Skeleton shape="pill" className="size-2 shrink-0" />
1321 <Skeleton shape="pill" className="size-4 shrink-0" />
1322 <Skeleton className="h-3.5 w-20" />
1323 </span>
1324 <Skeleton className="h-3.5 w-14" />
1325 </div>
1326 <Skeleton className="h-4 w-36" />
1327 </div>
1328 ))}
1329 </div>
1330
1331 <div className="flex flex-col gap-3">
1332 <Skeleton className="h-5 w-24" />
1333 <div className="flex flex-col gap-1">
1334 <Skeleton className="ml-16 h-56" />
1335 <Skeleton className="ml-16 h-4" />
1336 </div>
1337 </div>
1338 </section>
1339
1340 <section className="flex flex-col gap-2">
1341 <h2 className="text-sm font-medium text-foreground">Totals</h2>
1342 <MetricSkeletons
1343 labels={["Processed tokens", "Cached input", "Uncached input", "Output", "Cache savings"]}
1344 />
1345 </section>
1346
1347 <section className="grid gap-x-12 gap-y-8 lg:grid-cols-2">
1348 <div className="flex flex-col gap-2.5">
1349 <Skeleton className="h-5 w-28" />
1350 <Skeleton className="h-2" />
1351 <Skeleton className="h-4 w-72" />
1352 </div>
1353 </section>
1354
1355 <section className="flex flex-col gap-3">
1356 <div className="flex items-center justify-between gap-3">
1357 <h2 className="text-sm font-medium text-foreground">Breakdown</h2>
1358 <Skeleton shape="card" className="h-7 w-28" />
1359 </div>
1360 <Skeleton className="h-44" />
1361 </section>
1362 </>
1363 );
1364}
1365
1366function MetricSkeletons({ labels }: { readonly labels: readonly string[] }) {
1367 return (
1368 <div className="grid grid-cols-2 gap-x-6 gap-y-4 py-1 md:grid-cols-5">
1369 {labels.map((label) => (
1370 <div key={label} className="flex flex-col gap-0.5">
1371 <span className="text-xs text-muted-foreground">{label}</span>
1372 <Skeleton className="h-6 w-16" />
1373 </div>
1374 ))}
1375 </div>
1376 );
1377}