Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

UsageRouteScreen.tsx

661 lines23.9 KB

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