Open History to see the last commit
1import { ChatGptUsageButton } from "../settings/ChatGptUsageButton";
2import { usesChatGptSharing } from "@t3tools/shared/usageLimits";
3import { RefreshIcon } from "~/components/ui/refresh-icon";
4import { useAtomValue } from "@effect/atom-react";
5import {
6 ProviderDriverKind,
7 USAGE_CONTRACT_VERSION,
8 type EnvironmentId,
9 type UsageProviderKind,
10} from "@t3tools/contracts";
11import {
12 CircleAlertIcon,
13 ChevronDownIcon,
14 CircleDashedIcon,
15 InfoIcon,
16 SlidersHorizontalIcon,
17} from "lucide-react";
18import { useEffect, useEffectEvent, useMemo, useRef, useState } from "react";
19import {
20 cursorKeychainAccessEnvironments,
21 refreshUsageLimits,
22} from "@t3tools/client-runtime/state/usage";
23
24import {
25 isCompatibleUsageContractVersion,
26 isModelCostUnknown,
27 type DailyTotals,
28 type HourlyTotals,
29 type MergedUsage,
30} from "@t3tools/shared/usageMerge";
31
32import { isElectron } from "../../env";
33import { cn } from "../../lib/utils";
34import { environmentPresentations } from "../../state/presentation";
35import { primaryServerKeybindingsAtom, serverEnvironment } from "../../state/server";
36import { isCommandPaletteOpen } from "../../commandPaletteBus";
37import { isModelPickerOpen } from "../../modelPickerVisibility";
38import { shortcutLabelForCommand } from "../../keybindings";
39import { useUsage, type EnvironmentUsageStatus } from "../../state/usage";
40import { useAtomCommand } from "../../state/use-atom-command";
41import {
42 enumerateDays,
43 enumerateHourStarts,
44 formatCount,
45 formatDateTimeShort,
46 formatDayShort,
47 formatHourShort,
48 formatPercent,
49 formatTokens,
50 formatUsageContractMismatch,
51 formatUsd,
52 makeWindow,
53} from "@t3tools/shared/usageFormat";
54import { Button, InlineButton } from "../ui/button";
55import { ProviderInstanceIcon } from "../chat/ProviderInstanceIcon";
56import {
57 Menu,
58 MenuCheckboxItem,
59 MenuItem,
60 MenuPopup,
61 MenuSeparator,
62 MenuTrigger,
63} from "../ui/menu";
64import { ScrollArea } from "../ui/scroll-area";
65import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select";
66import { SidebarInset } from "../ui/sidebar";
67import { Skeleton } from "../ui/skeleton";
68import { Toggle, ToggleGroup } from "../ui/toggle-group";
69import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
70import { Popover, PopoverPopup, PopoverTrigger } from "../ui/popover";
71import {
72 WorkspaceBreadcrumb,
73 WorkspaceBreadcrumbItem,
74 WorkspaceBreadcrumbSeparator,
75} from "../WorkspaceBreadcrumb";
76import { WorkspacePageContainer } from "../WorkspacePageContainer";
77import { WorkspacePageHeader } from "../WorkspacePageHeader";
78import { UsageLimitsSection } from "./UsageLimits";
79import { UsagePriceOverrides } from "./UsagePriceOverrides";
80import { UsageProviderChart } from "./UsageProviderChart";
81import { sortModelsByTokens } from "./usageBreakdown";
82import {
83 METRIC_OPTIONS,
84 WINDOW_OPTIONS,
85 resolveUsageShortcut,
86 type UsageMetric,
87} from "./usageShortcuts";
88import { useEscapeToGoBack } from "../../hooks/useNavigateBack";
89import { PROVIDER_ORDER, PROVIDER_PRESENTATION, providersWithUsage } from "./usageProviders";
90import {
91 readUsagePagePreferences,
92 saveUsagePagePreferences,
93 type UsagePagePreferences,
94} from "./usagePagePreferences";
95
96function isUsageMetric(value: string | null | undefined): value is UsageMetric {
97 return METRIC_OPTIONS.some((option) => option.value === value);
98}
99
100function isUsageWindowDays(value: number): value is UsagePagePreferences["windowDays"] {
101 return WINDOW_OPTIONS.some((option) => option.days === value);
102}
103
104export function UsagePage() {
105 const [preferences, setPreferences] = useState(readUsagePagePreferences);
106 useEscapeToGoBack();
107 const keybindings = useAtomValue(primaryServerKeybindingsAtom);
108 const shortcutTitle = (
109 option: (typeof METRIC_OPTIONS)[number] | (typeof WINDOW_OPTIONS)[number],
110 ) => {
111 const shortcut = shortcutLabelForCommand(keybindings, option.command, {
112 context: { usagePageOpen: true },
113 });
114 return shortcut ? `${option.label} (${shortcut})` : option.label;
115 };
116 const [windowSelection, setWindowSelection] = useState(() => ({
117 days: preferences.windowDays,
118 window: makeWindow(
119 preferences.windowDays,
120 undefined,
121 preferences.windowDays === 1 ? "hour" : "day",
122 ),
123 }));
124 const metric = preferences.metric;
125 const showingLimits = metric === "limits";
126 const [isRefreshing, setIsRefreshing] = useState(false);
127 const [limitsNow, setLimitsNow] = useState(() => Date.now());
128 const refreshingRef = useRef(false);
129 const [breakdown, setBreakdown] = useState<"model" | "time">("model");
130 const [selectedEnvironmentIds, setSelectedEnvironmentIds] =
131 useState<ReadonlySet<EnvironmentId> | null>(null);
132 const { days: windowDays, window } = windowSelection;
133 const isPast24Hours = windowDays === 1;
134 const { merged, environments, selectedEnvironments, isPending, isPartial, refresh } = useUsage(
135 window,
136 selectedEnvironmentIds,
137 );
138 const presentations = useAtomValue(environmentPresentations.presentationsAtom);
139 const cursorAccessEnvironments = cursorKeychainAccessEnvironments(selectedEnvironments);
140 const sourceMessages = [
141 ...new Set(
142 selectedEnvironments.flatMap(
143 (environment) =>
144 environment.summary?.sources.flatMap((source) =>
145 source.message &&
146 !source.action &&
147 (source.status === "partial" ||
148 source.status === "failed" ||
149 source.fingerprint.provider === "cursor")
150 ? [source.message]
151 : [],
152 ) ?? [],
153 ),
154 ),
155 ];
156 const refreshProviders = useAtomCommand(serverEnvironment.refreshProviders, {
157 reportFailure: false,
158 });
159
160 const days = useMemo(
161 () => enumerateDays(window.sinceDay, window.untilDay),
162 [window.sinceDay, window.untilDay],
163 );
164 const hours = useMemo(
165 () =>
166 window.sinceTime === undefined || window.untilTime === undefined
167 ? []
168 : enumerateHourStarts(window.sinceTime, window.untilTime),
169 [window.sinceTime, window.untilTime],
170 );
171 // Newest first: the window can run 90 periods, so the interesting end
172 // belongs at the top of the table.
173 const breakdownPeriods = useMemo<readonly (DailyTotals | HourlyTotals)[]>(
174 () => (isPast24Hours ? merged.hourly : merged.daily).toReversed(),
175 [isPast24Hours, merged.daily, merged.hourly],
176 );
177 const breakdownModels = useMemo(
178 () =>
179 breakdown === "model" && metric === "tokens"
180 ? sortModelsByTokens(merged.models)
181 : merged.models,
182 [breakdown, merged.models, metric],
183 );
184 const activeProviders = useMemo(() => providersWithUsage(merged.providers), [merged.providers]);
185 const summaryRows: Array<
186 | { readonly kind: "usage"; readonly provider: UsageProviderKind }
187 | { readonly kind: "enable"; readonly environment: EnvironmentUsageStatus }
188 > = activeProviders.map((provider) => ({ kind: "usage", provider }));
189 const cursorInsertAt =
190 Math.max(activeProviders.indexOf("codex"), activeProviders.indexOf("claude")) + 1;
191 summaryRows.splice(
192 cursorInsertAt,
193 0,
194 ...cursorAccessEnvironments.map((environment) => ({ kind: "enable" as const, environment })),
195 );
196 const timeValueColumnWidth = `${60 / (activeProviders.length + 2)}%`;
197
198 const selectWindow = (days: number) => {
199 if (!isUsageWindowDays(days)) return;
200 const nextPreferences = { metric, windowDays: days };
201 setPreferences(nextPreferences);
202 saveUsagePagePreferences(nextPreferences);
203 setWindowSelection({
204 days,
205 window: makeWindow(days, undefined, days === 1 ? "hour" : "day"),
206 });
207 };
208 const selectMetric = (nextMetric: UsageMetric) => {
209 if (nextMetric === "limits") setLimitsNow(Date.now());
210 const nextPreferences = { metric: nextMetric, windowDays };
211 setPreferences(nextPreferences);
212 saveUsagePagePreferences(nextPreferences);
213 };
214 const refreshLimits = async (automatic = false, afterPending = false) => {
215 try {
216 await Promise.all(
217 Array.from(presentations, ([environmentId, presentation]) => {
218 if (selectedEnvironmentIds !== null && !selectedEnvironmentIds.has(environmentId)) return;
219 if (presentation.connection.phase === "connected" && presentation.serverConfig !== null) {
220 return refreshUsageLimits(
221 environmentId,
222 () => refreshProviders({ environmentId, input: {} }),
223 automatic,
224 afterPending,
225 );
226 }
227 }),
228 );
229 } finally {
230 setLimitsNow(Date.now());
231 }
232 };
233 const onUsageKeyDown = useEffectEvent((event: KeyboardEvent) => {
234 if (
235 event.defaultPrevented ||
236 event.repeat ||
237 event.isComposing ||
238 isCommandPaletteOpen() ||
239 isModelPickerOpen()
240 )
241 return;
242
243 const command = resolveUsageShortcut(event, keybindings);
244 const metricOption = METRIC_OPTIONS.find((option) => option.command === command);
245 const periodOption = WINDOW_OPTIONS.find((option) => option.command === command);
246 if (!metricOption && !periodOption) return;
247
248 event.preventDefault();
249 event.stopPropagation();
250 if (metricOption) selectMetric(metricOption.value);
251 if (periodOption && !showingLimits) selectWindow(periodOption.days);
252 });
253
254 useEffect(() => {
255 globalThis.window.addEventListener("keydown", onUsageKeyDown, true);
256 return () => globalThis.window.removeEventListener("keydown", onUsageKeyDown, true);
257 }, []);
258
259 const refreshWindow = () => {
260 if (refreshingRef.current) return;
261
262 if (showingLimits) {
263 refreshingRef.current = true;
264 setIsRefreshing(true);
265 void refreshLimits().finally(() => {
266 refreshingRef.current = false;
267 setIsRefreshing(false);
268 });
269 return;
270 }
271 const nextWindow = makeWindow(windowDays, undefined, isPast24Hours ? "hour" : "day");
272 if (
273 nextWindow.sinceDay !== window.sinceDay ||
274 nextWindow.untilDay !== window.untilDay ||
275 nextWindow.sinceTime !== window.sinceTime ||
276 nextWindow.untilTime !== window.untilTime
277 ) {
278 setWindowSelection({ days: windowDays, window: nextWindow });
279 }
280 refreshingRef.current = true;
281 setIsRefreshing(true);
282 void refresh(nextWindow).finally(() => {
283 refreshingRef.current = false;
284 setIsRefreshing(false);
285 });
286 };
287 const connectedLimitsEnvironments = [...presentations]
288 .filter(
289 ([environmentId, presentation]) =>
290 presentation.connection.phase === "connected" &&
291 presentation.serverConfig !== null &&
292 (selectedEnvironmentIds === null || selectedEnvironmentIds.has(environmentId)),
293 )
294 .map(([environmentId]) => environmentId)
295 .sort()
296 .join(",");
297 const autoRefreshLimits = useEffectEvent(() => {
298 void refreshLimits(true);
299 });
300 useEffect(() => {
301 if (showingLimits && connectedLimitsEnvironments) autoRefreshLimits();
302 }, [showingLimits, connectedLimitsEnvironments]);
303
304 const windowLabel =
305 isPast24Hours && window.sinceTime !== undefined && window.untilTime !== undefined
306 ? `${formatDateTimeShort(window.sinceTime, window.timeZone)} to ${formatDateTimeShort(window.untilTime, window.timeZone)}`
307 : `${formatDayShort(window.sinceDay)} to ${formatDayShort(window.untilDay)}`;
308 const topbarContent = (
309 <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">
310 <WorkspaceBreadcrumb ariaLabel="Usage breadcrumb" className="col-span-2 min-w-0">
311 <WorkspaceBreadcrumbItem>
312 <h1>Usage</h1>
313 </WorkspaceBreadcrumbItem>
314 <WorkspaceBreadcrumbSeparator />
315 <WorkspaceBreadcrumbItem current className="min-w-10">
316 <UsageEnvironmentFilter
317 environments={environments}
318 selectedEnvironments={selectedEnvironments}
319 selectedEnvironmentIds={selectedEnvironmentIds}
320 onSelectionChange={setSelectedEnvironmentIds}
321 showUsageStatus={!showingLimits}
322 isPartial={isPartial}
323 duplicateSources={merged.duplicateSources}
324 contractMismatches={merged.contractMismatches}
325 />
326 </WorkspaceBreadcrumbItem>
327 </WorkspaceBreadcrumb>
328 {!showingLimits ? (
329 <span className="hidden min-w-0 truncate text-xs text-muted-foreground 2xl:block">
330 {windowLabel}
331 </span>
332 ) : null}
333 <div className="ms-auto hidden min-w-0 items-center justify-end gap-2 xl:flex">
334 <ToggleGroup
335 aria-label="Usage metric"
336 variant="segmented"
337 value={[metric]}
338 onValueChange={(next) => {
339 const value = next[0];
340 if (isUsageMetric(value)) selectMetric(value);
341 }}
342 >
343 {METRIC_OPTIONS.map((option) => (
344 <Toggle key={option.value} value={option.value} title={shortcutTitle(option)}>
345 {option.label}
346 </Toggle>
347 ))}
348 </ToggleGroup>
349 {/* The period does not apply to Limits, so it stays in place but
350 disabled; unmounting it shifted the metric toggle ~300px. */}
351 <ToggleGroup
352 aria-label="Usage period"
353 variant="segmented"
354 value={[String(windowDays)]}
355 disabled={showingLimits}
356 onValueChange={(next) => {
357 const value = next[0];
358 if (value) selectWindow(Number(value));
359 }}
360 >
361 {WINDOW_OPTIONS.map((option) => (
362 <Toggle key={option.days} value={String(option.days)} title={shortcutTitle(option)}>
363 {option.label}
364 </Toggle>
365 ))}
366 </ToggleGroup>
367 <Button
368 onClick={refreshWindow}
369 aria-label={showingLimits ? "Refresh limits" : "Refresh usage"}
370 aria-busy={isRefreshing}
371 disabled={isRefreshing}
372 size="icon-sm"
373 variant="ghost"
374 >
375 <RefreshIcon size="sm" refreshing={isRefreshing} />
376 </Button>
377 </div>
378 <div className="col-span-2 ms-auto flex min-w-0 items-center justify-end gap-1 xl:hidden">
379 <Select
380 value={metric}
381 onValueChange={(value) => {
382 if (isUsageMetric(value)) selectMetric(value);
383 }}
384 >
385 <SelectTrigger
386 aria-label="Usage metric"
387 size="compact"
388 variant="ghost"
389 className="w-auto min-w-0"
390 >
391 <SelectValue>
392 {METRIC_OPTIONS.find((option) => option.value === metric)?.label}
393 </SelectValue>
394 </SelectTrigger>
395 <SelectPopup align="end" alignItemWithTrigger={false}>
396 {METRIC_OPTIONS.map((option) => (
397 <SelectItem key={option.value} value={option.value} title={shortcutTitle(option)}>
398 {option.label}
399 </SelectItem>
400 ))}
401 </SelectPopup>
402 </Select>
403 <Select
404 value={String(windowDays)}
405 disabled={showingLimits}
406 onValueChange={(value) => selectWindow(Number(value))}
407 >
408 <SelectTrigger
409 aria-label="Usage period"
410 size="compact"
411 variant="ghost"
412 className="w-auto min-w-0"
413 >
414 <SelectValue>
415 {WINDOW_OPTIONS.find((option) => option.days === windowDays)?.label}
416 </SelectValue>
417 </SelectTrigger>
418 <SelectPopup align="end" alignItemWithTrigger={false}>
419 {WINDOW_OPTIONS.map((option) => (
420 <SelectItem
421 key={option.days}
422 value={String(option.days)}
423 title={shortcutTitle(option)}
424 >
425 {option.label}
426 </SelectItem>
427 ))}
428 </SelectPopup>
429 </Select>
430 <Button
431 onClick={refreshWindow}
432 aria-label={showingLimits ? "Refresh limits" : "Refresh usage"}
433 aria-busy={isRefreshing}
434 disabled={isRefreshing}
435 size="icon-sm"
436 variant="ghost"
437 >
438 <RefreshIcon size="sm" refreshing={isRefreshing} />
439 </Button>
440 </div>
441 </div>
442 );
443
444 return (
445 <SidebarInset className="h-dvh min-h-0 overflow-hidden overscroll-y-none isolate">
446 <div className="flex min-h-0 min-w-0 flex-1 flex-col bg-background text-foreground">
447 <WorkspacePageHeader electron={isElectron} className="h-auto">
448 {topbarContent}
449 </WorkspacePageHeader>
450
451 <ScrollArea className="min-h-0 flex-1">
452 <WorkspacePageContainer width="wide">
453 {selectedEnvironments.length === 0 ? (
454 <p className="text-sm text-muted-foreground">
455 {environments.length === 0
456 ? `Connect an environment to see ${showingLimits ? "limits" : "usage"}.`
457 : `Select an environment to see ${showingLimits ? "limits" : "usage"}.`}
458 </p>
459 ) : showingLimits ? (
460 <UsageLimitsSection
461 selectedEnvironmentIds={selectedEnvironmentIds}
462 now={limitsNow}
463 cursorPrompt={
464 cursorAccessEnvironments.length > 0 ? (
465 <CursorEnableLimits
466 environments={cursorAccessEnvironments}
467 onEnabled={() => {
468 void refresh();
469 void refreshLimits(false, true);
470 }}
471 />
472 ) : null
473 }
474 />
475 ) : isPending ? (
476 <UsageSkeleton />
477 ) : (
478 <>
479 {sourceMessages.map((message) => (
480 <p key={message} className="mb-4 text-sm text-muted-foreground">
481 {message}
482 </p>
483 ))}
484 <section className="grid gap-6 lg:grid-cols-[minmax(0,18rem)_minmax(0,1fr)]">
485 <div className="flex min-w-0 flex-col gap-5">
486 <div className="flex flex-col gap-1">
487 <span className="text-4xl font-semibold text-foreground tabular-nums">
488 {metric === "cost"
489 ? formatUsd(merged.costUsd)
490 : formatTokens(merged.totalTokens)}
491 </span>
492 <span className="text-xs text-muted-foreground">
493 {formatCount(merged.sessions)} sessions
494 {metric === "cost" && (
495 <>
496 {" · API estimate"}
497 {merged.costQuality.unpricedShare > 0 && (
498 <>
499 {" "}
500 <Popover>
501 <PopoverTrigger
502 openOnHover
503 render={<InlineButton tone="muted" />}
504 aria-label="Unpriced usage details"
505 >
506 <InfoIcon className="size-3" aria-hidden />
507 </PopoverTrigger>
508 <PopoverPopup side="top" tooltipStyle>
509 API estimate excludes{" "}
510 {formatPercent(merged.costQuality.unpricedShare)} unpriced
511 records.
512 </PopoverPopup>
513 </Popover>
514 </>
515 )}
516 </>
517 )}
518 </span>
519 </div>
520
521 {[...presentations].some(
522 ([id, presentation]) =>
523 (selectedEnvironmentIds === null || selectedEnvironmentIds.has(id)) &&
524 presentation.serverConfig?.providers.some(usesChatGptSharing),
525 ) ? (
526 <div className="flex items-center justify-between gap-2 text-xs text-muted-foreground">
527 <span>ChatGPT shared usage</span>
528 <ChatGptUsageButton size="xs" />
529 </div>
530 ) : null}
531
532 {summaryRows.map((row) => {
533 if (row.kind === "enable") {
534 return (
535 <CursorEnableRow
536 key={`enable:${row.environment.environmentId}`}
537 environmentId={row.environment.environmentId}
538 label={row.environment.label}
539 showEnvironment={selectedEnvironments.length > 1}
540 onEnabled={() => {
541 void refresh();
542 void refreshLimits(false, true);
543 }}
544 />
545 );
546 }
547 const provider = row.provider;
548 const totals = merged.providers.find((entry) => entry.provider === provider);
549 const share =
550 metric === "cost" ? (totals?.costShare ?? 0) : (totals?.tokenShare ?? 0);
551 const providerSessions = totals?.sessions ?? 0;
552 const sessionLabel = `${formatCount(providerSessions)} ${
553 providerSessions === 1 ? "session" : "sessions"
554 }`;
555 return (
556 <div key={provider} className="flex flex-col gap-1">
557 <div className="flex items-baseline justify-between gap-4">
558 <span className="flex min-w-0 items-center gap-2 text-sm text-foreground">
559 <span
560 aria-hidden
561 className="size-2 shrink-0 rounded-full"
562 style={{
563 backgroundColor: PROVIDER_PRESENTATION[provider].color,
564 }}
565 />
566 <ProviderMark provider={provider} className="size-4" />
567 <span className="flex min-w-0 items-baseline gap-1.5">
568 <span className="truncate">
569 {PROVIDER_PRESENTATION[provider].label}
570 </span>
571 <span className="shrink-0 whitespace-nowrap text-2xs text-muted-foreground tabular-nums">
572 {sessionLabel}
573 </span>
574 </span>
575 </span>
576 <span className="shrink-0 text-sm font-medium text-foreground tabular-nums">
577 {metric === "cost"
578 ? formatUsd(totals?.costUsd ?? 0)
579 : formatTokens(totals?.totalTokens ?? 0)}
580 </span>
581 </div>
582 <span className="text-xs text-muted-foreground">
583 {metric === "cost"
584 ? `${formatPercent(share)} of cost · ${formatTokens(totals?.totalTokens ?? 0)} tokens`
585 : `${formatPercent(share)} of tokens · ${formatUsd(totals?.costUsd ?? 0)}`}
586 </span>
587 </div>
588 );
589 })}
590 </div>
591
592 <div className="flex min-w-0 flex-col gap-3">
593 <h2 className="text-sm font-medium text-foreground">
594 {isPast24Hours ? "Hourly" : "Daily"}{" "}
595 {metric === "tokens" ? "processed tokens" : "cost"}
596 </h2>
597 <UsageProviderChart
598 providers={activeProviders}
599 days={days}
600 daily={merged.daily}
601 hours={hours}
602 hourly={merged.hourly}
603 metric={metric}
604 referenceTime={window.untilTime}
605 resolution={isPast24Hours ? "hour" : "day"}
606 timeZone={window.timeZone}
607 />
608 </div>
609 </section>
610
611 <section className="flex flex-col gap-2">
612 <h2 className="text-sm font-medium text-foreground">Totals</h2>
613 <div className="grid grid-cols-2 gap-x-6 gap-y-4 py-1 md:grid-cols-5">
614 <Metric label="Processed tokens" value={formatTokens(merged.totalTokens)} />
615 <Metric label="Cached input" value={formatTokens(merged.cachedInputTokens)} />
616 <Metric
617 label="Uncached input"
618 value={formatTokens(merged.uncachedInputTokens)}
619 />
620 <Metric label="Output" value={formatTokens(merged.outputTokens)} />
621 <Metric
622 label="Cache savings"
623 value={formatUsd(merged.costQuality.cacheSavingsUsd)}
624 />
625 </div>
626 </section>
627
628 <section className="flex flex-col gap-3">
629 <div className="flex items-center justify-between gap-3">
630 <h2 className="text-sm font-medium text-foreground">Breakdown</h2>
631 <ToggleGroup
632 aria-label="Usage breakdown"
633 variant="segmented"
634 value={[breakdown]}
635 onValueChange={(next) => {
636 const value = next[0];
637 if (value === "model" || value === "time") setBreakdown(value);
638 }}
639 >
640 {(
641 [
642 { value: "model", label: "Model" },
643 { value: "time", label: isPast24Hours ? "Hour" : "Day" },
644 ] as const
645 ).map((option) => (
646 <Toggle key={option.value} value={option.value}>
647 {option.label}
648 </Toggle>
649 ))}
650 </ToggleGroup>
651 </div>
652
653 {breakdown === "model" ? (
654 <table className="w-full table-fixed text-sm">
655 <colgroup>
656 <col className="w-2/5" />
657 <col className="w-1/5" />
658 <col className="w-1/5" />
659 <col className="w-1/5" />
660 </colgroup>
661 <thead>
662 <tr className="border-b border-border text-left text-xs text-muted-foreground">
663 <th className="py-2 font-normal">Model</th>
664 <th className="py-2 text-right font-normal">Cost</th>
665 <th className="py-2 text-right font-normal">Share</th>
666 <th className="py-2 text-right font-normal">Tokens</th>
667 </tr>
668 </thead>
669 <tbody>
670 {breakdownModels.length === 0 ? (
671 <tr>
672 <td colSpan={4} className="py-6 text-center text-muted-foreground">
673 No activity in this window.
674 </td>
675 </tr>
676 ) : (
677 breakdownModels.map((model) => (
678 <tr
679 key={`${model.provider}:${model.model}`}
680 className="border-b border-border/50 transition-colors hover:bg-muted/50"
681 >
682 <td className="py-2 text-foreground">
683 <span className="flex items-center gap-2">
684 <ProviderMark provider={model.provider} className="size-3.5" />
685 {model.model}
686 </span>
687 </td>
688 <td className="py-2 text-right text-foreground tabular-nums">
689 {isModelCostUnknown(model) ? (
690 <span className="text-muted-foreground">Unpriced</span>
691 ) : (
692 formatUsd(model.costUsd)
693 )}
694 </td>
695 <td className="py-2 text-right text-muted-foreground tabular-nums">
696 {isModelCostUnknown(model) ? "—" : formatPercent(model.costShare)}
697 </td>
698 <td className="py-2 text-right text-muted-foreground tabular-nums">
699 {formatTokens(model.totalTokens)}
700 </td>
701 </tr>
702 ))
703 )}
704 </tbody>
705 </table>
706 ) : (
707 <table className="w-full table-fixed text-sm">
708 <colgroup>
709 <col className="w-2/5" />
710 {activeProviders.map((provider) => (
711 <col key={provider} style={{ width: timeValueColumnWidth }} />
712 ))}
713 <col style={{ width: timeValueColumnWidth }} />
714 <col style={{ width: timeValueColumnWidth }} />
715 </colgroup>
716 <thead>
717 <tr className="border-b border-border text-left text-xs text-muted-foreground">
718 <th className="py-2 font-normal">{isPast24Hours ? "Hour" : "Day"}</th>
719 {activeProviders.map((provider) => (
720 <th key={provider} className="py-2 text-right font-normal">
721 {PROVIDER_PRESENTATION[provider].label}
722 </th>
723 ))}
724 <th className="py-2 text-right font-normal">Total</th>
725 <th className="py-2 text-right font-normal">Tokens</th>
726 </tr>
727 </thead>
728 <tbody>
729 {breakdownPeriods.length === 0 ? (
730 <tr>
731 <td
732 colSpan={activeProviders.length + 3}
733 className="py-6 text-center text-muted-foreground"
734 >
735 No activity in this window.
736 </td>
737 </tr>
738 ) : (
739 breakdownPeriods.map((period) => (
740 <tr
741 key={"hourStart" in period ? period.hourStart : period.day}
742 className="border-b border-border/50 transition-colors hover:bg-muted/50"
743 >
744 <td className="py-2 text-foreground">
745 {"hourStart" in period
746 ? formatHourShort(period.hourStart, window.timeZone)
747 : formatDayShort(period.day)}
748 </td>
749 {activeProviders.map((provider) => (
750 <td
751 key={provider}
752 className="py-2 text-right text-muted-foreground tabular-nums"
753 >
754 {formatUsd(period.byProvider.get(provider)?.costUsd ?? 0)}
755 </td>
756 ))}
757 <td className="py-2 text-right text-foreground tabular-nums">
758 {formatUsd(period.costUsd)}
759 </td>
760 <td className="py-2 text-right text-muted-foreground tabular-nums">
761 {formatTokens(period.totalTokens)}
762 </td>
763 </tr>
764 ))
765 )}
766 </tbody>
767 </table>
768 )}
769 </section>
770 </>
771 )}
772 </WorkspacePageContainer>
773 </ScrollArea>
774 </div>
775 </SidebarInset>
776 );
777}
778
779const CURSOR_KEYCHAIN_COPY = "Requires access to your Cursor login in macOS Keychain.";
780
781function CursorEnableButton({
782 environmentId,
783 label,
784 onEnabled,
785 tooltip,
786 buttonText = "Enable",
787}: {
788 readonly environmentId: EnvironmentId;
789 readonly label: string;
790 readonly onEnabled: () => void;
791 readonly tooltip: boolean;
792 readonly buttonText?: string;
793}) {
794 const updateSettings = useAtomCommand(serverEnvironment.updateSettings, {
795 label: "enable Cursor account usage",
796 });
797 const [pending, setPending] = useState(false);
798 const enable = async () => {
799 setPending(true);
800 try {
801 const result = await updateSettings({
802 environmentId,
803 input: { patch: { cursorKeychainUsageEnabled: true } },
804 });
805 if (result._tag === "Success") onEnabled();
806 } finally {
807 setPending(false);
808 }
809 };
810 const button = tooltip ? (
811 <InlineButton
812 disabled={pending}
813 aria-busy={pending}
814 aria-label={`Enable Cursor usage from ${label}`}
815 onClick={() => void enable()}
816 >
817 {buttonText}
818 </InlineButton>
819 ) : (
820 <Button
821 size="sm"
822 variant="outline"
823 disabled={pending}
824 aria-busy={pending}
825 aria-label={`Enable Cursor usage from ${label}`}
826 onClick={() => void enable()}
827 >
828 {buttonText}
829 </Button>
830 );
831 if (!tooltip) return button;
832 return (
833 <Tooltip>
834 <TooltipTrigger render={button} />
835 <TooltipPopup>{CURSOR_KEYCHAIN_COPY}</TooltipPopup>
836 </Tooltip>
837 );
838}
839
840function CursorEnableRow({
841 environmentId,
842 label,
843 showEnvironment,
844 onEnabled,
845}: {
846 readonly environmentId: EnvironmentId;
847 readonly label: string;
848 readonly showEnvironment: boolean;
849 readonly onEnabled: () => void;
850}) {
851 return (
852 <div className="flex min-w-0 items-baseline justify-between gap-4 text-sm">
853 <span className="flex min-w-0 items-center gap-2 text-sm text-foreground">
854 <span
855 aria-hidden
856 className="size-2 shrink-0 rounded-full"
857 style={{ backgroundColor: PROVIDER_PRESENTATION.cursor.color }}
858 />
859 <ProviderMark provider="cursor" className="size-4" />
860 <span className="truncate">Cursor{showEnvironment ? ` · ${label}` : ""}</span>
861 </span>
862 <CursorEnableButton
863 environmentId={environmentId}
864 label={label}
865 onEnabled={onEnabled}
866 tooltip
867 />
868 </div>
869 );
870}
871
872function CursorEnableLimits({
873 environments,
874 onEnabled,
875}: {
876 readonly environments: readonly EnvironmentUsageStatus[];
877 readonly onEnabled: () => void;
878}) {
879 return (
880 <section className="flex flex-col gap-3">
881 <h2 className="flex items-center gap-2 text-sm font-medium text-foreground">
882 <ProviderInstanceIcon
883 driverKind={ProviderDriverKind.make("cursor")}
884 displayName="Cursor"
885 indicatorBackground="var(--background)"
886 className="size-5"
887 iconClassName="size-4 text-foreground/80"
888 />
889 Cursor
890 </h2>
891 <div className="flex flex-col items-start gap-3 rounded-lg border border-border/60 p-4">
892 <p className="text-xs text-muted-foreground">{CURSOR_KEYCHAIN_COPY}</p>
893 <div className="flex flex-wrap gap-2">
894 {environments.map((environment) => (
895 <CursorEnableButton
896 key={environment.environmentId}
897 environmentId={environment.environmentId}
898 label={environment.label}
899 buttonText={environments.length > 1 ? `Enable on ${environment.label}` : "Enable"}
900 onEnabled={onEnabled}
901 tooltip={false}
902 />
903 ))}
904 </div>
905 </div>
906 </section>
907 );
908}
909
910/** Brand mark for the harness a row belongs to. */
911function ProviderMark({
912 provider,
913 className,
914}: {
915 readonly provider: UsageProviderKind;
916 readonly className: string;
917}) {
918 const Mark = PROVIDER_PRESENTATION[provider].mark;
919 return <Mark className={cn("shrink-0", className)} aria-hidden />;
920}
921
922function Metric({ label, value }: { readonly label: string; readonly value: string }) {
923 return (
924 <div className="flex min-w-0 flex-col gap-0.5">
925 <span className="text-xs text-muted-foreground">{label}</span>
926 <span className="text-base font-medium text-foreground tabular-nums">{value}</span>
927 </div>
928 );
929}
930
931/**
932 * Explains failed or incompatible environments and deduplicated transcripts.
933 * Shown inside the environment filter so arriving results do not move the page.
934 */
935function UsageCoverageNotice({
936 environments,
937 duplicateSources,
938 contractMismatches,
939}: {
940 readonly environments: readonly EnvironmentUsageStatus[];
941 readonly duplicateSources: readonly string[];
942 readonly contractMismatches: MergedUsage["contractMismatches"];
943}) {
944 const failed = environments.filter((environment) => environment.error !== null);
945 const mismatchByEnvironment = new Map(
946 contractMismatches.map((mismatch) => [mismatch.environmentId, mismatch]),
947 );
948 const incompatible = environments.flatMap((environment) => {
949 const mismatch = mismatchByEnvironment.get(environment.environmentId);
950 return mismatch === undefined ? [] : [{ environment, mismatch }];
951 });
952 if (failed.length === 0 && incompatible.length === 0 && duplicateSources.length === 0) {
953 return null;
954 }
955
956 return (
957 <div className="flex flex-col gap-1 border-t border-border px-2 py-2 text-xs text-muted-foreground">
958 {failed.map((environment) => (
959 <span key={environment.label}>{environment.label} could not report usage.</span>
960 ))}
961 {incompatible.map(({ environment, mismatch }) => (
962 <span key={environment.environmentId}>
963 {formatUsageContractMismatch(environment.label, mismatch)}
964 </span>
965 ))}
966 {duplicateSources.length > 0 ? (
967 <span>
968 Counted once across environments sharing a transcript directory:{" "}
969 {duplicateSources.join(", ")}
970 </span>
971 ) : null}
972 </div>
973 );
974}
975
976/** Environment selection and scan progress share a permanent header control. */
977function UsageEnvironmentFilter({
978 environments,
979 selectedEnvironments,
980 selectedEnvironmentIds,
981 onSelectionChange,
982 showUsageStatus,
983 isPartial,
984 duplicateSources,
985 contractMismatches,
986}: {
987 readonly environments: readonly EnvironmentUsageStatus[];
988 readonly selectedEnvironments: readonly EnvironmentUsageStatus[];
989 readonly selectedEnvironmentIds: ReadonlySet<EnvironmentId> | null;
990 readonly onSelectionChange: (ids: ReadonlySet<EnvironmentId> | null) => void;
991 readonly showUsageStatus: boolean;
992 readonly isPartial: boolean;
993 readonly duplicateSources: readonly string[];
994 readonly contractMismatches: MergedUsage["contractMismatches"];
995}) {
996 const [modelPricesOpen, setModelPricesOpen] = useState(false);
997 const allSelected = selectedEnvironmentIds === null;
998 const label = allSelected
999 ? "All environments"
1000 : selectedEnvironments.length === 1
1001 ? selectedEnvironments[0]!.label
1002 : `${selectedEnvironments.length} environments`;
1003 const pendingCount = selectedEnvironments.filter(
1004 (environment) =>
1005 environment.error === null && (environment.isPending || environment.summary === null),
1006 ).length;
1007 const hasIssue =
1008 selectedEnvironments.some((environment) => environment.error !== null) ||
1009 contractMismatches.length > 0;
1010
1011 return (
1012 <>
1013 <Menu>
1014 <MenuTrigger
1015 render={<InlineButton />}
1016 className="group/usage-environment min-w-0 max-w-full"
1017 >
1018 <span className="min-w-0 truncate">{label}</span>
1019 <span className="flex size-3.5 shrink-0 items-center justify-center text-muted-foreground">
1020 {showUsageStatus && pendingCount > 0 ? (
1021 <>
1022 <CircleDashedIcon className="size-3.5" aria-hidden />
1023 <span className="sr-only">
1024 {pendingCount} {pendingCount === 1 ? "environment" : "environments"} still
1025 scanning
1026 {isPartial ? "; totals are partial" : ""}
1027 </span>
1028 </>
1029 ) : showUsageStatus && hasIssue ? (
1030 <CircleAlertIcon
1031 className="size-3.5 text-warning-foreground"
1032 aria-label="Some environments could not report usage"
1033 />
1034 ) : (
1035 <ChevronDownIcon
1036 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"
1037 aria-hidden
1038 />
1039 )}
1040 </span>
1041 </MenuTrigger>
1042 <MenuPopup align="start">
1043 <MenuCheckboxItem
1044 checked={allSelected}
1045 closeOnClick={false}
1046 onCheckedChange={(checked) => onSelectionChange(checked ? null : new Set())}
1047 >
1048 All environments
1049 </MenuCheckboxItem>
1050 <MenuSeparator />
1051 {environments.map((environment) => {
1052 const checked =
1053 selectedEnvironmentIds === null ||
1054 selectedEnvironmentIds.has(environment.environmentId);
1055 const status =
1056 environment.error !== null
1057 ? "Unavailable"
1058 : environment.summary !== null &&
1059 !isCompatibleUsageContractVersion(
1060 environment.summary.contractVersion,
1061 USAGE_CONTRACT_VERSION,
1062 )
1063 ? "Update required"
1064 : environment.summary === null
1065 ? "Scanning…"
1066 : environment.isPending
1067 ? "Refreshing…"
1068 : "Ready";
1069 return (
1070 <MenuCheckboxItem
1071 key={environment.environmentId}
1072 checked={checked}
1073 closeOnClick={false}
1074 onCheckedChange={(nextChecked) => {
1075 const next = new Set(selectedEnvironments.map((entry) => entry.environmentId));
1076 if (nextChecked) next.add(environment.environmentId);
1077 else next.delete(environment.environmentId);
1078 onSelectionChange(next.size === environments.length ? null : next);
1079 }}
1080 >
1081 <span className="flex min-w-0 items-center gap-3">
1082 <span className="min-w-0 flex-1 truncate">{environment.label}</span>
1083 {showUsageStatus ? (
1084 <span
1085 className={cn(
1086 "shrink-0 text-xs text-muted-foreground",
1087 environment.error !== null && "text-destructive",
1088 )}
1089 >
1090 {status}
1091 </span>
1092 ) : null}
1093 </span>
1094 </MenuCheckboxItem>
1095 );
1096 })}
1097 {environments.length === 0 ? (
1098 <p className="px-2 py-2 text-xs text-muted-foreground">No environments connected.</p>
1099 ) : null}
1100 {showUsageStatus && isPartial ? (
1101 <p className="px-2 py-2 text-xs text-muted-foreground">
1102 Totals are partial while selected environments scan.
1103 </p>
1104 ) : null}
1105 {showUsageStatus ? (
1106 <UsageCoverageNotice
1107 environments={selectedEnvironments}
1108 duplicateSources={duplicateSources}
1109 contractMismatches={contractMismatches}
1110 />
1111 ) : null}
1112 <MenuSeparator />
1113 <MenuItem onClick={() => setModelPricesOpen(true)}>
1114 <SlidersHorizontalIcon aria-hidden />
1115 Model prices
1116 </MenuItem>
1117 </MenuPopup>
1118 </Menu>
1119 {modelPricesOpen ? (
1120 <UsagePriceOverrides
1121 usage={environments}
1122 initialSelectedEnvironmentIds={selectedEnvironmentIds}
1123 onOpenChange={setModelPricesOpen}
1124 />
1125 ) : null}
1126 </>
1127 );
1128}
1129
1130/**
1131 * Stand-in with the loaded page's shape, using the shared `Skeleton` bars so it
1132 * breathes with the same `animate-skeleton` pulse as every other loading state.
1133 * Replaced by results as soon as the first environment answers.
1134 */
1135function UsageSkeleton() {
1136 return (
1137 <>
1138 <section className="grid gap-6 lg:grid-cols-[minmax(0,18rem)_minmax(0,1fr)]">
1139 <div className="flex flex-col gap-5">
1140 <div className="flex flex-col gap-1">
1141 <Skeleton className="h-10 w-36" />
1142 <Skeleton className="h-4 w-32" />
1143 </div>
1144 {PROVIDER_ORDER.map((provider) => (
1145 <div key={provider} className="flex flex-col gap-1">
1146 <div className="flex min-h-5 items-center justify-between gap-4">
1147 <span className="flex items-center gap-2">
1148 <Skeleton shape="pill" className="size-2 shrink-0" />
1149 <Skeleton shape="pill" className="size-4 shrink-0" />
1150 <Skeleton className="h-3.5 w-20" />
1151 </span>
1152 <Skeleton className="h-3.5 w-14" />
1153 </div>
1154 <Skeleton className="h-4 w-36" />
1155 </div>
1156 ))}
1157 </div>
1158
1159 <div className="flex flex-col gap-3">
1160 <Skeleton className="h-5 w-24" />
1161 <div className="flex flex-col gap-1">
1162 <Skeleton className="ml-16 h-56" />
1163 <Skeleton className="ml-16 h-4" />
1164 </div>
1165 </div>
1166 </section>
1167
1168 <section className="flex flex-col gap-2">
1169 <h2 className="text-sm font-medium text-foreground">Totals</h2>
1170 <div className="grid grid-cols-2 gap-x-6 gap-y-4 py-1 md:grid-cols-5">
1171 {["Processed tokens", "Cached input", "Uncached input", "Output", "Cache savings"].map(
1172 (label) => (
1173 <div key={label} className="flex flex-col gap-0.5">
1174 <span className="text-xs text-muted-foreground">{label}</span>
1175 <Skeleton className="h-6 w-16" />
1176 </div>
1177 ),
1178 )}
1179 </div>
1180 </section>
1181
1182 <section className="flex flex-col gap-3">
1183 <div className="flex items-center justify-between gap-3">
1184 <h2 className="text-sm font-medium text-foreground">Breakdown</h2>
1185 <Skeleton shape="card" className="h-7 w-28" />
1186 </div>
1187 <Skeleton className="h-44" />
1188 </section>
1189 </>
1190 );
1191}