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