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

UsageLimitsPooled.tsx

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