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