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

UsagePage.tsx

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