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

UsagePage.tsx

923 lines37.0 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 { useEffect, useEffectEvent, useMemo, useRef, useState } from "react";
16import { refreshUsageLimits } from "@t3tools/client-runtime/state/usage";
17​
18import {
19 isCompatibleUsageContractVersion,
20 isModelCostUnknown,
21 type DailyTotals,
22 type HourlyTotals,
23} from "@t3tools/shared/usageMerge";
24​
25import { isElectron } from "../../env";
26import { cn } from "../../lib/utils";
27import { environmentPresentations } from "../../state/presentation";
28import { serverEnvironment } from "../../state/server";
29import { useUsage, type EnvironmentUsageStatus } from "../../state/usage";
30import { useAtomCommand } from "../../state/use-atom-command";
31import {
32 enumerateDays,
33 enumerateHourStarts,
34 formatCount,
35 formatDateTimeShort,
36 formatDayShort,
37 formatHourShort,
38 formatPercent,
39 formatTokens,
40 formatUsd,
41 makeWindow,
42} from "@t3tools/shared/usageFormat";
43import { Button, InlineButton } from "../ui/button";
44import {
45 Menu,
46 MenuCheckboxItem,
47 MenuItem,
48 MenuPopup,
49 MenuSeparator,
50 MenuTrigger,
51} from "../ui/menu";
52import { ScrollArea } from "../ui/scroll-area";
53import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select";
54import { SidebarInset } from "../ui/sidebar";
55import { Skeleton } from "../ui/skeleton";
56import { Toggle, ToggleGroup } from "../ui/toggle-group";
57import {
58 WorkspaceBreadcrumb,
59 WorkspaceBreadcrumbItem,
60 WorkspaceBreadcrumbSeparator,
61} from "../WorkspaceBreadcrumb";
62import { WorkspacePageContainer } from "../WorkspacePageContainer";
63import { WorkspacePageHeader } from "../WorkspacePageHeader";
64import { UsageLimitsSection } from "./UsageLimits";
65import { UsagePriceOverrides } from "./UsagePriceOverrides";
66import { UsageProviderChart, type UsageChartMetric } from "./UsageProviderChart";
67import { sortModelsByTokens } from "./usageBreakdown";
68import { PROVIDER_ORDER, PROVIDER_PRESENTATION, providersWithUsage } from "./usageProviders";
69import {
70 readUsagePagePreferences,
71 saveUsagePagePreferences,
72 type UsagePagePreferences,
73} from "./usagePagePreferences";
74​
75type UsageMetric = UsageChartMetric | "limits";
76const METRIC_OPTIONS = [
77 { value: "cost", label: "Cost" },
78 { value: "tokens", label: "Tokens" },
79 { value: "limits", label: "Limits" },
80] as const satisfies readonly { value: UsageMetric; label: string }[];
81​
82function isUsageMetric(value: string | null | undefined): value is UsageMetric {
83 return METRIC_OPTIONS.some((option) => option.value === value);
85​
86const WINDOW_OPTIONS = [
87 { days: 1, label: "Past 24h" },
88 { days: 7, label: "7 days" },
89 { days: 30, label: "30 days" },
90 { days: 90, label: "90 days" },
91] as const;
92​
93function isUsageWindowDays(value: number): value is UsagePagePreferences["windowDays"] {
94 return WINDOW_OPTIONS.some((option) => option.days === value);
96​
97export function UsagePage() {
98 const [preferences, setPreferences] = useState(readUsagePagePreferences);
99 const [windowSelection, setWindowSelection] = useState(() => ({
100 days: preferences.windowDays,
101 window: makeWindow(
102 preferences.windowDays,
103 undefined,
104 preferences.windowDays === 1 ? "hour" : "day",
105 ),
106 }));
107 const metric = preferences.metric;
108 const showingLimits = metric === "limits";
109 const [isRefreshing, setIsRefreshing] = useState(false);
110 const [limitsNow, setLimitsNow] = useState(() => Date.now());
111 const refreshingRef = useRef(false);
112 const [breakdown, setBreakdown] = useState<"model" | "time">("model");
113 const [selectedEnvironmentIds, setSelectedEnvironmentIds] =
114 useState<ReadonlySet<EnvironmentId> | null>(null);
115 const { days: windowDays, window } = windowSelection;
116 const isPast24Hours = windowDays === 1;
117 const { merged, environments, selectedEnvironments, isPending, isPartial, refresh } = useUsage(
118 window,
119 selectedEnvironmentIds,
120 );
121 const presentations = useAtomValue(environmentPresentations.presentationsAtom);
122 const refreshProviders = useAtomCommand(serverEnvironment.refreshProviders, {
123 reportFailure: false,
124 });
125​
126 const days = useMemo(
127 () => enumerateDays(window.sinceDay, window.untilDay),
128 [window.sinceDay, window.untilDay],
129 );
130 const hours = useMemo(
131 () =>
132 window.sinceTime === undefined || window.untilTime === undefined
133 ? []
134 : enumerateHourStarts(window.sinceTime, window.untilTime),
135 [window.sinceTime, window.untilTime],
136 );
137 // Newest first: the window can run 90 periods, so the interesting end
138 // belongs at the top of the table.
139 const breakdownPeriods = useMemo<readonly (DailyTotals | HourlyTotals)[]>(
140 () => (isPast24Hours ? merged.hourly : merged.daily).toReversed(),
141 [isPast24Hours, merged.daily, merged.hourly],
142 );
143 const breakdownModels = useMemo(
144 () =>
145 breakdown === "model" && metric === "tokens"
146 ? sortModelsByTokens(merged.models)
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 size="sm" 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 size="sm" 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 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-2xs 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 );
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 presentation = PROVIDER_PRESENTATION[provider];
649 return (
650 <ProviderInstanceIcon
651 driverKind={presentation.driverKind}
652 displayName={presentation.label}
653 iconClassName={className}
654 />
655 );
657​
658function Metric({ label, value }: { readonly label: string; readonly value: string }) {
659 return (
660 <div className="flex min-w-0 flex-col gap-0.5">
661 <span className="text-xs text-muted-foreground">{label}</span>
662 <span className="text-base font-medium text-foreground tabular-nums">{value}</span>
663 </div>
664 );
666​
667/**
668 * Explains failed or incompatible environments and deduplicated transcripts.
669 * Shown inside the environment filter so arriving results do not move the page.
670 */
671function UsageCoverageNotice({
672 environments,
673 duplicateSources,
674 staleEnvironments,
675}: {
676 readonly environments: readonly EnvironmentUsageStatus[];
677 readonly duplicateSources: readonly string[];
678 readonly staleEnvironments: readonly string[];
679}) {
680 const failed = environments.filter((environment) => environment.error !== null);
681 const stale = environments.filter((environment) =>
682 staleEnvironments.includes(environment.environmentId),
683 );
684 if (failed.length === 0 && stale.length === 0 && duplicateSources.length === 0) {
685 return null;
686 }
687​
688 return (
689 <div className="flex flex-col gap-1 border-t border-border px-2 py-2 text-xs text-muted-foreground">
690 {failed.map((environment) => (
691 <span key={environment.label}>{environment.label} could not report usage.</span>
692 ))}
693 {stale.map((environment) => (
694 <span key={environment.label}>
695 {environment.label} runs an older server version and is excluded from totals.
696 </span>
697 ))}
698 {duplicateSources.length > 0 ? (
699 <span>
700 Counted once across environments sharing a transcript directory:{" "}
701 {duplicateSources.join(", ")}
702 </span>
703 ) : null}
704 </div>
705 );
707​
708/** Environment selection and scan progress share a permanent header control. */
709function UsageEnvironmentFilter({
710 environments,
711 selectedEnvironments,
712 selectedEnvironmentIds,
713 onSelectionChange,
714 showUsageStatus,
715 isPartial,
716 duplicateSources,
717 staleEnvironments,
718}: {
719 readonly environments: readonly EnvironmentUsageStatus[];
720 readonly selectedEnvironments: readonly EnvironmentUsageStatus[];
721 readonly selectedEnvironmentIds: ReadonlySet<EnvironmentId> | null;
722 readonly onSelectionChange: (ids: ReadonlySet<EnvironmentId> | null) => void;
723 readonly showUsageStatus: boolean;
724 readonly isPartial: boolean;
725 readonly duplicateSources: readonly string[];
726 readonly staleEnvironments: readonly string[];
727}) {
728 const [modelPricesOpen, setModelPricesOpen] = useState(false);
729 const allSelected = selectedEnvironmentIds === null;
730 const label = allSelected
731 ? "All environments"
732 : selectedEnvironments.length === 1
733 ? selectedEnvironments[0]!.label
734 : `${selectedEnvironments.length} environments`;
735 const pendingCount = selectedEnvironments.filter(
736 (environment) =>
737 environment.error === null && (environment.isPending || environment.summary === null),
738 ).length;
739 const hasIssue =
740 selectedEnvironments.some((environment) => environment.error !== null) ||
741 staleEnvironments.length > 0;
742​
743 return (
744 <>
745 <Menu>
746 <MenuTrigger
747 render={<InlineButton />}
748 className="group/usage-environment min-w-0 max-w-full"
749 >
750 <span className="min-w-0 truncate">{label}</span>
751 <span className="flex size-3.5 shrink-0 items-center justify-center text-muted-foreground">
752 {showUsageStatus && pendingCount > 0 ? (
753 <>
754 <CircleDashedIcon className="size-3.5" aria-hidden />
755 <span className="sr-only">
756 {pendingCount} {pendingCount === 1 ? "environment" : "environments"} still
757 scanning
758 {isPartial ? "; totals are partial" : ""}
759 </span>
760 </>
761 ) : showUsageStatus && hasIssue ? (
762 <CircleAlertIcon
763 className="size-3.5 text-warning-foreground"
764 aria-label="Some environments could not report usage"
765 />
766 ) : (
767 <ChevronDownIcon
768 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"
769 aria-hidden
770 />
771 )}
772 </span>
773 </MenuTrigger>
774 <MenuPopup align="start">
775 <MenuCheckboxItem
776 checked={allSelected}
777 closeOnClick={false}
778 onCheckedChange={(checked) => onSelectionChange(checked ? null : new Set())}
779 >
780 All environments
781 </MenuCheckboxItem>
782 <MenuSeparator />
783 {environments.map((environment) => {
784 const checked =
785 selectedEnvironmentIds === null ||
786 selectedEnvironmentIds.has(environment.environmentId);
787 const status =
788 environment.error !== null
789 ? "Unavailable"
790 : environment.summary !== null &&
791 !isCompatibleUsageContractVersion(
792 environment.summary.contractVersion,
793 USAGE_CONTRACT_VERSION,
794 )
795 ? "Update required"
796 : environment.summary === null
797 ? "Scanning…"
798 : environment.isPending
799 ? "Refreshing…"
800 : "Ready";
801 return (
802 <MenuCheckboxItem
803 key={environment.environmentId}
804 checked={checked}
805 closeOnClick={false}
806 onCheckedChange={(nextChecked) => {
807 const next = new Set(selectedEnvironments.map((entry) => entry.environmentId));
808 if (nextChecked) next.add(environment.environmentId);
809 else next.delete(environment.environmentId);
810 onSelectionChange(next.size === environments.length ? null : next);
811 }}
812 >
813 <span className="flex min-w-0 items-center gap-3">
814 <span className="min-w-0 flex-1 truncate">{environment.label}</span>
815 {showUsageStatus ? (
816 <span
817 className={cn(
818 "shrink-0 text-xs text-muted-foreground",
819 environment.error !== null && "text-destructive",
820 )}
821 >
822 {status}
823 </span>
824 ) : null}
825 </span>
826 </MenuCheckboxItem>
827 );
828 })}
829 {environments.length === 0 ? (
830 <p className="px-2 py-2 text-xs text-muted-foreground">No environments connected.</p>
831 ) : null}
832 {showUsageStatus && isPartial ? (
833 <p className="px-2 py-2 text-xs text-muted-foreground">
834 Totals are partial while selected environments scan.
835 </p>
836 ) : null}
837 {showUsageStatus ? (
838 <UsageCoverageNotice
839 environments={selectedEnvironments}
840 duplicateSources={duplicateSources}
841 staleEnvironments={staleEnvironments}
842 />
843 ) : null}
844 <MenuSeparator />
845 <MenuItem onClick={() => setModelPricesOpen(true)}>
846 <SlidersHorizontalIcon aria-hidden />
847 Model prices
848 </MenuItem>
849 </MenuPopup>
850 </Menu>
851 {modelPricesOpen ? (
852 <UsagePriceOverrides
853 usage={environments}
854 initialSelectedEnvironmentIds={selectedEnvironmentIds}
855 onOpenChange={setModelPricesOpen}
856 />
857 ) : null}
858 </>
859 );
861​
862/**
863 * Stand-in with the loaded page's shape, using the shared `Skeleton` bars so it
864 * breathes with the same `animate-skeleton` pulse as every other loading state.
865 * Replaced by results as soon as the first environment answers.
866 */
867function UsageSkeleton() {
868 return (
869 <>
870 <section className="grid gap-6 lg:grid-cols-[minmax(0,18rem)_minmax(0,1fr)]">
871 <div className="flex flex-col gap-5">
872 <div className="flex flex-col gap-1">
873 <Skeleton className="h-10 w-36" />
874 <Skeleton className="h-4 w-32" />
875 </div>
876 {PROVIDER_ORDER.map((provider) => (
877 <div key={provider} className="flex flex-col gap-1">
878 <div className="flex min-h-5 items-center justify-between gap-4">
879 <span className="flex items-center gap-2">
880 <Skeleton shape="pill" className="size-2 shrink-0" />
881 <Skeleton shape="pill" className="size-4 shrink-0" />
882 <Skeleton className="h-3.5 w-20" />
883 </span>
884 <Skeleton className="h-3.5 w-14" />
885 </div>
886 <Skeleton className="h-4 w-36" />
887 </div>
888 ))}
889 </div>
890​
891 <div className="flex flex-col gap-3">
892 <Skeleton className="h-5 w-24" />
893 <div className="flex flex-col gap-1">
894 <Skeleton className="ml-16 h-56" />
895 <Skeleton className="ml-16 h-4" />
896 </div>
897 </div>
898 </section>
899​
900 <section className="flex flex-col gap-2">
901 <h2 className="text-sm font-medium text-foreground">Totals</h2>
902 <div className="grid grid-cols-2 gap-x-6 gap-y-4 py-1 md:grid-cols-5">
903 {["Processed tokens", "Cached input", "Uncached input", "Output", "Cache savings"].map(
904 (label) => (
905 <div key={label} className="flex flex-col gap-0.5">
906 <span className="text-xs text-muted-foreground">{label}</span>
907 <Skeleton className="h-6 w-16" />
908 </div>
909 ),
910 )}
911 </div>
912 </section>
913​
914 <section className="flex flex-col gap-3">
915 <div className="flex items-center justify-between gap-3">
916 <h2 className="text-sm font-medium text-foreground">Breakdown</h2>
917 <Skeleton shape="card" className="h-7 w-28" />
918 </div>
919 <Skeleton className="h-44" />
920 </section>
921 </>
922 );