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