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

UsageRouteScreen.tsx

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