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