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

UsagePage.tsx

887 lines36.3 KB

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