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

UsageLimitsSection.tsx

394 lines13.4 KB

1import { useAtomValue } from "@effect/atom-react";
2import type {
3 EnvironmentId,
4 ProviderConsumeResetCreditOutcome,
5 ProviderInstanceId,
6 ServerProvider,
7 ServerProviderResetCredits,
8 ServerProviderUsageWindow,
9 UsageLimitSourceAccount,
10 UsageProviderKind,
11} from "@t3tools/contracts";
12import {
13 collectLimitSources,
14 collectLimitsGroups,
15 elapsedShare,
16 formatDuration,
17 formatResetsIn,
18 limitsNotice,
19 paceOf,
20 providerLimitsLabel,
21} from "@t3tools/shared/usageLimits";
22import { type ReactNode, useState } from "react";
23import { Alert, Pressable, View } from "react-native";
24​
25import { AppText as Text } from "../../components/AppText";
26import { ProviderIcon } from "../../components/ProviderIcon";
27import { environmentPresentations } from "../../state/presentation";
28import { serverEnvironment } from "../../state/server";
29import { useAtomCommand } from "../../state/use-atom-command";
30import { SettingsSection } from "../settings/components/SettingsSection";
31import { useProviderColors } from "./usageProviders";
32​
33const PACE_LABEL = { ahead: "ahead of pace", on: "on pace", under: "under pace" } as const;
34const DRIVER_LABEL: Partial<Record<string, string>> = { codex: "Codex", claudeAgent: "Claude" };
35​
36type Driver = ServerProvider["driver"];
37​
38/** The series colour the usage chart uses for this driver, so the two views read as one. */
39function useBarColor(driver: Driver): string | null {
40 const colors = useProviderColors();
41 const kind: UsageProviderKind | null =
42 driver === "codex" ? "codex" : driver === "claudeAgent" ? "claude" : null;
43 return kind ? colors[kind] : null;
45​
46/**
47 * One window as a bar spanning its whole duration: the fill is quota spent,
48 * the hairline is how far into the window the clock is. Pace sits under the
49 * left edge, the countdown under the right, so a row reads in one glance.
50 */
51function WindowRow(props: {
52 readonly window: ServerProviderUsageWindow;
53 readonly color: string | null;
54 readonly now: number;
55}) {
56 const { window, now } = props;
57 const used = Math.round(Math.max(0, Math.min(100, window.usedPercent)));
58 const elapsed = elapsedShare(window, now);
59 const pace = paceOf(window, now);
60 const resetsIn = formatResetsIn(window, now);
61 return (
62 <View className="gap-1">
63 <View className="flex-row items-baseline justify-between gap-3">
64 <Text className="text-sm text-foreground">{window.label}</Text>
65 <Text className="text-sm font-t3-medium tabular-nums text-foreground">{used}%</Text>
66 </View>
67 <View className="h-3 justify-center">
68 <View className="h-1.5 flex-row overflow-hidden rounded-full bg-subtle">
69 <View
70 className={
71 used >= 90
72 ? "h-full rounded-full bg-destructive"
73 : used >= 70
74 ? "h-full rounded-full bg-warning"
75 : "h-full rounded-full bg-foreground"
76 }
77 style={[
78 { flex: used },
79 used < 70 && props.color ? { backgroundColor: props.color } : null,
80 ]}
81 />
82 <View style={{ flex: 100 - used }} />
83 </View>
84 {elapsed !== null ? (
85 <View
86 className="absolute top-0 bottom-0 w-px bg-foreground"
87 style={{ left: `${elapsed * 100}%`, opacity: 0.6 }}
88 />
89 ) : null}
90 </View>
91 {pace || resetsIn ? (
92 <View className="flex-row justify-between gap-3">
93 <Text className="text-xs text-foreground-tertiary">{pace ? PACE_LABEL[pace] : ""}</Text>
94 <Text className="text-xs tabular-nums text-foreground-tertiary">{resetsIn ?? ""}</Text>
95 </View>
96 ) : null}
97 </View>
98 );
100​
101/** One account: icon, name and plan on a single line, then its windows. */
102function AccountLimits(props: {
103 readonly driver: Driver;
104 readonly label: string;
105 readonly instanceLabel: string;
106 readonly detail: string | undefined;
107 readonly limits: ServerProvider["usageLimits"];
108 readonly now: number;
109 readonly first: boolean;
110 readonly footer?: ReactNode;
111}) {
112 const { limits, now } = props;
113 const color = useBarColor(props.driver);
114 if (!limits) return null;
115 const notice = limitsNotice(limits);
116 return (
117 <View className={props.first ? "gap-3 p-4" : "gap-3 border-t border-border-subtle p-4"}>
118 <View className="flex-row items-center gap-2">
119 <ProviderIcon provider={props.driver} size={16} />
120 <View className="min-w-0 flex-1 flex-row items-baseline gap-2">
121 <Text className="text-base font-t3-medium text-foreground">{props.label}</Text>
122 {props.instanceLabel !== props.label ? (
123 <Text className="shrink text-xs text-foreground-tertiary" numberOfLines={1}>
124 · {props.instanceLabel}
125 </Text>
126 ) : null}
127 {props.detail ? (
128 <Text className="shrink text-sm text-foreground-muted" numberOfLines={1}>
129 · {props.detail}
130 </Text>
131 ) : null}
132 </View>
133 </View>
134 {notice ? (
135 <Text className="text-sm text-foreground-muted">{notice}</Text>
136 ) : (
137 <View className="gap-3">
138 {limits.windows.map((window) => (
139 <WindowRow key={window.id} window={window} color={color} now={now} />
140 ))}
141 </View>
142 )}
143 {props.footer}
144 </View>
145 );
147​
148const OUTCOME_TEXT: Record<ProviderConsumeResetCreditOutcome, string> = {
149 reset: "Reset applied. Your windows have cleared.",
150 nothingToReset: "Nothing to reset right now.",
151 noCredit: "No reset credit left.",
152 alreadyRedeemed: "That credit was already redeemed.",
153};
154​
155/**
156 * Banked reset credits with a confirmed redeem action. Redeeming spends a
157 * credit the provider granted the user, so it goes through the native
158 * confirm alert rather than firing on a bare tap.
159 */
160function ResetCredits(props: {
161 readonly environmentId: EnvironmentId;
162 readonly instanceId: ProviderInstanceId;
163 readonly credits: ServerProviderResetCredits;
164 readonly now: number;
165}) {
166 const { environmentId, instanceId, credits, now } = props;
167 const consume = useAtomCommand(serverEnvironment.consumeResetCredit, {
168 reportFailure: false,
169 });
170 const [busy, setBusy] = useState(false);
171 const [status, setStatus] = useState<string | null>(null);
172 if (credits.availableCount === 0 && status === null) return null;
173​
174 const expiresIn = credits.nextExpiresAt
175 ? formatDuration(Date.parse(credits.nextExpiresAt) - now)
176 : null;
177 const summary =
178 credits.availableCount === 0
179 ? "No reset credits banked"
180 : `${credits.availableCount} ${credits.availableCount === 1 ? "reset credit" : "reset credits"} banked${
181 expiresIn ? ` · next expires in ${expiresIn}` : ""
182 }`;
183​
184 const redeem = async () => {
185 setBusy(true);
186 setStatus(null);
187 const result = await consume({ environmentId, input: { instanceId } });
188 setBusy(false);
189 if (result._tag === "Success") {
190 setStatus(OUTCOME_TEXT[result.value.outcome]);
191 return;
192 }
193 setStatus(
194 "error" in result.cause && result.cause.error instanceof Error
195 ? result.cause.error.message
196 : "Could not use the reset credit.",
197 );
198 };
199​
200 const confirm = () => {
201 Alert.alert(
202 "Use a reset credit?",
203 "This redeems one credit on your account and clears the current rate-limit windows. It cannot be undone.",
204 [
205 { text: "Cancel", style: "cancel" },
206 { text: "Use credit", onPress: () => void redeem() },
207 ],
208 );
209 };
210​
211 return (
212 <View className="flex-row flex-wrap items-center gap-x-3 gap-y-1">
213 <Text className="text-xs tabular-nums text-foreground-tertiary">{summary}</Text>
214 {credits.availableCount > 0 ? (
215 <Pressable
216 accessibilityRole="button"
217 accessibilityState={{ disabled: busy }}
218 disabled={busy}
219 onPress={confirm}
220 className="rounded-full bg-subtle-strong px-3 py-1.5"
221 >
222 <Text className="text-sm font-t3-medium text-foreground">
223 {busy ? "Using credit…" : "Use a reset credit"}
224 </Text>
225 </Pressable>
226 ) : null}
227 {status ? <Text className="text-sm text-foreground">{status}</Text> : null}
228 </View>
229 );
231​
232function ProviderLimits(props: {
233 readonly provider: ServerProvider;
234 readonly environmentId: EnvironmentId;
235 readonly now: number;
236 readonly first: boolean;
237}) {
238 const { provider, environmentId, now } = props;
239 const credits = provider.usageLimits?.resetCredits;
240 return (
241 <AccountLimits
242 driver={provider.driver}
243 label={DRIVER_LABEL[provider.driver] ?? String(provider.driver)}
244 instanceLabel={providerLimitsLabel(provider, (driver) => DRIVER_LABEL[driver])}
245 detail={provider.auth.label}
246 limits={provider.usageLimits}
247 now={now}
248 first={props.first}
249 footer={
250 credits ? (
251 <ResetCredits
252 environmentId={environmentId}
253 instanceId={provider.instanceId}
254 credits={credits}
255 now={now}
256 />
257 ) : undefined
258 }
259 />
260 );
262​
263/** Emails stay off the phone screen; the plan and driver identify the row. */
264function SourceAccountLimits(props: {
265 readonly account: UsageLimitSourceAccount;
266 readonly now: number;
267 readonly first: boolean;
268}) {
269 const { account } = props;
270 return (
271 <AccountLimits
272 driver={account.driver}
273 label={DRIVER_LABEL[account.driver] ?? String(account.driver)}
274 instanceLabel="CLI Proxy"
275 detail={account.plan}
276 limits={account.usageLimits}
277 now={props.now}
278 first={props.first}
279 />
280 );
282​
283/**
284 * Re-probes every provider (and usage-limit source) on each connected
285 * environment; the fresh snapshots then arrive over the config stream.
286 * Countdowns and pace anchor to `now` rather than ticking, so a refresh also
287 * re-anchors the clock: quota and elapsed time move together, or not at all.
288 * Environments whose probe failed are named, since their rows keep showing
289 * the previous quota with nothing else to say so.
290 */
291export function useRefreshLimits() {
292 const presentations = useAtomValue(environmentPresentations.presentationsAtom);
293 const refreshProviders = useAtomCommand(serverEnvironment.refreshProviders, {
294 reportFailure: false,
295 });
296 const [now, setNow] = useState(() => Date.now());
297 const [refreshing, setRefreshing] = useState(false);
298 const [failedLabels, setFailedLabels] = useState<readonly string[]>([]);
299 // Always toggles `refreshing`, even with nothing to probe: Android's
300 // RefreshControl keeps its spinner up until it sees true then false.
301 const refresh = async () => {
302 const connected = [...presentations].filter(
303 ([, presentation]) => presentation.connection.phase === "connected",
304 );
305 setRefreshing(true);
306 try {
307 const results = await Promise.all(
308 connected.map(([environmentId]) => refreshProviders({ environmentId, input: {} })),
309 );
310 setFailedLabels(
311 connected
312 .filter((_, index) => results[index]?._tag === "Failure")
313 .map(([, presentation]) => presentation.entry.target.label),
314 );
315 } finally {
316 setNow(Date.now());
317 setRefreshing(false);
318 }
319 };
320 return { now, refreshing, failedLabels, refresh };
322​
323/**
324 * Subscription quota windows from every connected environment's providers,
325 * read from the config each environment already streams.
326 */
327export function UsageLimitsSection(props: {
328 readonly now: number;
329 readonly failedLabels: readonly string[];
330}) {
331 const { now } = props;
332 const presentations = useAtomValue(environmentPresentations.presentationsAtom);
333 const groups = collectLimitsGroups(presentations);
334 const sources = collectLimitSources(presentations);
335​
336 if (groups.length === 0 && sources.length === 0) {
337 return (
338 <Text className="py-16 text-center text-base text-foreground-muted">
339 No provider on a connected environment reports subscription limits.
340 </Text>
341 );
342 }
343​
344 return (
345 <>
346 {props.failedLabels.length > 0 ? (
347 <View className="rounded-[16px] border-continuous bg-card px-4 py-3">
348 <Text className="text-sm text-foreground-muted">
349 {props.failedLabels.join(", ")} could not refresh limits. Showing the last known values.
350 </Text>
351 </View>
352 ) : null}
353 {groups.map((group) => (
354 <SettingsSection
355 key={group.environmentId}
356 title={group.environmentLabel ?? "Providers"}
357 card
358 >
359 {group.providers.map((provider, index) => (
360 <ProviderLimits
361 key={provider.instanceId}
362 provider={provider}
363 environmentId={group.environmentId}
364 now={now}
365 first={index === 0}
366 />
367 ))}
368 </SettingsSection>
369 ))}
370 {sources.map((source) => (
371 <SettingsSection key={source.key} card>
372 {source.error ? (
373 <Text className="p-4 text-sm text-foreground-muted">{source.error}</Text>
374 ) : source.accounts.length === 0 ? (
375 <Text className="p-4 text-sm text-foreground-muted">
376 {source.hiddenAccountCount > 0
377 ? "All accounts are shown by connected providers."
378 : "No accounts reported."}
379 </Text>
380 ) : (
381 source.accounts.map((account, index) => (
382 <SourceAccountLimits
383 key={account.id}
384 account={account}
385 now={now}
386 first={index === 0}
387 />
388 ))
389 )}
390 </SettingsSection>
391 ))}
392 </>
393 );