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

UsageLimitsPooled.tsx

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