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