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