Open History to see the last commit
1import { EnvironmentId, USAGE_CONTRACT_VERSION } from "@t3tools/contracts";
2import { type RouteProp, useIsFocused, useNavigation, useRoute } from "@react-navigation/native";
3import {
4 isCompatibleUsageContractVersion,
5 isModelCostUnknown,
6 type DailyTotals,
7 type MergedUsage,
8} from "@t3tools/shared/usageMerge";
9import {
10 enumerateDays,
11 enumerateHourStarts,
12 formatCount,
13 formatDayShort,
14 formatHourShort,
15 formatPercent,
16 formatTokens,
17 formatUsd,
18 makeWindow,
19} from "@t3tools/shared/usageFormat";
20import { useCallback, useLayoutEffect, useMemo, useRef, useState } from "react";
21import { Platform, Pressable, RefreshControl, ScrollView, View } from "react-native";
22import Animated, { FadeIn, ReduceMotion } from "react-native-reanimated";
23import { useSafeAreaInsets } from "react-native-safe-area-context";
24
25import { SegmentedControl } from "../../components/SegmentedControl";
26import { AndroidScreenHeader } from "../../components/AndroidScreenHeader";
27import { AppText as Text } from "../../components/AppText";
28import { cn } from "../../lib/cn";
29import { NativeStackScreenOptions } from "../../native/StackHeader";
30import { useUsage, type EnvironmentUsageStatus } from "../../state/usage";
31import { SettingsSection } from "../settings/components/SettingsSection";
32import { UsageDailyChart } from "./UsageDailyChart";
33import { toggleUsageEnvironment } from "./usageEnvironmentSelection";
34import { useRefreshLimits } from "./UsageLimitsSection";
35import { UsageLimitsSection } from "./UsageLimitsPooled";
36import { ControlPillMenu } from "../../components/ControlPill";
37import { SymbolView } from "../../components/AppSymbol";
38import type { UsageChartMetric } from "./usageChartData";
39import { PROVIDER_LABEL, useProviderColors } from "./usageProviders";
40
41type UsageTab = "usage" | "limits";
42const TAB_OPTIONS = [
43 { value: "usage", label: "Usage" },
44 { value: "limits", label: "Limits" },
45] as const satisfies readonly { value: UsageTab; label: string }[];
46
47// Labels are abbreviated to share a row with the metric toggle; screen
48// readers get the full phrase.
49const WINDOW_OPTIONS = [
50 { value: 1, label: "24h", accessibilityLabel: "Past 24 hours" },
51 { value: 7, label: "7d", accessibilityLabel: "Past 7 days" },
52 { value: 30, label: "30d", accessibilityLabel: "Past 30 days" },
53 { value: 90, label: "90d", accessibilityLabel: "Past 90 days" },
54] as const;
55
56const METRIC_OPTIONS = [
57 { value: "cost", label: "Cost" },
58 { value: "tokens", label: "Tokens" },
59] as const satisfies readonly { value: UsageChartMetric; label: string }[];
60
61const CHART_HEIGHT = 180;
62
63/**
64 * Two tabs over one screen. Usage is the transcript-derived spend for a
65 * period; Limits is the live subscription quota, which has no period. Both
66 * pull to refresh, each refreshing its own data.
67 */
68export function UsageRouteScreen() {
69 const route = useRoute<RouteProp<{ Usage: { tab?: string } | undefined }, "Usage">>();
70 const navigation = useNavigation();
71 const insets = useSafeAreaInsets();
72 // Preserve the Limits default while honoring explicit widget/navigation links.
73 const [selection, setSelection] = useState(() => ({
74 params: route.params,
75 tab: (route.params?.tab === "usage" ? "usage" : "limits") as UsageTab,
76 }));
77 if (selection.params !== route.params) {
78 setSelection({
79 params: route.params,
80 tab: route.params?.tab === "usage" ? "usage" : "limits",
81 });
82 }
83 const { tab } = selection;
84 const setTab = (tab: UsageTab) => setSelection({ params: route.params, tab });
85 const [windowSelection, setWindowSelection] = useState(() => ({
86 days: 30,
87 window: makeWindow(30),
88 }));
89 const [metric, setMetric] = useState<UsageChartMetric>("cost");
90 const { days: windowDays, window } = windowSelection;
91 const isPast24Hours = windowDays === 1;
92 const [selectedEnvironmentIds, setSelectedEnvironmentIds] =
93 useState<ReadonlySet<EnvironmentId> | null>(null);
94 const { merged, environments, selectedEnvironments, isPending, refresh } = useUsage(
95 window,
96 selectedEnvironmentIds,
97 );
98 const isFocused = useIsFocused();
99 const limits = useRefreshLimits(selectedEnvironmentIds, isFocused && tab === "limits");
100
101 const days = useMemo(
102 () => enumerateDays(window.sinceDay, window.untilDay),
103 [window.sinceDay, window.untilDay],
104 );
105 const chartDays = useMemo(
106 () =>
107 isPast24Hours && window.sinceTime !== undefined && window.untilTime !== undefined
108 ? enumerateHourStarts(window.sinceTime, window.untilTime)
109 : days,
110 [days, isPast24Hours, window.sinceTime, window.untilTime],
111 );
112 const chartTotals = useMemo(
113 (): readonly DailyTotals[] =>
114 isPast24Hours
115 ? merged.hourly.map((hour) => ({
116 day: hour.hourStart,
117 costUsd: hour.costUsd,
118 totalTokens: hour.totalTokens,
119 byProvider: hour.byProvider,
120 }))
121 : merged.daily,
122 [isPast24Hours, merged.daily, merged.hourly],
123 );
124
125 const [refreshingUsage, setRefreshingUsage] = useState(false);
126 const refreshingRef = useRef(false);
127 const showingLimits = tab === "limits";
128 const selectWindow = (days: number) => {
129 setWindowSelection({
130 days,
131 window: makeWindow(days, undefined, days === 1 ? "hour" : "day"),
132 });
133 };
134 const refreshWindow = () => {
135 if (refreshingRef.current) return;
136 const nextWindow = makeWindow(windowDays, undefined, isPast24Hours ? "hour" : "day");
137 if (
138 nextWindow.sinceDay !== window.sinceDay ||
139 nextWindow.untilDay !== window.untilDay ||
140 nextWindow.sinceTime !== window.sinceTime ||
141 nextWindow.untilTime !== window.untilTime
142 ) {
143 setWindowSelection({ days: windowDays, window: nextWindow });
144 }
145 refreshingRef.current = true;
146 setRefreshingUsage(true);
147 void refresh(nextWindow).finally(() => {
148 refreshingRef.current = false;
149 setRefreshingUsage(false);
150 });
151 };
152
153 const showEnvironmentFilter = environments.length > 0 || selectedEnvironmentIds !== null;
154 const hasLoadingEnvironments = selectedEnvironments.some(isUsageLoading);
155 const filterAccessibilityLabel = hasLoadingEnvironments
156 ? "Filter usage environments, some environments are loading"
157 : "Filter usage environments";
158 const filterIcon =
159 selectedEnvironmentIds === null
160 ? "line.3.horizontal.decrease"
161 : "line.3.horizontal.decrease.circle.fill";
162 const environmentActions = useMemo(
163 () => [
164 {
165 id: "all",
166 title: "All environments",
167 subtitle: undefined,
168 state: selectedEnvironmentIds === null ? ("on" as const) : ("off" as const),
169 },
170 ...environments.map((environment) => ({
171 id: environment.environmentId,
172 title: environment.label,
173 subtitle: usageEnvironmentStatus(environment),
174 state:
175 selectedEnvironmentIds === null || selectedEnvironmentIds.has(environment.environmentId)
176 ? ("on" as const)
177 : ("off" as const),
178 })),
179 ],
180 [environments, selectedEnvironmentIds],
181 );
182 const selectEnvironment = useCallback(
183 (value: string) => {
184 if (value === "all") {
185 setSelectedEnvironmentIds(null);
186 return;
187 }
188 const id = EnvironmentId.make(value);
189 setSelectedEnvironmentIds((selected) => toggleUsageEnvironment(selected, environments, id));
190 },
191 [environments],
192 );
193 const environmentFilter = useMemo(
194 () =>
195 showEnvironmentFilter ? (
196 <ControlPillMenu
197 accessible
198 accessibilityRole="button"
199 accessibilityLabel={filterAccessibilityLabel}
200 title="Environments"
201 actions={environmentActions}
202 onPressAction={({ nativeEvent }) => selectEnvironment(nativeEvent.event)}
203 >
204 <Pressable
205 accessibilityRole="button"
206 accessibilityLabel={filterAccessibilityLabel}
207 className={cn(
208 "items-center justify-center rounded-full",
209 Platform.OS === "ios" ? "size-[28px]" : "size-[44px]",
210 )}
211 >
212 <SymbolView name={filterIcon} size={22} tintColorClassName="accent-icon" />
213 {hasLoadingEnvironments ? (
214 <View
215 pointerEvents="none"
216 className="absolute -right-[2px] -top-[2px] size-[9px] rounded-full bg-amber-500"
217 />
218 ) : null}
219 </Pressable>
220 </ControlPillMenu>
221 ) : null,
222 [
223 showEnvironmentFilter,
224 environmentActions,
225 selectEnvironment,
226 filterAccessibilityLabel,
227 filterIcon,
228 hasLoadingEnvironments,
229 ],
230 );
231
232 useLayoutEffect(() => {
233 if (Platform.OS === "ios") {
234 navigation.setOptions({ headerRight: () => environmentFilter });
235 }
236 }, [navigation, environmentFilter]);
237
238 return (
239 <View collapsable={false} className="flex-1 bg-sheet">
240 {Platform.OS === "android" ? (
241 <>
242 <NativeStackScreenOptions options={{ headerShown: false }} />
243 <AndroidScreenHeader
244 title="Usage"
245 onBack={() => navigation.goBack()}
246 trailing={environmentFilter}
247 />
248 </>
249 ) : null}
250 <ScrollView
251 contentInsetAdjustmentBehavior="automatic"
252 showsVerticalScrollIndicator={false}
253 className="flex-1"
254 contentContainerClassName="gap-6 px-5 pt-4"
255 contentContainerStyle={{ paddingBottom: Math.max(insets.bottom, 18) + 18 }}
256 refreshControl={
257 <RefreshControl
258 refreshing={showingLimits ? limits.refreshing : refreshingUsage}
259 onRefresh={showingLimits ? () => void limits.refresh() : refreshWindow}
260 />
261 }
262 >
263 <SegmentedControl options={TAB_OPTIONS} selected={tab} onSelect={setTab} role="tab" />
264
265 <Animated.View
266 key={tab}
267 entering={FadeIn.duration(160).reduceMotion(ReduceMotion.System)}
268 className="gap-6"
269 >
270 {showingLimits ? (
271 <UsageLimitsSection
272 now={limits.now}
273 failedLabels={limits.failedLabels}
274 selectedEnvironmentIds={selectedEnvironmentIds}
275 />
276 ) : (
277 <>
278 {/* Period and metric together: neither applies to Limits, and
279 both change every number below, so they share one bar. */}
280 <View className="flex-row items-center gap-3">
281 <SegmentedControl
282 options={WINDOW_OPTIONS}
283 selected={windowDays}
284 onSelect={selectWindow}
285 size="compact"
286 className="flex-1"
287 />
288 <SegmentedControl
289 options={METRIC_OPTIONS}
290 selected={metric}
291 onSelect={setMetric}
292 size="compact"
293 className="w-36"
294 />
295 </View>
296 {merged.duplicateSources.length > 0 ? (
297 <Text className="text-sm text-foreground-muted">
298 Counted once across environments sharing a transcript directory:{" "}
299 {merged.duplicateSources.join(", ")}
300 </Text>
301 ) : null}
302 {isPending ? (
303 <Text className="py-16 text-center text-base text-foreground-muted">
304 Scanning provider transcripts…
305 </Text>
306 ) : selectedEnvironments.length === 0 ? (
307 <Text className="py-16 text-center text-base text-foreground-muted">
308 {environments.length === 0
309 ? "Connect an environment to see usage."
310 : "Select an environment to see usage."}
311 </Text>
312 ) : (
313 <>
314 <ChartCard
315 merged={merged}
316 days={chartDays}
317 daily={chartTotals}
318 metric={metric}
319 sinceDay={window.sinceDay}
320 untilDay={window.untilDay}
321 isPast24Hours={isPast24Hours}
322 timeZone={window.timeZone}
323 />
324 <ProviderSection merged={merged} metric={metric} />
325 <TotalsSection merged={merged} isPast24Hours={isPast24Hours} />
326 <ModelsSection merged={merged} />
327 </>
328 )}
329 </>
330 )}
331 </Animated.View>
332 </ScrollView>
333 </View>
334 );
335}
336
337/** Headline figure, the animated daily chart, and its legend, in one card. */
338function ChartCard(props: {
339 readonly merged: MergedUsage;
340 readonly days: readonly string[];
341 readonly daily: readonly DailyTotals[];
342 readonly metric: UsageChartMetric;
343 readonly sinceDay: string;
344 readonly untilDay: string;
345 readonly isPast24Hours: boolean;
346 readonly timeZone: string;
347}) {
348 const { merged, metric } = props;
349 const colors = useProviderColors();
350 const hasActivity = props.daily.some((period) => period.totalTokens > 0);
351
352 return (
353 <View className="gap-4 rounded-[24px] border-continuous bg-card p-4">
354 <View className="gap-0.5">
355 <Text className="text-sm text-foreground-muted">
356 {metric === "cost" ? "Raw token cost" : "Processed tokens"}
357 </Text>
358 <Text className="text-4xl font-t3-bold tabular-nums text-foreground">
359 {metric === "cost" ? `${formatUsd(merged.costUsd)}*` : formatTokens(merged.totalTokens)}
360 </Text>
361 <Text className="text-sm text-foreground-muted">
362 {metric === "cost"
363 ? "* if billed at full API rate"
364 : `Across ${formatCount(merged.sessions)} sessions`}
365 </Text>
366 </View>
367
368 {hasActivity ? (
369 <UsageDailyChart
370 days={props.days}
371 daily={props.daily}
372 metric={metric}
373 height={CHART_HEIGHT}
374 />
375 ) : (
376 <View style={{ height: CHART_HEIGHT }} className="items-center justify-center">
377 <Text className="text-base text-foreground-muted">No activity in this window.</Text>
378 </View>
379 )}
380
381 <View className="flex-row items-center justify-between">
382 <Text className="text-xs text-foreground-tertiary">
383 {props.isPast24Hours
384 ? formatHourShort(props.days[0] ?? "", props.timeZone)
385 : formatDayShort(props.sinceDay)}
386 </Text>
387 <View className="flex-row items-center gap-4">
388 {merged.providers.map((provider) => (
389 <View key={provider.provider} className="flex-row items-center gap-1.5">
390 <View
391 className="size-2 rounded-full"
392 style={{ backgroundColor: colors[provider.provider] }}
393 />
394 <Text className="text-xs text-foreground-muted">
395 {PROVIDER_LABEL[provider.provider]}
396 </Text>
397 </View>
398 ))}
399 </View>
400 <Text className="text-xs text-foreground-tertiary">
401 {props.isPast24Hours
402 ? formatHourShort(props.days[props.days.length - 1] ?? "", props.timeZone)
403 : formatDayShort(props.untilDay)}
404 </Text>
405 </View>
406 </View>
407 );
408}
409
410function ProviderSection(props: {
411 readonly merged: MergedUsage;
412 readonly metric: UsageChartMetric;
413}) {
414 const { merged, metric } = props;
415 const colors = useProviderColors();
416 if (merged.providers.length === 0) return null;
417
418 // Ranked by whatever the toggle is showing, so the rows always descend.
419 // .sort() on a copy, not .toSorted(): Hermes doesn't ship the ES2023 method.
420 const ordered = [...merged.providers].sort((a, b) =>
421 metric === "cost" ? b.costUsd - a.costUsd : b.totalTokens - a.totalTokens,
422 );
423
424 return (
425 <SettingsSection title="Providers" card>
426 {ordered.map((provider, index) => {
427 const share = metric === "cost" ? provider.costShare : provider.tokenShare;
428 return (
429 <View
430 key={provider.provider}
431 className={index === 0 ? "gap-2 p-4" : "gap-2 border-t border-border-subtle p-4"}
432 >
433 <View className="flex-row items-baseline justify-between gap-3">
434 <View className="flex-row items-center gap-2">
435 <View
436 className="size-2.5 rounded-full"
437 style={{ backgroundColor: colors[provider.provider] }}
438 />
439 <Text className="text-lg text-foreground">{PROVIDER_LABEL[provider.provider]}</Text>
440 </View>
441 <Text className="text-lg tabular-nums text-foreground">
442 {metric === "cost"
443 ? formatUsd(provider.costUsd)
444 : formatTokens(provider.totalTokens)}
445 </Text>
446 </View>
447 <View className="h-1 flex-row overflow-hidden rounded-full bg-subtle">
448 <View
449 className="h-full rounded-full"
450 style={{ flex: share, backgroundColor: colors[provider.provider] }}
451 />
452 <View style={{ flex: 1 - share }} />
453 </View>
454 <Text className="text-sm text-foreground-muted">
455 {metric === "cost"
456 ? `${formatPercent(share)} of cost · ${formatTokens(provider.totalTokens)} tokens`
457 : `${formatPercent(share)} of tokens · ${formatUsd(provider.costUsd)}`}
458 </Text>
459 </View>
460 );
461 })}
462 </SettingsSection>
463 );
464}
465
466function TotalsSection(props: { readonly merged: MergedUsage; readonly isPast24Hours: boolean }) {
467 const { merged } = props;
468 const activePeriods = (props.isPast24Hours ? merged.hourly : merged.daily).filter(
469 (period) => period.totalTokens > 0,
470 ).length;
471 const periodAverage = activePeriods === 0 ? 0 : merged.totalTokens / activePeriods;
472 const observedInput = merged.uncachedInputTokens + merged.cachedInputTokens;
473 const cachedShare = observedInput === 0 ? 0 : merged.cachedInputTokens / observedInput;
474
475 return (
476 <SettingsSection title="Totals" card>
477 <View className="flex-row flex-wrap">
478 <MetricCell
479 label="Processed tokens"
480 value={formatTokens(merged.totalTokens)}
481 detail={`${formatTokens(periodAverage)} per active ${props.isPast24Hours ? "hour" : "day"}`}
482 />
483 <MetricCell
484 label="Cache savings"
485 value={formatUsd(merged.costQuality.cacheSavingsUsd)}
486 detail={
487 merged.costUsd > 0
488 ? `${(merged.costQuality.cacheSavingsUsd / merged.costUsd).toFixed(1)}x the raw cost`
489 : "vs full input rates"
490 }
491 />
492 <MetricCell
493 label="Cached input"
494 value={formatTokens(merged.cachedInputTokens)}
495 detail={`${formatPercent(cachedShare)} of observed input`}
496 />
497 <MetricCell
498 label="Uncached input"
499 value={formatTokens(merged.uncachedInputTokens)}
500 detail={`${formatTokens(merged.cacheCreationTokens)} cache writes`}
501 />
502 <MetricCell
503 label="Output"
504 value={formatTokens(merged.outputTokens)}
505 detail={`incl. ${formatTokens(merged.reasoningTokens)} reasoning`}
506 />
507 <MetricCell
508 label="Unpriced"
509 value={formatPercent(merged.costQuality.unpricedShare)}
510 detail="of records, excluded from cost"
511 />
512 </View>
513 </SettingsSection>
514 );
515}
516
517function MetricCell(props: {
518 readonly label: string;
519 readonly value: string;
520 readonly detail: string;
521}) {
522 return (
523 <View className="w-1/2 gap-0.5 p-4">
524 <Text className="text-sm text-foreground-muted">{props.label}</Text>
525 <Text className="text-xl font-t3-medium tabular-nums text-foreground">{props.value}</Text>
526 <Text className="text-xs text-foreground-tertiary">{props.detail}</Text>
527 </View>
528 );
529}
530
531function ModelsSection(props: { readonly merged: MergedUsage }) {
532 const { merged } = props;
533 const colors = useProviderColors();
534 if (merged.models.length === 0) return null;
535
536 return (
537 <SettingsSection title="By model" card>
538 {merged.models.map((model, index) => (
539 <View
540 key={`${model.provider}:${model.model}`}
541 className={
542 index === 0
543 ? "flex-row items-center gap-3 p-4"
544 : "flex-row items-center gap-3 border-t border-border-subtle p-4"
545 }
546 >
547 <View
548 className="size-2.5 shrink-0 rounded-full"
549 style={{ backgroundColor: colors[model.provider] }}
550 />
551 <View className="min-w-0 flex-1 gap-0.5">
552 <Text className="text-base text-foreground" numberOfLines={1}>
553 {model.model}
554 </Text>
555 <Text className="text-sm text-foreground-muted">
556 {isModelCostUnknown(model)
557 ? `no known rates · ${formatTokens(model.totalTokens)} tokens`
558 : `${formatPercent(model.costShare)} of cost · ${formatTokens(model.totalTokens)} tokens`}
559 </Text>
560 </View>
561 <Text className="text-base tabular-nums text-foreground">
562 {isModelCostUnknown(model) ? "Unpriced" : formatUsd(model.costUsd)}
563 </Text>
564 </View>
565 ))}
566 </SettingsSection>
567 );
568}
569
570/**
571 * Says plainly when the totals are incomplete: an environment still answering,
572 * one that failed, or one whose transcripts another environment already
573 * reported.
574 */
575function isUsageLoading(environment: EnvironmentUsageStatus) {
576 return environment.isPending || (environment.summary === null && environment.error === null);
577}
578
579function usageEnvironmentStatus(environment: EnvironmentUsageStatus): string {
580 if (
581 environment.summary &&
582 !isCompatibleUsageContractVersion(environment.summary.contractVersion, USAGE_CONTRACT_VERSION)
583 ) {
584 return "Older server · excluded from usage totals";
585 }
586 if (!environment.isConnected)
587 return environment.summary ? "Disconnected · showing saved usage" : "Waiting for connection…";
588 if (environment.error)
589 return environment.summary ? "Usage unavailable · showing saved totals" : "Usage unavailable";
590 if (isUsageLoading(environment))
591 return environment.summary ? "Updating usage…" : "Loading usage…";
592 return "Usage up to date";
593}