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