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