Open History to see the last commit
1import { useAtomValue } from "@effect/atom-react";
2import { useNavigation, type StaticScreenProps } from "@react-navigation/native";
3import { EnvironmentId } from "@t3tools/contracts";
4import {
5 collectLimitAccounts,
6 collectLimitNotices,
7 collectLimitPools,
8 formatDuration,
9 formatResetsIn,
10 remainingPercent,
11 type LimitAccount,
12 type LimitPoolWindow,
13} from "@t3tools/shared/usageLimits";
14import { useId, useState } from "react";
15import { Platform, Pressable, ScrollView, View } from "react-native";
16import { Defs, Path, Pattern, Rect, Svg } from "react-native-svg";
17import { useSafeAreaInsets } from "react-native-safe-area-context";
18
19import { AndroidScreenHeader } from "../../components/AndroidScreenHeader";
20import { SymbolView } from "../../components/AppSymbol";
21import { AppText as Text } from "../../components/AppText";
22import { ProviderIcon } from "../../components/ProviderIcon";
23import { NativeStackScreenOptions } from "../../native/StackHeader";
24import { environmentPresentations } from "../../state/presentation";
25import { ResetCredits } from "./UsageLimitsSection";
26import { useProviderColors } from "./usageProviders";
27
28const DRIVER_LABEL: Partial<Record<string, string>> = { codex: "Codex", claudeAgent: "Claude" };
29const PACE_LABEL = { ahead: "Ahead of pace", on: "On pace", under: "Under pace" } as const;
30
31function accountName(account: LimitAccount) {
32 if (account.displayName) return account.displayName;
33 if (!account.email) return DRIVER_LABEL[account.driver] ?? String(account.driver);
34 const [local = "", domain = ""] = account.email.split("@");
35 return `${local[0] ?? ""}${domain[0] ?? ""}`.toUpperCase() || "Account";
36}
37
38/** The spent share comes back at reset. SVG keeps the hatching static on both platforms. */
39function AccountSegment({
40 remaining,
41 color,
42 pending,
43}: {
44 readonly remaining: number;
45 readonly color: string;
46 readonly pending: boolean;
47}) {
48 const patternId = useId().replace(/:/g, "");
49 return (
50 <Svg width="100%" height="100%" accessible={false}>
51 <Defs>
52 <Pattern id={patternId} width={6} height={6} patternUnits="userSpaceOnUse">
53 <Path d="M-1 1L1 -1M0 6L6 0M5 7L7 5" stroke={color} strokeWidth={1} opacity={0.22} />
54 </Pattern>
55 </Defs>
56 {pending ? (
57 <Rect
58 x={`${remaining}%`}
59 width={`${100 - remaining}%`}
60 height="100%"
61 fill={`url(#${patternId})`}
62 />
63 ) : null}
64 <Rect width={`${remaining}%`} height="100%" fill={color} opacity={0.35} />
65 </Svg>
66 );
67}
68
69function PoolWindowCard({
70 pool,
71 color,
72 now,
73 environmentIds,
74}: {
75 readonly pool: LimitPoolWindow;
76 readonly color: string;
77 readonly now: number;
78 readonly environmentIds: readonly string[] | null;
79}) {
80 const navigation = useNavigation();
81 const nextRefill = pool.resets.find((reset) => reset.restoresPercent > 0);
82 const openAccount = (account: LimitAccount) =>
83 navigation.navigate("SettingsSheet", {
84 screen: "SettingsContent",
85 params: {
86 screen: "SettingsUsageAccount",
87 params: {
88 accountKey: account.key,
89 windowId: pool.id,
90 windowKind: pool.kind,
91 environmentIds,
92 now,
93 },
94 },
95 });
96 return (
97 <View className="gap-3 rounded-[24px] border-continuous bg-card p-4">
98 <View className="flex-row items-start justify-between gap-3">
99 <View className="gap-1">
100 <Text className="text-sm font-t3-medium text-foreground">{pool.label}</Text>
101 <View className="flex-row items-baseline gap-1.5">
102 <Text className="text-3xl font-t3-bold tabular-nums text-foreground">
103 {pool.remainingPercent}%
104 </Text>
105 <Text className="text-sm text-foreground-muted">left</Text>
106 </View>
107 </View>
108 {pool.pace ? (
109 <Text className="text-xs text-foreground-tertiary">{PACE_LABEL[pool.pace]}</Text>
110 ) : null}
111 </View>
112 {nextRefill ? (
113 <Text className="text-xs tabular-nums text-foreground-muted">
114 ↻ +{nextRefill.restoresPercent}%{" "}
115 {nextRefill.at <= now ? "now" : `in ${formatDuration(nextRefill.at - now)}`}
116 </Text>
117 ) : null}
118 <View className="flex-row gap-1">
119 {pool.columns.map(({ account, window }, index) => {
120 if (!window) return <View key={account.key} className="h-7 min-w-0 flex-1" />;
121 return (
122 <Pressable
123 key={account.key}
124 accessibilityRole="button"
125 accessibilityLabel={`Segment ${index + 1}, ${accountName(account)}, ${remainingPercent(window)}% left`}
126 accessibilityHint="Show account details"
127 onPress={() => openAccount(account)}
128 className="h-7 min-w-0 flex-1 overflow-hidden rounded-md bg-subtle"
129 >
130 <AccountSegment
131 remaining={remainingPercent(window)}
132 color={color}
133 pending={Boolean(window.resetsAt)}
134 />
135 <View pointerEvents="none" className="absolute inset-0 items-center justify-center">
136 <Text className="text-xs font-t3-medium tabular-nums text-foreground">
137 {index + 1}
138 </Text>
139 </View>
140 </Pressable>
141 );
142 })}
143 </View>
144 <View>
145 {pool.columns.map(({ account, window }, index) => {
146 if (!window) return null;
147 const credits = account.limits.resetCredits?.availableCount ?? 0;
148 const resetsIn = formatResetsIn(window, now);
149 return (
150 <Pressable
151 key={account.key}
152 accessibilityRole="button"
153 accessibilityLabel={`Segment ${index + 1}, ${accountName(account)}, ${remainingPercent(window)}% left${resetsIn ? `, ${resetsIn}` : ""}${credits ? `, ${credits} reset credits banked` : ""}`}
154 accessibilityHint="Show account details"
155 onPress={() => openAccount(account)}
156 className="min-h-[44px] flex-row items-center gap-2 active:opacity-60"
157 >
158 <View className="size-5 items-center justify-center overflow-hidden rounded-md bg-subtle-strong">
159 <Text className="text-xs font-t3-medium tabular-nums text-foreground">
160 {index + 1}
161 </Text>
162 </View>
163 <Text
164 numberOfLines={1}
165 className="min-w-0 flex-1 text-sm font-t3-medium text-foreground"
166 >
167 {accountName(account)}
168 </Text>
169 <Text className="text-sm font-t3-medium tabular-nums text-foreground">
170 {remainingPercent(window)}%
171 </Text>
172 <View className="flex-row items-center gap-1">
173 {resetsIn ? (
174 <Text className="text-xs tabular-nums text-foreground-muted">
175 {resetsIn.replace("resets in ", "↻ ")}
176 </Text>
177 ) : null}
178 {credits ? (
179 <>
180 {resetsIn ? <Text className="text-xs text-foreground-tertiary">·</Text> : null}
181 <SymbolView name="ticket" size={13} tintColorClassName="accent-icon" />
182 <Text className="text-xs font-t3-medium tabular-nums text-foreground">
183 {credits}
184 </Text>
185 </>
186 ) : null}
187 </View>
188 </Pressable>
189 );
190 })}
191 </View>
192 </View>
193 );
194}
195
196export function UsageLimitsSection({
197 now,
198 failedLabels,
199 selectedEnvironmentIds,
200}: {
201 readonly now: number;
202 readonly failedLabels: readonly string[];
203 readonly selectedEnvironmentIds: ReadonlySet<EnvironmentId> | null;
204}) {
205 const presentations = useAtomValue(environmentPresentations.presentationsAtom);
206 const selected =
207 selectedEnvironmentIds === null
208 ? presentations
209 : new Map([...presentations].filter(([id]) => selectedEnvironmentIds.has(id)));
210 const pools = collectLimitPools(collectLimitAccounts(selected), now);
211 const notices = collectLimitNotices(selected);
212 const colors = useProviderColors();
213 return (
214 <View className="gap-6">
215 {pools.length === 0 && notices.length === 0 && failedLabels.length === 0 ? (
216 <Text className="py-12 text-center text-base text-foreground-muted">
217 {selected.size === 0
218 ? "Select an environment to see limits."
219 : "No provider on the selected environments reports subscription limits."}
220 </Text>
221 ) : null}
222 {pools.map((pool) => (
223 <View key={pool.driver} className="gap-3">
224 <View className="flex-row items-center gap-2 px-1">
225 <ProviderIcon provider={pool.driver} size={18} />
226 <Text className="text-base font-t3-medium text-foreground">
227 {DRIVER_LABEL[pool.driver] ?? pool.driver}
228 </Text>
229 </View>
230 {pool.windows.map((window) => (
231 <PoolWindowCard
232 key={`${window.kind}:${window.id}`}
233 pool={window}
234 color={pool.driver === "claudeAgent" ? colors.claude : colors.codex}
235 now={now}
236 environmentIds={selectedEnvironmentIds === null ? null : [...selectedEnvironmentIds]}
237 />
238 ))}
239 </View>
240 ))}
241 {notices.length > 0 || failedLabels.length > 0 ? (
242 <View
243 accessible
244 accessibilityRole="alert"
245 accessibilityLiveRegion="polite"
246 className="flex-row items-start gap-2 rounded-xl border border-warning-border bg-warning px-3.5 py-3"
247 >
248 <SymbolView
249 name="exclamationmark.triangle"
250 size={16}
251 tintColorClassName="accent-warning-foreground"
252 />
253 <View className="min-w-0 flex-1 gap-0.5">
254 {notices.map((notice) => (
255 <Text key={notice} className="text-sm font-t3-medium text-warning-foreground">
256 {notice}
257 </Text>
258 ))}
259 {failedLabels.length > 0 ? (
260 <Text className="text-sm font-t3-medium text-warning-foreground">
261 {failedLabels.join(", ")} could not refresh limits. Showing the last known values.
262 </Text>
263 ) : null}
264 </View>
265 </View>
266 ) : null}
267 </View>
268 );
269}
270
271type AccountScreenProps = StaticScreenProps<{
272 accountKey: string;
273 windowId: string;
274 windowKind: LimitPoolWindow["kind"];
275 environmentIds: readonly string[] | null;
276 now: number;
277}>;
278
279/** Resolve the account again so live quota and credit updates reach the open detail screen. */
280export function UsageLimitAccountScreen({ route }: AccountScreenProps) {
281 const navigation = useNavigation();
282 const insets = useSafeAreaInsets();
283 const presentations = useAtomValue(environmentPresentations.presentationsAtom);
284 const { accountKey, windowId, windowKind, environmentIds, now } = route.params;
285 const selectedIds =
286 environmentIds === null ? null : new Set(environmentIds.map((id) => EnvironmentId.make(id)));
287 const selected =
288 selectedIds === null
289 ? presentations
290 : new Map([...presentations].filter(([id]) => selectedIds.has(id)));
291 const accounts = collectLimitAccounts(selected);
292 const account = accounts.find((candidate) => candidate.key === accountKey);
293 const pool = collectLimitPools(accounts, now)
294 .find((candidate) => candidate.driver === account?.driver)
295 ?.windows.find((candidate) => candidate.id === windowId && candidate.kind === windowKind);
296 const window = pool?.members.find((member) => member.account.key === accountKey)?.window;
297 const reset = pool?.resets.find((candidate) => candidate.member.account.key === accountKey);
298 const [revealed, setRevealed] = useState(false);
299 return (
300 <View collapsable={false} className="flex-1 bg-sheet">
301 {Platform.OS === "android" ? (
302 <>
303 <NativeStackScreenOptions options={{ headerShown: false }} />
304 <AndroidScreenHeader title="Account" onBack={() => navigation.goBack()} />
305 </>
306 ) : null}
307 <ScrollView
308 contentInsetAdjustmentBehavior="automatic"
309 contentContainerClassName="gap-5 p-5"
310 contentContainerStyle={{ paddingBottom: insets.bottom + 24 }}
311 >
312 {!account || !window ? (
313 <Text className="text-base text-foreground-muted">
314 This account is no longer reporting limits on the selected environments.
315 </Text>
316 ) : (
317 <>
318 <View className="gap-2">
319 <View className="flex-row items-center gap-2">
320 <ProviderIcon provider={account.driver} size={24} />
321 <Text className="flex-1 text-xl font-t3-bold text-foreground">
322 {account.displayName ?? DRIVER_LABEL[account.driver] ?? account.driver}
323 </Text>
324 </View>
325 {account.email ? (
326 <Pressable
327 accessibilityRole="button"
328 accessibilityLabel={revealed ? "Hide account email" : "Reveal account email"}
329 onPress={() => setRevealed((value) => !value)}
330 className="min-h-[44px] justify-center"
331 >
332 <Text className="text-sm text-foreground-muted">
333 {revealed ? account.email : "••••••@••••••"}
334 </Text>
335 </Pressable>
336 ) : null}
337 {account.plan ? (
338 <Text selectable className="text-sm text-foreground-muted">
339 {account.plan}
340 </Text>
341 ) : null}
342 </View>
343 <View className="gap-3 rounded-[24px] border-continuous bg-card p-4">
344 <Text className="text-sm font-t3-medium text-foreground">{window.label}</Text>
345 <Text className="text-3xl font-t3-bold tabular-nums text-foreground">
346 {remainingPercent(window)}% left
347 </Text>
348 {window.resetsAt ? (
349 <Text selectable className="text-sm text-foreground-muted">
350 Resets{" "}
351 {new Date(window.resetsAt).toLocaleString(undefined, {
352 dateStyle: "medium",
353 timeStyle: "short",
354 })}
355 </Text>
356 ) : null}
357 {reset && reset.restoresPercent > 0 ? (
358 <Text className="text-sm text-foreground-muted">
359 Restores {reset.restoresPercent}% of the pool
360 </Text>
361 ) : null}
362 </View>
363 <View className="gap-2 rounded-[24px] border-continuous bg-card p-4">
364 <Text className="text-sm font-t3-medium text-foreground">
365 {account.environments.length ? "Signed in" : "Source"}
366 </Text>
367 {account.environments.length ? (
368 account.environments.map((environment) => (
369 <Text key={environment.environmentId} className="text-sm text-foreground-muted">
370 {environment.label}
371 </Text>
372 ))
373 ) : (
374 <Text className="text-sm text-foreground-muted">{account.sourceLabel}</Text>
375 )}
376 </View>
377 {account.redeem && account.limits.resetCredits ? (
378 <View className="gap-3 rounded-[24px] border-continuous bg-card p-4">
379 <Text className="text-sm font-t3-medium text-foreground">Reset credits</Text>
380 <ResetCredits
381 key={account.key}
382 environmentId={account.redeem.environmentId}
383 input={account.redeem.input}
384 credits={account.limits.resetCredits}
385 now={now}
386 />
387 </View>
388 ) : null}
389 </>
390 )}
391 </ScrollView>
392 </View>
393 );
394}