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