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

UsageLimitsPooled.tsx

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