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

UsageRouteScreen.tsx

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