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