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