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

UsageRouteScreen.tsx

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