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

UsageLimitsPooled.tsx

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