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

UsageRouteScreen.tsx

946 lines34.6 KB

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