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

UsagePage.tsx

833 lines34.0 KB

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