Open History to see the last commit
1import { EnvironmentId, USAGE_CONTRACT_VERSION } from "@t3tools/contracts";
2import type { UsageAccountConsumption } from "@t3tools/contracts";
3import { useNavigation } from "@react-navigation/native";
4import {
5 isCompatibleUsageContractVersion,
6 type DailyTotals,
7 type MergedUsage,
8} from "@t3tools/shared/usageMerge";
9import {
10 enumerateDays,
11 enumerateHourStarts,
12 formatCount,
13 formatDayShort,
14 formatHourShort,
15 formatPercent,
16 formatTokens,
17 formatUsd,
18 makeWindow,
19} from "@t3tools/shared/usageFormat";
20import { useCallback, useLayoutEffect, useMemo, useRef, useState } from "react";
21import { Platform, Pressable, RefreshControl, ScrollView, View } from "react-native";
22import Animated, { Easing, FadeIn, LinearTransition, ReduceMotion } from "react-native-reanimated";
23import { useSafeAreaInsets } from "react-native-safe-area-context";
24
25import { AndroidScreenHeader } from "../../components/AndroidScreenHeader";
26import { AppText as Text } from "../../components/AppText";
27import { cn } from "../../lib/cn";
28import { NativeStackScreenOptions } from "../../native/StackHeader";
29import { useUsage, type EnvironmentUsageStatus } from "../../state/usage";
30import { SettingsSection } from "../settings/components/SettingsSection";
31import { UsageDailyChart } from "./UsageDailyChart";
32import { toggleUsageEnvironment } from "./usageEnvironmentSelection";
33import { useRefreshLimits } from "./UsageLimitsSection";
34import { UsageLimitsSection } from "./UsageLimitsPooled";
35import { ControlPillMenu } from "../../components/ControlPill";
36import { SymbolView } from "../../components/AppSymbol";
37import type { UsageChartMetric } from "./usageChartData";
38import { PROVIDER_LABEL, useProviderColors } from "./usageProviders";
39
40type UsageTab = "usage" | "limits";
41const TAB_OPTIONS = [
42 { value: "usage", label: "Usage" },
43 { value: "limits", label: "Limits" },
44] as const satisfies readonly { value: UsageTab; label: string }[];
45
46// Labels are abbreviated to share a row with the metric toggle; screen
47// readers get the full phrase.
48const WINDOW_OPTIONS = [
49 { value: 1, label: "24h", accessibilityLabel: "Past 24 hours" },
50 { value: 7, label: "7d", accessibilityLabel: "Past 7 days" },
51 { value: 30, label: "30d", accessibilityLabel: "Past 30 days" },
52 { value: 90, label: "90d", accessibilityLabel: "Past 90 days" },
53] as const;
54
55const METRIC_OPTIONS = [
56 { value: "cost", label: "Cost" },
57 { value: "tokens", label: "Tokens" },
58] as const satisfies readonly { value: UsageChartMetric; label: string }[];
59
60const CHART_HEIGHT = 180;
61
62/**
63 * Two tabs over one screen. Usage is the transcript-derived spend for a
64 * period; Limits is the live subscription quota, which has no period. Both
65 * pull to refresh, each refreshing its own data.
66 */
67export function UsageRouteScreen() {
68 const navigation = useNavigation();
69 const insets = useSafeAreaInsets();
70 const [tab, setTab] = useState<UsageTab>("usage");
71 const [windowSelection, setWindowSelection] = useState(() => ({
72 days: 30,
73 window: makeWindow(30),
74 }));
75 const [metric, setMetric] = useState<UsageChartMetric>("cost");
76 const { days: windowDays, window } = windowSelection;
77 const isPast24Hours = windowDays === 1;
78 const [selectedEnvironmentIds, setSelectedEnvironmentIds] =
79 useState<ReadonlySet<EnvironmentId> | null>(null);
80 const { merged, environments, selectedEnvironments, isPending, isPartial, refresh } = useUsage(
81 window,
82 selectedEnvironmentIds,
83 );
84 const limits = useRefreshLimits(selectedEnvironmentIds);
85
86 const days = useMemo(
87 () => enumerateDays(window.sinceDay, window.untilDay),
88 [window.sinceDay, window.untilDay],
89 );
90 const chartDays = useMemo(
91 () =>
92 isPast24Hours && window.sinceTime !== undefined && window.untilTime !== undefined
93 ? enumerateHourStarts(window.sinceTime, window.untilTime)
94 : days,
95 [days, isPast24Hours, window.sinceTime, window.untilTime],
96 );
97 const chartTotals = useMemo(
98 (): readonly DailyTotals[] =>
99 isPast24Hours
100 ? merged.hourly.map((hour) => ({
101 day: hour.hourStart,
102 costUsd: hour.costUsd,
103 totalTokens: hour.totalTokens,
104 byProvider: hour.byProvider,
105 }))
106 : merged.daily,
107 [isPast24Hours, merged.daily, merged.hourly],
108 );
109
110 const [refreshingUsage, setRefreshingUsage] = useState(false);
111 const refreshingRef = useRef(false);
112 const showingLimits = tab === "limits";
113 const selectWindow = (days: number) => {
114 setWindowSelection({
115 days,
116 window: makeWindow(days, undefined, days === 1 ? "hour" : "day"),
117 });
118 };
119 const refreshWindow = () => {
120 if (refreshingRef.current) return;
121 const nextWindow = makeWindow(windowDays, undefined, isPast24Hours ? "hour" : "day");
122 if (
123 nextWindow.sinceDay !== window.sinceDay ||
124 nextWindow.untilDay !== window.untilDay ||
125 nextWindow.sinceTime !== window.sinceTime ||
126 nextWindow.untilTime !== window.untilTime
127 ) {
128 setWindowSelection({ days: windowDays, window: nextWindow });
129 }
130 refreshingRef.current = true;
131 setRefreshingUsage(true);
132 void refresh(nextWindow).finally(() => {
133 refreshingRef.current = false;
134 setRefreshingUsage(false);
135 });
136 };
137
138 const showEnvironmentFilter = environments.length > 0 || selectedEnvironmentIds !== null;
139 const hasLoadingEnvironments = selectedEnvironments.some(isUsageLoading);
140 const filterAccessibilityLabel = hasLoadingEnvironments
141 ? "Filter usage environments, some environments are loading"
142 : "Filter usage environments";
143 const filterIcon =
144 selectedEnvironmentIds === null
145 ? "line.3.horizontal.decrease"
146 : "line.3.horizontal.decrease.circle.fill";
147 const environmentActions = useMemo(
148 () => [
149 {
150 id: "all",
151 title: "All environments",
152 subtitle: undefined,
153 state: selectedEnvironmentIds === null ? ("on" as const) : ("off" as const),
154 },
155 ...environments.map((environment) => ({
156 id: environment.environmentId,
157 title: environment.label,
158 subtitle: usageEnvironmentStatus(environment),
159 state:
160 selectedEnvironmentIds === null || selectedEnvironmentIds.has(environment.environmentId)
161 ? ("on" as const)
162 : ("off" as const),
163 })),
164 ],
165 [environments, selectedEnvironmentIds],
166 );
167 const selectEnvironment = useCallback(
168 (value: string) => {
169 if (value === "all") {
170 setSelectedEnvironmentIds(null);
171 return;
172 }
173 const id = EnvironmentId.make(value);
174 setSelectedEnvironmentIds((selected) => toggleUsageEnvironment(selected, environments, id));
175 },
176 [environments],
177 );
178 const environmentFilter = useMemo(
179 () =>
180 showEnvironmentFilter ? (
181 <ControlPillMenu
182 accessible
183 accessibilityRole="button"
184 accessibilityLabel={filterAccessibilityLabel}
185 title="Environments"
186 actions={environmentActions}
187 onPressAction={({ nativeEvent }) => selectEnvironment(nativeEvent.event)}
188 >
189 <Pressable
190 accessibilityRole="button"
191 accessibilityLabel={filterAccessibilityLabel}
192 className={cn(
193 "items-center justify-center rounded-full",
194 Platform.OS === "ios" ? "size-[28px]" : "size-[44px]",
195 )}
196 >
197 <SymbolView name={filterIcon} size={22} tintColorClassName="accent-icon" />
198 {hasLoadingEnvironments ? (
199 <View
200 pointerEvents="none"
201 className="absolute -right-[2px] -top-[2px] size-[9px] rounded-full bg-amber-500"
202 />
203 ) : null}
204 </Pressable>
205 </ControlPillMenu>
206 ) : null,
207 [
208 showEnvironmentFilter,
209 environmentActions,
210 selectEnvironment,
211 filterAccessibilityLabel,
212 filterIcon,
213 hasLoadingEnvironments,
214 ],
215 );
216
217 useLayoutEffect(() => {
218 if (Platform.OS === "ios") {
219 navigation.setOptions({ headerRight: () => environmentFilter });
220 }
221 }, [navigation, environmentFilter]);
222
223 return (
224 <View collapsable={false} className="flex-1 bg-sheet">
225 {Platform.OS === "android" ? (
226 <>
227 <NativeStackScreenOptions options={{ headerShown: false }} />
228 <AndroidScreenHeader
229 title="Usage"
230 onBack={() => navigation.goBack()}
231 trailing={environmentFilter}
232 />
233 </>
234 ) : null}
235 <ScrollView
236 contentInsetAdjustmentBehavior="automatic"
237 showsVerticalScrollIndicator={false}
238 className="flex-1"
239 contentContainerClassName="gap-6 px-5 pt-4"
240 contentContainerStyle={{ paddingBottom: Math.max(insets.bottom, 18) + 18 }}
241 refreshControl={
242 <RefreshControl
243 refreshing={showingLimits ? limits.refreshing : refreshingUsage}
244 onRefresh={showingLimits ? () => void limits.refresh() : refreshWindow}
245 />
246 }
247 >
248 <SegmentedControl options={TAB_OPTIONS} selected={tab} onSelect={setTab} role="tab" />
249
250 <Animated.View
251 key={tab}
252 entering={FadeIn.duration(160).reduceMotion(ReduceMotion.System)}
253 className="gap-6"
254 >
255 {showingLimits ? (
256 <UsageLimitsSection
257 now={limits.now}
258 failedLabels={limits.failedLabels}
259 selectedEnvironmentIds={selectedEnvironmentIds}
260 />
261 ) : (
262 <>
263 <View className="flex-row items-center gap-3">
264 <SegmentedControl
265 options={WINDOW_OPTIONS}
266 selected={windowDays}
267 onSelect={selectWindow}
268 size="compact"
269 className="flex-1"
270 />
271 <SegmentedControl
272 options={METRIC_OPTIONS}
273 selected={metric}
274 onSelect={setMetric}
275 size="compact"
276 className="w-36"
277 />
278 </View>
279 <UsageCoverageNotice
280 environments={environments}
281 merged={merged}
282 isPartial={isPartial}
283 />
284
285 {merged.accountUsage !== null ? (
286 <DevinAccountUsageSection usage={merged.accountUsage} />
287 ) : null}
288 {isPending ? (
289 <Text className="py-16 text-center text-base text-foreground-muted">
290 Scanning provider transcripts…
291 </Text>
292 ) : selectedEnvironments.length === 0 ? (
293 <Text className="py-16 text-center text-base text-foreground-muted">
294 {environments.length === 0
295 ? "Connect an environment to see usage."
296 : "Select an environment to see usage."}
297 </Text>
298 ) : (
299 <>
300 <ChartCard
301 merged={merged}
302 days={chartDays}
303 daily={chartTotals}
304 metric={metric}
305 sinceDay={window.sinceDay}
306 untilDay={window.untilDay}
307 isPast24Hours={isPast24Hours}
308 timeZone={window.timeZone}
309 />
310 <ProviderSection merged={merged} metric={metric} />
311 <TotalsSection merged={merged} isPast24Hours={isPast24Hours} />
312 <ModelsSection merged={merged} />
313 </>
314 )}
315 </>
316 )}
317 </Animated.View>
318 </ScrollView>
319 </View>
320 );
321}
322
323function formatAcus(value: number): string {
324 return new Intl.NumberFormat("en-US", { maximumFractionDigits: 2 }).format(value);
325}
326
327function DevinAccountUsageSection({ usage }: { readonly usage: UsageAccountConsumption }) {
328 const message =
329 usage.status === "notConfigured"
330 ? "Optional account ACU data is not configured on the server."
331 : usage.status === "forbidden"
332 ? "The configured Devin key cannot read organization consumption."
333 : usage.status === "failed"
334 ? (usage.message ?? "Devin account consumption could not be loaded.")
335 : null;
336
337 return (
338 <SettingsSection title="Devin account usage" card>
339 <View className="gap-1 p-4">
340 {usage.status === "available" ? (
341 <Text className="text-2xl font-t3-medium tabular-nums text-foreground">
342 {formatAcus(usage.totalAcus)} ACUs
343 </Text>
344 ) : null}
345 <Text className="text-sm text-foreground-muted">
346 {message ?? "Official organization consumption for this window."}
347 </Text>
348 {usage.status === "available" ? (
349 <Text className="text-xs text-foreground-tertiary">
350 {usage.days.length} billing days returned · Source: {usage.source}
351 </Text>
352 ) : null}
353 </View>
354 </SettingsSection>
355 );
356}
357
358function SegmentedControl<Value extends number | string>(props: {
359 readonly options: readonly {
360 readonly value: Value;
361 readonly label: string;
362 readonly accessibilityLabel?: string;
363 }[];
364 readonly selected: Value;
365 readonly onSelect: (value: Value) => void;
366 /** The tab bar is full height; filters under it are shorter so it stays primary. */
367 readonly size?: "default" | "compact";
368 /** "tab" for the view switcher; filters stay plain buttons. */
369 readonly role?: "tab" | "button";
370 readonly className?: string;
371}) {
372 const compact = props.size === "compact";
373 return (
374 <View
375 accessible={false}
376 className={cn(
377 "flex-row overflow-hidden rounded-full border-continuous bg-card",
378 props.className,
379 )}
380 >
381 <Animated.View
382 pointerEvents="none"
383 layout={LinearTransition.duration(200)
384 .easing(Easing.out(Easing.cubic))
385 .reduceMotion(ReduceMotion.System)}
386 className="absolute bottom-0 top-0 rounded-full bg-subtle-strong"
387 style={{
388 width: `${100 / props.options.length}%`,
389 start: `${
390 (Math.max(
391 0,
392 props.options.findIndex((option) => option.value === props.selected),
393 ) *
394 100) /
395 props.options.length
396 }%`,
397 }}
398 />
399 {props.options.map((option) => {
400 const active = option.value === props.selected;
401 return (
402 <Pressable
403 key={String(option.value)}
404 accessibilityRole={Platform.OS === "ios" ? "button" : (props.role ?? "button")}
405 accessibilityLabel={option.accessibilityLabel ?? option.label}
406 accessibilityState={{ selected: active }}
407 onPress={() => props.onSelect(option.value)}
408 className={cn(
409 "flex-1 items-center justify-center rounded-full",
410 compact ? "h-9" : "h-11",
411 )}
412 >
413 <Text
414 className={cn(
415 compact ? "text-xs" : "text-sm",
416 active ? "font-t3-medium text-foreground" : "text-foreground-muted",
417 )}
418 >
419 {option.label}
420 </Text>
421 </Pressable>
422 );
423 })}
424 </View>
425 );
426}
427
428/** Headline figure, the animated daily chart, and its legend, in one card. */
429function ChartCard(props: {
430 readonly merged: MergedUsage;
431 readonly days: readonly string[];
432 readonly daily: readonly DailyTotals[];
433 readonly metric: UsageChartMetric;
434 readonly sinceDay: string;
435 readonly untilDay: string;
436 readonly isPast24Hours: boolean;
437 readonly timeZone: string;
438}) {
439 const { merged, metric } = props;
440 const colors = useProviderColors();
441 const hasActivity = props.daily.some((period) => period.totalTokens > 0);
442
443 return (
444 <View className="gap-4 rounded-[24px] border-continuous bg-card p-4">
445 <View className="gap-0.5">
446 <Text className="text-sm text-foreground-muted">
447 {metric === "cost" ? "Raw token cost" : "Processed tokens"}
448 </Text>
449 <Text className="text-4xl font-t3-bold tabular-nums text-foreground">
450 {metric === "cost" ? `${formatUsd(merged.costUsd)}*` : formatTokens(merged.totalTokens)}
451 </Text>
452 <Text className="text-sm text-foreground-muted">
453 {metric === "cost"
454 ? "* if billed at full API rate"
455 : `Across ${formatCount(merged.sessions)} sessions`}
456 </Text>
457 </View>
458
459 {hasActivity ? (
460 <UsageDailyChart
461 days={props.days}
462 daily={props.daily}
463 metric={metric}
464 height={CHART_HEIGHT}
465 />
466 ) : (
467 <View style={{ height: CHART_HEIGHT }} className="items-center justify-center">
468 <Text className="text-base text-foreground-muted">No activity in this window.</Text>
469 </View>
470 )}
471
472 <View className="flex-row items-center justify-between">
473 <Text className="text-xs text-foreground-tertiary">
474 {props.isPast24Hours
475 ? formatHourShort(props.days[0] ?? "", props.timeZone)
476 : formatDayShort(props.sinceDay)}
477 </Text>
478 <View className="flex-row items-center gap-4">
479 {merged.providers.map((provider) => (
480 <View key={provider.provider} className="flex-row items-center gap-1.5">
481 <View
482 className="size-2 rounded-full"
483 style={{ backgroundColor: colors[provider.provider] }}
484 />
485 <Text className="text-xs text-foreground-muted">
486 {PROVIDER_LABEL[provider.provider]}
487 </Text>
488 </View>
489 ))}
490 </View>
491 <Text className="text-xs text-foreground-tertiary">
492 {props.isPast24Hours
493 ? formatHourShort(props.days[props.days.length - 1] ?? "", props.timeZone)
494 : formatDayShort(props.untilDay)}
495 </Text>
496 </View>
497 </View>
498 );
499}
500
501function ProviderSection(props: {
502 readonly merged: MergedUsage;
503 readonly metric: UsageChartMetric;
504}) {
505 const { merged, metric } = props;
506 const colors = useProviderColors();
507 if (merged.providers.length === 0) return null;
508
509 // Ranked by whatever the toggle is showing, so the rows always descend.
510 // .sort() on a copy, not .toSorted(): Hermes doesn't ship the ES2023 method.
511 const ordered = [...merged.providers].sort((a, b) =>
512 metric === "cost" ? b.costUsd - a.costUsd : b.totalTokens - a.totalTokens,
513 );
514
515 return (
516 <SettingsSection title="Providers" card>
517 {ordered.map((provider, index) => {
518 const share = metric === "cost" ? provider.costShare : provider.tokenShare;
519 return (
520 <View
521 key={provider.provider}
522 className={index === 0 ? "gap-2 p-4" : "gap-2 border-t border-border-subtle p-4"}
523 >
524 <View className="flex-row items-baseline justify-between gap-3">
525 <View className="flex-row items-center gap-2">
526 <View
527 className="size-2.5 rounded-full"
528 style={{ backgroundColor: colors[provider.provider] }}
529 />
530 <Text className="text-lg text-foreground">{PROVIDER_LABEL[provider.provider]}</Text>
531 </View>
532 <Text className="text-lg tabular-nums text-foreground">
533 {metric === "cost"
534 ? formatUsd(provider.costUsd)
535 : formatTokens(provider.totalTokens)}
536 </Text>
537 </View>
538 <View className="h-1 flex-row overflow-hidden rounded-full bg-subtle">
539 <View
540 className="h-full rounded-full"
541 style={{ flex: share, backgroundColor: colors[provider.provider] }}
542 />
543 <View style={{ flex: 1 - share }} />
544 </View>
545 <Text className="text-sm text-foreground-muted">
546 {metric === "cost"
547 ? `${formatPercent(share)} of cost · ${formatTokens(provider.totalTokens)} tokens`
548 : `${formatPercent(share)} of tokens · ${formatUsd(provider.costUsd)}`}
549 </Text>
550 </View>
551 );
552 })}
553 </SettingsSection>
554 );
555}
556
557function TotalsSection(props: { readonly merged: MergedUsage; readonly isPast24Hours: boolean }) {
558 const { merged } = props;
559 const activePeriods = (props.isPast24Hours ? merged.hourly : merged.daily).filter(
560 (period) => period.totalTokens > 0,
561 ).length;
562 const periodAverage = activePeriods === 0 ? 0 : merged.totalTokens / activePeriods;
563 const observedInput = merged.uncachedInputTokens + merged.cachedInputTokens;
564 const cachedShare = observedInput === 0 ? 0 : merged.cachedInputTokens / observedInput;
565
566 return (
567 <SettingsSection title="Totals" card>
568 <View className="flex-row flex-wrap">
569 <MetricCell
570 label="Processed tokens"
571 value={formatTokens(merged.totalTokens)}
572 detail={`${formatTokens(periodAverage)} per active ${props.isPast24Hours ? "hour" : "day"}`}
573 />
574 <MetricCell
575 label="Cache savings"
576 value={formatUsd(merged.costQuality.cacheSavingsUsd)}
577 detail={
578 merged.costUsd > 0
579 ? `${(merged.costQuality.cacheSavingsUsd / merged.costUsd).toFixed(1)}x the raw cost`
580 : "vs full input rates"
581 }
582 />
583 <MetricCell
584 label="Cached input"
585 value={formatTokens(merged.cachedInputTokens)}
586 detail={`${formatPercent(cachedShare)} of observed input`}
587 />
588 <MetricCell
589 label="Uncached input"
590 value={formatTokens(merged.uncachedInputTokens)}
591 detail={`${formatTokens(merged.cacheCreationTokens)} cache writes`}
592 />
593 <MetricCell
594 label="Output"
595 value={formatTokens(merged.outputTokens)}
596 detail={`incl. ${formatTokens(merged.reasoningTokens)} reasoning`}
597 />
598 <MetricCell
599 label="Unpriced"
600 value={formatPercent(merged.costQuality.unpricedShare)}
601 detail="of records, excluded from cost"
602 />
603 </View>
604 </SettingsSection>
605 );
606}
607
608function MetricCell(props: {
609 readonly label: string;
610 readonly value: string;
611 readonly detail: string;
612}) {
613 return (
614 <View className="w-1/2 gap-0.5 p-4">
615 <Text className="text-sm text-foreground-muted">{props.label}</Text>
616 <Text className="text-xl font-t3-medium tabular-nums text-foreground">{props.value}</Text>
617 <Text className="text-xs text-foreground-tertiary">{props.detail}</Text>
618 </View>
619 );
620}
621
622function ModelsSection(props: { readonly merged: MergedUsage }) {
623 const { merged } = props;
624 const colors = useProviderColors();
625 if (merged.models.length === 0) return null;
626
627 return (
628 <SettingsSection title="By model" card>
629 {merged.models.map((model, index) => (
630 <View
631 key={`${model.provider}:${model.model}`}
632 className={
633 index === 0
634 ? "flex-row items-center gap-3 p-4"
635 : "flex-row items-center gap-3 border-t border-border-subtle p-4"
636 }
637 >
638 <View
639 className="size-2.5 shrink-0 rounded-full"
640 style={{ backgroundColor: colors[model.provider] }}
641 />
642 <View className="min-w-0 flex-1 gap-0.5">
643 <Text className="text-base text-foreground" numberOfLines={1}>
644 {model.model}
645 </Text>
646 <Text className="text-sm text-foreground-muted">
647 {formatPercent(model.costShare)} of cost · {formatTokens(model.totalTokens)} tokens
648 </Text>
649 </View>
650 <Text className="text-base tabular-nums text-foreground">{formatUsd(model.costUsd)}</Text>
651 </View>
652 ))}
653 </SettingsSection>
654 );
655}
656
657/**
658 * Says plainly when the totals are incomplete: an environment still answering,
659 * one that failed, or one whose transcripts another environment already
660 * reported.
661 */
662function isUsageLoading(environment: EnvironmentUsageStatus) {
663 return environment.isPending || (environment.summary === null && environment.error === null);
664}
665
666function usageEnvironmentStatus(environment: EnvironmentUsageStatus): string {
667 if (
668 environment.summary &&
669 !isCompatibleUsageContractVersion(environment.summary.contractVersion, USAGE_CONTRACT_VERSION)
670 ) {
671 return "Older server · excluded from usage totals";
672 }
673 if (!environment.isConnected)
674 return environment.summary ? "Disconnected · showing saved usage" : "Waiting for connection…";
675 if (environment.error)
676 return environment.summary ? "Usage unavailable · showing saved totals" : "Usage unavailable";
677 if (isUsageLoading(environment))
678 return environment.summary ? "Updating usage…" : "Loading usage…";
679 return "Usage up to date";
680}
681
682/**
683 * Says plainly when the totals are incomplete: an environment still answering,
684 * one that failed, or one whose transcripts another environment already
685 * reported.
686 */
687function UsageCoverageNotice(props: {
688 readonly environments: readonly EnvironmentUsageStatus[];
689 readonly merged: MergedUsage;
690 readonly isPartial: boolean;
691}) {
692 const failed = props.environments.filter((environment) => environment.error !== null);
693 const stale = props.environments.filter((environment) =>
694 props.merged.staleEnvironments.includes(environment.environmentId),
695 );
696 const duplicateSources = props.merged.duplicateSources;
697 if (
698 failed.length === 0 &&
699 stale.length === 0 &&
700 duplicateSources.length === 0 &&
701 !props.isPartial
702 ) {
703 return null;
704 }
705
706 return (
707 <View className="gap-1 rounded-[16px] border-continuous bg-card px-4 py-3">
708 {props.isPartial ? (
709 <Text className="text-sm text-foreground-muted">
710 Some environments are still reporting. Totals are partial.
711 </Text>
712 ) : null}
713 {failed.map((environment) => (
714 <Text key={environment.environmentId} className="text-sm text-foreground-muted">
715 {environment.label} could not report usage.
716 </Text>
717 ))}
718 {stale.map((environment) => (
719 <Text key={environment.environmentId} className="text-sm text-foreground-muted">
720 {environment.label} runs an older server version and is excluded from totals.
721 </Text>
722 ))}
723 {duplicateSources.length > 0 ? (
724 <Text className="text-sm text-foreground-muted">
725 Counted once across environments sharing a transcript directory:{" "}
726 {duplicateSources.join(", ")}
727 </Text>
728 ) : null}
729 </View>
730 );
731}