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 {failedLabels.length ? (
216 <Text className="text-sm text-foreground-muted">
217 {failedLabels.join(", ")} could not refresh limits. Showing the last known values.
218 </Text>
219 ) : null}
220 {pools.length === 0 ? (
221 <Text className="py-12 text-center text-base text-foreground-muted">
222 {selected.size === 0
223 ? "Select an environment to see limits."
224 : "No provider on the selected environments reports subscription limits."}
225 </Text>
226 ) : null}
227 {pools.map((pool) => (
228 <View key={pool.driver} className="gap-3">
229 <View className="flex-row items-center gap-2 px-1">
230 <ProviderIcon provider={pool.driver} size={18} />
231 <Text className="text-base font-t3-medium text-foreground">
232 {DRIVER_LABEL[pool.driver] ?? pool.driver}
233 </Text>
234 </View>
235 {pool.windows.map((window) => (
236 <PoolWindowCard
237 key={`${window.kind}:${window.id}`}
238 pool={window}
239 color={pool.driver === "claudeAgent" ? colors.claude : colors.codex}
240 now={now}
241 environmentIds={selectedEnvironmentIds === null ? null : [...selectedEnvironmentIds]}
242 />
243 ))}
244 </View>
245 ))}
246 {notices.map((notice) => (
247 <Text key={notice} className="text-sm text-foreground-muted">
248 {notice}
249 </Text>
250 ))}
251 </View>
252 );
253}
254
255type AccountScreenProps = StaticScreenProps<{
256 accountKey: string;
257 windowId: string;
258 windowKind: LimitPoolWindow["kind"];
259 environmentIds: readonly string[] | null;
260 now: number;
261}>;
262
263/** Resolve the account again so live quota and credit updates reach the open detail screen. */
264export function UsageLimitAccountScreen({ route }: AccountScreenProps) {
265 const navigation = useNavigation();
266 const insets = useSafeAreaInsets();
267 const presentations = useAtomValue(environmentPresentations.presentationsAtom);
268 const { accountKey, windowId, windowKind, environmentIds, now } = route.params;
269 const selectedIds =
270 environmentIds === null ? null : new Set(environmentIds.map((id) => EnvironmentId.make(id)));
271 const selected =
272 selectedIds === null
273 ? presentations
274 : new Map([...presentations].filter(([id]) => selectedIds.has(id)));
275 const accounts = collectLimitAccounts(selected);
276 const account = accounts.find((candidate) => candidate.key === accountKey);
277 const pool = collectLimitPools(accounts, now)
278 .find((candidate) => candidate.driver === account?.driver)
279 ?.windows.find((candidate) => candidate.id === windowId && candidate.kind === windowKind);
280 const window = pool?.members.find((member) => member.account.key === accountKey)?.window;
281 const reset = pool?.resets.find((candidate) => candidate.member.account.key === accountKey);
282 const [revealed, setRevealed] = useState(false);
283 return (
284 <View collapsable={false} className="flex-1 bg-sheet">
285 {Platform.OS === "android" ? (
286 <>
287 <NativeStackScreenOptions options={{ headerShown: false }} />
288 <AndroidScreenHeader title="Account" onBack={() => navigation.goBack()} />
289 </>
290 ) : null}
291 <ScrollView
292 contentInsetAdjustmentBehavior="automatic"
293 contentContainerClassName="gap-5 p-5"
294 contentContainerStyle={{ paddingBottom: insets.bottom + 24 }}
295 >
296 {!account || !window ? (
297 <Text className="text-base text-foreground-muted">
298 This account is no longer reporting limits on the selected environments.
299 </Text>
300 ) : (
301 <>
302 <View className="gap-2">
303 <View className="flex-row items-center gap-2">
304 <ProviderIcon provider={account.driver} size={24} />
305 <Text className="flex-1 text-xl font-t3-bold text-foreground">
306 {account.displayName ?? DRIVER_LABEL[account.driver] ?? account.driver}
307 </Text>
308 </View>
309 {account.email ? (
310 <Pressable
311 accessibilityRole="button"
312 accessibilityLabel={revealed ? "Hide account email" : "Reveal account email"}
313 onPress={() => setRevealed((value) => !value)}
314 className="min-h-[44px] justify-center"
315 >
316 <Text className="text-sm text-foreground-muted">
317 {revealed ? account.email : "••••••@••••••"}
318 </Text>
319 </Pressable>
320 ) : null}
321 {account.plan ? (
322 <Text selectable className="text-sm text-foreground-muted">
323 {account.plan}
324 </Text>
325 ) : null}
326 </View>
327 <View className="gap-3 rounded-[24px] border-continuous bg-card p-4">
328 <Text className="text-sm font-t3-medium text-foreground">{window.label}</Text>
329 <Text className="text-3xl font-t3-bold tabular-nums text-foreground">
330 {remainingPercent(window)}% left
331 </Text>
332 {window.resetsAt ? (
333 <Text selectable className="text-sm text-foreground-muted">
334 Resets{" "}
335 {new Date(window.resetsAt).toLocaleString(undefined, {
336 dateStyle: "medium",
337 timeStyle: "short",
338 })}
339 </Text>
340 ) : null}
341 {reset && reset.restoresPercent > 0 ? (
342 <Text className="text-sm text-foreground-muted">
343 Restores {reset.restoresPercent}% of the pool
344 </Text>
345 ) : null}
346 </View>
347 <View className="gap-2 rounded-[24px] border-continuous bg-card p-4">
348 <Text className="text-sm font-t3-medium text-foreground">
349 {account.environments.length ? "Signed in" : "Source"}
350 </Text>
351 {account.environments.length ? (
352 account.environments.map((environment) => (
353 <Text key={environment.environmentId} className="text-sm text-foreground-muted">
354 {environment.label}
355 </Text>
356 ))
357 ) : (
358 <Text className="text-sm text-foreground-muted">{account.sourceLabel}</Text>
359 )}
360 </View>
361 {account.redeem && account.limits.resetCredits ? (
362 <View className="gap-3 rounded-[24px] border-continuous bg-card p-4">
363 <Text className="text-sm font-t3-medium text-foreground">Reset credits</Text>
364 <ResetCredits
365 key={account.key}
366 environmentId={account.redeem.environmentId}
367 input={account.redeem.input}
368 credits={account.limits.resetCredits}
369 now={now}
370 />
371 </View>
372 ) : null}
373 </>
374 )}
375 </ScrollView>
376 </View>
377 );
378}