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