Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

UsageLimitsPooled.tsx

453 lines17.7 KB

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