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, useNavigation, 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 { useLayoutEffect, useRef, useState, type ReactNode } from "react";
32import { Platform, Pressable, RefreshControl, View } from "react-native";
33import Animated, {
34 FadeIn,
35 ReduceMotion,
36 useAnimatedStyle,
37 useSharedValue,
38 withDelay,
39 withTiming,
40} from "react-native-reanimated";
41import { useSafeAreaInsets } from "react-native-safe-area-context";
42
43import { SegmentedControl } from "../../components/ui/SegmentedControl";
44import { AppText as Text } from "../../components/ui/AppText";
45import { ProviderIcon } from "../../components/ProviderIcon";
46import { cn } from "../../lib/cn";
47import { SettingsScreen } from "../settings/components/SettingsScreen";
48import { useUsage, type EnvironmentUsageStatus } from "../../state/usage";
49import { serverEnvironment } from "../../state/server";
50import { useAtomCommand } from "../../state/use-atom-command";
51import { SettingsSection } from "../settings/components/SettingsSection";
52import { UsageDailyChart } from "./UsageDailyChart";
53import { toggleUsageEnvironment } from "./usageEnvironmentSelection";
54import { useRefreshLimits } from "./UsageLimitsSection";
55import { UsageLimitsSection } from "./UsageLimitsPooled";
56import { Menu } from "../../components/ui/Menu";
57import { SymbolView } from "../../components/ui/AppSymbol";
58import type { UsageChartMetric } from "./usageChartData";
59import { PROVIDER_LABEL, useProviderColors, useUsageMixColors } from "./usageProviders";
60
61type UsageTab = "usage" | "limits";
62const TAB_OPTIONS = [
63 { value: "usage", label: "Usage" },
64 { value: "limits", label: "Limits" },
65] as const satisfies readonly { value: UsageTab; label: string }[];
66
67const WINDOW_OPTIONS = [
68 { value: 1, label: "24h", accessibilityLabel: "Past 24 hours" },
69 { value: 7, label: "7d", accessibilityLabel: "Past 7 days" },
70 { value: 30, label: "30d", accessibilityLabel: "Past 30 days" },
71 { value: 90, label: "90d", accessibilityLabel: "Past 90 days" },
72] as const;
73
74const METRIC_OPTIONS = [
75 { value: "cost", label: "Cost" },
76 { value: "tokens", label: "Tokens" },
77] as const satisfies readonly { value: UsageChartMetric; label: string }[];
78
79const CHART_HEIGHT = 180;
80const providerLabel = (provider: UsageProviderKind) => PROVIDER_LABEL[provider];
81const CURSOR_KEYCHAIN_COPY = "Requires access to your Cursor login in macOS Keychain.";
82
83export function UsageRouteScreen() {
84 const route = useRoute<RouteProp<{ Usage: { tab?: string } | undefined }, "Usage">>();
85 const navigation = useNavigation();
86 const insets = useSafeAreaInsets();
87 const [selection, setSelection] = useState(() => ({
88 params: route.params,
89 tab: (route.params?.tab === "usage" ? "usage" : "limits") as UsageTab,
90 }));
91 if (selection.params !== route.params) {
92 setSelection({
93 params: route.params,
94 tab: route.params?.tab === "usage" ? "usage" : "limits",
95 });
96 }
97 const { tab } = selection;
98 const setTab = (tab: UsageTab) => setSelection({ params: route.params, tab });
99 const [windowSelection, setWindowSelection] = useState(() => ({
100 days: 30,
101 window: makeWindow(30),
102 }));
103 const [metric, setMetric] = useState<UsageChartMetric>("cost");
104 const { days: windowDays, window } = windowSelection;
105 const isPast24Hours = windowDays === 1;
106 const [selectedEnvironmentIds, setSelectedEnvironmentIds] =
107 useState<ReadonlySet<EnvironmentId> | null>(null);
108 const { merged, environments, selectedEnvironments, isPending, refresh } = useUsage(
109 window,
110 selectedEnvironmentIds,
111 );
112 const isFocused = useIsFocused();
113 const limits = useRefreshLimits(selectedEnvironmentIds, isFocused && tab === "limits");
114 const cursorAccessEnvironments = cursorKeychainAccessEnvironments(selectedEnvironments);
115 const refreshAfterCursorEnable = () => {
116 void refresh();
117 void limits.refreshAfterEnable();
118 };
119 const sourceMessages = [
120 ...new Set(
121 selectedEnvironments.flatMap(
122 (environment) =>
123 environment.summary?.sources.flatMap((source) =>
124 source.message &&
125 !source.action &&
126 (source.status === "partial" ||
127 source.status === "failed" ||
128 source.fingerprint.provider === "cursor")
129 ? [source.message]
130 : [],
131 ) ?? [],
132 ),
133 ),
134 ];
135 const canReadDiagnostics = selectedEnvironments.some(
136 (environment) => environment.canReadDiagnostics,
137 );
138
139 const days = enumerateDays(window.sinceDay, window.untilDay);
140 const chartDays =
141 isPast24Hours && window.sinceTime !== undefined && window.untilTime !== undefined
142 ? enumerateHourStarts(window.sinceTime, window.untilTime)
143 : days;
144 const chartTotals: readonly DailyTotals[] = isPast24Hours
145 ? merged.hourly.map((hour) => ({
146 day: hour.hourStart,
147 costUsd: hour.costUsd,
148 totalTokens: hour.totalTokens,
149 byProvider: hour.byProvider,
150 }))
151 : merged.daily;
152
153 const [refreshingUsage, setRefreshingUsage] = useState(false);
154 const refreshingRef = useRef(false);
155 const showingLimits = tab === "limits";
156 const progress = usageProgress(selectedEnvironments, {
157 refreshing: refreshingUsage,
158 providerLabel,
159 });
160 const selectWindow = (days: number) => {
161 setWindowSelection({
162 days,
163 window: makeWindow(days, undefined, days === 1 ? "hour" : "day"),
164 });
165 };
166 const refreshWindow = () => {
167 if (refreshingRef.current) return;
168 const nextWindow = makeWindow(windowDays, undefined, isPast24Hours ? "hour" : "day");
169 if (
170 nextWindow.sinceDay !== window.sinceDay ||
171 nextWindow.untilDay !== window.untilDay ||
172 nextWindow.sinceTime !== window.sinceTime ||
173 nextWindow.untilTime !== window.untilTime
174 ) {
175 setWindowSelection({ days: windowDays, window: nextWindow });
176 }
177 refreshingRef.current = true;
178 setRefreshingUsage(true);
179 void refresh(nextWindow).finally(() => {
180 refreshingRef.current = false;
181 setRefreshingUsage(false);
182 });
183 };
184
185 const showEnvironmentFilter = environments.length > 0 || selectedEnvironmentIds !== null;
186 const filterIcon =
187 selectedEnvironmentIds === null
188 ? "line.3.horizontal.decrease"
189 : "line.3.horizontal.decrease.circle.fill";
190 const environmentActions = [
191 {
192 id: "all",
193 title: "All environments",
194 subtitle: undefined,
195 state: selectedEnvironmentIds === null ? ("on" as const) : ("off" as const),
196 },
197 ...environments.map((environment) => ({
198 id: environment.environmentId,
199 title: environment.label,
200 subtitle: usageEnvironmentStatus(environment, refreshingUsage),
201 state:
202 selectedEnvironmentIds === null || selectedEnvironmentIds.has(environment.environmentId)
203 ? ("on" as const)
204 : ("off" as const),
205 })),
206 ];
207 const selectEnvironment = (value: string) => {
208 if (value === "all") {
209 setSelectedEnvironmentIds(null);
210 return;
211 }
212 const id = EnvironmentId.make(value);
213 setSelectedEnvironmentIds((selected) => toggleUsageEnvironment(selected, environments, id));
214 };
215 const environmentFilter = showEnvironmentFilter ? (
216 <Menu
217 accessible
218 accessibilityRole="button"
219 accessibilityLabel="Filter usage environments"
220 title="Environments"
221 actions={environmentActions}
222 onPressAction={({ nativeEvent }) => selectEnvironment(nativeEvent.event)}
223 >
224 <Pressable
225 accessibilityRole="button"
226 accessibilityLabel="Filter usage environments"
227 className={cn(
228 "items-center justify-center rounded-full",
229 Platform.OS === "ios" ? "size-[28px]" : "size-[44px]",
230 )}
231 >
232 <SymbolView name={filterIcon} size={22} tintColorClassName="accent-icon" />
233 </Pressable>
234 </Menu>
235 ) : null;
236
237 useLayoutEffect(() => {
238 if (Platform.OS === "ios") {
239 navigation.setOptions({ headerRight: () => environmentFilter });
240 }
241 }, [navigation, environmentFilter]);
242
243 return (
244 <SettingsScreen title="Usage" trailing={environmentFilter}>
245 <ScrollView
246 contentInsetAdjustmentBehavior="automatic"
247 showsVerticalScrollIndicator={false}
248 className="flex-1"
249 contentContainerClassName="gap-6 px-5 pt-4"
250 contentContainerStyle={{ paddingBottom: Math.max(insets.bottom, 18) + 18 }}
251 refreshControl={
252 showingLimits || canReadDiagnostics ? (
253 <RefreshControl
254 refreshing={showingLimits ? limits.refreshing : refreshingUsage}
255 onRefresh={showingLimits ? () => void limits.refresh() : refreshWindow}
256 />
257 ) : undefined
258 }
259 >
260 <SegmentedControl options={TAB_OPTIONS} selected={tab} onSelect={setTab} role="tab" />
261 <Animated.View
262 key={tab}
263 entering={FadeIn.duration(160).reduceMotion(ReduceMotion.System)}
264 className="gap-6"
265 >
266 {showingLimits ? (
267 <UsageLimitsSection
268 now={limits.now}
269 failedLabels={limits.failedLabels}
270 selectedEnvironmentIds={selectedEnvironmentIds}
271 cursorPrompt={
272 cursorAccessEnvironments.length > 0 ? (
273 <CursorEnableLimits
274 environments={cursorAccessEnvironments}
275 onEnabled={refreshAfterCursorEnable}
276 />
277 ) : null
278 }
279 />
280 ) : (
281 <>
282 <View className="gap-3 ios:flex-row ios:items-center">
283 <SegmentedControl
284 options={WINDOW_OPTIONS}
285 selected={windowDays}
286 onSelect={selectWindow}
287 size="compact"
288 className="w-full ios:flex-1"
289 />
290 <SegmentedControl
291 options={METRIC_OPTIONS}
292 selected={metric}
293 onSelect={setMetric}
294 size="compact"
295 className="w-full ios:w-36"
296 />
297 </View>
298 <ChatGptUsageSummary selectedEnvironmentIds={selectedEnvironmentIds} />
299 {merged.duplicateSources.length > 0 ? (
300 <Text className="text-sm text-foreground-muted">
301 Counted once across environments sharing a transcript directory:{" "}
302 {merged.duplicateSources.join(", ")}
303 </Text>
304 ) : null}
305 {isPending ? (
306 <Text className="py-16 text-center text-base text-foreground-muted">
307 Scanning provider transcripts…
308 </Text>
309 ) : selectedEnvironments.length === 0 ? (
310 <Text className="py-16 text-center text-base text-foreground-muted">
311 {environments.length === 0
312 ? "Connect an environment to see usage."
313 : "Select an environment to see usage."}
314 </Text>
315 ) : !canReadDiagnostics ? (
316 <View className="gap-2 py-16">
317 {selectedEnvironments.map((environment) => (
318 <Text
319 key={environment.environmentId}
320 className="text-center text-base text-foreground-muted"
321 >
322 {selectedEnvironments.length > 1 ? `${environment.label}: ` : null}
323 {environment.error}
324 </Text>
325 ))}
326 </View>
327 ) : (
328 <>
329 {sourceMessages.map((message) => (
330 <Text key={message} className="text-sm text-foreground-muted">
331 {message}
332 </Text>
333 ))}
334 <UsageUpdating dimmed={progress.dimmed} label={progress.label}>
335 <ChartCard
336 merged={merged}
337 days={chartDays}
338 daily={chartTotals}
339 metric={metric}
340 sinceDay={window.sinceDay}
341 untilDay={window.untilDay}
342 isPast24Hours={isPast24Hours}
343 timeZone={window.timeZone}
344 />
345 <ProviderSection
346 merged={merged}
347 metric={metric}
348 cursorAccessEnvironments={cursorAccessEnvironments}
349 showCursorEnvironment={selectedEnvironments.length > 1}
350 onCursorEnabled={refreshAfterCursorEnable}
351 />
352 <TotalsSection merged={merged} isPast24Hours={isPast24Hours} />
353 <CostSection merged={merged} />
354 <ModelsSection merged={merged} metric={metric} />
355 </UsageUpdating>
356 </>
357 )}
358 </>
359 )}
360 </Animated.View>
361 </ScrollView>
362 </SettingsScreen>
363 );
364}
365
366function UsageUpdating({
367 dimmed,
368 label,
369 children,
370}: {
371 readonly dimmed: boolean;
372 readonly label: string | null;
373 readonly children: ReactNode;
374}) {
375 const opacity = useSharedValue(1);
376 useLayoutEffect(() => {
377 opacity.set(
378 dimmed
379 ? withDelay(150, withTiming(0.5, { duration: 150, reduceMotion: ReduceMotion.System }))
380 : withTiming(1, { duration: 150, reduceMotion: ReduceMotion.System }),
381 );
382 }, [opacity, dimmed]);
383 const dimStyle = useAnimatedStyle(() => ({ opacity: opacity.get() }));
384
385 return (
386 <View>
387 <Animated.View style={dimStyle} className="gap-6" accessibilityState={{ busy: dimmed }}>
388 {children}
389 </Animated.View>
390 {label !== null ? (
391 <Animated.View
392 entering={FadeIn.delay(150).duration(150).reduceMotion(ReduceMotion.System)}
393 accessibilityLiveRegion="polite"
394 pointerEvents="none"
395 className="absolute right-4 top-4 h-5 max-w-[55%] flex-row items-center gap-1.5"
396 >
397 <AppActivityIndicator size="small" colorClassName="accent-adaptive-sky-600-400" />
398 <Text className="shrink text-sm text-adaptive-sky-600-400" numberOfLines={1}>
399 {label}
400 </Text>
401 </Animated.View>
402 ) : null}
403 </View>
404 );
405}
406
407function CursorEnableAction({
408 environmentId,
409 label,
410 onEnabled,
411 buttonText = "Enable",
412}: {
413 readonly environmentId: EnvironmentId;
414 readonly label: string;
415 readonly onEnabled: () => void;
416 readonly buttonText?: string;
417}) {
418 const updateSettings = useAtomCommand(serverEnvironment.updateSettings, {
419 label: "enable Cursor account usage",
420 });
421 const [pending, setPending] = useState(false);
422 const enable = async () => {
423 setPending(true);
424 const result = await updateSettings({
425 environmentId,
426 input: { patch: { cursorKeychainUsageEnabled: true } },
427 }).finally(() => setPending(false));
428 if (result._tag === "Success") onEnabled();
429 };
430 return (
431 <Button
432 label={buttonText}
433 tone="primary"
434 accessibilityLabel={`Enable Cursor usage from ${label}`}
435 accessibilityHint={CURSOR_KEYCHAIN_COPY}
436 disabled={pending}
437 onPress={() => void enable()}
438 loading={pending}
439 />
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}