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

UsageRouteScreen.tsx

442 lines15.8 KB

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