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

UsageLimitsPooled.tsx

639 lines24.3 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 wide = false,
412}: {
413 readonly now: number;
414 readonly failedLabels: readonly string[];
415 readonly selectedEnvironmentIds: ReadonlySet<EnvironmentId> | null;
416 readonly wide?: boolean;
417}) {
418 const presentations = useAtomValue(environmentPresentations.presentationsWithProvidersAtom);
419 const selected =
420 selectedEnvironmentIds === null
421 ? presentations
422 : new Map([...presentations].filter(([id]) => selectedEnvironmentIds.has(id)));
423 const pools = collectLimitPools(collectLimitAccounts(selected), now);
424 const notices = collectLimitNotices(selected);
425 const externalLinks = collectExternalUsageLinks(selected);
426 const colors = useProviderColors();
427 return (
428 <View className="gap-6">
429 {pools.length === 0 &&
430 notices.length === 0 &&
431 failedLabels.length === 0 &&
432 externalLinks.length === 0 ? (
433 <Text className="py-12 text-center text-base text-foreground-muted">
434 {selected.size === 0
435 ? "Select an environment to see limits."
436 : "No provider on the selected environments reports subscription limits."}
437 </Text>
438 ) : null}
439 {pools.map((pool) => {
440 const windows = displayLimitWindows(pool);
441 return (
442 <Fragment key={pool.driver}>
443 <View className="gap-3">
444 <View className="flex-row items-center gap-2 px-1">
445 <ProviderIcon provider={pool.driver} size={18} />
446 <Text className="text-base font-t3-medium text-foreground">
447 {DRIVER_LABEL[pool.driver] ?? pool.driver}
448 </Text>
449 </View>
450 {windows.map((window) => {
451 const details =
452 pool.driver === "cursor" ? cursorUsageWindowDetails(window.id) : undefined;
453 return (
454 <PoolWindowCard
455 key={`${window.kind}:${window.id}`}
456 pool={window}
457 color={colors[usageProviderKind(pool.driver) ?? "codex"]}
458 now={now}
459 environmentIds={
460 selectedEnvironmentIds === null ? null : [...selectedEnvironmentIds]
461 }
462 label={details?.label}
463 description={details?.description}
464 wide={wide}
465 />
466 );
467 })}
468 </View>
469 </Fragment>
470 );
471 })}
472 {externalLinks.map((link) => (
473 <View key={link.url} className="gap-3 rounded-xl border border-border-subtle p-4">
474 <Text className="text-base font-t3-medium text-foreground">{link.label}</Text>
475 <Text className="text-xs text-foreground-muted">{link.accounts.join(", ")}</Text>
476 {link.message ? (
477 <Text className="text-sm text-foreground-muted">{link.message}</Text>
478 ) : null}
479 <Pressable
480 accessibilityRole="link"
481 className="min-h-11 justify-center"
482 onPress={() => void Linking.openURL(link.url).catch(() => undefined)}
483 >
484 <Text className="text-sm font-t3-medium text-primary">Manage usage</Text>
485 </Pressable>
486 </View>
487 ))}
488 {notices.length > 0 || failedLabels.length > 0 ? (
489 <View
490 accessible
491 accessibilityRole="alert"
492 accessibilityLiveRegion="polite"
493 className="flex-row items-start gap-2 rounded-xl border border-warning-border bg-warning px-3.5 py-3"
494 >
495 <SymbolView
496 name="exclamationmark.triangle"
497 size={16}
498 tintColorClassName="accent-warning-foreground"
499 />
500 <View className="min-w-0 flex-1 gap-0.5">
501 {notices.map((notice) => (
502 <Text key={notice} className="text-sm font-t3-medium text-warning-foreground">
503 {notice}
504 </Text>
505 ))}
506 {failedLabels.length > 0 ? (
507 <Text className="text-sm font-t3-medium text-warning-foreground">
508 {failedLabels.join(", ")} could not refresh limits. Showing the last known values.
509 </Text>
510 ) : null}
511 </View>
512 </View>
513 ) : null}
514 </View>
515 );
517​
518type AccountScreenProps = StaticScreenProps<{
519 accountKey: string;
520 windowId: string;
521 windowKind: LimitPoolWindow["kind"];
522 environmentIds: readonly string[] | null;
523 now: number;
524}>;
525​
526export function UsageLimitAccountScreen({ route }: AccountScreenProps) {
527 const insets = useSafeAreaInsets();
528 const presentations = useAtomValue(environmentPresentations.presentationsWithProvidersAtom);
529 const { accountKey, windowId, windowKind, environmentIds, now } = route.params;
530 const selectedIds =
531 environmentIds === null ? null : new Set(environmentIds.map((id) => EnvironmentId.make(id)));
532 const selected =
533 selectedIds === null
534 ? presentations
535 : new Map([...presentations].filter(([id]) => selectedIds.has(id)));
536 const accounts = collectLimitAccounts(selected);
537 const account = accounts.find((candidate) => candidate.key === accountKey);
538 const pool = collectLimitPools(accounts, now)
539 .find((candidate) => candidate.driver === account?.driver)
540 ?.windows.find((candidate) => candidate.id === windowId && candidate.kind === windowKind);
541 const window = pool?.members.find((member) => member.account.key === accountKey)?.window;
542 const evenPace = window ? paceRemainingPercent(window, now) : null;
543 const reset = pool?.resets.find((candidate) => candidate.member.account.key === accountKey);
544 const [revealed, setRevealed] = useState(false);
545 return (
546 <SettingsScreen title="Account">
547 <ScrollView
548 contentInsetAdjustmentBehavior="automatic"
549 contentContainerClassName="gap-5 p-5"
550 contentContainerStyle={{ paddingBottom: insets.bottom + 24 }}
551 >
552 {!account || !window ? (
553 <Text className="text-base text-foreground-muted">
554 This account is no longer reporting limits on the selected environments.
555 </Text>
556 ) : (
557 <>
558 <View className="gap-2">
559 <View className="flex-row items-center gap-2">
560 <ProviderIcon provider={account.driver} size={24} />
561 <Text className="flex-1 text-xl font-t3-bold text-foreground">
562 {account.displayName ?? DRIVER_LABEL[account.driver] ?? account.driver}
563 </Text>
564 </View>
565 {account.email ? (
566 <Pressable
567 accessibilityRole="button"
568 accessibilityLabel={revealed ? "Hide account email" : "Reveal account email"}
569 onPress={() => setRevealed((value) => !value)}
570 className="min-h-[44px] justify-center"
571 >
572 <Text className="text-sm text-foreground-muted">
573 {revealed ? account.email : "••••••@••••••"}
574 </Text>
575 </Pressable>
576 ) : null}
577 {account.plan ? (
578 <Text selectable className="text-sm text-foreground-muted">
579 {account.plan}
580 </Text>
581 ) : null}
582 </View>
583 <View className="gap-3 rounded-[24px] border-continuous bg-grouped-card p-4">
584 <Text className="text-sm font-t3-medium text-foreground">{window.label}</Text>
585 <Text className="text-3xl font-t3-bold tabular-nums text-foreground">
586 {remainingPercent(window)}% left
587 </Text>
588 {window.resetsAt ? (
589 <Text selectable className="text-sm text-foreground-muted">
590 Resets{" "}
591 {new Date(window.resetsAt).toLocaleString(undefined, {
592 dateStyle: "medium",
593 timeStyle: "short",
594 })}
595 </Text>
596 ) : null}
597 {evenPace !== null ? (
598 <Text className="text-sm text-foreground-muted">
599 Even pace: {evenPace}% left by now
600 </Text>
601 ) : null}
602 {reset && reset.restoresPercent > 0 ? (
603 <Text className="text-sm text-foreground-muted">
604 Restores {reset.restoresPercent}% of the pool
605 </Text>
606 ) : null}
607 </View>
608 <View className="gap-2 rounded-[24px] border-continuous bg-grouped-card p-4">
609 <Text className="text-sm font-t3-medium text-foreground">
610 {account.environments.length ? "Signed in" : "Source"}
611 </Text>
612 {account.environments.length ? (
613 account.environments.map((environment) => (
614 <Text key={environment.environmentId} className="text-sm text-foreground-muted">
615 {environment.label}
616 </Text>
617 ))
618 ) : (
619 <Text className="text-sm text-foreground-muted">{account.sourceLabel}</Text>
620 )}
621 </View>
622 {account.redeem && account.limits.resetCredits ? (
623 <View className="gap-3 rounded-[24px] border-continuous bg-grouped-card p-4">
624 <Text className="text-sm font-t3-medium text-foreground">Reset credits</Text>
625 <ResetCredits
626 key={account.key}
627 environmentId={account.redeem.environmentId}
628 input={account.redeem.input}
629 credits={account.limits.resetCredits}
630 now={now}
631 />
632 </View>
633 ) : null}
634 </>
635 )}
636 </ScrollView>
637 </SettingsScreen>
638 );