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

UsageRouteScreen.tsx

583 lines21.6 KB

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