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

UsageRouteScreen.tsx

1,042 lines37.6 KB

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