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

UsagePage.tsx

894 lines36.5 KB

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