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