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