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

UsageRouteScreen.tsx

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