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