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 py-2 xl:flex">
332 <WorkspaceBreadcrumb ariaLabel="Usage breadcrumb" className="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="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}>{topbarContent}</WorkspacePageHeader>
471
472 <ScrollArea className="min-h-0 flex-1">
473 <WorkspacePageContainer width="wide">
474 {selectedEnvironments.length === 0 ? (
475 <p className="text-sm text-muted-foreground">
476 {environments.length === 0
477 ? `Connect an environment to see ${showingLimits ? "limits" : "usage"}.`
478 : `Select an environment to see ${showingLimits ? "limits" : "usage"}.`}
479 </p>
480 ) : showingLimits ? (
481 <UsageLimitsSection
482 selectedEnvironmentIds={selectedEnvironmentIds}
483 now={limitsNow}
484 cursorPrompt={
485 cursorAccessEnvironments.length > 0 ? (
486 <CursorEnableLimits
487 environments={cursorAccessEnvironments}
488 onEnabled={() => {
489 void refresh();
490 void refreshLimits(false, true);
491 }}
492 />
493 ) : null
494 }
495 />
496 ) : isPending ? (
497 <UsageSkeleton />
498 ) : !canReadDiagnostics ? (
499 <div className="space-y-2 py-12 text-center text-sm text-muted-foreground">
500 {selectedEnvironments.map((environment) => (
501 <p key={environment.environmentId}>
502 {selectedEnvironments.length > 1 ? `${environment.label}: ` : null}
503 {environment.error}
504 </p>
505 ))}
506 </div>
507 ) : (
508 <>
509 {sourceMessages.map((message) => (
510 <p key={message} className="mb-4 text-sm text-muted-foreground">
511 {message}
512 </p>
513 ))}
514 <section className="grid gap-6 lg:grid-cols-[minmax(0,18rem)_minmax(0,1fr)]">
515 <div className="flex min-w-0 flex-col gap-5">
516 <div className="flex flex-col gap-1">
517 <span className="text-4xl font-semibold text-foreground tabular-nums">
518 {metric === "cost"
519 ? formatUsd(merged.costUsd)
520 : formatTokens(merged.totalTokens)}
521 </span>
522 <span className="text-xs text-muted-foreground">
523 {formatCount(merged.sessions)} sessions
524 {metric === "cost" && (
525 <>
526 {" · API estimate"}
527 {merged.costQuality.unpricedShare > 0 && (
528 <>
529 {" "}
530 <Popover>
531 <PopoverTrigger
532 openOnHover
533 render={<InlineButton tone="muted" />}
534 aria-label="Unpriced usage details"
535 >
536 <InfoIcon className="size-3" aria-hidden />
537 </PopoverTrigger>
538 <PopoverPopup side="top" tooltipStyle>
539 API estimate excludes{" "}
540 {formatPercent(merged.costQuality.unpricedShare)} unpriced
541 records.
542 </PopoverPopup>
543 </Popover>
544 </>
545 )}
546 </>
547 )}
548 </span>
549 </div>
550
551 {[...presentations].some(
552 ([id, presentation]) =>
553 (selectedEnvironmentIds === null || selectedEnvironmentIds.has(id)) &&
554 presentation.serverConfig?.providers.some(usesChatGptSharing),
555 ) ? (
556 <div className="flex items-center justify-between gap-2 text-xs text-muted-foreground">
557 <span>ChatGPT shared usage</span>
558 <ChatGptUsageButton size="xs" />
559 </div>
560 ) : null}
561
562 {summaryRows.map((row) => {
563 if (row.kind === "enable") {
564 return (
565 <CursorEnableRow
566 key={`enable:${row.environment.environmentId}`}
567 environmentId={row.environment.environmentId}
568 label={row.environment.label}
569 showEnvironment={selectedEnvironments.length > 1}
570 onEnabled={() => {
571 void refresh();
572 void refreshLimits(false, true);
573 }}
574 />
575 );
576 }
577 const provider = row.provider;
578 const totals = merged.providers.find((entry) => entry.provider === provider);
579 const share =
580 metric === "cost" ? (totals?.costShare ?? 0) : (totals?.tokenShare ?? 0);
581 const providerSessions = totals?.sessions ?? 0;
582 const sessionLabel = `${formatCount(providerSessions)} ${
583 providerSessions === 1 ? "session" : "sessions"
584 }`;
585 return (
586 <div key={provider} className="flex flex-col gap-1">
587 <div className="flex items-baseline justify-between gap-4">
588 <span className="flex min-w-0 items-center gap-2 text-sm text-foreground">
589 <span
590 aria-hidden
591 className="size-2 shrink-0 rounded-full"
592 style={{
593 backgroundColor: PROVIDER_PRESENTATION[provider].color,
594 }}
595 />
596 <ProviderMark provider={provider} className="size-4" />
597 <span className="flex min-w-0 items-baseline gap-1.5">
598 <span className="truncate">
599 {PROVIDER_PRESENTATION[provider].label}
600 </span>
601 <span className="shrink-0 whitespace-nowrap text-2xs text-muted-foreground tabular-nums">
602 {sessionLabel}
603 </span>
604 </span>
605 </span>
606 <span className="shrink-0 text-sm font-medium text-foreground tabular-nums">
607 {metric === "cost"
608 ? formatUsd(totals?.costUsd ?? 0)
609 : formatTokens(totals?.totalTokens ?? 0)}
610 </span>
611 </div>
612 <span className="text-xs text-muted-foreground">
613 {metric === "cost"
614 ? `${formatPercent(share)} of cost · ${formatTokens(totals?.totalTokens ?? 0)} tokens`
615 : `${formatPercent(share)} of tokens · ${formatUsd(totals?.costUsd ?? 0)}`}
616 </span>
617 </div>
618 );
619 })}
620 </div>
621
622 <div className="flex min-w-0 flex-col gap-3">
623 <h2 className="text-sm font-medium text-foreground">
624 {isPast24Hours ? "Hourly" : "Daily"}{" "}
625 {metric === "tokens" ? "processed tokens" : "cost"}
626 </h2>
627 <UsageProviderChart
628 providers={activeProviders}
629 days={days}
630 daily={merged.daily}
631 hours={hours}
632 hourly={merged.hourly}
633 metric={metric}
634 referenceTime={window.untilTime}
635 resolution={isPast24Hours ? "hour" : "day"}
636 timeZone={window.timeZone}
637 />
638 </div>
639 </section>
640
641 <section className="flex flex-col gap-2">
642 <h2 className="text-sm font-medium text-foreground">Totals</h2>
643 <div className="grid grid-cols-2 gap-x-6 gap-y-4 py-1 md:grid-cols-5">
644 <Metric label="Processed tokens" value={formatTokens(merged.totalTokens)} />
645 <Metric label="Cached input" value={formatTokens(merged.cachedInputTokens)} />
646 <Metric
647 label="Uncached input"
648 value={formatTokens(merged.uncachedInputTokens)}
649 />
650 <Metric label="Output" value={formatTokens(merged.outputTokens)} />
651 <Metric
652 label="Cache savings"
653 value={formatUsd(merged.costQuality.cacheSavingsUsd)}
654 />
655 </div>
656 </section>
657
658 {merged.totalTokens > 0 ? (
659 <section className="grid gap-x-12 gap-y-8 lg:grid-cols-2">
660 {metric === "tokens" ? (
661 <UsageShareBar
662 label="Tokens by type"
663 segments={tokenTypeSegments(merged)}
664 format={formatTokens}
665 />
666 ) : (
667 <>
668 <UsageShareBar
669 label="Cost by type"
670 segments={costTypeSegments(merged.categoryCost)}
671 format={formatUsd}
672 />
673 {merged.speedCost.fast + merged.speedCost.ultrafast > 0 ? (
674 <UsageShareBar
675 label="Cost by speed"
676 segments={speedCostSegments(merged.speedCost)}
677 format={formatUsd}
678 aside={<SpeedPremium premiumUsd={merged.speedCost.premium} />}
679 />
680 ) : null}
681 </>
682 )}
683 </section>
684 ) : null}
685
686 <section className="flex flex-col gap-3">
687 <div className="flex items-center justify-between gap-3">
688 <h2 className="text-sm font-medium text-foreground">Breakdown</h2>
689 <ToggleGroup
690 aria-label="Usage breakdown"
691 variant="segmented"
692 value={[breakdown]}
693 onValueChange={(next) => {
694 const value = next[0];
695 if (value === "model" || value === "time") setBreakdown(value);
696 }}
697 >
698 {(
699 [
700 { value: "model", label: "Model" },
701 { value: "time", label: isPast24Hours ? "Hour" : "Day" },
702 ] as const
703 ).map((option) => (
704 <Toggle key={option.value} value={option.value}>
705 {option.label}
706 </Toggle>
707 ))}
708 </ToggleGroup>
709 </div>
710
711 {breakdown === "model" ? (
712 <table className="w-full text-sm">
713 <thead>
714 <tr className="border-b border-border text-right text-xs text-muted-foreground">
715 <th className="py-2 pr-3 text-left font-normal">#</th>
716 <th className="w-full py-2 text-left font-normal">Model</th>
717 <th className="py-2 pl-6 font-normal">Cost</th>
718 <th className="hidden py-2 pl-6 font-normal sm:table-cell">Share</th>
719 <th className="py-2 pl-6 font-normal">Tokens</th>
720 </tr>
721 </thead>
722 <tbody>
723 {breakdownModels.length === 0 ? (
724 <tr>
725 <td colSpan={5} className="py-6 text-center text-muted-foreground">
726 No activity in this window.
727 </td>
728 </tr>
729 ) : (
730 breakdownModels.map((model, index) => {
731 const key = `${model.provider}:${model.model}`;
732 const value = metric === "tokens" ? model.totalTokens : model.costUsd;
733 const share = modelShare(
734 model,
735 metric === "tokens" ? "tokens" : "cost",
736 );
737 return (
738 <tr
739 key={key}
740 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"
741 >
742 <td className="py-2.5 pr-3 text-left text-xs">{index + 1}</td>
743 <td className="py-2.5 text-left whitespace-normal">
744 {/* The button's overlay makes the whole row open the model.
745 Focus shows as the row's hover fill, not a ring. */}
746 <button
747 type="button"
748 onClick={() => setSelectedModelKey(key)}
749 className="flex items-center gap-2 text-left text-foreground outline-none after:absolute after:inset-0"
750 >
751 <ProviderMark provider={model.provider} className="size-3.5" />
752 {model.model}
753 </button>
754 <div aria-hidden className="mt-1.5 h-0.5 max-w-48">
755 <div
756 className="h-full rounded-full"
757 style={{
758 // A short minimum keeps tiny shares a dash, not a dot.
759 width:
760 value > 0 && breakdownPeak > 0
761 ? `max(0.5rem, ${(value / breakdownPeak) * 100}%)`
762 : 0,
763 backgroundColor:
764 PROVIDER_PRESENTATION[model.provider].color,
765 }}
766 />
767 </div>
768 </td>
769 <td className="py-2.5 pl-6 text-foreground">
770 {isModelCostUnknown(model) ? (
771 <span className="text-muted-foreground">Unpriced</span>
772 ) : (
773 formatUsd(model.costUsd)
774 )}
775 </td>
776 <td className="hidden py-2.5 pl-6 sm:table-cell">
777 {share === null ? "" : formatPercent(share)}
778 </td>
779 <td className="py-2.5 pl-6">{formatTokens(model.totalTokens)}</td>
780 </tr>
781 );
782 })
783 )}
784 </tbody>
785 </table>
786 ) : (
787 <table className="w-full table-fixed text-sm">
788 <colgroup>
789 <col className="w-2/5" />
790 {activeProviders.map((provider) => (
791 <col key={provider} style={{ width: timeValueColumnWidth }} />
792 ))}
793 <col style={{ width: timeValueColumnWidth }} />
794 <col style={{ width: timeValueColumnWidth }} />
795 </colgroup>
796 <thead>
797 <tr className="border-b border-border text-left text-xs text-muted-foreground">
798 <th className="py-2 font-normal">{isPast24Hours ? "Hour" : "Day"}</th>
799 {activeProviders.map((provider) => (
800 <th key={provider} className="py-2 text-right font-normal">
801 {PROVIDER_PRESENTATION[provider].label}
802 </th>
803 ))}
804 <th className="py-2 text-right font-normal">Total</th>
805 <th className="py-2 text-right font-normal">Tokens</th>
806 </tr>
807 </thead>
808 <tbody>
809 {breakdownPeriods.length === 0 ? (
810 <tr>
811 <td
812 colSpan={activeProviders.length + 3}
813 className="py-6 text-center text-muted-foreground"
814 >
815 No activity in this window.
816 </td>
817 </tr>
818 ) : (
819 breakdownPeriods.map((period) => (
820 <tr
821 key={"hourStart" in period ? period.hourStart : period.day}
822 className="border-b border-border/50 transition-colors hover:bg-muted/50"
823 >
824 <td className="py-2 text-foreground">
825 {"hourStart" in period
826 ? formatHourShort(period.hourStart, window.timeZone)
827 : formatDayShort(period.day)}
828 </td>
829 {activeProviders.map((provider) => (
830 <td
831 key={provider}
832 className="py-2 text-right text-muted-foreground tabular-nums"
833 >
834 {formatUsd(period.byProvider.get(provider)?.costUsd ?? 0)}
835 </td>
836 ))}
837 <td className="py-2 text-right text-foreground tabular-nums">
838 {formatUsd(period.costUsd)}
839 </td>
840 <td className="py-2 text-right text-muted-foreground tabular-nums">
841 {formatTokens(period.totalTokens)}
842 </td>
843 </tr>
844 ))
845 )}
846 </tbody>
847 </table>
848 )}
849 </section>
850 </>
851 )}
852 </WorkspacePageContainer>
853 </ScrollArea>
854 </div>
855 {selectedModel !== undefined && !showingLimits ? (
856 <UsageModelDialog
857 model={selectedModel}
858 environments={selectedEnvironments}
859 metric={metric === "tokens" ? "tokens" : "cost"}
860 chartWindow={{
861 days,
862 hours,
863 resolution: isPast24Hours ? "hour" : "day",
864 timeZone: window.timeZone,
865 referenceTime: window.untilTime,
866 }}
867 onSetPrice={() => {
868 setSelectedModelKey(null);
869 setPriceDialog({ model: selectedModel.model });
870 }}
871 onClose={() => setSelectedModelKey(null)}
872 />
873 ) : null}
874 {priceDialog ? (
875 <UsagePriceOverrides
876 usage={environments}
877 initialSelectedEnvironmentIds={selectedEnvironmentIds}
878 initialModel={priceDialog.model}
879 onOpenChange={(open) => {
880 if (!open) setPriceDialog(null);
881 }}
882 />
883 ) : null}
884 </SidebarInset>
885 );
886}
887
888const CURSOR_KEYCHAIN_COPY = "Requires access to your Cursor login in macOS Keychain.";
889
890function CursorEnableButton({
891 environmentId,
892 label,
893 onEnabled,
894 tooltip,
895 buttonText = "Enable",
896}: {
897 readonly environmentId: EnvironmentId;
898 readonly label: string;
899 readonly onEnabled: () => void;
900 readonly tooltip: boolean;
901 readonly buttonText?: string;
902}) {
903 const updateSettings = useAtomCommand(serverEnvironment.updateSettings, {
904 label: "enable Cursor account usage",
905 });
906 const [pending, setPending] = useState(false);
907 const enable = async () => {
908 setPending(true);
909 try {
910 const result = await updateSettings({
911 environmentId,
912 input: { patch: { cursorKeychainUsageEnabled: true } },
913 });
914 if (result._tag === "Success") onEnabled();
915 } finally {
916 setPending(false);
917 }
918 };
919 const button = tooltip ? (
920 <InlineButton
921 disabled={pending}
922 aria-busy={pending}
923 aria-label={`Enable Cursor usage from ${label}`}
924 onClick={() => void enable()}
925 >
926 {buttonText}
927 </InlineButton>
928 ) : (
929 <Button
930 size="sm"
931 variant="outline"
932 disabled={pending}
933 aria-busy={pending}
934 aria-label={`Enable Cursor usage from ${label}`}
935 onClick={() => void enable()}
936 >
937 {buttonText}
938 </Button>
939 );
940 if (!tooltip) return button;
941 return (
942 <Tooltip>
943 <TooltipTrigger render={button} />
944 <TooltipPopup>{CURSOR_KEYCHAIN_COPY}</TooltipPopup>
945 </Tooltip>
946 );
947}
948
949function CursorEnableRow({
950 environmentId,
951 label,
952 showEnvironment,
953 onEnabled,
954}: {
955 readonly environmentId: EnvironmentId;
956 readonly label: string;
957 readonly showEnvironment: boolean;
958 readonly onEnabled: () => void;
959}) {
960 return (
961 <div className="flex min-w-0 items-baseline justify-between gap-4 text-sm">
962 <span className="flex min-w-0 items-center gap-2 text-sm text-foreground">
963 <span
964 aria-hidden
965 className="size-2 shrink-0 rounded-full"
966 style={{ backgroundColor: PROVIDER_PRESENTATION.cursor.color }}
967 />
968 <ProviderMark provider="cursor" className="size-4" />
969 <span className="truncate">Cursor{showEnvironment ? ` · ${label}` : ""}</span>
970 </span>
971 <CursorEnableButton
972 environmentId={environmentId}
973 label={label}
974 onEnabled={onEnabled}
975 tooltip
976 />
977 </div>
978 );
979}
980
981function CursorEnableLimits({
982 environments,
983 onEnabled,
984}: {
985 readonly environments: readonly EnvironmentUsageStatus[];
986 readonly onEnabled: () => void;
987}) {
988 return (
989 <section className="flex flex-col gap-3">
990 <h2 className="flex items-center gap-2 text-sm font-medium text-foreground">
991 <ProviderInstanceIcon
992 driverKind={ProviderDriverKind.make("cursor")}
993 displayName="Cursor"
994 indicatorBackground="var(--background)"
995 className="size-5"
996 iconClassName="size-4 text-foreground/80"
997 />
998 Cursor
999 </h2>
1000 <div className="flex flex-col items-start gap-3 rounded-lg border border-border/60 p-4">
1001 <p className="text-xs text-muted-foreground">{CURSOR_KEYCHAIN_COPY}</p>
1002 <div className="flex flex-wrap gap-2">
1003 {environments.map((environment) => (
1004 <CursorEnableButton
1005 key={environment.environmentId}
1006 environmentId={environment.environmentId}
1007 label={environment.label}
1008 buttonText={environments.length > 1 ? `Enable on ${environment.label}` : "Enable"}
1009 onEnabled={onEnabled}
1010 tooltip={false}
1011 />
1012 ))}
1013 </div>
1014 </div>
1015 </section>
1016 );
1017}
1018
1019/** Brand mark for the harness a row belongs to. */
1020function ProviderMark({
1021 provider,
1022 className,
1023}: {
1024 readonly provider: UsageProviderKind;
1025 readonly className: string;
1026}) {
1027 const presentation = PROVIDER_PRESENTATION[provider];
1028 return (
1029 <ProviderInstanceIcon
1030 driverKind={presentation.driverKind}
1031 displayName={presentation.label}
1032 iconClassName={className}
1033 />
1034 );
1035}
1036
1037function Metric({ label, value }: { readonly label: string; readonly value: string }) {
1038 return (
1039 <div className="flex min-w-0 flex-col gap-0.5">
1040 <span className="text-xs text-muted-foreground">{label}</span>
1041 <span className="text-base font-medium text-foreground tabular-nums">{value}</span>
1042 </div>
1043 );
1044}
1045
1046/**
1047 * Explains failed or incompatible environments and deduplicated transcripts.
1048 * Shown inside the environment filter so arriving results do not move the page.
1049 */
1050function UsageCoverageNotice({
1051 environments,
1052 duplicateSources,
1053 contractMismatches,
1054}: {
1055 readonly environments: readonly EnvironmentUsageStatus[];
1056 readonly duplicateSources: readonly string[];
1057 readonly contractMismatches: MergedUsage["contractMismatches"];
1058}) {
1059 const failed = environments.filter((environment) => environment.error !== null);
1060 const mismatchByEnvironment = new Map(
1061 contractMismatches.map((mismatch) => [mismatch.environmentId, mismatch]),
1062 );
1063 const incompatible = environments.flatMap((environment) => {
1064 const mismatch = mismatchByEnvironment.get(environment.environmentId);
1065 return mismatch === undefined ? [] : [{ environment, mismatch }];
1066 });
1067 if (failed.length === 0 && incompatible.length === 0 && duplicateSources.length === 0) {
1068 return null;
1069 }
1070
1071 return (
1072 <div className="flex flex-col gap-1 border-t border-border px-2 py-2 text-xs text-muted-foreground">
1073 {failed.map((environment) => (
1074 <span key={environment.label}>
1075 {environment.label}: {environment.error}
1076 </span>
1077 ))}
1078 {incompatible.map(({ environment, mismatch }) => (
1079 <span key={environment.environmentId}>
1080 {formatUsageContractMismatch(environment.label, mismatch)}
1081 </span>
1082 ))}
1083 {duplicateSources.length > 0 ? (
1084 <span>
1085 Counted once across environments sharing a transcript directory:{" "}
1086 {duplicateSources.join(", ")}
1087 </span>
1088 ) : null}
1089 </div>
1090 );
1091}
1092
1093/** Environment selection and scan progress share a permanent header control. */
1094function UsageEnvironmentFilter({
1095 environments,
1096 selectedEnvironments,
1097 selectedEnvironmentIds,
1098 onSelectionChange,
1099 showUsageStatus,
1100 isPartial,
1101 duplicateSources,
1102 contractMismatches,
1103 onOpenModelPrices,
1104}: {
1105 readonly environments: readonly EnvironmentUsageStatus[];
1106 readonly selectedEnvironments: readonly EnvironmentUsageStatus[];
1107 readonly selectedEnvironmentIds: ReadonlySet<EnvironmentId> | null;
1108 readonly onSelectionChange: (ids: ReadonlySet<EnvironmentId> | null) => void;
1109 readonly showUsageStatus: boolean;
1110 readonly isPartial: boolean;
1111 readonly duplicateSources: readonly string[];
1112 readonly contractMismatches: MergedUsage["contractMismatches"];
1113 readonly onOpenModelPrices: () => void;
1114}) {
1115 const allSelected = selectedEnvironmentIds === null;
1116 const label = allSelected
1117 ? "All environments"
1118 : selectedEnvironments.length === 1
1119 ? selectedEnvironments[0]!.label
1120 : `${selectedEnvironments.length} environments`;
1121 const pendingCount = selectedEnvironments.filter(
1122 (environment) =>
1123 environment.error === null && (environment.isPending || environment.summary === null),
1124 ).length;
1125 const hasIssue =
1126 selectedEnvironments.some((environment) => environment.error !== null) ||
1127 contractMismatches.length > 0;
1128
1129 return (
1130 <Menu>
1131 <MenuTrigger render={<InlineButton />} className="group/usage-environment min-w-0 max-w-full">
1132 <span className="min-w-0 truncate">{label}</span>
1133 <span className="flex size-3.5 shrink-0 items-center justify-center text-muted-foreground">
1134 {showUsageStatus && pendingCount > 0 ? (
1135 <>
1136 <CircleDashedIcon className="size-3.5" aria-hidden />
1137 <span className="sr-only">
1138 {pendingCount} {pendingCount === 1 ? "environment" : "environments"} still scanning
1139 {isPartial ? "; totals are partial" : ""}
1140 </span>
1141 </>
1142 ) : showUsageStatus && hasIssue ? (
1143 <CircleAlertIcon
1144 className="size-3.5 text-warning-foreground"
1145 aria-label="Some environments could not report usage"
1146 />
1147 ) : (
1148 <ChevronDownIcon
1149 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"
1150 aria-hidden
1151 />
1152 )}
1153 </span>
1154 </MenuTrigger>
1155 <MenuPopup align="start">
1156 <MenuCheckboxItem
1157 checked={allSelected}
1158 closeOnClick={false}
1159 onCheckedChange={(checked) => onSelectionChange(checked ? null : new Set())}
1160 >
1161 All environments
1162 </MenuCheckboxItem>
1163 <MenuSeparator />
1164 {environments.map((environment) => {
1165 const checked =
1166 selectedEnvironmentIds === null ||
1167 selectedEnvironmentIds.has(environment.environmentId);
1168 const status =
1169 environment.error !== null
1170 ? "Unavailable"
1171 : environment.summary !== null &&
1172 !isCompatibleUsageContractVersion(
1173 environment.summary.contractVersion,
1174 USAGE_CONTRACT_VERSION,
1175 )
1176 ? "Update required"
1177 : environment.summary === null
1178 ? "Scanning…"
1179 : environment.isPending
1180 ? "Refreshing…"
1181 : "Ready";
1182 return (
1183 <MenuCheckboxItem
1184 key={environment.environmentId}
1185 checked={checked}
1186 closeOnClick={false}
1187 onCheckedChange={(nextChecked) => {
1188 const next = new Set(selectedEnvironments.map((entry) => entry.environmentId));
1189 if (nextChecked) next.add(environment.environmentId);
1190 else next.delete(environment.environmentId);
1191 onSelectionChange(next.size === environments.length ? null : next);
1192 }}
1193 >
1194 <span className="flex min-w-0 items-center gap-3">
1195 <span className="min-w-0 flex-1 truncate">{environment.label}</span>
1196 {showUsageStatus ? (
1197 <span
1198 className={cn(
1199 "shrink-0 text-xs text-muted-foreground",
1200 environment.error !== null && "text-destructive",
1201 )}
1202 >
1203 {status}
1204 </span>
1205 ) : null}
1206 </span>
1207 </MenuCheckboxItem>
1208 );
1209 })}
1210 {environments.length === 0 ? (
1211 <p className="px-2 py-2 text-xs text-muted-foreground">No environments connected.</p>
1212 ) : null}
1213 {showUsageStatus && isPartial ? (
1214 <p className="px-2 py-2 text-xs text-muted-foreground">
1215 Totals are partial while selected environments scan.
1216 </p>
1217 ) : null}
1218 {showUsageStatus ? (
1219 <UsageCoverageNotice
1220 environments={selectedEnvironments}
1221 duplicateSources={duplicateSources}
1222 contractMismatches={contractMismatches}
1223 />
1224 ) : null}
1225 <MenuSeparator />
1226 <MenuItem onClick={onOpenModelPrices}>
1227 <SlidersHorizontalIcon aria-hidden />
1228 Model prices
1229 </MenuItem>
1230 </MenuPopup>
1231 </Menu>
1232 );
1233}
1234
1235/**
1236 * Stand-in with the loaded page's shape, using the shared `Skeleton` bars so it
1237 * breathes with the same `animate-skeleton` pulse as every other loading state.
1238 * Replaced by results as soon as the first environment answers.
1239 */
1240function UsageSkeleton() {
1241 return (
1242 <>
1243 <section className="grid gap-6 lg:grid-cols-[minmax(0,18rem)_minmax(0,1fr)]">
1244 <div className="flex flex-col gap-5">
1245 <div className="flex flex-col gap-1">
1246 <Skeleton className="h-10 w-36" />
1247 <Skeleton className="h-4 w-32" />
1248 </div>
1249 {PROVIDER_ORDER.map((provider) => (
1250 <div key={provider} className="flex flex-col gap-1">
1251 <div className="flex min-h-5 items-center justify-between gap-4">
1252 <span className="flex items-center gap-2">
1253 <Skeleton shape="pill" className="size-2 shrink-0" />
1254 <Skeleton shape="pill" className="size-4 shrink-0" />
1255 <Skeleton className="h-3.5 w-20" />
1256 </span>
1257 <Skeleton className="h-3.5 w-14" />
1258 </div>
1259 <Skeleton className="h-4 w-36" />
1260 </div>
1261 ))}
1262 </div>
1263
1264 <div className="flex flex-col gap-3">
1265 <Skeleton className="h-5 w-24" />
1266 <div className="flex flex-col gap-1">
1267 <Skeleton className="ml-16 h-56" />
1268 <Skeleton className="ml-16 h-4" />
1269 </div>
1270 </div>
1271 </section>
1272
1273 <section className="flex flex-col gap-2">
1274 <h2 className="text-sm font-medium text-foreground">Totals</h2>
1275 <MetricSkeletons
1276 labels={["Processed tokens", "Cached input", "Uncached input", "Output", "Cache savings"]}
1277 />
1278 </section>
1279
1280 <section className="grid gap-x-12 gap-y-8 lg:grid-cols-2">
1281 <div className="flex flex-col gap-2.5">
1282 <Skeleton className="h-5 w-28" />
1283 <Skeleton className="h-2" />
1284 <Skeleton className="h-4 w-72" />
1285 </div>
1286 </section>
1287
1288 <section className="flex flex-col gap-3">
1289 <div className="flex items-center justify-between gap-3">
1290 <h2 className="text-sm font-medium text-foreground">Breakdown</h2>
1291 <Skeleton shape="card" className="h-7 w-28" />
1292 </div>
1293 <Skeleton className="h-44" />
1294 </section>
1295 </>
1296 );
1297}
1298
1299function MetricSkeletons({ labels }: { readonly labels: readonly string[] }) {
1300 return (
1301 <div className="grid grid-cols-2 gap-x-6 gap-y-4 py-1 md:grid-cols-5">
1302 {labels.map((label) => (
1303 <div key={label} className="flex flex-col gap-0.5">
1304 <span className="text-xs text-muted-foreground">{label}</span>
1305 <Skeleton className="h-6 w-16" />
1306 </div>
1307 ))}
1308 </div>
1309 );
1310}