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

UsageLimitsPooled.tsx

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