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