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