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