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

UsageLimitsPooled.tsx

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