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

UsageLimitsPooled.tsx

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