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