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

UsagePage.tsx

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