Open History to see the last commit
1import { Button } from "../../components/ui/Button";
2import { AppActivityIndicator } from "../../components/ui/AppActivityIndicator";
3import { ChatGptUsageSummary } from "./ChatGptUsageSummary";
4import { ScreenScrollView as ScrollView } from "../../components/ui/ScreenScrollView";
5import { EnvironmentId, USAGE_CONTRACT_VERSION, type UsageProviderKind } from "@t3tools/contracts";
6import { type RouteProp, useIsFocused, useRoute } from "@react-navigation/native";
7import { cursorKeychainAccessEnvironments } from "@t3tools/client-runtime/state/usage";
8import {
9 updatingProvidersLabel,
10 usageEnvironmentProgress,
11 usageProgress,
12} from "@t3tools/client-runtime/state/usage-progress";
13import {
14 isCompatibleUsageContractVersion,
15 isModelCostUnknown,
16 type DailyTotals,
17 type MergedUsage,
18} from "@t3tools/shared/usageMerge";
19import {
20 enumerateDays,
21 enumerateHourStarts,
22 formatCount,
23 formatDayShort,
24 formatHourShort,
25 formatPercent,
26 formatTokens,
27 formatUsageContractMismatch,
28 formatUsd,
29 makeWindow,
30 usageSourceMessages,
31} from "@t3tools/shared/usageFormat";
32import { useRef, useState, type ReactNode } from "react";
33import { Platform, RefreshControl, View } from "react-native";
34import Animated, { FadeIn, ReduceMotion } from "react-native-reanimated";
35import { useSafeAreaInsets } from "react-native-safe-area-context";
36
37import { SegmentedControl } from "../../components/ui/SegmentedControl";
38import { useReduceMotionEnabled } from "../../lib/appState";
39import { AppText as Text } from "../../components/ui/AppText";
40import { useWorkspaceSettledContentWidth } from "../layout/workspace-content-width";
41import { ProviderIcon } from "../../components/ProviderIcon";
42import { cn } from "../../lib/cn";
43import { SettingsScreen } from "../settings/components/SettingsScreen";
44import { useUsage, type EnvironmentUsageStatus } from "../../state/usage";
45import { serverEnvironment } from "../../state/server";
46import { useAtomCommand } from "../../state/use-atom-command";
47import { SettingsSection } from "../settings/components/SettingsSection";
48import { UsageDailyChart } from "./UsageDailyChart";
49import { toggleUsageEnvironment } from "./usageEnvironmentSelection";
50import { useRefreshLimits } from "./UsageLimitsSection";
51import { UsageLimitsSection } from "./UsageLimitsPooled";
52import { NativeStackScreenOptions } from "../../native/StackHeader";
53import { withNativeGlassHeaderItem } from "../layout/native-glass-header-items";
54import type { UsageChartMetric } from "./usageChartData";
55import { PROVIDER_LABEL, useProviderColors, useUsageMixColors } from "./usageProviders";
56
57type UsageView = UsageChartMetric | "limits";
58const VIEW_OPTIONS = [
59 { value: "cost", label: "Cost" },
60 { value: "tokens", label: "Tokens" },
61 { value: "limits", label: "Limits" },
62] as const satisfies readonly { value: UsageView; label: string }[];
63
64const WINDOW_OPTIONS = [
65 { value: 1, label: "24h", accessibilityLabel: "Past 24 hours" },
66 { value: 7, label: "7d", accessibilityLabel: "Past 7 days" },
67 { value: 30, label: "30d", accessibilityLabel: "Past 30 days" },
68 { value: 90, label: "90d", accessibilityLabel: "Past 90 days" },
69] as const;
70
71const CHART_HEIGHT = 180;
72const WIDE_CHART_HEIGHT = 260;
73// Below this the page keeps the phone's single column.
74const WIDE_WIDTH = 600;
75const MAX_CONTENT_WIDTH = 1080;
76const providerLabel = (provider: UsageProviderKind) => PROVIDER_LABEL[provider];
77const CURSOR_KEYCHAIN_COPY = "Requires access to your Cursor login in macOS Keychain.";
78
79export function UsageRouteScreen(props: { readonly workspace?: boolean }) {
80 const route = useRoute<RouteProp<{ Usage: { tab?: string } | undefined }, "Usage">>();
81 return <UsageScreen workspace={props.workspace} tabParam={route.params?.tab} />;
82}
83
84function UsageScreen(props: {
85 readonly workspace?: boolean;
86 readonly tabParam: string | undefined;
87}) {
88 const insets = useSafeAreaInsets();
89 const [selection, setSelection] = useState(() => ({
90 params: props.tabParam,
91 view: (props.tabParam === "usage" ? "cost" : "limits") as UsageView,
92 }));
93 if (selection.params !== props.tabParam) {
94 setSelection({
95 params: props.tabParam,
96 view: props.tabParam === "usage" ? "cost" : "limits",
97 });
98 }
99 const { view } = selection;
100 const setView = (view: UsageView) => setSelection({ params: props.tabParam, view });
101 const [measuredWidth, setWidth] = useState(0);
102 // A workspace pane knows its width in the render that resizes it; measuring lags a frame.
103 const width = useWorkspaceSettledContentWidth() ?? measuredWidth;
104 const wide = width >= WIDE_WIDTH;
105 const [windowSelection, setWindowSelection] = useState(() => ({
106 days: 30,
107 window: makeWindow(30),
108 }));
109 const { days: windowDays, window } = windowSelection;
110 const isPast24Hours = windowDays === 1;
111 const [selectedEnvironmentIds, setSelectedEnvironmentIds] =
112 useState<ReadonlySet<EnvironmentId> | null>(null);
113 const { merged, environments, selectedEnvironments, isPending, refresh } = useUsage(
114 window,
115 selectedEnvironmentIds,
116 );
117 const isFocused = useIsFocused();
118 const limits = useRefreshLimits(selectedEnvironmentIds, isFocused && view === "limits");
119 const cursorAccessEnvironments = cursorKeychainAccessEnvironments(selectedEnvironments);
120 const refreshAfterCursorEnable = () => {
121 void refresh();
122 void limits.refreshAfterEnable();
123 };
124 const sourceMessages = usageSourceMessages(
125 selectedEnvironments.flatMap((environment) => environment.summary?.sources ?? []),
126 );
127 const canReadDiagnostics = selectedEnvironments.some(
128 (environment) => environment.canReadDiagnostics,
129 );
130
131 const days = enumerateDays(window.sinceDay, window.untilDay);
132 const chartDays =
133 isPast24Hours && window.sinceTime !== undefined && window.untilTime !== undefined
134 ? enumerateHourStarts(window.sinceTime, window.untilTime)
135 : days;
136 const chartTotals: readonly DailyTotals[] = isPast24Hours
137 ? merged.hourly.map((hour) => ({
138 day: hour.hourStart,
139 costUsd: hour.costUsd,
140 totalTokens: hour.totalTokens,
141 byProvider: hour.byProvider,
142 }))
143 : merged.daily;
144
145 const [refreshingUsage, setRefreshingUsage] = useState(false);
146 const refreshingRef = useRef(false);
147 const showingLimits = view === "limits";
148 const metric: UsageChartMetric = view === "tokens" ? "tokens" : "cost";
149 const progress = usageProgress(selectedEnvironments, {
150 refreshing: refreshingUsage,
151 providerLabel,
152 });
153 const selectWindow = (days: number) => {
154 setWindowSelection({
155 days,
156 window: makeWindow(days, undefined, days === 1 ? "hour" : "day"),
157 });
158 };
159 const refreshWindow = () => {
160 if (refreshingRef.current) return;
161 const nextWindow = makeWindow(windowDays, undefined, isPast24Hours ? "hour" : "day");
162 if (
163 nextWindow.sinceDay !== window.sinceDay ||
164 nextWindow.untilDay !== window.untilDay ||
165 nextWindow.sinceTime !== window.sinceTime ||
166 nextWindow.untilTime !== window.untilTime
167 ) {
168 setWindowSelection({ days: windowDays, window: nextWindow });
169 }
170 refreshingRef.current = true;
171 setRefreshingUsage(true);
172 void refresh(nextWindow).finally(() => {
173 refreshingRef.current = false;
174 setRefreshingUsage(false);
175 });
176 };
177
178 const chart = {
179 merged,
180 days: chartDays,
181 daily: chartTotals,
182 metric,
183 sinceDay: window.sinceDay,
184 untilDay: window.untilDay,
185 isPast24Hours,
186 timeZone: window.timeZone,
187 };
188 const providers = (
189 <ProviderSection
190 merged={merged}
191 metric={metric}
192 cursorAccessEnvironments={cursorAccessEnvironments}
193 showCursorEnvironment={selectedEnvironments.length > 1}
194 onCursorEnabled={refreshAfterCursorEnable}
195 compact={wide}
196 />
197 );
198
199 const showEnvironmentFilter = environments.length > 0 || selectedEnvironmentIds !== null;
200 const filterIcon =
201 selectedEnvironmentIds === null
202 ? "line.3.horizontal.decrease"
203 : "line.3.horizontal.decrease.circle.fill";
204 const environmentActions = [
205 {
206 id: "all",
207 title: "All environments",
208 subtitle: undefined,
209 state: selectedEnvironmentIds === null ? ("on" as const) : ("off" as const),
210 },
211 ...environments.map((environment) => ({
212 id: environment.environmentId,
213 title: environment.label,
214 subtitle: usageEnvironmentStatus(environment, refreshingUsage),
215 state:
216 selectedEnvironmentIds === null || selectedEnvironmentIds.has(environment.environmentId)
217 ? ("on" as const)
218 : ("off" as const),
219 })),
220 ];
221 const selectEnvironment = (value: string) => {
222 if (value === "all") {
223 setSelectedEnvironmentIds(null);
224 return;
225 }
226 const id = EnvironmentId.make(value);
227 setSelectedEnvironmentIds((selected) => toggleUsageEnvironment(selected, environments, id));
228 };
229 const environmentMenu = {
230 title: "Filter usage environments",
231 icon:
232 selectedEnvironmentIds === null
233 ? ("line.3.horizontal.decrease.circle" as const)
234 : ("line.3.horizontal.decrease.circle.fill" as const),
235 items: environmentActions.map((action) => ({
236 id: action.id,
237 title: action.title,
238 subtitle: action.subtitle,
239 selected: action.state === "on",
240 onPress: () => selectEnvironment(action.id),
241 })),
242 };
243
244 return (
245 <SettingsScreen
246 title="Usage"
247 menus={showEnvironmentFilter ? [environmentMenu] : undefined}
248 workspaceRoot={props.workspace}
249 >
250 {Platform.OS === "ios" ? (
251 <NativeStackScreenOptions
252 optionsVersion={JSON.stringify({ showEnvironmentFilter, filterIcon, environmentActions })}
253 options={{
254 // A native menu item, unlike a custom view, moves into the Duo's vertical bar.
255 unstable_headerRightItems: () =>
256 showEnvironmentFilter
257 ? [
258 withNativeGlassHeaderItem({
259 accessibilityLabel: "Filter usage environments",
260 icon: { name: filterIcon, type: "sfSymbol" },
261 label: "",
262 type: "menu",
263 menu: {
264 title: "Environments",
265 items: environmentActions.map((action) => ({
266 type: "action" as const,
267 label: action.title,
268 description: action.subtitle,
269 state: action.state === "on" ? ("on" as const) : undefined,
270 onPress: () => selectEnvironment(action.id),
271 })),
272 },
273 }),
274 ]
275 : [],
276 }}
277 />
278 ) : null}
279 <ScrollView
280 contentInsetAdjustmentBehavior="automatic"
281 showsVerticalScrollIndicator={false}
282 className="flex-1"
283 contentContainerClassName="px-5 pt-4"
284 contentContainerStyle={{ paddingBottom: Math.max(insets.bottom, 18) + 18 }}
285 onLayout={(event) => setWidth(event.nativeEvent.layout.width)}
286 refreshControl={
287 showingLimits || canReadDiagnostics ? (
288 <RefreshControl
289 refreshing={showingLimits ? limits.refreshing : refreshingUsage}
290 onRefresh={showingLimits ? () => void limits.refresh() : refreshWindow}
291 />
292 ) : undefined
293 }
294 >
295 <View className="w-full gap-6 self-center" style={{ maxWidth: MAX_CONTENT_WIDTH }}>
296 {wide ? (
297 <View className="flex-row items-center gap-3">
298 {showingLimits ? (
299 <View className="flex-1" />
300 ) : (
301 <SegmentedControl
302 options={WINDOW_OPTIONS}
303 selected={windowDays}
304 onSelect={selectWindow}
305 size="compact"
306 className="flex-1"
307 />
308 )}
309 <SegmentedControl
310 options={VIEW_OPTIONS}
311 selected={view}
312 onSelect={setView}
313 size="compact"
314 role="tab"
315 className="w-60"
316 />
317 </View>
318 ) : (
319 <SegmentedControl
320 options={VIEW_OPTIONS}
321 selected={view}
322 onSelect={setView}
323 role="tab"
324 />
325 )}
326 <Animated.View
327 key={showingLimits ? "limits" : "usage"}
328 entering={FadeIn.duration(160).reduceMotion(ReduceMotion.System)}
329 className="gap-6"
330 >
331 {showingLimits ? (
332 <UsageLimitsSection
333 now={limits.now}
334 failedLabels={limits.failedLabels}
335 selectedEnvironmentIds={selectedEnvironmentIds}
336 wide={wide}
337 cursorPrompt={
338 cursorAccessEnvironments.length > 0 ? (
339 <CursorEnableLimits
340 environments={cursorAccessEnvironments}
341 onEnabled={refreshAfterCursorEnable}
342 />
343 ) : null
344 }
345 />
346 ) : (
347 <>
348 {wide ? null : (
349 <SegmentedControl
350 options={WINDOW_OPTIONS}
351 selected={windowDays}
352 onSelect={selectWindow}
353 size="compact"
354 />
355 )}
356 <ChatGptUsageSummary selectedEnvironmentIds={selectedEnvironmentIds} />
357 {merged.duplicateSources.length > 0 ? (
358 <Text className="text-sm text-foreground-muted">
359 Counted once across environments sharing a transcript directory:{" "}
360 {merged.duplicateSources.join(", ")}
361 </Text>
362 ) : null}
363 {isPending ? (
364 <Text className="py-16 text-center text-base text-foreground-muted">
365 Scanning provider transcripts…
366 </Text>
367 ) : selectedEnvironments.length === 0 ? (
368 <Text className="py-16 text-center text-base text-foreground-muted">
369 {environments.length === 0
370 ? "Connect an environment to see usage."
371 : "Select an environment to see usage."}
372 </Text>
373 ) : !canReadDiagnostics ? (
374 <View className="gap-2 py-16">
375 {selectedEnvironments.map((environment) => (
376 <Text
377 key={environment.environmentId}
378 className="text-center text-base text-foreground-muted"
379 >
380 {selectedEnvironments.length > 1 ? `${environment.label}: ` : null}
381 {environment.error}
382 </Text>
383 ))}
384 </View>
385 ) : (
386 <>
387 {sourceMessages.map((message) => (
388 <Text key={message} className="text-sm text-foreground-muted">
389 {message}
390 </Text>
391 ))}
392 <UsageUpdating dimmed={progress.dimmed} label={progress.label}>
393 {wide ? (
394 <View className="flex-row gap-6">
395 <View className="w-72 gap-6">
396 <View className="rounded-[24px] border-continuous bg-grouped-card p-4">
397 <UsageSummary merged={merged} metric={metric} />
398 </View>
399 {providers}
400 </View>
401 <View className="min-w-0 flex-1">
402 <ChartCard
403 {...chart}
404 height={WIDE_CHART_HEIGHT}
405 fill
406 title={`${isPast24Hours ? "Hourly" : "Daily"} ${metric === "cost" ? "cost" : "processed tokens"}`}
407 />
408 </View>
409 </View>
410 ) : (
411 <>
412 <ChartCard {...chart} height={CHART_HEIGHT} />
413 {providers}
414 </>
415 )}
416 <TotalsSection
417 merged={merged}
418 isPast24Hours={isPast24Hours}
419 columns={width >= 900 ? 6 : wide ? 3 : 2}
420 />
421 <CostSection merged={merged} wide={wide} />
422 <ModelsSection merged={merged} metric={metric} columns={wide ? 2 : 1} />
423 </UsageUpdating>
424 </>
425 )}
426 </>
427 )}
428 </Animated.View>
429 </View>
430 </ScrollView>
431 </SettingsScreen>
432 );
433}
434
435function UsageUpdating({
436 dimmed,
437 label,
438 children,
439}: {
440 readonly dimmed: boolean;
441 readonly label: string | null;
442 readonly children: ReactNode;
443}) {
444 const reduceMotion = useReduceMotionEnabled();
445 // The delay keeps a quick refresh from flashing the content.
446 const dimStyle = {
447 opacity: dimmed ? 0.5 : 1,
448 transitionProperty: "opacity",
449 transitionDuration: reduceMotion ? 0 : 150,
450 transitionDelay: dimmed ? 150 : 0,
451 } as const;
452
453 return (
454 <View>
455 <Animated.View style={dimStyle} className="gap-6" accessibilityState={{ busy: dimmed }}>
456 {children}
457 </Animated.View>
458 {label !== null ? (
459 <Animated.View
460 entering={FadeIn.delay(150).duration(150).reduceMotion(ReduceMotion.System)}
461 accessibilityLiveRegion="polite"
462 pointerEvents="none"
463 className="absolute right-4 top-4 h-5 max-w-[55%] flex-row items-center gap-1.5"
464 >
465 <AppActivityIndicator size="small" colorClassName="accent-adaptive-sky-600-400" />
466 <Text className="shrink text-sm text-adaptive-sky-600-400" numberOfLines={1}>
467 {label}
468 </Text>
469 </Animated.View>
470 ) : null}
471 </View>
472 );
473}
474
475function CursorEnableAction({
476 environmentId,
477 label,
478 onEnabled,
479 buttonText = "Enable",
480}: {
481 readonly environmentId: EnvironmentId;
482 readonly label: string;
483 readonly onEnabled: () => void;
484 readonly buttonText?: string;
485}) {
486 const updateSettings = useAtomCommand(serverEnvironment.updateSettings, {
487 label: "enable Cursor account usage",
488 });
489 const [pending, setPending] = useState(false);
490 const enable = async () => {
491 setPending(true);
492 const result = await updateSettings({
493 environmentId,
494 input: { patch: { cursorKeychainUsageEnabled: true } },
495 }).finally(() => setPending(false));
496 if (result._tag === "Success") onEnabled();
497 };
498 return (
499 <Button
500 label={buttonText}
501 tone="primary"
502 accessibilityLabel={`Enable Cursor usage from ${label}`}
503 accessibilityHint={CURSOR_KEYCHAIN_COPY}
504 disabled={pending}
505 onPress={() => void enable()}
506 loading={pending}
507 />
508 );
509}
510
511function CursorEnableRow({
512 environmentId,
513 label,
514 showEnvironment,
515 bordered,
516 onEnabled,
517}: {
518 readonly environmentId: EnvironmentId;
519 readonly label: string;
520 readonly showEnvironment: boolean;
521 readonly bordered: boolean;
522 readonly onEnabled: () => void;
523}) {
524 const colors = useProviderColors();
525 return (
526 <View
527 className={cn(
528 "flex-row items-center justify-between gap-3 p-4",
529 bordered && "border-t border-border-subtle",
530 )}
531 >
532 <View className="min-w-0 flex-1 flex-row items-center gap-2">
533 <View className="size-2.5 rounded-full" style={{ backgroundColor: colors.cursor }} />
534 <Text className="shrink text-lg text-foreground">
535 Cursor{showEnvironment ? ` · ${label}` : ""}
536 </Text>
537 </View>
538 <CursorEnableAction environmentId={environmentId} label={label} onEnabled={onEnabled} />
539 </View>
540 );
541}
542
543function CursorEnableLimits({
544 environments,
545 onEnabled,
546}: {
547 readonly environments: readonly EnvironmentUsageStatus[];
548 readonly onEnabled: () => void;
549}) {
550 return (
551 <View className="gap-3">
552 <View className="flex-row items-center gap-2 px-1">
553 <ProviderIcon provider="cursor" size={18} />
554 <Text className="text-base font-t3-medium text-foreground">Cursor</Text>
555 </View>
556 <View className="items-start gap-3 rounded-[24px] border-continuous bg-grouped-card p-4">
557 <Text className="text-xs text-foreground-muted">{CURSOR_KEYCHAIN_COPY}</Text>
558 <View className="flex-row flex-wrap gap-2">
559 {environments.map((environment) => (
560 <CursorEnableAction
561 key={environment.environmentId}
562 environmentId={environment.environmentId}
563 label={environment.label}
564 buttonText={environments.length > 1 ? `Enable on ${environment.label}` : "Enable"}
565 onEnabled={onEnabled}
566 />
567 ))}
568 </View>
569 </View>
570 </View>
571 );
572}
573
574function ChartCard(props: {
575 readonly merged: MergedUsage;
576 readonly days: readonly string[];
577 readonly daily: readonly DailyTotals[];
578 readonly metric: UsageChartMetric;
579 readonly sinceDay: string;
580 readonly untilDay: string;
581 readonly isPast24Hours: boolean;
582 readonly timeZone: string;
583 readonly height: number;
584 /** Replaces the summary when it sits beside the chart. */
585 readonly title?: string;
586 /** Grows the chart past `height` to match a taller neighbouring column. */
587 readonly fill?: boolean;
588}) {
589 const { merged, metric } = props;
590 const colors = useProviderColors();
591 const hasActivity = props.daily.some((period) => period.totalTokens > 0);
592 const [fillHeight, setFillHeight] = useState(0);
593 const height = props.fill ? Math.max(fillHeight, props.height) : props.height;
594 const chart = hasActivity ? (
595 <UsageDailyChart days={props.days} daily={props.daily} metric={metric} height={height} />
596 ) : (
597 <View style={{ height }} className="items-center justify-center">
598 <Text className="text-base text-foreground-muted">No activity in this window.</Text>
599 </View>
600 );
601
602 return (
603 <View
604 className={`gap-4 rounded-[24px] border-continuous bg-grouped-card p-4${props.fill ? " flex-1" : ""}`}
605 >
606 {props.title ? (
607 <Text className="text-sm font-t3-medium text-foreground">{props.title}</Text>
608 ) : (
609 <UsageSummary merged={merged} metric={metric} />
610 )}
611
612 {props.fill ? (
613 // Absolute so the measured slot can shrink again when the neighbour gets shorter.
614 <View
615 className="flex-1"
616 style={{ minHeight: props.height }}
617 onLayout={(event) => setFillHeight(event.nativeEvent.layout.height)}
618 >
619 <View className="absolute inset-0">{chart}</View>
620 </View>
621 ) : (
622 chart
623 )}
624
625 <View className="gap-2">
626 <View className="flex-row items-center justify-between">
627 <Text className="text-xs text-foreground-tertiary">
628 {props.isPast24Hours
629 ? formatHourShort(props.days[0] ?? "", props.timeZone)
630 : formatDayShort(props.sinceDay)}
631 </Text>
632 <Text className="text-xs text-foreground-tertiary">
633 {props.isPast24Hours
634 ? formatHourShort(props.days[props.days.length - 1] ?? "", props.timeZone)
635 : formatDayShort(props.untilDay)}
636 </Text>
637 </View>
638 <View className="flex-row flex-wrap items-center gap-x-4 gap-y-1">
639 {merged.providers.map((provider) => (
640 <View key={provider.provider} className="flex-row items-center gap-1.5">
641 <View
642 className="size-2 rounded-full"
643 style={{ backgroundColor: colors[provider.provider] }}
644 />
645 <Text className="text-xs text-foreground-muted">
646 {PROVIDER_LABEL[provider.provider]}
647 </Text>
648 </View>
649 ))}
650 </View>
651 </View>
652 </View>
653 );
654}
655
656function UsageSummary(props: { readonly merged: MergedUsage; readonly metric: UsageChartMetric }) {
657 const { merged, metric } = props;
658 return (
659 <View className="gap-0.5">
660 <Text className="text-sm text-foreground-muted">
661 {metric === "cost" ? "Raw token cost" : "Processed tokens"}
662 </Text>
663 <Text className="text-4xl font-t3-bold tabular-nums text-foreground">
664 {metric === "cost" ? `${formatUsd(merged.costUsd)}*` : formatTokens(merged.totalTokens)}
665 </Text>
666 <Text className="text-sm text-foreground-muted">
667 {metric === "cost"
668 ? "* if billed at full API rate"
669 : `Across ${formatCount(merged.sessions)} sessions`}
670 </Text>
671 </View>
672 );
673}
674
675function ProviderSection(props: {
676 readonly merged: MergedUsage;
677 readonly metric: UsageChartMetric;
678 readonly cursorAccessEnvironments: readonly EnvironmentUsageStatus[];
679 readonly showCursorEnvironment: boolean;
680 readonly onCursorEnabled: () => void;
681 /** Drops the share bar so the list fits beside the chart. */
682 readonly compact: boolean;
683}) {
684 const { merged, metric } = props;
685 const colors = useProviderColors();
686 if (merged.providers.length === 0 && props.cursorAccessEnvironments.length === 0) return null;
687
688 // Hermes lacks toSorted.
689 const ordered = [...merged.providers].sort((a, b) =>
690 metric === "cost" ? b.costUsd - a.costUsd : b.totalTokens - a.totalTokens,
691 );
692 const rows: Array<
693 | { readonly kind: "usage"; readonly provider: (typeof ordered)[number] }
694 | { readonly kind: "enable"; readonly environment: EnvironmentUsageStatus }
695 > = ordered.map((provider) => ({ kind: "usage", provider }));
696 const cursorInsertAt =
697 Math.max(
698 ordered.findIndex((provider) => provider.provider === "codex"),
699 ordered.findIndex((provider) => provider.provider === "claude"),
700 ) + 1;
701 rows.splice(
702 cursorInsertAt,
703 0,
704 ...props.cursorAccessEnvironments.map((environment) => ({
705 kind: "enable" as const,
706 environment,
707 })),
708 );
709
710 return (
711 <SettingsSection title="Providers">
712 {rows.map((row, index) => {
713 if (row.kind === "enable") {
714 return (
715 <CursorEnableRow
716 key={`enable:${row.environment.environmentId}`}
717 environmentId={row.environment.environmentId}
718 label={row.environment.label}
719 showEnvironment={props.showCursorEnvironment}
720 bordered={index > 0}
721 onEnabled={props.onCursorEnabled}
722 />
723 );
724 }
725 const provider = row.provider;
726 const share = metric === "cost" ? provider.costShare : provider.tokenShare;
727 return (
728 <View
729 key={provider.provider}
730 className={cn(
731 props.compact ? "gap-0.5 px-4 py-3" : "gap-2 p-4",
732 index > 0 && "border-t border-border-subtle",
733 )}
734 >
735 <View className="flex-row items-baseline justify-between gap-3">
736 <View className="flex-row items-center gap-2">
737 <View
738 className="size-2.5 rounded-full"
739 style={{ backgroundColor: colors[provider.provider] }}
740 />
741 <Text
742 className={
743 props.compact ? "text-base text-foreground" : "text-lg text-foreground"
744 }
745 >
746 {PROVIDER_LABEL[provider.provider]}
747 </Text>
748 </View>
749 <Text
750 className={
751 props.compact
752 ? "text-base tabular-nums text-foreground"
753 : "text-lg tabular-nums text-foreground"
754 }
755 >
756 {metric === "cost"
757 ? formatUsd(provider.costUsd)
758 : formatTokens(provider.totalTokens)}
759 </Text>
760 </View>
761 {props.compact ? null : (
762 <View className="h-1 flex-row overflow-hidden rounded-full bg-subtle">
763 <View
764 className="h-full rounded-full"
765 style={{ flex: share, backgroundColor: colors[provider.provider] }}
766 />
767 <View style={{ flex: 1 - share }} />
768 </View>
769 )}
770 <Text className="text-sm text-foreground-muted">
771 {metric === "cost"
772 ? `${formatPercent(share)} of cost · ${formatTokens(provider.totalTokens)} tokens`
773 : `${formatPercent(share)} of tokens · ${formatUsd(provider.costUsd)}`}
774 </Text>
775 </View>
776 );
777 })}
778 </SettingsSection>
779 );
780}
781
782function TotalsSection(props: {
783 readonly merged: MergedUsage;
784 readonly isPast24Hours: boolean;
785 readonly columns: number;
786}) {
787 const { merged } = props;
788 const activePeriods = (props.isPast24Hours ? merged.hourly : merged.daily).filter(
789 (period) => period.totalTokens > 0,
790 ).length;
791 const periodAverage = activePeriods === 0 ? 0 : merged.totalTokens / activePeriods;
792 const observedInput = merged.uncachedInputTokens + merged.cachedInputTokens;
793 const cachedShare = observedInput === 0 ? 0 : merged.cachedInputTokens / observedInput;
794
795 return (
796 <SettingsSection title="Totals">
797 <View className="flex-row flex-wrap">
798 <MetricCell
799 columns={props.columns}
800 label="Processed tokens"
801 value={formatTokens(merged.totalTokens)}
802 detail={`${formatTokens(periodAverage)} per active ${props.isPast24Hours ? "hour" : "day"}`}
803 />
804 <MetricCell
805 columns={props.columns}
806 label="Cache savings"
807 value={formatUsd(merged.costQuality.cacheSavingsUsd)}
808 detail={
809 merged.costUsd > 0
810 ? `${(merged.costQuality.cacheSavingsUsd / merged.costUsd).toFixed(1)}x the raw cost`
811 : "vs full input rates"
812 }
813 />
814 <MetricCell
815 columns={props.columns}
816 label="Cached input"
817 value={formatTokens(merged.cachedInputTokens)}
818 detail={`${formatPercent(cachedShare)} of observed input`}
819 />
820 <MetricCell
821 columns={props.columns}
822 label="Uncached input"
823 value={formatTokens(merged.uncachedInputTokens)}
824 detail={`${formatTokens(merged.cacheCreationTokens)} cache writes`}
825 />
826 <MetricCell
827 columns={props.columns}
828 label="Output"
829 value={formatTokens(merged.outputTokens)}
830 detail={`incl. ${formatTokens(merged.reasoningTokens)} reasoning`}
831 />
832 <MetricCell
833 columns={props.columns}
834 label="Unpriced"
835 value={formatPercent(merged.costQuality.unpricedShare)}
836 detail="of records, excluded from cost"
837 />
838 </View>
839 </SettingsSection>
840 );
841}
842
843function CostSection(props: { readonly merged: MergedUsage; readonly wide: boolean }) {
844 const { categoryCost, speedCost } = props.merged;
845 const colors = useUsageMixColors();
846 const byType = [
847 { label: "Input", value: categoryCost.input, color: colors.input },
848 { label: "Cache read", value: categoryCost.cacheRead, color: colors.cacheRead },
849 { label: "Cache write", value: categoryCost.cacheWrite, color: colors.cacheWrite },
850 { label: "Output", value: categoryCost.output, color: colors.output },
851 // Reported cost with no rates to split it, or from older servers. Below a
852 // cent it is rounding, not usage.
853 {
854 label: "Other",
855 value: categoryCost.unsplit >= 0.005 ? categoryCost.unsplit : 0,
856 color: colors.other,
857 },
858 ];
859 const bySpeed = [
860 { label: "Standard", value: speedCost.standard, color: colors.standard },
861 { label: "Fast", value: speedCost.fast, color: colors.fast },
862 { label: "Ultrafast", value: speedCost.ultrafast, color: colors.ultrafast },
863 ];
864 if (props.merged.costUsd <= 0) return null;
865
866 return (
867 <SettingsSection title="Cost">
868 <View className={props.wide ? "flex-row" : undefined}>
869 <View className={props.wide ? "min-w-0 flex-1" : undefined}>
870 <ShareBar label="By type" segments={byType} />
871 </View>
872 {speedCost.fast + speedCost.ultrafast > 0 ? (
873 <View
874 className={
875 props.wide
876 ? "min-w-0 flex-1 border-l border-border-subtle"
877 : "border-t border-border-subtle"
878 }
879 >
880 <ShareBar
881 label="By speed"
882 segments={bySpeed}
883 aside={`${formatUsd(speedCost.premium)} premium`}
884 />
885 </View>
886 ) : null}
887 </View>
888 </SettingsSection>
889 );
890}
891
892function ShareBar(props: {
893 readonly label: string;
894 readonly segments: readonly { label: string; value: number; color: string }[];
895 readonly aside?: string;
896}) {
897 const visible = props.segments.filter((segment) => segment.value > 0);
898 if (visible.length === 0) return null;
899
900 return (
901 <View className="gap-3 p-4">
902 <View className="flex-row items-baseline justify-between gap-3">
903 <Text className="text-sm text-foreground-muted">{props.label}</Text>
904 {props.aside ? (
905 <Text className="text-sm tabular-nums text-foreground-muted">{props.aside}</Text>
906 ) : null}
907 </View>
908 <View className="h-2 flex-row gap-0.5">
909 {visible.map((segment) => (
910 <View
911 key={segment.label}
912 className="h-full rounded-sm"
913 style={{ flex: segment.value, backgroundColor: segment.color }}
914 />
915 ))}
916 </View>
917 <View className="flex-row flex-wrap gap-x-4 gap-y-1.5">
918 {visible.map((segment) => (
919 <View key={segment.label} className="flex-row items-center gap-1.5">
920 <View className="size-2 rounded-sm" style={{ backgroundColor: segment.color }} />
921 <Text className="text-sm text-foreground-muted">{segment.label}</Text>
922 <Text className="text-sm tabular-nums text-foreground">{formatUsd(segment.value)}</Text>
923 </View>
924 ))}
925 </View>
926 </View>
927 );
928}
929
930function MetricCell(props: {
931 readonly label: string;
932 readonly value: string;
933 readonly detail: string;
934 readonly columns: number;
935}) {
936 return (
937 <View className="gap-0.5 p-4" style={{ width: `${100 / props.columns}%` }}>
938 <Text className="text-sm text-foreground-muted">{props.label}</Text>
939 <Text className="text-xl font-t3-medium tabular-nums text-foreground">{props.value}</Text>
940 <Text className="text-xs text-foreground-tertiary">{props.detail}</Text>
941 </View>
942 );
943}
944
945function ModelsSection(props: {
946 readonly merged: MergedUsage;
947 readonly metric: UsageChartMetric;
948 readonly columns: 1 | 2;
949}) {
950 const { merged, metric } = props;
951 const colors = useProviderColors();
952 if (merged.models.length === 0) return null;
953
954 // Hermes lacks toSorted.
955 const ordered = [...merged.models].sort((a, b) =>
956 metric === "cost"
957 ? b.costUsd - a.costUsd || b.totalTokens - a.totalTokens
958 : b.totalTokens - a.totalTokens || b.costUsd - a.costUsd,
959 );
960
961 return (
962 <SettingsSection title="By model">
963 <View className="flex-row flex-wrap">
964 {ordered.map((model, index) => (
965 <View
966 key={`${model.provider}:${model.model}`}
967 className={cn(
968 "flex-row items-center gap-3 p-4",
969 index >= props.columns && "border-t border-border-subtle",
970 index % props.columns === 1 && "border-l border-border-subtle",
971 )}
972 style={{ width: `${100 / props.columns}%` }}
973 >
974 <View
975 className="size-2.5 shrink-0 rounded-full"
976 style={{ backgroundColor: colors[model.provider] }}
977 />
978 <View className="min-w-0 flex-1 gap-0.5">
979 <Text className="text-base text-foreground" numberOfLines={1}>
980 {model.model}
981 </Text>
982 <Text className="text-sm text-foreground-muted">
983 {metric === "tokens"
984 ? `${formatPercent(model.tokenShare)} of tokens · ${
985 isModelCostUnknown(model) ? "no known rates" : formatUsd(model.costUsd)
986 }`
987 : isModelCostUnknown(model)
988 ? `no known rates · ${formatTokens(model.totalTokens)} tokens`
989 : `${formatPercent(model.costShare)} of cost · ${formatTokens(model.totalTokens)} tokens`}
990 </Text>
991 </View>
992 <Text className="text-base tabular-nums text-foreground">
993 {metric === "tokens"
994 ? formatTokens(model.totalTokens)
995 : isModelCostUnknown(model)
996 ? "Unpriced"
997 : formatUsd(model.costUsd)}
998 </Text>
999 </View>
1000 ))}
1001 </View>
1002 </SettingsSection>
1003 );
1004}
1005
1006function usageEnvironmentStatus(environment: EnvironmentUsageStatus, refreshing: boolean): string {
1007 if (
1008 environment.summary &&
1009 !isCompatibleUsageContractVersion(environment.summary.contractVersion, USAGE_CONTRACT_VERSION)
1010 ) {
1011 return formatUsageContractMismatch(environment.label, {
1012 direction:
1013 environment.summary.contractVersion < USAGE_CONTRACT_VERSION
1014 ? "serverBehind"
1015 : "clientBehind",
1016 });
1017 }
1018 if (environment.error)
1019 return environment.summary ? `${environment.error} Showing saved totals.` : environment.error;
1020 if (!environment.isConnected)
1021 return environment.summary ? "Disconnected · showing saved usage" : "Waiting for connection…";
1022 const progress = usageEnvironmentProgress(environment, refreshing);
1023 if (progress.phase === "loading") return "Loading usage…";
1024 if (progress.phase === "stale") return "Updating usage…";
1025 if (progress.phase === "partway")
1026 return updatingProvidersLabel(progress.providers, providerLabel);
1027 return "Usage up to date";
1028}