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

UsageRouteScreen.tsx

851 lines30.8 KB

1import { ChatGptUsageSummary } from "./ChatGptUsageSummary";
2import { ScreenScrollView as ScrollView } from "../../components/ScreenScrollView";
3import { EnvironmentId, USAGE_CONTRACT_VERSION } from "@t3tools/contracts";
4import { type RouteProp, useIsFocused, useNavigation, useRoute } from "@react-navigation/native";
5import { cursorKeychainAccessEnvironments } from "@t3tools/client-runtime/state/usage";
6import {
7 isCompatibleUsageContractVersion,
8 isModelCostUnknown,
9 type DailyTotals,
10 type MergedUsage,
11} from "@t3tools/shared/usageMerge";
12import {
13 enumerateDays,
14 enumerateHourStarts,
15 formatCount,
16 formatDayShort,
17 formatHourShort,
18 formatPercent,
19 formatTokens,
20 formatUsageContractMismatch,
21 formatUsd,
22 makeWindow,
23} from "@t3tools/shared/usageFormat";
24import { useCallback, useLayoutEffect, useMemo, useRef, useState } from "react";
25import { Platform, Pressable, RefreshControl, View } from "react-native";
26import Animated, { FadeIn, ReduceMotion } from "react-native-reanimated";
27import { useSafeAreaInsets } from "react-native-safe-area-context";
28​
29import { SegmentedControl } from "../../components/SegmentedControl";
30import { AppText as Text } from "../../components/AppText";
31import { ProviderIcon } from "../../components/ProviderIcon";
32import { cn } from "../../lib/cn";
33import { SettingsScreen } from "../settings/components/SettingsScreen";
34import { useUsage, type EnvironmentUsageStatus } from "../../state/usage";
35import { serverEnvironment } from "../../state/server";
36import { useAtomCommand } from "../../state/use-atom-command";
37import { SettingsSection } from "../settings/components/SettingsSection";
38import { UsageDailyChart } from "./UsageDailyChart";
39import { toggleUsageEnvironment } from "./usageEnvironmentSelection";
40import { useRefreshLimits } from "./UsageLimitsSection";
41import { UsageLimitsSection } from "./UsageLimitsPooled";
42import { ControlPillMenu } from "../../components/ControlPill";
43import { SymbolView } from "../../components/AppSymbol";
44import type { UsageChartMetric } from "./usageChartData";
45import { PROVIDER_LABEL, useProviderColors, useUsageMixColors } from "./usageProviders";
46​
47type UsageTab = "usage" | "limits";
48const TAB_OPTIONS = [
49 { value: "usage", label: "Usage" },
50 { value: "limits", label: "Limits" },
51] as const satisfies readonly { value: UsageTab; label: string }[];
52​
53// Labels are abbreviated to share a row with the metric toggle; screen
54// readers get the full phrase.
55const WINDOW_OPTIONS = [
56 { value: 1, label: "24h", accessibilityLabel: "Past 24 hours" },
57 { value: 7, label: "7d", accessibilityLabel: "Past 7 days" },
58 { value: 30, label: "30d", accessibilityLabel: "Past 30 days" },
59 { value: 90, label: "90d", accessibilityLabel: "Past 90 days" },
60] as const;
61​
62const METRIC_OPTIONS = [
63 { value: "cost", label: "Cost" },
64 { value: "tokens", label: "Tokens" },
65] as const satisfies readonly { value: UsageChartMetric; label: string }[];
66​
67const CHART_HEIGHT = 180;
68const CURSOR_KEYCHAIN_COPY = "Requires access to your Cursor login in macOS Keychain.";
69​
70/**
71 * Two tabs over one screen. Usage is the transcript-derived spend for a
72 * period; Limits is the live subscription quota, which has no period. Both
73 * pull to refresh, each refreshing its own data.
74 */
75export function UsageRouteScreen() {
76 const route = useRoute<RouteProp<{ Usage: { tab?: string } | undefined }, "Usage">>();
77 const navigation = useNavigation();
78 const insets = useSafeAreaInsets();
79 // Preserve the Limits default while honoring explicit widget/navigation links.
80 const [selection, setSelection] = useState(() => ({
81 params: route.params,
82 tab: (route.params?.tab === "usage" ? "usage" : "limits") as UsageTab,
83 }));
84 if (selection.params !== route.params) {
85 setSelection({
86 params: route.params,
87 tab: route.params?.tab === "usage" ? "usage" : "limits",
88 });
89 }
90 const { tab } = selection;
91 const setTab = (tab: UsageTab) => setSelection({ params: route.params, tab });
92 const [windowSelection, setWindowSelection] = useState(() => ({
93 days: 30,
94 window: makeWindow(30),
95 }));
96 const [metric, setMetric] = useState<UsageChartMetric>("cost");
97 const { days: windowDays, window } = windowSelection;
98 const isPast24Hours = windowDays === 1;
99 const [selectedEnvironmentIds, setSelectedEnvironmentIds] =
100 useState<ReadonlySet<EnvironmentId> | null>(null);
101 const { merged, environments, selectedEnvironments, isPending, refresh } = useUsage(
102 window,
103 selectedEnvironmentIds,
104 );
105 const isFocused = useIsFocused();
106 const limits = useRefreshLimits(selectedEnvironmentIds, isFocused && tab === "limits");
107 const cursorAccessEnvironments = cursorKeychainAccessEnvironments(selectedEnvironments);
108 const refreshAfterCursorEnable = () => {
109 void refresh();
110 void limits.refreshAfterEnable();
111 };
112 const sourceMessages = [
113 ...new Set(
114 selectedEnvironments.flatMap(
115 (environment) =>
116 environment.summary?.sources.flatMap((source) =>
117 source.message &&
118 !source.action &&
119 (source.status === "partial" ||
120 source.status === "failed" ||
121 source.fingerprint.provider === "cursor")
122 ? [source.message]
123 : [],
124 ) ?? [],
125 ),
126 ),
127 ];
128​
129 const days = useMemo(
130 () => enumerateDays(window.sinceDay, window.untilDay),
131 [window.sinceDay, window.untilDay],
132 );
133 const chartDays = useMemo(
134 () =>
135 isPast24Hours && window.sinceTime !== undefined && window.untilTime !== undefined
136 ? enumerateHourStarts(window.sinceTime, window.untilTime)
137 : days,
138 [days, isPast24Hours, window.sinceTime, window.untilTime],
139 );
140 const chartTotals = useMemo(
141 (): readonly DailyTotals[] =>
142 isPast24Hours
143 ? merged.hourly.map((hour) => ({
144 day: hour.hourStart,
145 costUsd: hour.costUsd,
146 totalTokens: hour.totalTokens,
147 byProvider: hour.byProvider,
148 }))
149 : merged.daily,
150 [isPast24Hours, merged.daily, merged.hourly],
151 );
152​
153 const [refreshingUsage, setRefreshingUsage] = useState(false);
154 const refreshingRef = useRef(false);
155 const showingLimits = tab === "limits";
156 const selectWindow = (days: number) => {
157 setWindowSelection({
158 days,
159 window: makeWindow(days, undefined, days === 1 ? "hour" : "day"),
160 });
161 };
162 const refreshWindow = () => {
163 if (refreshingRef.current) return;
164 const nextWindow = makeWindow(windowDays, undefined, isPast24Hours ? "hour" : "day");
165 if (
166 nextWindow.sinceDay !== window.sinceDay ||
167 nextWindow.untilDay !== window.untilDay ||
168 nextWindow.sinceTime !== window.sinceTime ||
169 nextWindow.untilTime !== window.untilTime
170 ) {
171 setWindowSelection({ days: windowDays, window: nextWindow });
172 }
173 refreshingRef.current = true;
174 setRefreshingUsage(true);
175 void refresh(nextWindow).finally(() => {
176 refreshingRef.current = false;
177 setRefreshingUsage(false);
178 });
179 };
180​
181 const showEnvironmentFilter = environments.length > 0 || selectedEnvironmentIds !== null;
182 const hasLoadingEnvironments = selectedEnvironments.some(isUsageLoading);
183 const filterAccessibilityLabel = hasLoadingEnvironments
184 ? "Filter usage environments, some environments are loading"
185 : "Filter usage environments";
186 const filterIcon =
187 selectedEnvironmentIds === null
188 ? "line.3.horizontal.decrease"
189 : "line.3.horizontal.decrease.circle.fill";
190 const environmentActions = useMemo(
191 () => [
192 {
193 id: "all",
194 title: "All environments",
195 subtitle: undefined,
196 state: selectedEnvironmentIds === null ? ("on" as const) : ("off" as const),
197 },
198 ...environments.map((environment) => ({
199 id: environment.environmentId,
200 title: environment.label,
201 subtitle: usageEnvironmentStatus(environment),
202 state:
203 selectedEnvironmentIds === null || selectedEnvironmentIds.has(environment.environmentId)
204 ? ("on" as const)
205 : ("off" as const),
206 })),
207 ],
208 [environments, selectedEnvironmentIds],
209 );
210 const selectEnvironment = useCallback(
211 (value: string) => {
212 if (value === "all") {
213 setSelectedEnvironmentIds(null);
214 return;
215 }
216 const id = EnvironmentId.make(value);
217 setSelectedEnvironmentIds((selected) => toggleUsageEnvironment(selected, environments, id));
218 },
219 [environments],
220 );
221 const environmentFilter = useMemo(
222 () =>
223 showEnvironmentFilter ? (
224 <ControlPillMenu
225 accessible
226 accessibilityRole="button"
227 accessibilityLabel={filterAccessibilityLabel}
228 title="Environments"
229 actions={environmentActions}
230 onPressAction={({ nativeEvent }) => selectEnvironment(nativeEvent.event)}
231 >
232 <Pressable
233 accessibilityRole="button"
234 accessibilityLabel={filterAccessibilityLabel}
235 className={cn(
236 "items-center justify-center rounded-full",
237 Platform.OS === "ios" ? "size-[28px]" : "size-[44px]",
238 )}
239 >
240 <SymbolView name={filterIcon} size={22} tintColorClassName="accent-icon" />
241 {hasLoadingEnvironments ? (
242 <View
243 pointerEvents="none"
244 className="absolute -right-[2px] -top-[2px] size-[9px] rounded-full bg-amber-500"
245 />
246 ) : null}
247 </Pressable>
248 </ControlPillMenu>
249 ) : null,
250 [
251 showEnvironmentFilter,
252 environmentActions,
253 selectEnvironment,
254 filterAccessibilityLabel,
255 filterIcon,
256 hasLoadingEnvironments,
257 ],
258 );
259​
260 useLayoutEffect(() => {
261 if (Platform.OS === "ios") {
262 navigation.setOptions({ headerRight: () => environmentFilter });
263 }
264 }, [navigation, environmentFilter]);
265​
266 return (
267 <SettingsScreen title="Usage" trailing={environmentFilter}>
268 <ScrollView
269 contentInsetAdjustmentBehavior="automatic"
270 showsVerticalScrollIndicator={false}
271 className="flex-1"
272 contentContainerClassName="gap-6 px-5 pt-4"
273 contentContainerStyle={{ paddingBottom: Math.max(insets.bottom, 18) + 18 }}
274 refreshControl={
275 <RefreshControl
276 refreshing={showingLimits ? limits.refreshing : refreshingUsage}
277 onRefresh={showingLimits ? () => void limits.refresh() : refreshWindow}
278 />
279 }
280 >
281 <SegmentedControl options={TAB_OPTIONS} selected={tab} onSelect={setTab} role="tab" />
282 <Animated.View
283 key={tab}
284 entering={FadeIn.duration(160).reduceMotion(ReduceMotion.System)}
285 className="gap-6"
286 >
287 {showingLimits ? (
288 <UsageLimitsSection
289 now={limits.now}
290 failedLabels={limits.failedLabels}
291 selectedEnvironmentIds={selectedEnvironmentIds}
292 cursorPrompt={
293 cursorAccessEnvironments.length > 0 ? (
294 <CursorEnableLimits
295 environments={cursorAccessEnvironments}
296 onEnabled={refreshAfterCursorEnable}
297 />
298 ) : null
299 }
300 />
301 ) : (
302 <>
303 {/* Period and metric together: neither applies to Limits, and
304 both change every number below, so they share one bar. */}
305 <View className="gap-3 ios:flex-row ios:items-center">
306 <SegmentedControl
307 options={WINDOW_OPTIONS}
308 selected={windowDays}
309 onSelect={selectWindow}
310 size="compact"
311 className="w-full ios:flex-1"
312 />
313 <SegmentedControl
314 options={METRIC_OPTIONS}
315 selected={metric}
316 onSelect={setMetric}
317 size="compact"
318 className="w-full ios:w-36"
319 />
320 </View>
321 <ChatGptUsageSummary selectedEnvironmentIds={selectedEnvironmentIds} />
322 {merged.duplicateSources.length > 0 ? (
323 <Text className="text-sm text-foreground-muted">
324 Counted once across environments sharing a transcript directory:{" "}
325 {merged.duplicateSources.join(", ")}
326 </Text>
327 ) : null}
328 {isPending ? (
329 <Text className="py-16 text-center text-base text-foreground-muted">
330 Scanning provider transcripts…
331 </Text>
332 ) : selectedEnvironments.length === 0 ? (
333 <Text className="py-16 text-center text-base text-foreground-muted">
334 {environments.length === 0
335 ? "Connect an environment to see usage."
336 : "Select an environment to see usage."}
337 </Text>
338 ) : (
339 <>
340 {sourceMessages.map((message) => (
341 <Text key={message} className="text-sm text-foreground-muted">
342 {message}
343 </Text>
344 ))}
345 <ChartCard
346 merged={merged}
347 days={chartDays}
348 daily={chartTotals}
349 metric={metric}
350 sinceDay={window.sinceDay}
351 untilDay={window.untilDay}
352 isPast24Hours={isPast24Hours}
353 timeZone={window.timeZone}
354 />
355 <ProviderSection
356 merged={merged}
357 metric={metric}
358 cursorAccessEnvironments={cursorAccessEnvironments}
359 showCursorEnvironment={selectedEnvironments.length > 1}
360 onCursorEnabled={refreshAfterCursorEnable}
361 />
362 <TotalsSection merged={merged} isPast24Hours={isPast24Hours} />
363 <CostSection merged={merged} />
364 <ModelsSection merged={merged} />
365 </>
366 )}
367 </>
368 )}
369 </Animated.View>
370 </ScrollView>
371 </SettingsScreen>
372 );
374​
375function CursorEnableAction({
376 environmentId,
377 label,
378 onEnabled,
379 buttonText = "Enable",
380}: {
381 readonly environmentId: EnvironmentId;
382 readonly label: string;
383 readonly onEnabled: () => void;
384 readonly buttonText?: string;
385}) {
386 const updateSettings = useAtomCommand(serverEnvironment.updateSettings, {
387 label: "enable Cursor account usage",
388 });
389 const [pending, setPending] = useState(false);
390 const enable = async () => {
391 setPending(true);
392 try {
393 const result = await updateSettings({
394 environmentId,
395 input: { patch: { cursorKeychainUsageEnabled: true } },
396 });
397 if (result._tag === "Success") onEnabled();
398 } finally {
399 setPending(false);
400 }
401 };
402 return (
403 <Pressable
404 accessibilityRole="button"
405 accessibilityLabel={`Enable Cursor usage from ${label}`}
406 accessibilityHint={CURSOR_KEYCHAIN_COPY}
407 disabled={pending}
408 onPress={() => void enable()}
409 className="rounded-full bg-primary px-4 py-2"
410 >
411 <Text className="text-sm font-medium text-primary-foreground">{buttonText}</Text>
412 </Pressable>
413 );
415​
416function CursorEnableRow({
417 environmentId,
418 label,
419 showEnvironment,
420 bordered,
421 onEnabled,
422}: {
423 readonly environmentId: EnvironmentId;
424 readonly label: string;
425 readonly showEnvironment: boolean;
426 readonly bordered: boolean;
427 readonly onEnabled: () => void;
428}) {
429 const colors = useProviderColors();
430 return (
431 <View
432 className={cn(
433 "flex-row items-center justify-between gap-3 p-4",
434 bordered && "border-t border-border-subtle",
435 )}
436 >
437 <View className="min-w-0 flex-1 flex-row items-center gap-2">
438 <View className="size-2.5 rounded-full" style={{ backgroundColor: colors.cursor }} />
439 <Text className="shrink text-lg text-foreground">
440 Cursor{showEnvironment ? ` · ${label}` : ""}
441 </Text>
442 </View>
443 <CursorEnableAction environmentId={environmentId} label={label} onEnabled={onEnabled} />
444 </View>
445 );
447​
448function CursorEnableLimits({
449 environments,
450 onEnabled,
451}: {
452 readonly environments: readonly EnvironmentUsageStatus[];
453 readonly onEnabled: () => void;
454}) {
455 return (
456 <View className="gap-3">
457 <View className="flex-row items-center gap-2 px-1">
458 <ProviderIcon provider="cursor" size={18} />
459 <Text className="text-base font-t3-medium text-foreground">Cursor</Text>
460 </View>
461 <View className="items-start gap-3 rounded-[24px] border-continuous bg-grouped-card p-4">
462 <Text className="text-xs text-foreground-muted">{CURSOR_KEYCHAIN_COPY}</Text>
463 <View className="flex-row flex-wrap gap-2">
464 {environments.map((environment) => (
465 <CursorEnableAction
466 key={environment.environmentId}
467 environmentId={environment.environmentId}
468 label={environment.label}
469 buttonText={environments.length > 1 ? `Enable on ${environment.label}` : "Enable"}
470 onEnabled={onEnabled}
471 />
472 ))}
473 </View>
474 </View>
475 </View>
476 );
478​
479/** Headline figure, the animated daily chart, and its legend, in one card. */
480function ChartCard(props: {
481 readonly merged: MergedUsage;
482 readonly days: readonly string[];
483 readonly daily: readonly DailyTotals[];
484 readonly metric: UsageChartMetric;
485 readonly sinceDay: string;
486 readonly untilDay: string;
487 readonly isPast24Hours: boolean;
488 readonly timeZone: string;
489}) {
490 const { merged, metric } = props;
491 const colors = useProviderColors();
492 const hasActivity = props.daily.some((period) => period.totalTokens > 0);
493​
494 return (
495 <View className="gap-4 rounded-[24px] border-continuous bg-grouped-card p-4">
496 <View className="gap-0.5">
497 <Text className="text-sm text-foreground-muted">
498 {metric === "cost" ? "Raw token cost" : "Processed tokens"}
499 </Text>
500 <Text className="text-4xl font-t3-bold tabular-nums text-foreground">
501 {metric === "cost" ? `${formatUsd(merged.costUsd)}*` : formatTokens(merged.totalTokens)}
502 </Text>
503 <Text className="text-sm text-foreground-muted">
504 {metric === "cost"
505 ? "* if billed at full API rate"
506 : `Across ${formatCount(merged.sessions)} sessions`}
507 </Text>
508 </View>
509​
510 {hasActivity ? (
511 <UsageDailyChart
512 days={props.days}
513 daily={props.daily}
514 metric={metric}
515 height={CHART_HEIGHT}
516 />
517 ) : (
518 <View style={{ height: CHART_HEIGHT }} className="items-center justify-center">
519 <Text className="text-base text-foreground-muted">No activity in this window.</Text>
520 </View>
521 )}
522​
523 <View className="flex-row items-center justify-between">
524 <Text className="text-xs text-foreground-tertiary">
525 {props.isPast24Hours
526 ? formatHourShort(props.days[0] ?? "", props.timeZone)
527 : formatDayShort(props.sinceDay)}
528 </Text>
529 <View className="flex-row items-center gap-4">
530 {merged.providers.map((provider) => (
531 <View key={provider.provider} className="flex-row items-center gap-1.5">
532 <View
533 className="size-2 rounded-full"
534 style={{ backgroundColor: colors[provider.provider] }}
535 />
536 <Text className="text-xs text-foreground-muted">
537 {PROVIDER_LABEL[provider.provider]}
538 </Text>
539 </View>
540 ))}
541 </View>
542 <Text className="text-xs text-foreground-tertiary">
543 {props.isPast24Hours
544 ? formatHourShort(props.days[props.days.length - 1] ?? "", props.timeZone)
545 : formatDayShort(props.untilDay)}
546 </Text>
547 </View>
548 </View>
549 );
551​
552function ProviderSection(props: {
553 readonly merged: MergedUsage;
554 readonly metric: UsageChartMetric;
555 readonly cursorAccessEnvironments: readonly EnvironmentUsageStatus[];
556 readonly showCursorEnvironment: boolean;
557 readonly onCursorEnabled: () => void;
558}) {
559 const { merged, metric } = props;
560 const colors = useProviderColors();
561 if (merged.providers.length === 0 && props.cursorAccessEnvironments.length === 0) return null;
562​
563 // Ranked by whatever the toggle is showing, so the rows always descend.
564 // .sort() on a copy, not .toSorted(): Hermes doesn't ship the ES2023 method.
565 const ordered = [...merged.providers].sort((a, b) =>
566 metric === "cost" ? b.costUsd - a.costUsd : b.totalTokens - a.totalTokens,
567 );
568 const rows: Array<
569 | { readonly kind: "usage"; readonly provider: (typeof ordered)[number] }
570 | { readonly kind: "enable"; readonly environment: EnvironmentUsageStatus }
571 > = ordered.map((provider) => ({ kind: "usage", provider }));
572 const cursorInsertAt =
573 Math.max(
574 ordered.findIndex((provider) => provider.provider === "codex"),
575 ordered.findIndex((provider) => provider.provider === "claude"),
576 ) + 1;
577 rows.splice(
578 cursorInsertAt,
579 0,
580 ...props.cursorAccessEnvironments.map((environment) => ({
581 kind: "enable" as const,
582 environment,
583 })),
584 );
585​
586 return (
587 <SettingsSection title="Providers">
588 {rows.map((row, index) => {
589 if (row.kind === "enable") {
590 return (
591 <CursorEnableRow
592 key={`enable:${row.environment.environmentId}`}
593 environmentId={row.environment.environmentId}
594 label={row.environment.label}
595 showEnvironment={props.showCursorEnvironment}
596 bordered={index > 0}
597 onEnabled={props.onCursorEnabled}
598 />
599 );
600 }
601 const provider = row.provider;
602 const share = metric === "cost" ? provider.costShare : provider.tokenShare;
603 return (
604 <View
605 key={provider.provider}
606 className={index === 0 ? "gap-2 p-4" : "gap-2 border-t border-border-subtle p-4"}
607 >
608 <View className="flex-row items-baseline justify-between gap-3">
609 <View className="flex-row items-center gap-2">
610 <View
611 className="size-2.5 rounded-full"
612 style={{ backgroundColor: colors[provider.provider] }}
613 />
614 <Text className="text-lg text-foreground">{PROVIDER_LABEL[provider.provider]}</Text>
615 </View>
616 <Text className="text-lg tabular-nums text-foreground">
617 {metric === "cost"
618 ? formatUsd(provider.costUsd)
619 : formatTokens(provider.totalTokens)}
620 </Text>
621 </View>
622 <View className="h-1 flex-row overflow-hidden rounded-full bg-subtle">
623 <View
624 className="h-full rounded-full"
625 style={{ flex: share, backgroundColor: colors[provider.provider] }}
626 />
627 <View style={{ flex: 1 - share }} />
628 </View>
629 <Text className="text-sm text-foreground-muted">
630 {metric === "cost"
631 ? `${formatPercent(share)} of cost · ${formatTokens(provider.totalTokens)} tokens`
632 : `${formatPercent(share)} of tokens · ${formatUsd(provider.costUsd)}`}
633 </Text>
634 </View>
635 );
636 })}
637 </SettingsSection>
638 );
640​
641function TotalsSection(props: { readonly merged: MergedUsage; readonly isPast24Hours: boolean }) {
642 const { merged } = props;
643 const activePeriods = (props.isPast24Hours ? merged.hourly : merged.daily).filter(
644 (period) => period.totalTokens > 0,
645 ).length;
646 const periodAverage = activePeriods === 0 ? 0 : merged.totalTokens / activePeriods;
647 const observedInput = merged.uncachedInputTokens + merged.cachedInputTokens;
648 const cachedShare = observedInput === 0 ? 0 : merged.cachedInputTokens / observedInput;
649​
650 return (
651 <SettingsSection title="Totals">
652 <View className="flex-row flex-wrap">
653 <MetricCell
654 label="Processed tokens"
655 value={formatTokens(merged.totalTokens)}
656 detail={`${formatTokens(periodAverage)} per active ${props.isPast24Hours ? "hour" : "day"}`}
657 />
658 <MetricCell
659 label="Cache savings"
660 value={formatUsd(merged.costQuality.cacheSavingsUsd)}
661 detail={
662 merged.costUsd > 0
663 ? `${(merged.costQuality.cacheSavingsUsd / merged.costUsd).toFixed(1)}x the raw cost`
664 : "vs full input rates"
665 }
666 />
667 <MetricCell
668 label="Cached input"
669 value={formatTokens(merged.cachedInputTokens)}
670 detail={`${formatPercent(cachedShare)} of observed input`}
671 />
672 <MetricCell
673 label="Uncached input"
674 value={formatTokens(merged.uncachedInputTokens)}
675 detail={`${formatTokens(merged.cacheCreationTokens)} cache writes`}
676 />
677 <MetricCell
678 label="Output"
679 value={formatTokens(merged.outputTokens)}
680 detail={`incl. ${formatTokens(merged.reasoningTokens)} reasoning`}
681 />
682 <MetricCell
683 label="Unpriced"
684 value={formatPercent(merged.costQuality.unpricedShare)}
685 detail="of records, excluded from cost"
686 />
687 </View>
688 </SettingsSection>
689 );
691​
692function CostSection(props: { readonly merged: MergedUsage }) {
693 const { categoryCost, speedCost } = props.merged;
694 const colors = useUsageMixColors();
695 const byType = [
696 { label: "Input", value: categoryCost.input, color: colors.input },
697 { label: "Cache read", value: categoryCost.cacheRead, color: colors.cacheRead },
698 { label: "Cache write", value: categoryCost.cacheWrite, color: colors.cacheWrite },
699 { label: "Output", value: categoryCost.output, color: colors.output },
700 // Reported cost with no rates to split it, or from older servers. Below a
701 // cent it is rounding, not usage.
702 {
703 label: "Other",
704 value: categoryCost.unsplit >= 0.005 ? categoryCost.unsplit : 0,
705 color: colors.other,
706 },
707 ];
708 const bySpeed = [
709 { label: "Standard", value: speedCost.standard, color: colors.standard },
710 { label: "Fast", value: speedCost.fast, color: colors.fast },
711 { label: "Ultrafast", value: speedCost.ultrafast, color: colors.ultrafast },
712 ];
713 if (props.merged.costUsd <= 0) return null;
714​
715 return (
716 <SettingsSection title="Cost">
717 <ShareBar label="By type" segments={byType} />
718 {speedCost.fast + speedCost.ultrafast > 0 ? (
719 <View className="border-t border-border-subtle">
720 <ShareBar
721 label="By speed"
722 segments={bySpeed}
723 aside={`${formatUsd(speedCost.premium)} premium`}
724 />
725 </View>
726 ) : null}
727 </SettingsSection>
728 );
730​
731/** One part-to-whole cost bar with its legend. Empty segments are left out. */
732function ShareBar(props: {
733 readonly label: string;
734 readonly segments: readonly { label: string; value: number; color: string }[];
735 readonly aside?: string;
736}) {
737 const visible = props.segments.filter((segment) => segment.value > 0);
738 if (visible.length === 0) return null;
739​
740 return (
741 <View className="gap-3 p-4">
742 <View className="flex-row items-baseline justify-between gap-3">
743 <Text className="text-sm text-foreground-muted">{props.label}</Text>
744 {props.aside ? (
745 <Text className="text-sm tabular-nums text-foreground-muted">{props.aside}</Text>
746 ) : null}
747 </View>
748 <View className="h-2 flex-row gap-0.5">
749 {visible.map((segment) => (
750 <View
751 key={segment.label}
752 className="h-full rounded-sm"
753 style={{ flex: segment.value, backgroundColor: segment.color }}
754 />
755 ))}
756 </View>
757 <View className="flex-row flex-wrap gap-x-4 gap-y-1.5">
758 {visible.map((segment) => (
759 <View key={segment.label} className="flex-row items-center gap-1.5">
760 <View className="size-2 rounded-sm" style={{ backgroundColor: segment.color }} />
761 <Text className="text-sm text-foreground-muted">{segment.label}</Text>
762 <Text className="text-sm tabular-nums text-foreground">{formatUsd(segment.value)}</Text>
763 </View>
764 ))}
765 </View>
766 </View>
767 );
769​
770function MetricCell(props: {
771 readonly label: string;
772 readonly value: string;
773 readonly detail: string;
774}) {
775 return (
776 <View className="w-1/2 gap-0.5 p-4">
777 <Text className="text-sm text-foreground-muted">{props.label}</Text>
778 <Text className="text-xl font-t3-medium tabular-nums text-foreground">{props.value}</Text>
779 <Text className="text-xs text-foreground-tertiary">{props.detail}</Text>
780 </View>
781 );
783​
784function ModelsSection(props: { readonly merged: MergedUsage }) {
785 const { merged } = props;
786 const colors = useProviderColors();
787 if (merged.models.length === 0) return null;
788​
789 return (
790 <SettingsSection title="By model">
791 {merged.models.map((model, index) => (
792 <View
793 key={`${model.provider}:${model.model}`}
794 className={
795 index === 0
796 ? "flex-row items-center gap-3 p-4"
797 : "flex-row items-center gap-3 border-t border-border-subtle p-4"
798 }
799 >
800 <View
801 className="size-2.5 shrink-0 rounded-full"
802 style={{ backgroundColor: colors[model.provider] }}
803 />
804 <View className="min-w-0 flex-1 gap-0.5">
805 <Text className="text-base text-foreground" numberOfLines={1}>
806 {model.model}
807 </Text>
808 <Text className="text-sm text-foreground-muted">
809 {isModelCostUnknown(model)
810 ? `no known rates · ${formatTokens(model.totalTokens)} tokens`
811 : `${formatPercent(model.costShare)} of cost · ${formatTokens(model.totalTokens)} tokens`}
812 </Text>
813 </View>
814 <Text className="text-base tabular-nums text-foreground">
815 {isModelCostUnknown(model) ? "Unpriced" : formatUsd(model.costUsd)}
816 </Text>
817 </View>
818 ))}
819 </SettingsSection>
820 );
822​
823/**
824 * Says plainly when the totals are incomplete: an environment still answering,
825 * one that failed, or one whose transcripts another environment already
826 * reported.
827 */
828function isUsageLoading(environment: EnvironmentUsageStatus) {
829 return environment.isPending || (environment.summary === null && environment.error === null);
831​
832function usageEnvironmentStatus(environment: EnvironmentUsageStatus): string {
833 if (
834 environment.summary &&
835 !isCompatibleUsageContractVersion(environment.summary.contractVersion, USAGE_CONTRACT_VERSION)
836 ) {
837 return formatUsageContractMismatch(environment.label, {
838 direction:
839 environment.summary.contractVersion < USAGE_CONTRACT_VERSION
840 ? "serverBehind"
841 : "clientBehind",
842 });
843 }
844 if (!environment.isConnected)
845 return environment.summary ? "Disconnected · showing saved usage" : "Waiting for connection…";
846 if (environment.error)
847 return environment.summary ? "Usage unavailable · showing saved totals" : "Usage unavailable";
848 if (isUsageLoading(environment))
849 return environment.summary ? "Updating usage…" : "Loading usage…";
850 return "Usage up to date";