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

UsagePage.tsx

884 lines36.1 KB

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