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