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