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

UsageRouteScreen.tsx

936 lines34.1 KB

1import { AppActivityIndicator } from "../../components/ui/AppActivityIndicator";
2import { ChatGptUsageSummary } from "./ChatGptUsageSummary";
3import { ScreenScrollView as ScrollView } from "../../components/ui/ScreenScrollView";
4import { EnvironmentId, USAGE_CONTRACT_VERSION, type UsageProviderKind } from "@t3tools/contracts";
5import { type RouteProp, useIsFocused, useNavigation, useRoute } from "@react-navigation/native";
6import { cursorKeychainAccessEnvironments } from "@t3tools/client-runtime/state/usage";
7import {
8 updatingProvidersLabel,
9 usageEnvironmentProgress,
10 usageProgress,
11} from "@t3tools/client-runtime/state/usage-progress";
12import {
13 isCompatibleUsageContractVersion,
14 isModelCostUnknown,
15 type DailyTotals,
16 type MergedUsage,
17} from "@t3tools/shared/usageMerge";
18import {
19 enumerateDays,
20 enumerateHourStarts,
21 formatCount,
22 formatDayShort,
23 formatHourShort,
24 formatPercent,
25 formatTokens,
26 formatUsageContractMismatch,
27 formatUsd,
28 makeWindow,
29} from "@t3tools/shared/usageFormat";
30import { useCallback, useLayoutEffect, useMemo, useRef, useState, type ReactNode } from "react";
31import { Platform, Pressable, RefreshControl, View } from "react-native";
32import Animated, {
33 FadeIn,
34 ReduceMotion,
35 useAnimatedStyle,
36 useSharedValue,
37 withDelay,
38 withTiming,
39} from "react-native-reanimated";
40import { useSafeAreaInsets } from "react-native-safe-area-context";
41​
42import { SegmentedControl } from "../../components/ui/SegmentedControl";
43import { AppText as Text } from "../../components/ui/AppText";
44import { ProviderIcon } from "../../components/ProviderIcon";
45import { cn } from "../../lib/cn";
46import { SettingsScreen } from "../settings/components/SettingsScreen";
47import { useUsage, type EnvironmentUsageStatus } from "../../state/usage";
48import { serverEnvironment } from "../../state/server";
49import { useAtomCommand } from "../../state/use-atom-command";
50import { SettingsSection } from "../settings/components/SettingsSection";
51import { UsageDailyChart } from "./UsageDailyChart";
52import { toggleUsageEnvironment } from "./usageEnvironmentSelection";
53import { useRefreshLimits } from "./UsageLimitsSection";
54import { UsageLimitsSection } from "./UsageLimitsPooled";
55import { Menu } from "../../components/ui/Menu";
56import { SymbolView } from "../../components/ui/AppSymbol";
57import type { UsageChartMetric } from "./usageChartData";
58import { PROVIDER_LABEL, useProviderColors, useUsageMixColors } from "./usageProviders";
59​
60type UsageTab = "usage" | "limits";
61const TAB_OPTIONS = [
62 { value: "usage", label: "Usage" },
63 { value: "limits", label: "Limits" },
64] as const satisfies readonly { value: UsageTab; label: string }[];
65​
66// Labels are abbreviated to share a row with the metric toggle; screen
67// readers get the full phrase.
68const WINDOW_OPTIONS = [
69 { value: 1, label: "24h", accessibilityLabel: "Past 24 hours" },
70 { value: 7, label: "7d", accessibilityLabel: "Past 7 days" },
71 { value: 30, label: "30d", accessibilityLabel: "Past 30 days" },
72 { value: 90, label: "90d", accessibilityLabel: "Past 90 days" },
73] as const;
74​
75const METRIC_OPTIONS = [
76 { value: "cost", label: "Cost" },
77 { value: "tokens", label: "Tokens" },
78] as const satisfies readonly { value: UsageChartMetric; label: string }[];
79​
80const CHART_HEIGHT = 180;
81const providerLabel = (provider: UsageProviderKind) => PROVIDER_LABEL[provider];
82const CURSOR_KEYCHAIN_COPY = "Requires access to your Cursor login in macOS Keychain.";
83​
84/**
85 * Two tabs over one screen. Usage is the transcript-derived spend for a
86 * period; Limits is the live subscription quota, which has no period. Both
87 * pull to refresh, each refreshing its own data.
88 */
89export function UsageRouteScreen() {
90 const route = useRoute<RouteProp<{ Usage: { tab?: string } | undefined }, "Usage">>();
91 const navigation = useNavigation();
92 const insets = useSafeAreaInsets();
93 // Preserve the Limits default while honoring explicit widget/navigation links.
94 const [selection, setSelection] = useState(() => ({
95 params: route.params,
96 tab: (route.params?.tab === "usage" ? "usage" : "limits") as UsageTab,
97 }));
98 if (selection.params !== route.params) {
99 setSelection({
100 params: route.params,
101 tab: route.params?.tab === "usage" ? "usage" : "limits",
102 });
103 }
104 const { tab } = selection;
105 const setTab = (tab: UsageTab) => setSelection({ params: route.params, tab });
106 const [windowSelection, setWindowSelection] = useState(() => ({
107 days: 30,
108 window: makeWindow(30),
109 }));
110 const [metric, setMetric] = useState<UsageChartMetric>("cost");
111 const { days: windowDays, window } = windowSelection;
112 const isPast24Hours = windowDays === 1;
113 const [selectedEnvironmentIds, setSelectedEnvironmentIds] =
114 useState<ReadonlySet<EnvironmentId> | null>(null);
115 const { merged, environments, selectedEnvironments, isPending, refresh } = useUsage(
116 window,
117 selectedEnvironmentIds,
118 );
119 const isFocused = useIsFocused();
120 const limits = useRefreshLimits(selectedEnvironmentIds, isFocused && tab === "limits");
121 const cursorAccessEnvironments = cursorKeychainAccessEnvironments(selectedEnvironments);
122 const refreshAfterCursorEnable = () => {
123 void refresh();
124 void limits.refreshAfterEnable();
125 };
126 const sourceMessages = [
127 ...new Set(
128 selectedEnvironments.flatMap(
129 (environment) =>
130 environment.summary?.sources.flatMap((source) =>
131 source.message &&
132 !source.action &&
133 (source.status === "partial" ||
134 source.status === "failed" ||
135 source.fingerprint.provider === "cursor")
136 ? [source.message]
137 : [],
138 ) ?? [],
139 ),
140 ),
141 ];
142 const canReadDiagnostics = selectedEnvironments.some(
143 (environment) => environment.canReadDiagnostics,
144 );
145​
146 const days = useMemo(
147 () => enumerateDays(window.sinceDay, window.untilDay),
148 [window.sinceDay, window.untilDay],
149 );
150 const chartDays = useMemo(
151 () =>
152 isPast24Hours && window.sinceTime !== undefined && window.untilTime !== undefined
153 ? enumerateHourStarts(window.sinceTime, window.untilTime)
154 : days,
155 [days, isPast24Hours, window.sinceTime, window.untilTime],
156 );
157 const chartTotals = useMemo(
158 (): readonly DailyTotals[] =>
159 isPast24Hours
160 ? merged.hourly.map((hour) => ({
161 day: hour.hourStart,
162 costUsd: hour.costUsd,
163 totalTokens: hour.totalTokens,
164 byProvider: hour.byProvider,
165 }))
166 : merged.daily,
167 [isPast24Hours, merged.daily, merged.hourly],
168 );
169​
170 const [refreshingUsage, setRefreshingUsage] = useState(false);
171 const refreshingRef = useRef(false);
172 const showingLimits = tab === "limits";
173 const progress = usageProgress(selectedEnvironments, {
174 refreshing: refreshingUsage,
175 providerLabel,
176 });
177 const selectWindow = (days: number) => {
178 setWindowSelection({
179 days,
180 window: makeWindow(days, undefined, days === 1 ? "hour" : "day"),
181 });
182 };
183 const refreshWindow = () => {
184 if (refreshingRef.current) return;
185 const nextWindow = makeWindow(windowDays, undefined, isPast24Hours ? "hour" : "day");
186 if (
187 nextWindow.sinceDay !== window.sinceDay ||
188 nextWindow.untilDay !== window.untilDay ||
189 nextWindow.sinceTime !== window.sinceTime ||
190 nextWindow.untilTime !== window.untilTime
191 ) {
192 setWindowSelection({ days: windowDays, window: nextWindow });
193 }
194 refreshingRef.current = true;
195 setRefreshingUsage(true);
196 void refresh(nextWindow).finally(() => {
197 refreshingRef.current = false;
198 setRefreshingUsage(false);
199 });
200 };
201​
202 const showEnvironmentFilter = environments.length > 0 || selectedEnvironmentIds !== null;
203 const filterIcon =
204 selectedEnvironmentIds === null
205 ? "line.3.horizontal.decrease"
206 : "line.3.horizontal.decrease.circle.fill";
207 const environmentActions = useMemo(
208 () => [
209 {
210 id: "all",
211 title: "All environments",
212 subtitle: undefined,
213 state: selectedEnvironmentIds === null ? ("on" as const) : ("off" as const),
214 },
215 ...environments.map((environment) => ({
216 id: environment.environmentId,
217 title: environment.label,
218 subtitle: usageEnvironmentStatus(environment, refreshingUsage),
219 state:
220 selectedEnvironmentIds === null || selectedEnvironmentIds.has(environment.environmentId)
221 ? ("on" as const)
222 : ("off" as const),
223 })),
224 ],
225 [environments, refreshingUsage, selectedEnvironmentIds],
226 );
227 const selectEnvironment = useCallback(
228 (value: string) => {
229 if (value === "all") {
230 setSelectedEnvironmentIds(null);
231 return;
232 }
233 const id = EnvironmentId.make(value);
234 setSelectedEnvironmentIds((selected) => toggleUsageEnvironment(selected, environments, id));
235 },
236 [environments],
237 );
238 const environmentFilter = useMemo(
239 () =>
240 showEnvironmentFilter ? (
241 <Menu
242 accessible
243 accessibilityRole="button"
244 accessibilityLabel="Filter usage environments"
245 title="Environments"
246 actions={environmentActions}
247 onPressAction={({ nativeEvent }) => selectEnvironment(nativeEvent.event)}
248 >
249 <Pressable
250 accessibilityRole="button"
251 accessibilityLabel="Filter usage environments"
252 className={cn(
253 "items-center justify-center rounded-full",
254 Platform.OS === "ios" ? "size-[28px]" : "size-[44px]",
255 )}
256 >
257 <SymbolView name={filterIcon} size={22} tintColorClassName="accent-icon" />
258 </Pressable>
259 </Menu>
260 ) : null,
261 [showEnvironmentFilter, environmentActions, selectEnvironment, filterIcon],
262 );
263​
264 useLayoutEffect(() => {
265 if (Platform.OS === "ios") {
266 navigation.setOptions({ headerRight: () => environmentFilter });
267 }
268 }, [navigation, environmentFilter]);
269​
270 return (
271 <SettingsScreen title="Usage" trailing={environmentFilter}>
272 <ScrollView
273 contentInsetAdjustmentBehavior="automatic"
274 showsVerticalScrollIndicator={false}
275 className="flex-1"
276 contentContainerClassName="gap-6 px-5 pt-4"
277 contentContainerStyle={{ paddingBottom: Math.max(insets.bottom, 18) + 18 }}
278 refreshControl={
279 showingLimits || canReadDiagnostics ? (
280 <RefreshControl
281 refreshing={showingLimits ? limits.refreshing : refreshingUsage}
282 onRefresh={showingLimits ? () => void limits.refresh() : refreshWindow}
283 />
284 ) : undefined
285 }
286 >
287 <SegmentedControl options={TAB_OPTIONS} selected={tab} onSelect={setTab} role="tab" />
288 <Animated.View
289 key={tab}
290 entering={FadeIn.duration(160).reduceMotion(ReduceMotion.System)}
291 className="gap-6"
292 >
293 {showingLimits ? (
294 <UsageLimitsSection
295 now={limits.now}
296 failedLabels={limits.failedLabels}
297 selectedEnvironmentIds={selectedEnvironmentIds}
298 cursorPrompt={
299 cursorAccessEnvironments.length > 0 ? (
300 <CursorEnableLimits
301 environments={cursorAccessEnvironments}
302 onEnabled={refreshAfterCursorEnable}
303 />
304 ) : null
305 }
306 />
307 ) : (
308 <>
309 {/* Period and metric together: neither applies to Limits, and
310 both change every number below, so they share one bar. */}
311 <View className="gap-3 ios:flex-row ios:items-center">
312 <SegmentedControl
313 options={WINDOW_OPTIONS}
314 selected={windowDays}
315 onSelect={selectWindow}
316 size="compact"
317 className="w-full ios:flex-1"
318 />
319 <SegmentedControl
320 options={METRIC_OPTIONS}
321 selected={metric}
322 onSelect={setMetric}
323 size="compact"
324 className="w-full ios:w-36"
325 />
326 </View>
327 <ChatGptUsageSummary selectedEnvironmentIds={selectedEnvironmentIds} />
328 {merged.duplicateSources.length > 0 ? (
329 <Text className="text-sm text-foreground-muted">
330 Counted once across environments sharing a transcript directory:{" "}
331 {merged.duplicateSources.join(", ")}
332 </Text>
333 ) : null}
334 {isPending ? (
335 <Text className="py-16 text-center text-base text-foreground-muted">
336 Scanning provider transcripts…
337 </Text>
338 ) : selectedEnvironments.length === 0 ? (
339 <Text className="py-16 text-center text-base text-foreground-muted">
340 {environments.length === 0
341 ? "Connect an environment to see usage."
342 : "Select an environment to see usage."}
343 </Text>
344 ) : !canReadDiagnostics ? (
345 // Each environment explains itself: a denied grant and a failed
346 // access check are different problems.
347 <View className="gap-2 py-16">
348 {selectedEnvironments.map((environment) => (
349 <Text
350 key={environment.environmentId}
351 className="text-center text-base text-foreground-muted"
352 >
353 {selectedEnvironments.length > 1 ? `${environment.label}: ` : null}
354 {environment.error}
355 </Text>
356 ))}
357 </View>
358 ) : (
359 <>
360 {sourceMessages.map((message) => (
361 <Text key={message} className="text-sm text-foreground-muted">
362 {message}
363 </Text>
364 ))}
365 <UsageUpdating dimmed={progress.dimmed} label={progress.label}>
366 <ChartCard
367 merged={merged}
368 days={chartDays}
369 daily={chartTotals}
370 metric={metric}
371 sinceDay={window.sinceDay}
372 untilDay={window.untilDay}
373 isPast24Hours={isPast24Hours}
374 timeZone={window.timeZone}
375 />
376 <ProviderSection
377 merged={merged}
378 metric={metric}
379 cursorAccessEnvironments={cursorAccessEnvironments}
380 showCursorEnvironment={selectedEnvironments.length > 1}
381 onCursorEnabled={refreshAfterCursorEnable}
382 />
383 <TotalsSection merged={merged} isPast24Hours={isPast24Hours} />
384 <CostSection merged={merged} />
385 <ModelsSection merged={merged} metric={metric} />
386 </UsageUpdating>
387 </>
388 )}
389 </>
390 )}
391 </Animated.View>
392 </ScrollView>
393 </SettingsScreen>
394 );
396​
397/**
398 * Dims totals that are about to change and says what is still updating. The
399 * status overlays the first child's top-right corner, the chart card's label
400 * row, so appearing never moves anything.
401 */
402function UsageUpdating({
403 dimmed,
404 label,
405 children,
406}: {
407 readonly dimmed: boolean;
408 readonly label: string | null;
409 readonly children: ReactNode;
410}) {
411 const opacity = useSharedValue(1);
412 useLayoutEffect(() => {
413 // The delay keeps a quick cached answer from flashing the dim.
414 opacity.set(
415 dimmed
416 ? withDelay(150, withTiming(0.5, { duration: 150, reduceMotion: ReduceMotion.System }))
417 : withTiming(1, { duration: 150, reduceMotion: ReduceMotion.System }),
418 );
419 }, [opacity, dimmed]);
420 const dimStyle = useAnimatedStyle(() => ({ opacity: opacity.get() }));
421​
422 return (
423 <View>
424 <Animated.View style={dimStyle} className="gap-6" accessibilityState={{ busy: dimmed }}>
425 {children}
426 </Animated.View>
427 {label !== null ? (
428 <Animated.View
429 entering={FadeIn.delay(150).duration(150).reduceMotion(ReduceMotion.System)}
430 accessibilityLiveRegion="polite"
431 pointerEvents="none"
432 className="absolute right-4 top-4 h-5 max-w-[55%] flex-row items-center gap-1.5"
433 >
434 <AppActivityIndicator size="small" colorClassName="accent-adaptive-sky-600-400" />
435 <Text className="shrink text-sm text-adaptive-sky-600-400" numberOfLines={1}>
436 {label}
437 </Text>
438 </Animated.View>
439 ) : null}
440 </View>
441 );
443​
444function CursorEnableAction({
445 environmentId,
446 label,
447 onEnabled,
448 buttonText = "Enable",
449}: {
450 readonly environmentId: EnvironmentId;
451 readonly label: string;
452 readonly onEnabled: () => void;
453 readonly buttonText?: string;
454}) {
455 const updateSettings = useAtomCommand(serverEnvironment.updateSettings, {
456 label: "enable Cursor account usage",
457 });
458 const [pending, setPending] = useState(false);
459 const enable = async () => {
460 setPending(true);
461 try {
462 const result = await updateSettings({
463 environmentId,
464 input: { patch: { cursorKeychainUsageEnabled: true } },
465 });
466 if (result._tag === "Success") onEnabled();
467 } finally {
468 setPending(false);
469 }
470 };
471 return (
472 <Pressable
473 accessibilityRole="button"
474 accessibilityLabel={`Enable Cursor usage from ${label}`}
475 accessibilityHint={CURSOR_KEYCHAIN_COPY}
476 disabled={pending}
477 onPress={() => void enable()}
478 className="rounded-full bg-primary px-4 py-2"
479 >
480 <Text className="text-sm font-medium text-primary-foreground">{buttonText}</Text>
481 </Pressable>
482 );
484​
485function CursorEnableRow({
486 environmentId,
487 label,
488 showEnvironment,
489 bordered,
490 onEnabled,
491}: {
492 readonly environmentId: EnvironmentId;
493 readonly label: string;
494 readonly showEnvironment: boolean;
495 readonly bordered: boolean;
496 readonly onEnabled: () => void;
497}) {
498 const colors = useProviderColors();
499 return (
500 <View
501 className={cn(
502 "flex-row items-center justify-between gap-3 p-4",
503 bordered && "border-t border-border-subtle",
504 )}
505 >
506 <View className="min-w-0 flex-1 flex-row items-center gap-2">
507 <View className="size-2.5 rounded-full" style={{ backgroundColor: colors.cursor }} />
508 <Text className="shrink text-lg text-foreground">
509 Cursor{showEnvironment ? ` · ${label}` : ""}
510 </Text>
511 </View>
512 <CursorEnableAction environmentId={environmentId} label={label} onEnabled={onEnabled} />
513 </View>
514 );
516​
517function CursorEnableLimits({
518 environments,
519 onEnabled,
520}: {
521 readonly environments: readonly EnvironmentUsageStatus[];
522 readonly onEnabled: () => void;
523}) {
524 return (
525 <View className="gap-3">
526 <View className="flex-row items-center gap-2 px-1">
527 <ProviderIcon provider="cursor" size={18} />
528 <Text className="text-base font-t3-medium text-foreground">Cursor</Text>
529 </View>
530 <View className="items-start gap-3 rounded-[24px] border-continuous bg-grouped-card p-4">
531 <Text className="text-xs text-foreground-muted">{CURSOR_KEYCHAIN_COPY}</Text>
532 <View className="flex-row flex-wrap gap-2">
533 {environments.map((environment) => (
534 <CursorEnableAction
535 key={environment.environmentId}
536 environmentId={environment.environmentId}
537 label={environment.label}
538 buttonText={environments.length > 1 ? `Enable on ${environment.label}` : "Enable"}
539 onEnabled={onEnabled}
540 />
541 ))}
542 </View>
543 </View>
544 </View>
545 );
547​
548/** Headline figure, the animated daily chart, and its legend, in one card. */
549function ChartCard(props: {
550 readonly merged: MergedUsage;
551 readonly days: readonly string[];
552 readonly daily: readonly DailyTotals[];
553 readonly metric: UsageChartMetric;
554 readonly sinceDay: string;
555 readonly untilDay: string;
556 readonly isPast24Hours: boolean;
557 readonly timeZone: string;
558}) {
559 const { merged, metric } = props;
560 const colors = useProviderColors();
561 const hasActivity = props.daily.some((period) => period.totalTokens > 0);
562​
563 return (
564 <View className="gap-4 rounded-[24px] border-continuous bg-grouped-card p-4">
565 <View className="gap-0.5">
566 <Text className="text-sm text-foreground-muted">
567 {metric === "cost" ? "Raw token cost" : "Processed tokens"}
568 </Text>
569 <Text className="text-4xl font-t3-bold tabular-nums text-foreground">
570 {metric === "cost" ? `${formatUsd(merged.costUsd)}*` : formatTokens(merged.totalTokens)}
571 </Text>
572 <Text className="text-sm text-foreground-muted">
573 {metric === "cost"
574 ? "* if billed at full API rate"
575 : `Across ${formatCount(merged.sessions)} sessions`}
576 </Text>
577 </View>
578​
579 {hasActivity ? (
580 <UsageDailyChart
581 days={props.days}
582 daily={props.daily}
583 metric={metric}
584 height={CHART_HEIGHT}
585 />
586 ) : (
587 <View style={{ height: CHART_HEIGHT }} className="items-center justify-center">
588 <Text className="text-base text-foreground-muted">No activity in this window.</Text>
589 </View>
590 )}
591​
592 <View className="flex-row items-center justify-between">
593 <Text className="text-xs text-foreground-tertiary">
594 {props.isPast24Hours
595 ? formatHourShort(props.days[0] ?? "", props.timeZone)
596 : formatDayShort(props.sinceDay)}
597 </Text>
598 <View className="flex-row items-center gap-4">
599 {merged.providers.map((provider) => (
600 <View key={provider.provider} className="flex-row items-center gap-1.5">
601 <View
602 className="size-2 rounded-full"
603 style={{ backgroundColor: colors[provider.provider] }}
604 />
605 <Text className="text-xs text-foreground-muted">
606 {PROVIDER_LABEL[provider.provider]}
607 </Text>
608 </View>
609 ))}
610 </View>
611 <Text className="text-xs text-foreground-tertiary">
612 {props.isPast24Hours
613 ? formatHourShort(props.days[props.days.length - 1] ?? "", props.timeZone)
614 : formatDayShort(props.untilDay)}
615 </Text>
616 </View>
617 </View>
618 );
620​
621function ProviderSection(props: {
622 readonly merged: MergedUsage;
623 readonly metric: UsageChartMetric;
624 readonly cursorAccessEnvironments: readonly EnvironmentUsageStatus[];
625 readonly showCursorEnvironment: boolean;
626 readonly onCursorEnabled: () => void;
627}) {
628 const { merged, metric } = props;
629 const colors = useProviderColors();
630 if (merged.providers.length === 0 && props.cursorAccessEnvironments.length === 0) return null;
631​
632 // Ranked by whatever the toggle is showing, so the rows always descend.
633 // .sort() on a copy, not .toSorted(): Hermes doesn't ship the ES2023 method.
634 const ordered = [...merged.providers].sort((a, b) =>
635 metric === "cost" ? b.costUsd - a.costUsd : b.totalTokens - a.totalTokens,
636 );
637 const rows: Array<
638 | { readonly kind: "usage"; readonly provider: (typeof ordered)[number] }
639 | { readonly kind: "enable"; readonly environment: EnvironmentUsageStatus }
640 > = ordered.map((provider) => ({ kind: "usage", provider }));
641 const cursorInsertAt =
642 Math.max(
643 ordered.findIndex((provider) => provider.provider === "codex"),
644 ordered.findIndex((provider) => provider.provider === "claude"),
645 ) + 1;
646 rows.splice(
647 cursorInsertAt,
648 0,
649 ...props.cursorAccessEnvironments.map((environment) => ({
650 kind: "enable" as const,
651 environment,
652 })),
653 );
654​
655 return (
656 <SettingsSection title="Providers">
657 {rows.map((row, index) => {
658 if (row.kind === "enable") {
659 return (
660 <CursorEnableRow
661 key={`enable:${row.environment.environmentId}`}
662 environmentId={row.environment.environmentId}
663 label={row.environment.label}
664 showEnvironment={props.showCursorEnvironment}
665 bordered={index > 0}
666 onEnabled={props.onCursorEnabled}
667 />
668 );
669 }
670 const provider = row.provider;
671 const share = metric === "cost" ? provider.costShare : provider.tokenShare;
672 return (
673 <View
674 key={provider.provider}
675 className={index === 0 ? "gap-2 p-4" : "gap-2 border-t border-border-subtle p-4"}
676 >
677 <View className="flex-row items-baseline justify-between gap-3">
678 <View className="flex-row items-center gap-2">
679 <View
680 className="size-2.5 rounded-full"
681 style={{ backgroundColor: colors[provider.provider] }}
682 />
683 <Text className="text-lg text-foreground">{PROVIDER_LABEL[provider.provider]}</Text>
684 </View>
685 <Text className="text-lg tabular-nums text-foreground">
686 {metric === "cost"
687 ? formatUsd(provider.costUsd)
688 : formatTokens(provider.totalTokens)}
689 </Text>
690 </View>
691 <View className="h-1 flex-row overflow-hidden rounded-full bg-subtle">
692 <View
693 className="h-full rounded-full"
694 style={{ flex: share, backgroundColor: colors[provider.provider] }}
695 />
696 <View style={{ flex: 1 - share }} />
697 </View>
698 <Text className="text-sm text-foreground-muted">
699 {metric === "cost"
700 ? `${formatPercent(share)} of cost · ${formatTokens(provider.totalTokens)} tokens`
701 : `${formatPercent(share)} of tokens · ${formatUsd(provider.costUsd)}`}
702 </Text>
703 </View>
704 );
705 })}
706 </SettingsSection>
707 );
709​
710function TotalsSection(props: { readonly merged: MergedUsage; readonly isPast24Hours: boolean }) {
711 const { merged } = props;
712 const activePeriods = (props.isPast24Hours ? merged.hourly : merged.daily).filter(
713 (period) => period.totalTokens > 0,
714 ).length;
715 const periodAverage = activePeriods === 0 ? 0 : merged.totalTokens / activePeriods;
716 const observedInput = merged.uncachedInputTokens + merged.cachedInputTokens;
717 const cachedShare = observedInput === 0 ? 0 : merged.cachedInputTokens / observedInput;
718​
719 return (
720 <SettingsSection title="Totals">
721 <View className="flex-row flex-wrap">
722 <MetricCell
723 label="Processed tokens"
724 value={formatTokens(merged.totalTokens)}
725 detail={`${formatTokens(periodAverage)} per active ${props.isPast24Hours ? "hour" : "day"}`}
726 />
727 <MetricCell
728 label="Cache savings"
729 value={formatUsd(merged.costQuality.cacheSavingsUsd)}
730 detail={
731 merged.costUsd > 0
732 ? `${(merged.costQuality.cacheSavingsUsd / merged.costUsd).toFixed(1)}x the raw cost`
733 : "vs full input rates"
734 }
735 />
736 <MetricCell
737 label="Cached input"
738 value={formatTokens(merged.cachedInputTokens)}
739 detail={`${formatPercent(cachedShare)} of observed input`}
740 />
741 <MetricCell
742 label="Uncached input"
743 value={formatTokens(merged.uncachedInputTokens)}
744 detail={`${formatTokens(merged.cacheCreationTokens)} cache writes`}
745 />
746 <MetricCell
747 label="Output"
748 value={formatTokens(merged.outputTokens)}
749 detail={`incl. ${formatTokens(merged.reasoningTokens)} reasoning`}
750 />
751 <MetricCell
752 label="Unpriced"
753 value={formatPercent(merged.costQuality.unpricedShare)}
754 detail="of records, excluded from cost"
755 />
756 </View>
757 </SettingsSection>
758 );
760​
761function CostSection(props: { readonly merged: MergedUsage }) {
762 const { categoryCost, speedCost } = props.merged;
763 const colors = useUsageMixColors();
764 const byType = [
765 { label: "Input", value: categoryCost.input, color: colors.input },
766 { label: "Cache read", value: categoryCost.cacheRead, color: colors.cacheRead },
767 { label: "Cache write", value: categoryCost.cacheWrite, color: colors.cacheWrite },
768 { label: "Output", value: categoryCost.output, color: colors.output },
769 // Reported cost with no rates to split it, or from older servers. Below a
770 // cent it is rounding, not usage.
771 {
772 label: "Other",
773 value: categoryCost.unsplit >= 0.005 ? categoryCost.unsplit : 0,
774 color: colors.other,
775 },
776 ];
777 const bySpeed = [
778 { label: "Standard", value: speedCost.standard, color: colors.standard },
779 { label: "Fast", value: speedCost.fast, color: colors.fast },
780 { label: "Ultrafast", value: speedCost.ultrafast, color: colors.ultrafast },
781 ];
782 if (props.merged.costUsd <= 0) return null;
783​
784 return (
785 <SettingsSection title="Cost">
786 <ShareBar label="By type" segments={byType} />
787 {speedCost.fast + speedCost.ultrafast > 0 ? (
788 <View className="border-t border-border-subtle">
789 <ShareBar
790 label="By speed"
791 segments={bySpeed}
792 aside={`${formatUsd(speedCost.premium)} premium`}
793 />
794 </View>
795 ) : null}
796 </SettingsSection>
797 );
799​
800/** One part-to-whole cost bar with its legend. Empty segments are left out. */
801function ShareBar(props: {
802 readonly label: string;
803 readonly segments: readonly { label: string; value: number; color: string }[];
804 readonly aside?: string;
805}) {
806 const visible = props.segments.filter((segment) => segment.value > 0);
807 if (visible.length === 0) return null;
808​
809 return (
810 <View className="gap-3 p-4">
811 <View className="flex-row items-baseline justify-between gap-3">
812 <Text className="text-sm text-foreground-muted">{props.label}</Text>
813 {props.aside ? (
814 <Text className="text-sm tabular-nums text-foreground-muted">{props.aside}</Text>
815 ) : null}
816 </View>
817 <View className="h-2 flex-row gap-0.5">
818 {visible.map((segment) => (
819 <View
820 key={segment.label}
821 className="h-full rounded-sm"
822 style={{ flex: segment.value, backgroundColor: segment.color }}
823 />
824 ))}
825 </View>
826 <View className="flex-row flex-wrap gap-x-4 gap-y-1.5">
827 {visible.map((segment) => (
828 <View key={segment.label} className="flex-row items-center gap-1.5">
829 <View className="size-2 rounded-sm" style={{ backgroundColor: segment.color }} />
830 <Text className="text-sm text-foreground-muted">{segment.label}</Text>
831 <Text className="text-sm tabular-nums text-foreground">{formatUsd(segment.value)}</Text>
832 </View>
833 ))}
834 </View>
835 </View>
836 );
838​
839function MetricCell(props: {
840 readonly label: string;
841 readonly value: string;
842 readonly detail: string;
843}) {
844 return (
845 <View className="w-1/2 gap-0.5 p-4">
846 <Text className="text-sm text-foreground-muted">{props.label}</Text>
847 <Text className="text-xl font-t3-medium tabular-nums text-foreground">{props.value}</Text>
848 <Text className="text-xs text-foreground-tertiary">{props.detail}</Text>
849 </View>
850 );
852​
853function ModelsSection(props: { readonly merged: MergedUsage; readonly metric: UsageChartMetric }) {
854 const { merged, metric } = props;
855 const colors = useProviderColors();
856 if (merged.models.length === 0) return null;
857​
858 // Ranked like the provider rows. .sort() on a copy, not .toSorted(): Hermes
859 // doesn't ship the ES2023 method.
860 const ordered = [...merged.models].sort((a, b) =>
861 metric === "cost"
862 ? b.costUsd - a.costUsd || b.totalTokens - a.totalTokens
863 : b.totalTokens - a.totalTokens || b.costUsd - a.costUsd,
864 );
865​
866 return (
867 <SettingsSection title="By model">
868 {ordered.map((model, index) => (
869 <View
870 key={`${model.provider}:${model.model}`}
871 className={
872 index === 0
873 ? "flex-row items-center gap-3 p-4"
874 : "flex-row items-center gap-3 border-t border-border-subtle p-4"
875 }
876 >
877 <View
878 className="size-2.5 shrink-0 rounded-full"
879 style={{ backgroundColor: colors[model.provider] }}
880 />
881 <View className="min-w-0 flex-1 gap-0.5">
882 <Text className="text-base text-foreground" numberOfLines={1}>
883 {model.model}
884 </Text>
885 <Text className="text-sm text-foreground-muted">
886 {metric === "tokens"
887 ? `${formatPercent(model.tokenShare)} of tokens · ${
888 isModelCostUnknown(model) ? "no known rates" : formatUsd(model.costUsd)
889 }`
890 : isModelCostUnknown(model)
891 ? `no known rates · ${formatTokens(model.totalTokens)} tokens`
892 : `${formatPercent(model.costShare)} of cost · ${formatTokens(model.totalTokens)} tokens`}
893 </Text>
894 </View>
895 <Text className="text-base tabular-nums text-foreground">
896 {metric === "tokens"
897 ? formatTokens(model.totalTokens)
898 : isModelCostUnknown(model)
899 ? "Unpriced"
900 : formatUsd(model.costUsd)}
901 </Text>
902 </View>
903 ))}
904 </SettingsSection>
905 );
907​
908/**
909 * Says plainly when the totals are incomplete: an environment still answering,
910 * one that failed, or one whose transcripts another environment already
911 * reported.
912 */
913function usageEnvironmentStatus(environment: EnvironmentUsageStatus, refreshing: boolean): string {
914 if (
915 environment.summary &&
916 !isCompatibleUsageContractVersion(environment.summary.contractVersion, USAGE_CONTRACT_VERSION)
917 ) {
918 return formatUsageContractMismatch(environment.label, {
919 direction:
920 environment.summary.contractVersion < USAGE_CONTRACT_VERSION
921 ? "serverBehind"
922 : "clientBehind",
923 });
924 }
925 // The reason matters: a denied grant and a failed scan need different fixes.
926 if (environment.error)
927 return environment.summary ? `${environment.error} Showing saved totals.` : environment.error;
928 if (!environment.isConnected)
929 return environment.summary ? "Disconnected · showing saved usage" : "Waiting for connection…";
930 const progress = usageEnvironmentProgress(environment, refreshing);
931 if (progress.phase === "loading") return "Loading usage…";
932 if (progress.phase === "stale") return "Updating usage…";
933 if (progress.phase === "partway")
934 return updatingProvidersLabel(progress.providers, providerLabel);
935 return "Usage up to date";