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