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

UsageRouteScreen.tsx

910 lines33.3 KB

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