Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

UsagePage.tsx

1,499 lines58.4 KB

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