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

UsagePage.tsx

1,297 lines50.8 KB

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