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

UsageLimitsPooled.tsx

649 lines24.7 KB

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