Open History to see the last commit
1import { RefreshIcon } from "~/components/ui/refresh-icon";
2import { useAtomValue } from "@effect/atom-react";
3import {
4 USAGE_CONTRACT_VERSION,
5 type EnvironmentId,
6 type UsageProviderKind,
7} from "@t3tools/contracts";
8import {
9 CircleAlertIcon,
10 ChevronDownIcon,
11 CircleDashedIcon,
12 SlidersHorizontalIcon,
13} from "lucide-react";
14import { useMemo, useRef, useState } from "react";
15
16import {
17 isCompatibleUsageContractVersion,
18 type DailyTotals,
19 type HourlyTotals,
20} from "@t3tools/shared/usageMerge";
21
22import { isElectron } from "../../env";
23import { cn } from "../../lib/utils";
24import { environmentPresentations } from "../../state/presentation";
25import { serverEnvironment } from "../../state/server";
26import { useUsage, type EnvironmentUsageStatus } from "../../state/usage";
27import { useAtomCommand } from "../../state/use-atom-command";
28import {
29 enumerateDays,
30 enumerateHourStarts,
31 formatCount,
32 formatDateTimeShort,
33 formatDayShort,
34 formatHourShort,
35 formatPercent,
36 formatTokens,
37 formatUsd,
38 makeWindow,
39} from "@t3tools/shared/usageFormat";
40import { Button } from "../ui/button";
41import {
42 Menu,
43 MenuCheckboxItem,
44 MenuItem,
45 MenuPopup,
46 MenuSeparator,
47 MenuTrigger,
48} from "../ui/menu";
49import { ScrollArea } from "../ui/scroll-area";
50import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select";
51import { SidebarInset } from "../ui/sidebar";
52import { Skeleton } from "../ui/skeleton";
53import { Toggle, ToggleGroup } from "../ui/toggle-group";
54import {
55 WorkspaceBreadcrumb,
56 WorkspaceBreadcrumbItem,
57 WorkspaceBreadcrumbSeparator,
58} from "../WorkspaceBreadcrumb";
59import { WorkspacePageContainer } from "../WorkspacePageContainer";
60import { WorkspacePageHeader } from "../WorkspacePageHeader";
61import { UsageLimitsSection } from "./UsageLimits";
62import { UsagePriceOverrides } from "./UsagePriceOverrides";
63import { UsageProviderChart, type UsageChartMetric } from "./UsageProviderChart";
64import { PROVIDER_ORDER, PROVIDER_PRESENTATION, providersWithUsage } from "./usageProviders";
65import {
66 readUsagePagePreferences,
67 saveUsagePagePreferences,
68 type UsagePagePreferences,
69} from "./usagePagePreferences";
70
71type UsageMetric = UsageChartMetric | "limits";
72const METRIC_OPTIONS = [
73 { value: "cost", label: "Cost" },
74 { value: "tokens", label: "Tokens" },
75 { value: "limits", label: "Limits" },
76] as const satisfies readonly { value: UsageMetric; label: string }[];
77
78function isUsageMetric(value: string | null | undefined): value is UsageMetric {
79 return METRIC_OPTIONS.some((option) => option.value === value);
80}
81
82const WINDOW_OPTIONS = [
83 { days: 1, label: "Past 24h" },
84 { days: 7, label: "7 days" },
85 { days: 30, label: "30 days" },
86 { days: 90, label: "90 days" },
87] as const;
88
89function isUsageWindowDays(value: number): value is UsagePagePreferences["windowDays"] {
90 return WINDOW_OPTIONS.some((option) => option.days === value);
91}
92
93export function UsagePage() {
94 const [preferences, setPreferences] = useState(readUsagePagePreferences);
95 const [windowSelection, setWindowSelection] = useState(() => ({
96 days: preferences.windowDays,
97 window: makeWindow(
98 preferences.windowDays,
99 undefined,
100 preferences.windowDays === 1 ? "hour" : "day",
101 ),
102 }));
103 const metric = preferences.metric;
104 const showingLimits = metric === "limits";
105 const [isRefreshing, setIsRefreshing] = useState(false);
106 const refreshingRef = useRef(false);
107 const [breakdown, setBreakdown] = useState<"model" | "time">("model");
108 const [selectedEnvironmentIds, setSelectedEnvironmentIds] =
109 useState<ReadonlySet<EnvironmentId> | null>(null);
110 const { days: windowDays, window } = windowSelection;
111 const isPast24Hours = windowDays === 1;
112 const { merged, environments, selectedEnvironments, isPending, isPartial, refresh } = useUsage(
113 window,
114 selectedEnvironmentIds,
115 );
116 const presentations = useAtomValue(environmentPresentations.presentationsAtom);
117 const refreshProviders = useAtomCommand(serverEnvironment.refreshProviders, {
118 reportFailure: false,
119 });
120
121 const days = useMemo(
122 () => enumerateDays(window.sinceDay, window.untilDay),
123 [window.sinceDay, window.untilDay],
124 );
125 const hours = useMemo(
126 () =>
127 window.sinceTime === undefined || window.untilTime === undefined
128 ? []
129 : enumerateHourStarts(window.sinceTime, window.untilTime),
130 [window.sinceTime, window.untilTime],
131 );
132 // Newest first: the window can run 90 periods, so the interesting end
133 // belongs at the top of the table.
134 const breakdownPeriods = useMemo<readonly (DailyTotals | HourlyTotals)[]>(
135 () => (isPast24Hours ? merged.hourly : merged.daily).toReversed(),
136 [isPast24Hours, merged.daily, merged.hourly],
137 );
138 const breakdownModels = useMemo(
139 () =>
140 breakdown === "model" && metric === "tokens"
141 ? merged.models.toSorted(
142 (left, right) => right.totalTokens - left.totalTokens || right.costUsd - left.costUsd,
143 )
144 : merged.models,
145 [breakdown, merged.models, metric],
146 );
147 const activeProviders = useMemo(() => providersWithUsage(merged.providers), [merged.providers]);
148 const timeValueColumnWidth = `${60 / (activeProviders.length + 2)}%`;
149
150 const selectWindow = (days: number) => {
151 if (!isUsageWindowDays(days)) return;
152 const nextPreferences = { metric, windowDays: days };
153 setPreferences(nextPreferences);
154 saveUsagePagePreferences(nextPreferences);
155 setWindowSelection({
156 days,
157 window: makeWindow(days, undefined, days === 1 ? "hour" : "day"),
158 });
159 };
160 const selectMetric = (nextMetric: UsageMetric) => {
161 const nextPreferences = { metric: nextMetric, windowDays };
162 setPreferences(nextPreferences);
163 saveUsagePagePreferences(nextPreferences);
164 };
165 const refreshWindow = () => {
166 if (refreshingRef.current) return;
167
168 if (showingLimits) {
169 refreshingRef.current = true;
170 setIsRefreshing(true);
171 void Promise.all(
172 Array.from(presentations, ([environmentId, presentation]) => {
173 if (selectedEnvironmentIds !== null && !selectedEnvironmentIds.has(environmentId)) return;
174 if (presentation.connection.phase === "connected" && presentation.serverConfig !== null) {
175 return refreshProviders({ environmentId, input: {} });
176 }
177 }),
178 ).finally(() => {
179 refreshingRef.current = false;
180 setIsRefreshing(false);
181 });
182 return;
183 }
184 const nextWindow = makeWindow(windowDays, undefined, isPast24Hours ? "hour" : "day");
185 if (
186 nextWindow.sinceDay !== window.sinceDay ||
187 nextWindow.untilDay !== window.untilDay ||
188 nextWindow.sinceTime !== window.sinceTime ||
189 nextWindow.untilTime !== window.untilTime
190 ) {
191 setWindowSelection({ days: windowDays, window: nextWindow });
192 }
193 refreshingRef.current = true;
194 setIsRefreshing(true);
195 void refresh(nextWindow).finally(() => {
196 refreshingRef.current = false;
197 setIsRefreshing(false);
198 });
199 };
200 const windowLabel =
201 isPast24Hours && window.sinceTime !== undefined && window.untilTime !== undefined
202 ? `${formatDateTimeShort(window.sinceTime, window.timeZone)} to ${formatDateTimeShort(window.untilTime, window.timeZone)}`
203 : `${formatDayShort(window.sinceDay)} to ${formatDayShort(window.untilDay)}`;
204 const topbarContent = (
205 <div className="grid w-full min-w-0 grid-cols-[minmax(0,1fr)_auto] items-center gap-x-3 gap-y-2 py-2 xl:flex">
206 <WorkspaceBreadcrumb ariaLabel="Usage breadcrumb" className="col-span-2 min-w-0">
207 <WorkspaceBreadcrumbItem>
208 <h1>Usage</h1>
209 </WorkspaceBreadcrumbItem>
210 <WorkspaceBreadcrumbSeparator />
211 <WorkspaceBreadcrumbItem current className="min-w-10">
212 <UsageEnvironmentFilter
213 environments={environments}
214 selectedEnvironments={selectedEnvironments}
215 selectedEnvironmentIds={selectedEnvironmentIds}
216 onSelectionChange={setSelectedEnvironmentIds}
217 showUsageStatus={!showingLimits}
218 isPartial={isPartial}
219 duplicateSources={merged.duplicateSources}
220 staleEnvironments={merged.staleEnvironments}
221 />
222 </WorkspaceBreadcrumbItem>
223 </WorkspaceBreadcrumb>
224 {!showingLimits ? (
225 <span className="hidden min-w-0 truncate text-xs text-muted-foreground 2xl:block">
226 {windowLabel}
227 </span>
228 ) : null}
229 <div className="ms-auto hidden min-w-0 items-center justify-end gap-2 xl:flex">
230 <ToggleGroup
231 aria-label="Usage metric"
232 variant="segmented"
233 value={[metric]}
234 onValueChange={(next) => {
235 const value = next[0];
236 if (isUsageMetric(value)) selectMetric(value);
237 }}
238 >
239 {METRIC_OPTIONS.map((option) => (
240 <Toggle key={option.value} value={option.value}>
241 {option.label}
242 </Toggle>
243 ))}
244 </ToggleGroup>
245 {/* The period does not apply to Limits, so it stays in place but
246 disabled; unmounting it shifted the metric toggle ~300px. */}
247 <ToggleGroup
248 aria-label="Usage period"
249 variant="segmented"
250 value={[String(windowDays)]}
251 disabled={showingLimits}
252 onValueChange={(next) => {
253 const value = next[0];
254 if (value) selectWindow(Number(value));
255 }}
256 >
257 {WINDOW_OPTIONS.map((option) => (
258 <Toggle key={option.days} value={String(option.days)}>
259 {option.label}
260 </Toggle>
261 ))}
262 </ToggleGroup>
263 <Button
264 onClick={refreshWindow}
265 aria-label={showingLimits ? "Refresh limits" : "Refresh usage"}
266 aria-busy={isRefreshing}
267 disabled={isRefreshing}
268 size="icon-sm"
269 variant="ghost"
270 >
271 <RefreshIcon className="size-3.5" refreshing={isRefreshing} />
272 </Button>
273 </div>
274 <div className="col-span-2 ms-auto flex min-w-0 items-center justify-end gap-1 xl:hidden">
275 <Select
276 value={metric}
277 onValueChange={(value) => {
278 if (isUsageMetric(value)) selectMetric(value);
279 }}
280 >
281 <SelectTrigger
282 aria-label="Usage metric"
283 size="compact"
284 variant="ghost"
285 className="w-auto min-w-0"
286 >
287 <SelectValue>
288 {METRIC_OPTIONS.find((option) => option.value === metric)?.label}
289 </SelectValue>
290 </SelectTrigger>
291 <SelectPopup align="end" alignItemWithTrigger={false}>
292 {METRIC_OPTIONS.map((option) => (
293 <SelectItem key={option.value} value={option.value}>
294 {option.label}
295 </SelectItem>
296 ))}
297 </SelectPopup>
298 </Select>
299 <Select
300 value={String(windowDays)}
301 disabled={showingLimits}
302 onValueChange={(value) => selectWindow(Number(value))}
303 >
304 <SelectTrigger
305 aria-label="Usage period"
306 size="compact"
307 variant="ghost"
308 className="w-auto min-w-0"
309 >
310 <SelectValue>
311 {WINDOW_OPTIONS.find((option) => option.days === windowDays)?.label}
312 </SelectValue>
313 </SelectTrigger>
314 <SelectPopup align="end" alignItemWithTrigger={false}>
315 {WINDOW_OPTIONS.map((option) => (
316 <SelectItem key={option.days} value={String(option.days)}>
317 {option.label}
318 </SelectItem>
319 ))}
320 </SelectPopup>
321 </Select>
322 <Button
323 onClick={refreshWindow}
324 aria-label={showingLimits ? "Refresh limits" : "Refresh usage"}
325 aria-busy={isRefreshing}
326 disabled={isRefreshing}
327 size="icon-sm"
328 variant="ghost"
329 >
330 <RefreshIcon className="size-3.5" refreshing={isRefreshing} />
331 </Button>
332 </div>
333 </div>
334 );
335
336 return (
337 <SidebarInset className="h-dvh min-h-0 overflow-hidden overscroll-y-none bg-background text-foreground isolate">
338 <div className="flex min-h-0 min-w-0 flex-1 flex-col bg-background text-foreground">
339 <WorkspacePageHeader electron={isElectron} className="h-auto">
340 {topbarContent}
341 </WorkspacePageHeader>
342
343 <ScrollArea className="min-h-0 flex-1">
344 <WorkspacePageContainer width="wide">
345 {selectedEnvironments.length === 0 ? (
346 <p className="text-sm text-muted-foreground">
347 {environments.length === 0
348 ? `Connect an environment to see ${showingLimits ? "limits" : "usage"}.`
349 : `Select an environment to see ${showingLimits ? "limits" : "usage"}.`}
350 </p>
351 ) : showingLimits ? (
352 <UsageLimitsSection selectedEnvironmentIds={selectedEnvironmentIds} />
353 ) : isPending ? (
354 <UsageSkeleton />
355 ) : (
356 <>
357 <section className="grid gap-6 lg:grid-cols-[minmax(0,18rem)_minmax(0,1fr)]">
358 <div className="flex min-w-0 flex-col gap-5">
359 <div className="flex flex-col gap-1">
360 <span className="text-4xl font-semibold text-foreground tabular-nums">
361 {metric === "cost"
362 ? formatUsd(merged.costUsd)
363 : formatTokens(merged.totalTokens)}
364 </span>
365 <span className="text-xs text-muted-foreground">
366 {metric === "cost"
367 ? `${formatCount(merged.sessions)} sessions · API estimate`
368 : `${formatCount(merged.sessions)} sessions`}
369 </span>
370 </div>
371
372 {activeProviders.map((provider) => {
373 const totals = merged.providers.find((entry) => entry.provider === provider);
374 const share =
375 metric === "cost" ? (totals?.costShare ?? 0) : (totals?.tokenShare ?? 0);
376 const providerSessions = totals?.sessions ?? 0;
377 const sessionLabel = `${formatCount(providerSessions)} ${
378 providerSessions === 1 ? "session" : "sessions"
379 }`;
380 return (
381 <div key={provider} className="flex flex-col gap-1">
382 <div className="flex items-baseline justify-between gap-4">
383 <span className="flex min-w-0 items-center gap-2 text-sm text-foreground">
384 <span
385 aria-hidden
386 className="size-2 shrink-0 rounded-full"
387 style={{
388 backgroundColor: PROVIDER_PRESENTATION[provider].color,
389 }}
390 />
391 <ProviderMark provider={provider} className="size-4" />
392 <span className="flex min-w-0 items-baseline gap-1.5">
393 <span className="truncate">
394 {PROVIDER_PRESENTATION[provider].label}
395 </span>
396 <span className="shrink-0 whitespace-nowrap text-[11px] text-muted-foreground tabular-nums">
397 {sessionLabel}
398 </span>
399 </span>
400 </span>
401 <span className="shrink-0 text-sm font-medium text-foreground tabular-nums">
402 {metric === "cost"
403 ? formatUsd(totals?.costUsd ?? 0)
404 : formatTokens(totals?.totalTokens ?? 0)}
405 </span>
406 </div>
407 <span className="text-xs text-muted-foreground">
408 {metric === "cost"
409 ? `${formatPercent(share)} of cost · ${formatTokens(totals?.totalTokens ?? 0)} tokens`
410 : `${formatPercent(share)} of tokens · ${formatUsd(totals?.costUsd ?? 0)}`}
411 </span>
412 </div>
413 );
414 })}
415 </div>
416
417 <div className="flex min-w-0 flex-col gap-3">
418 <h2 className="text-sm font-medium text-foreground">
419 {isPast24Hours ? "Hourly" : "Daily"}{" "}
420 {metric === "tokens" ? "processed tokens" : "cost"}
421 </h2>
422 <UsageProviderChart
423 providers={activeProviders}
424 days={days}
425 daily={merged.daily}
426 hours={hours}
427 hourly={merged.hourly}
428 metric={metric}
429 referenceTime={window.untilTime}
430 resolution={isPast24Hours ? "hour" : "day"}
431 timeZone={window.timeZone}
432 />
433 </div>
434 </section>
435
436 <section className="flex flex-col gap-2">
437 <h2 className="text-sm font-medium text-foreground">Totals</h2>
438 <div className="grid grid-cols-2 gap-x-6 gap-y-4 py-1 md:grid-cols-5">
439 <Metric label="Processed tokens" value={formatTokens(merged.totalTokens)} />
440 <Metric label="Cached input" value={formatTokens(merged.cachedInputTokens)} />
441 <Metric
442 label="Uncached input"
443 value={formatTokens(merged.uncachedInputTokens)}
444 />
445 <Metric label="Output" value={formatTokens(merged.outputTokens)} />
446 <Metric
447 label="Cache savings"
448 value={formatUsd(merged.costQuality.cacheSavingsUsd)}
449 />
450 </div>
451 </section>
452
453 <section className="flex flex-col gap-3">
454 <div className="flex items-center justify-between gap-3">
455 <h2 className="text-sm font-medium text-foreground">Breakdown</h2>
456 <ToggleGroup
457 aria-label="Usage breakdown"
458 variant="segmented"
459 value={[breakdown]}
460 onValueChange={(next) => {
461 const value = next[0];
462 if (value === "model" || value === "time") setBreakdown(value);
463 }}
464 >
465 {(
466 [
467 { value: "model", label: "Model" },
468 { value: "time", label: isPast24Hours ? "Hour" : "Day" },
469 ] as const
470 ).map((option) => (
471 <Toggle key={option.value} value={option.value}>
472 {option.label}
473 </Toggle>
474 ))}
475 </ToggleGroup>
476 </div>
477
478 {breakdown === "model" ? (
479 <table className="w-full table-fixed text-sm">
480 <colgroup>
481 <col className="w-2/5" />
482 <col className="w-1/5" />
483 <col className="w-1/5" />
484 <col className="w-1/5" />
485 </colgroup>
486 <thead>
487 <tr className="border-b border-border text-left text-xs text-muted-foreground">
488 <th className="py-2 font-normal">Model</th>
489 <th className="py-2 text-right font-normal">Cost</th>
490 <th className="py-2 text-right font-normal">Share</th>
491 <th className="py-2 text-right font-normal">Tokens</th>
492 </tr>
493 </thead>
494 <tbody>
495 {breakdownModels.length === 0 ? (
496 <tr>
497 <td colSpan={4} className="py-6 text-center text-muted-foreground">
498 No activity in this window.
499 </td>
500 </tr>
501 ) : (
502 breakdownModels.map((model) => (
503 <tr
504 key={`${model.provider}:${model.model}`}
505 className="border-b border-border/50 transition-colors hover:bg-muted/50"
506 >
507 <td className="py-2 text-foreground">
508 <span className="flex items-center gap-2">
509 <ProviderMark provider={model.provider} className="size-3.5" />
510 {model.model}
511 </span>
512 </td>
513 <td className="py-2 text-right text-foreground tabular-nums">
514 {formatUsd(model.costUsd)}
515 </td>
516 <td className="py-2 text-right text-muted-foreground tabular-nums">
517 {formatPercent(model.costShare)}
518 </td>
519 <td className="py-2 text-right text-muted-foreground tabular-nums">
520 {formatTokens(model.totalTokens)}
521 </td>
522 </tr>
523 ))
524 )}
525 </tbody>
526 </table>
527 ) : (
528 <table className="w-full table-fixed text-sm">
529 <colgroup>
530 <col className="w-2/5" />
531 {activeProviders.map((provider) => (
532 <col key={provider} style={{ width: timeValueColumnWidth }} />
533 ))}
534 <col style={{ width: timeValueColumnWidth }} />
535 <col style={{ width: timeValueColumnWidth }} />
536 </colgroup>
537 <thead>
538 <tr className="border-b border-border text-left text-xs text-muted-foreground">
539 <th className="py-2 font-normal">{isPast24Hours ? "Hour" : "Day"}</th>
540 {activeProviders.map((provider) => (
541 <th key={provider} className="py-2 text-right font-normal">
542 {PROVIDER_PRESENTATION[provider].label}
543 </th>
544 ))}
545 <th className="py-2 text-right font-normal">Total</th>
546 <th className="py-2 text-right font-normal">Tokens</th>
547 </tr>
548 </thead>
549 <tbody>
550 {breakdownPeriods.length === 0 ? (
551 <tr>
552 <td
553 colSpan={activeProviders.length + 3}
554 className="py-6 text-center text-muted-foreground"
555 >
556 No activity in this window.
557 </td>
558 </tr>
559 ) : (
560 breakdownPeriods.map((period) => (
561 <tr
562 key={"hourStart" in period ? period.hourStart : period.day}
563 className="border-b border-border/50 transition-colors hover:bg-muted/50"
564 >
565 <td className="py-2 text-foreground">
566 {"hourStart" in period
567 ? formatHourShort(period.hourStart, window.timeZone)
568 : formatDayShort(period.day)}
569 </td>
570 {activeProviders.map((provider) => (
571 <td
572 key={provider}
573 className="py-2 text-right text-muted-foreground tabular-nums"
574 >
575 {formatUsd(period.byProvider.get(provider)?.costUsd ?? 0)}
576 </td>
577 ))}
578 <td className="py-2 text-right text-foreground tabular-nums">
579 {formatUsd(period.costUsd)}
580 </td>
581 <td className="py-2 text-right text-muted-foreground tabular-nums">
582 {formatTokens(period.totalTokens)}
583 </td>
584 </tr>
585 ))
586 )}
587 </tbody>
588 </table>
589 )}
590 </section>
591 </>
592 )}
593 </WorkspacePageContainer>
594 </ScrollArea>
595 </div>
596 </SidebarInset>
597 );
598}
599
600/** Brand mark for the harness a row belongs to. */
601function ProviderMark({
602 provider,
603 className,
604}: {
605 readonly provider: UsageProviderKind;
606 readonly className: string;
607}) {
608 const Mark = PROVIDER_PRESENTATION[provider].mark;
609 return <Mark className={cn("shrink-0", className)} aria-hidden />;
610}
611
612function Metric({ label, value }: { readonly label: string; readonly value: string }) {
613 return (
614 <div className="flex min-w-0 flex-col gap-0.5">
615 <span className="text-xs text-muted-foreground">{label}</span>
616 <span className="text-base font-medium text-foreground tabular-nums">{value}</span>
617 </div>
618 );
619}
620
621/**
622 * Explains failed or incompatible environments and deduplicated transcripts.
623 * Shown inside the environment filter so arriving results do not move the page.
624 */
625function UsageCoverageNotice({
626 environments,
627 duplicateSources,
628 staleEnvironments,
629}: {
630 readonly environments: readonly EnvironmentUsageStatus[];
631 readonly duplicateSources: readonly string[];
632 readonly staleEnvironments: readonly string[];
633}) {
634 const failed = environments.filter((environment) => environment.error !== null);
635 const stale = environments.filter((environment) =>
636 staleEnvironments.includes(environment.environmentId),
637 );
638 if (failed.length === 0 && stale.length === 0 && duplicateSources.length === 0) {
639 return null;
640 }
641
642 return (
643 <div className="flex flex-col gap-1 border-t border-border px-2 py-2 text-xs text-muted-foreground">
644 {failed.map((environment) => (
645 <span key={environment.label}>{environment.label} could not report usage.</span>
646 ))}
647 {stale.map((environment) => (
648 <span key={environment.label}>
649 {environment.label} runs an older server version and is excluded from totals.
650 </span>
651 ))}
652 {duplicateSources.length > 0 ? (
653 <span>
654 Counted once across environments sharing a transcript directory:{" "}
655 {duplicateSources.join(", ")}
656 </span>
657 ) : null}
658 </div>
659 );
660}
661
662/** Environment selection and scan progress share a permanent header control. */
663function UsageEnvironmentFilter({
664 environments,
665 selectedEnvironments,
666 selectedEnvironmentIds,
667 onSelectionChange,
668 showUsageStatus,
669 isPartial,
670 duplicateSources,
671 staleEnvironments,
672}: {
673 readonly environments: readonly EnvironmentUsageStatus[];
674 readonly selectedEnvironments: readonly EnvironmentUsageStatus[];
675 readonly selectedEnvironmentIds: ReadonlySet<EnvironmentId> | null;
676 readonly onSelectionChange: (ids: ReadonlySet<EnvironmentId> | null) => void;
677 readonly showUsageStatus: boolean;
678 readonly isPartial: boolean;
679 readonly duplicateSources: readonly string[];
680 readonly staleEnvironments: readonly string[];
681}) {
682 const [modelPricesOpen, setModelPricesOpen] = useState(false);
683 const allSelected = selectedEnvironmentIds === null;
684 const label = allSelected
685 ? "All environments"
686 : selectedEnvironments.length === 1
687 ? selectedEnvironments[0]!.label
688 : `${selectedEnvironments.length} environments`;
689 const pendingCount = selectedEnvironments.filter(
690 (environment) =>
691 environment.error === null && (environment.isPending || environment.summary === null),
692 ).length;
693 const hasIssue =
694 selectedEnvironments.some((environment) => environment.error !== null) ||
695 staleEnvironments.length > 0;
696
697 return (
698 <>
699 <Menu>
700 <MenuTrigger className="group/usage-environment inline-flex min-w-0 max-w-full cursor-pointer items-center gap-1 rounded-sm text-left focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-ring">
701 <span className="min-w-0 truncate">{label}</span>
702 <span className="flex size-3.5 shrink-0 items-center justify-center text-muted-foreground">
703 {showUsageStatus && pendingCount > 0 ? (
704 <>
705 <CircleDashedIcon className="size-3.5" aria-hidden />
706 <span className="sr-only">
707 {pendingCount} {pendingCount === 1 ? "environment" : "environments"} still
708 scanning
709 {isPartial ? "; totals are partial" : ""}
710 </span>
711 </>
712 ) : showUsageStatus && hasIssue ? (
713 <CircleAlertIcon
714 className="size-3.5 text-amber-600 dark:text-amber-400"
715 aria-label="Some environments could not report usage"
716 />
717 ) : (
718 <ChevronDownIcon
719 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"
720 aria-hidden
721 />
722 )}
723 </span>
724 </MenuTrigger>
725 <MenuPopup align="start" className="w-80 max-w-[calc(100vw-2rem)]">
726 <MenuCheckboxItem
727 checked={allSelected}
728 closeOnClick={false}
729 onCheckedChange={(checked) => onSelectionChange(checked ? null : new Set())}
730 >
731 All environments
732 </MenuCheckboxItem>
733 <MenuSeparator />
734 {environments.map((environment) => {
735 const checked =
736 selectedEnvironmentIds === null ||
737 selectedEnvironmentIds.has(environment.environmentId);
738 const status =
739 environment.error !== null
740 ? "Unavailable"
741 : environment.summary !== null &&
742 !isCompatibleUsageContractVersion(
743 environment.summary.contractVersion,
744 USAGE_CONTRACT_VERSION,
745 )
746 ? "Update required"
747 : environment.summary === null
748 ? "Scanning…"
749 : environment.isPending
750 ? "Refreshing…"
751 : "Ready";
752 return (
753 <MenuCheckboxItem
754 key={environment.environmentId}
755 checked={checked}
756 closeOnClick={false}
757 className="grid-cols-[1rem_minmax(0,1fr)]"
758 onCheckedChange={(nextChecked) => {
759 const next = new Set(selectedEnvironments.map((entry) => entry.environmentId));
760 if (nextChecked) next.add(environment.environmentId);
761 else next.delete(environment.environmentId);
762 onSelectionChange(next.size === environments.length ? null : next);
763 }}
764 >
765 <span className="flex min-w-0 items-center gap-3">
766 <span className="min-w-0 flex-1 truncate">{environment.label}</span>
767 {showUsageStatus ? (
768 <span
769 className={cn(
770 "shrink-0 text-xs text-muted-foreground",
771 environment.error !== null && "text-destructive",
772 )}
773 >
774 {status}
775 </span>
776 ) : null}
777 </span>
778 </MenuCheckboxItem>
779 );
780 })}
781 {environments.length === 0 ? (
782 <p className="px-2 py-2 text-xs text-muted-foreground">No environments connected.</p>
783 ) : null}
784 {showUsageStatus && isPartial ? (
785 <p className="px-2 py-2 text-xs text-muted-foreground">
786 Totals are partial while selected environments scan.
787 </p>
788 ) : null}
789 {showUsageStatus ? (
790 <UsageCoverageNotice
791 environments={selectedEnvironments}
792 duplicateSources={duplicateSources}
793 staleEnvironments={staleEnvironments}
794 />
795 ) : null}
796 <MenuSeparator />
797 <MenuItem onClick={() => setModelPricesOpen(true)}>
798 <SlidersHorizontalIcon aria-hidden />
799 Model prices
800 </MenuItem>
801 </MenuPopup>
802 </Menu>
803 {modelPricesOpen ? (
804 <UsagePriceOverrides
805 usage={environments}
806 initialSelectedEnvironmentIds={selectedEnvironmentIds}
807 onOpenChange={setModelPricesOpen}
808 />
809 ) : null}
810 </>
811 );
812}
813
814/**
815 * Stand-in with the loaded page's shape, using the shared `Skeleton` bars so it
816 * breathes with the same `animate-skeleton` pulse as every other loading state.
817 * Replaced by results as soon as the first environment answers.
818 */
819function UsageSkeleton() {
820 return (
821 <>
822 <section className="grid gap-6 lg:grid-cols-[minmax(0,18rem)_minmax(0,1fr)]">
823 <div className="flex flex-col gap-5">
824 <div className="flex flex-col gap-1">
825 <Skeleton className="h-10 w-36" />
826 <Skeleton className="h-4 w-32" />
827 </div>
828 {PROVIDER_ORDER.map((provider) => (
829 <div key={provider} className="flex flex-col gap-1">
830 <div className="flex min-h-5 items-center justify-between gap-4">
831 <span className="flex items-center gap-2">
832 <Skeleton className="size-2 shrink-0 rounded-full" />
833 <Skeleton className="size-4 shrink-0 rounded-full" />
834 <Skeleton className="h-3.5 w-20" />
835 </span>
836 <Skeleton className="h-3.5 w-14" />
837 </div>
838 <Skeleton className="h-4 w-36" />
839 </div>
840 ))}
841 </div>
842
843 <div className="flex flex-col gap-3">
844 <Skeleton className="h-5 w-24" />
845 <div className="flex flex-col gap-1">
846 <Skeleton className="ml-16 h-56 bg-muted-foreground/10" />
847 <Skeleton className="ml-16 h-4 bg-muted-foreground/10" />
848 </div>
849 </div>
850 </section>
851
852 <section className="flex flex-col gap-2">
853 <h2 className="text-sm font-medium text-foreground">Totals</h2>
854 <div className="grid grid-cols-2 gap-x-6 gap-y-4 py-1 md:grid-cols-5">
855 {["Processed tokens", "Cached input", "Uncached input", "Output", "Cache savings"].map(
856 (label) => (
857 <div key={label} className="flex flex-col gap-0.5">
858 <span className="text-xs text-muted-foreground">{label}</span>
859 <Skeleton className="h-6 w-16" />
860 </div>
861 ),
862 )}
863 </div>
864 </section>
865
866 <section className="flex flex-col gap-3">
867 <div className="flex items-center justify-between gap-3">
868 <h2 className="text-sm font-medium text-foreground">Breakdown</h2>
869 <Skeleton className="h-7 w-28 rounded-lg" />
870 </div>
871 <Skeleton className="h-44 bg-muted-foreground/10" />
872 </section>
873 </>
874 );
875}