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

UsageLimitsPooled.tsx

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