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