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, 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 const selectWindow = (days: number) => {
100 setWindowSelection({
101 days,
102 window: makeWindow(days, undefined, days === 1 ? "hour" : "day"),
103 });
104 };
105 const refreshWindow = () => {
106 const nextWindow = makeWindow(windowDays, undefined, isPast24Hours ? "hour" : "day");
107 if (
108 nextWindow.sinceDay === window.sinceDay &&
109 nextWindow.untilDay === window.untilDay &&
110 nextWindow.sinceTime === window.sinceTime &&
111 nextWindow.untilTime === window.untilTime
112 ) {
113 refresh();
114 } else {
115 setWindowSelection({ days: windowDays, window: nextWindow });
116 }
117 };
118
119 return (
120 <View collapsable={false} className="flex-1 bg-sheet">
121 {Platform.OS === "android" ? (
122 <>
123 <NativeStackScreenOptions options={{ headerShown: false }} />
124 <AndroidScreenHeader title="Usage" onBack={() => navigation.goBack()} />
125 </>
126 ) : null}
127 <ScrollView
128 // Remount at each tab's native top. Scrolling to y: 0 ignores iOS's
129 // automatic header inset and hides the tab bar under the header.
130 key={tab}
131 contentInsetAdjustmentBehavior="automatic"
132 showsVerticalScrollIndicator={false}
133 className="flex-1"
134 contentContainerClassName="gap-6 px-5 pt-4"
135 contentContainerStyle={{ paddingBottom: Math.max(insets.bottom, 18) + 18 }}
136 refreshControl={
137 <RefreshControl
138 refreshing={showingLimits ? limits.refreshing : refreshingUsage}
139 onRefresh={showingLimits ? () => void limits.refresh() : refreshWindow}
140 />
141 }
142 >
143 <SegmentedControl options={TAB_OPTIONS} selected={tab} onSelect={setTab} role="tab" />
144
145 {showingLimits ? (
146 <UsageLimitsSection now={limits.now} failedLabels={limits.failedLabels} />
147 ) : (
148 <>
149 {/* Period and metric together: neither applies to Limits, and
150 both change every number below, so they share one bar. */}
151 <View className="flex-row items-center gap-3">
152 <SegmentedControl
153 options={WINDOW_OPTIONS}
154 selected={windowDays}
155 onSelect={selectWindow}
156 size="compact"
157 className="flex-1"
158 />
159 <SegmentedControl
160 options={METRIC_OPTIONS}
161 selected={metric}
162 onSelect={setMetric}
163 size="compact"
164 className="w-36"
165 />
166 </View>
167 <UsageCoverageNotice
168 environments={environments}
169 merged={merged}
170 isPartial={isPartial}
171 />
172 {isPending ? (
173 <Text className="py-16 text-center text-base text-foreground-muted">
174 Scanning provider transcripts…
175 </Text>
176 ) : environments.length === 0 ? (
177 <Text className="py-16 text-center text-base text-foreground-muted">
178 Connect an environment to see usage.
179 </Text>
180 ) : (
181 <>
182 <ChartCard
183 merged={merged}
184 days={chartDays}
185 daily={chartTotals}
186 metric={metric}
187 sinceDay={window.sinceDay}
188 untilDay={window.untilDay}
189 isPast24Hours={isPast24Hours}
190 timeZone={window.timeZone}
191 />
192 <ProviderSection merged={merged} metric={metric} />
193 <TotalsSection merged={merged} isPast24Hours={isPast24Hours} />
194 <ModelsSection merged={merged} />
195 </>
196 )}
197 </>
198 )}
199 </ScrollView>
200 </View>
201 );
202}
203
204function SegmentedControl<Value extends number | string>(props: {
205 readonly options: readonly {
206 readonly value: Value;
207 readonly label: string;
208 readonly accessibilityLabel?: string;
209 }[];
210 readonly selected: Value;
211 readonly onSelect: (value: Value) => void;
212 /** The tab bar is full height; filters under it are shorter so it stays primary. */
213 readonly size?: "default" | "compact";
214 /** "tab" for the view switcher; filters stay plain buttons. */
215 readonly role?: "tab" | "button";
216 readonly className?: string;
217}) {
218 const compact = props.size === "compact";
219 return (
220 <View
221 accessibilityRole={props.role === "tab" ? "tablist" : undefined}
222 className={cn(
223 "flex-row overflow-hidden rounded-full border-continuous bg-card",
224 props.className,
225 )}
226 >
227 {props.options.map((option) => {
228 const active = option.value === props.selected;
229 return (
230 <Pressable
231 key={String(option.value)}
232 accessibilityRole={props.role ?? "button"}
233 accessibilityLabel={option.accessibilityLabel}
234 accessibilityState={{ selected: active }}
235 onPress={() => props.onSelect(option.value)}
236 className={cn(
237 "flex-1 items-center justify-center rounded-full",
238 compact ? "h-9" : "h-11",
239 active && "bg-subtle-strong",
240 )}
241 >
242 <Text
243 className={cn(
244 compact ? "text-xs" : "text-sm",
245 active ? "font-t3-medium text-foreground" : "text-foreground-muted",
246 )}
247 >
248 {option.label}
249 </Text>
250 </Pressable>
251 );
252 })}
253 </View>
254 );
255}
256
257/** Headline figure, the animated daily chart, and its legend, in one card. */
258function ChartCard(props: {
259 readonly merged: MergedUsage;
260 readonly days: readonly string[];
261 readonly daily: readonly DailyTotals[];
262 readonly metric: UsageChartMetric;
263 readonly sinceDay: string;
264 readonly untilDay: string;
265 readonly isPast24Hours: boolean;
266 readonly timeZone: string;
267}) {
268 const { merged, metric } = props;
269 const colors = useProviderColors();
270 const hasActivity = props.daily.some((period) => period.totalTokens > 0);
271
272 return (
273 <View className="gap-4 rounded-[24px] border-continuous bg-card p-4">
274 <View className="gap-0.5">
275 <Text className="text-sm text-foreground-muted">
276 {metric === "cost" ? "Raw token cost" : "Processed tokens"}
277 </Text>
278 <Text className="text-4xl font-t3-bold tabular-nums text-foreground">
279 {metric === "cost" ? `${formatUsd(merged.costUsd)}*` : formatTokens(merged.totalTokens)}
280 </Text>
281 <Text className="text-sm text-foreground-muted">
282 {metric === "cost"
283 ? "* if billed at full API rate"
284 : `Across ${formatCount(merged.sessions)} sessions`}
285 </Text>
286 </View>
287
288 {hasActivity ? (
289 <UsageDailyChart
290 days={props.days}
291 daily={props.daily}
292 metric={metric}
293 height={CHART_HEIGHT}
294 />
295 ) : (
296 <View style={{ height: CHART_HEIGHT }} className="items-center justify-center">
297 <Text className="text-base text-foreground-muted">No activity in this window.</Text>
298 </View>
299 )}
300
301 <View className="flex-row items-center justify-between">
302 <Text className="text-xs text-foreground-tertiary">
303 {props.isPast24Hours
304 ? formatHourShort(props.days[0] ?? "", props.timeZone)
305 : formatDayShort(props.sinceDay)}
306 </Text>
307 <View className="flex-row items-center gap-4">
308 {merged.providers.map((provider) => (
309 <View key={provider.provider} className="flex-row items-center gap-1.5">
310 <View
311 className="size-2 rounded-full"
312 style={{ backgroundColor: colors[provider.provider] }}
313 />
314 <Text className="text-xs text-foreground-muted">
315 {PROVIDER_LABEL[provider.provider]}
316 </Text>
317 </View>
318 ))}
319 </View>
320 <Text className="text-xs text-foreground-tertiary">
321 {props.isPast24Hours
322 ? formatHourShort(props.days[props.days.length - 1] ?? "", props.timeZone)
323 : formatDayShort(props.untilDay)}
324 </Text>
325 </View>
326 </View>
327 );
328}
329
330function ProviderSection(props: {
331 readonly merged: MergedUsage;
332 readonly metric: UsageChartMetric;
333}) {
334 const { merged, metric } = props;
335 const colors = useProviderColors();
336 if (merged.providers.length === 0) return null;
337
338 // Ranked by whatever the toggle is showing, so the rows always descend.
339 // .sort() on a copy, not .toSorted(): Hermes doesn't ship the ES2023 method.
340 const ordered = [...merged.providers].sort((a, b) =>
341 metric === "cost" ? b.costUsd - a.costUsd : b.totalTokens - a.totalTokens,
342 );
343
344 return (
345 <SettingsSection title="Providers" card>
346 {ordered.map((provider, index) => {
347 const share = metric === "cost" ? provider.costShare : provider.tokenShare;
348 return (
349 <View
350 key={provider.provider}
351 className={index === 0 ? "gap-2 p-4" : "gap-2 border-t border-border-subtle p-4"}
352 >
353 <View className="flex-row items-baseline justify-between gap-3">
354 <View className="flex-row items-center gap-2">
355 <View
356 className="size-2.5 rounded-full"
357 style={{ backgroundColor: colors[provider.provider] }}
358 />
359 <Text className="text-lg text-foreground">{PROVIDER_LABEL[provider.provider]}</Text>
360 </View>
361 <Text className="text-lg tabular-nums text-foreground">
362 {metric === "cost"
363 ? formatUsd(provider.costUsd)
364 : formatTokens(provider.totalTokens)}
365 </Text>
366 </View>
367 <View className="h-1 flex-row overflow-hidden rounded-full bg-subtle">
368 <View
369 className="h-full rounded-full"
370 style={{ flex: share, backgroundColor: colors[provider.provider] }}
371 />
372 <View style={{ flex: 1 - share }} />
373 </View>
374 <Text className="text-sm text-foreground-muted">
375 {metric === "cost"
376 ? `${formatPercent(share)} of cost · ${formatTokens(provider.totalTokens)} tokens`
377 : `${formatPercent(share)} of tokens · ${formatUsd(provider.costUsd)}`}
378 </Text>
379 </View>
380 );
381 })}
382 </SettingsSection>
383 );
384}
385
386function TotalsSection(props: { readonly merged: MergedUsage; readonly isPast24Hours: boolean }) {
387 const { merged } = props;
388 const activePeriods = (props.isPast24Hours ? merged.hourly : merged.daily).filter(
389 (period) => period.totalTokens > 0,
390 ).length;
391 const periodAverage = activePeriods === 0 ? 0 : merged.totalTokens / activePeriods;
392 const observedInput = merged.uncachedInputTokens + merged.cachedInputTokens;
393 const cachedShare = observedInput === 0 ? 0 : merged.cachedInputTokens / observedInput;
394
395 return (
396 <SettingsSection title="Totals" card>
397 <View className="flex-row flex-wrap">
398 <MetricCell
399 label="Processed tokens"
400 value={formatTokens(merged.totalTokens)}
401 detail={`${formatTokens(periodAverage)} per active ${props.isPast24Hours ? "hour" : "day"}`}
402 />
403 <MetricCell
404 label="Cache savings"
405 value={formatUsd(merged.costQuality.cacheSavingsUsd)}
406 detail={
407 merged.costUsd > 0
408 ? `${(merged.costQuality.cacheSavingsUsd / merged.costUsd).toFixed(1)}x the raw cost`
409 : "vs full input rates"
410 }
411 />
412 <MetricCell
413 label="Cached input"
414 value={formatTokens(merged.cachedInputTokens)}
415 detail={`${formatPercent(cachedShare)} of observed input`}
416 />
417 <MetricCell
418 label="Uncached input"
419 value={formatTokens(merged.uncachedInputTokens)}
420 detail={`${formatTokens(merged.cacheCreationTokens)} cache writes`}
421 />
422 <MetricCell
423 label="Output"
424 value={formatTokens(merged.outputTokens)}
425 detail={`incl. ${formatTokens(merged.reasoningTokens)} reasoning`}
426 />
427 <MetricCell
428 label="Unpriced"
429 value={formatPercent(merged.costQuality.unpricedShare)}
430 detail="of records, excluded from cost"
431 />
432 </View>
433 </SettingsSection>
434 );
435}
436
437function MetricCell(props: {
438 readonly label: string;
439 readonly value: string;
440 readonly detail: string;
441}) {
442 return (
443 <View className="w-1/2 gap-0.5 p-4">
444 <Text className="text-sm text-foreground-muted">{props.label}</Text>
445 <Text className="text-xl font-t3-medium tabular-nums text-foreground">{props.value}</Text>
446 <Text className="text-xs text-foreground-tertiary">{props.detail}</Text>
447 </View>
448 );
449}
450
451function ModelsSection(props: { readonly merged: MergedUsage }) {
452 const { merged } = props;
453 const colors = useProviderColors();
454 if (merged.models.length === 0) return null;
455
456 return (
457 <SettingsSection title="By model" card>
458 {merged.models.map((model, index) => (
459 <View
460 key={`${model.provider}:${model.model}`}
461 className={
462 index === 0
463 ? "flex-row items-center gap-3 p-4"
464 : "flex-row items-center gap-3 border-t border-border-subtle p-4"
465 }
466 >
467 <View
468 className="size-2.5 shrink-0 rounded-full"
469 style={{ backgroundColor: colors[model.provider] }}
470 />
471 <View className="min-w-0 flex-1 gap-0.5">
472 <Text className="text-base text-foreground" numberOfLines={1}>
473 {model.model}
474 </Text>
475 <Text className="text-sm text-foreground-muted">
476 {formatPercent(model.costShare)} of cost · {formatTokens(model.totalTokens)} tokens
477 </Text>
478 </View>
479 <Text className="text-base tabular-nums text-foreground">{formatUsd(model.costUsd)}</Text>
480 </View>
481 ))}
482 </SettingsSection>
483 );
484}
485
486/**
487 * Says plainly when the totals are incomplete: an environment still answering,
488 * one that failed, or one whose transcripts another environment already
489 * reported.
490 */
491function UsageCoverageNotice(props: {
492 readonly environments: readonly EnvironmentUsageStatus[];
493 readonly merged: MergedUsage;
494 readonly isPartial: boolean;
495}) {
496 const failed = props.environments.filter((environment) => environment.error !== null);
497 const stale = props.environments.filter((environment) =>
498 props.merged.staleEnvironments.includes(environment.environmentId),
499 );
500 const duplicateSources = props.merged.duplicateSources;
501 if (
502 failed.length === 0 &&
503 stale.length === 0 &&
504 duplicateSources.length === 0 &&
505 !props.isPartial
506 ) {
507 return null;
508 }
509
510 return (
511 <View className="gap-1 rounded-[16px] border-continuous bg-card px-4 py-3">
512 {props.isPartial ? (
513 <Text className="text-sm text-foreground-muted">
514 Some environments are still reporting. Totals are partial.
515 </Text>
516 ) : null}
517 {failed.map((environment) => (
518 <Text key={environment.environmentId} className="text-sm text-foreground-muted">
519 {environment.label} could not report usage.
520 </Text>
521 ))}
522 {stale.map((environment) => (
523 <Text key={environment.environmentId} className="text-sm text-foreground-muted">
524 {environment.label} runs an older server version and is excluded from totals.
525 </Text>
526 ))}
527 {duplicateSources.length > 0 ? (
528 <Text className="text-sm text-foreground-muted">
529 Counted once across environments sharing a transcript directory:{" "}
530 {duplicateSources.join(", ")}
531 </Text>
532 ) : null}
533 </View>
534 );
535}