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