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