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

UsageLimitsSection.tsx

298 lines9.9 KB

1import { useAtomValue } from "@effect/atom-react";
2import type {
3 EnvironmentId,
4 ProviderConsumeResetCreditOutcome,
5 ProviderInstanceId,
6 ServerProvider,
7 ServerProviderResetCredits,
8 ServerProviderUsageWindow,
9 UsageLimitSourceAccount,
10} from "@t3tools/contracts";
11import {
12 collectLimitSources,
13 collectLimitsGroups,
14 elapsedShare,
15 formatDuration,
16 formatResetsIn,
17 limitsNotice,
18 paceOf,
19 providerLimitsLabel,
20} from "@t3tools/shared/usageLimits";
21import { type ReactNode, useState } from "react";
22import { Alert, Pressable, View } from "react-native";
23​
24import { AppText as Text } from "../../components/AppText";
25import { environmentPresentations } from "../../state/presentation";
26import { serverEnvironment } from "../../state/server";
27import { useAtomCommand } from "../../state/use-atom-command";
28import { SettingsSection } from "../settings/components/SettingsSection";
29​
30const PACE_LABEL = { ahead: "ahead of pace", on: "on pace", under: "under pace" } as const;
31const DRIVER_LABEL: Partial<Record<string, string>> = { codex: "Codex", claudeAgent: "Claude" };
32​
33/**
34 * One window as a bar spanning its whole duration: the fill is quota spent,
35 * the hairline is how far into the window the clock is.
36 */
37function WindowBar(props: { readonly window: ServerProviderUsageWindow; readonly now: number }) {
38 const { window, now } = props;
39 const used = Math.round(Math.max(0, Math.min(100, window.usedPercent)));
40 const elapsed = elapsedShare(window, now);
41 const pace = paceOf(window, now);
42 const resetsIn = formatResetsIn(window, now);
43 const detail = [pace ? PACE_LABEL[pace] : null, resetsIn].filter(Boolean).join(" · ");
44 return (
45 <View className="gap-1.5">
46 <View className="flex-row items-baseline justify-between gap-3">
47 <Text className="text-base text-foreground">{window.label}</Text>
48 <Text className="text-base tabular-nums text-foreground">{used}% used</Text>
49 </View>
50 <View className="h-3 justify-center">
51 <View className="h-1.5 flex-row overflow-hidden rounded-full bg-subtle">
52 <View
53 className={
54 used >= 90
55 ? "h-full rounded-full bg-destructive"
56 : used >= 70
57 ? "h-full rounded-full bg-warning"
58 : "h-full rounded-full bg-foreground"
59 }
60 style={{ flex: used }}
61 />
62 <View style={{ flex: 100 - used }} />
63 </View>
64 {elapsed !== null ? (
65 <View
66 className="absolute top-0 bottom-0 w-px bg-foreground"
67 style={{ left: `${elapsed * 100}%`, opacity: 0.6 }}
68 />
69 ) : null}
70 </View>
71 {detail ? <Text className="text-xs text-foreground-tertiary">{detail}</Text> : null}
72 </View>
73 );
75​
76function AccountLimits(props: {
77 readonly label: string;
78 readonly instanceLabel: string;
79 readonly detail: string | undefined;
80 readonly limits: ServerProvider["usageLimits"];
81 readonly now: number;
82 readonly first: boolean;
83 readonly footer?: ReactNode;
84}) {
85 const { limits, now } = props;
86 if (!limits) return null;
87 const notice = limitsNotice(limits);
88 return (
89 <View className={props.first ? "gap-3 p-4" : "gap-3 border-t border-border-subtle p-4"}>
90 <View className="flex-row flex-wrap items-baseline gap-x-2 gap-y-1">
91 <Text className="text-lg text-foreground">{props.label}</Text>
92 {props.instanceLabel !== props.label ? (
93 <Text className="shrink text-xs text-foreground-tertiary">· {props.instanceLabel}</Text>
94 ) : null}
95 {props.detail ? (
96 <Text className="shrink text-sm text-foreground-muted">· {props.detail}</Text>
97 ) : null}
98 </View>
99 {notice ? (
100 <Text className="text-sm text-foreground-muted">{notice}</Text>
101 ) : (
102 limits.windows.map((window) => <WindowBar key={window.id} window={window} now={now} />)
103 )}
104 {props.footer}
105 </View>
106 );
108​
109const OUTCOME_TEXT: Record<ProviderConsumeResetCreditOutcome, string> = {
110 reset: "Reset applied. Your windows have cleared.",
111 nothingToReset: "Nothing to reset right now.",
112 noCredit: "No reset credit left.",
113 alreadyRedeemed: "That credit was already redeemed.",
114};
115​
116/**
117 * Banked reset credits with a confirmed redeem action. Redeeming spends a
118 * credit the provider granted the user, so it goes through the native
119 * confirm alert rather than firing on a bare tap.
120 */
121function ResetCredits(props: {
122 readonly environmentId: EnvironmentId;
123 readonly instanceId: ProviderInstanceId;
124 readonly credits: ServerProviderResetCredits;
125 readonly now: number;
126}) {
127 const { environmentId, instanceId, credits, now } = props;
128 const consume = useAtomCommand(serverEnvironment.consumeResetCredit, {
129 reportFailure: false,
130 });
131 const [busy, setBusy] = useState(false);
132 const [status, setStatus] = useState<string | null>(null);
133 if (credits.availableCount === 0 && status === null) return null;
134​
135 const expiresIn = credits.nextExpiresAt
136 ? formatDuration(Date.parse(credits.nextExpiresAt) - now)
137 : null;
138 const summary =
139 credits.availableCount === 0
140 ? "No reset credits banked"
141 : `${credits.availableCount} ${credits.availableCount === 1 ? "reset credit" : "reset credits"} banked${
142 expiresIn ? ` · next expires in ${expiresIn}` : ""
143 }`;
144​
145 const redeem = async () => {
146 setBusy(true);
147 setStatus(null);
148 const result = await consume({ environmentId, input: { instanceId } });
149 setBusy(false);
150 if (result._tag === "Success") {
151 setStatus(OUTCOME_TEXT[result.value.outcome]);
152 return;
153 }
154 setStatus(
155 "error" in result.cause && result.cause.error instanceof Error
156 ? result.cause.error.message
157 : "Could not use the reset credit.",
158 );
159 };
160​
161 const confirm = () => {
162 Alert.alert(
163 "Use a reset credit?",
164 "This redeems one credit on your account and clears the current rate-limit windows. It cannot be undone.",
165 [
166 { text: "Cancel", style: "cancel" },
167 { text: "Use credit", onPress: () => void redeem() },
168 ],
169 );
170 };
171​
172 return (
173 <View className="gap-2">
174 <Text className="text-xs tabular-nums text-foreground-tertiary">{summary}</Text>
175 {credits.availableCount > 0 ? (
176 <Pressable
177 accessibilityRole="button"
178 accessibilityState={{ disabled: busy }}
179 disabled={busy}
180 onPress={confirm}
181 className="self-start rounded-full bg-subtle-strong px-3 py-1.5"
182 >
183 <Text className="text-sm font-t3-medium text-foreground">
184 {busy ? "Using credit…" : "Use a reset credit"}
185 </Text>
186 </Pressable>
187 ) : null}
188 {status ? <Text className="text-sm text-foreground">{status}</Text> : null}
189 </View>
190 );
192​
193function ProviderLimits(props: {
194 readonly provider: ServerProvider;
195 readonly environmentId: EnvironmentId;
196 readonly now: number;
197 readonly first: boolean;
198}) {
199 const { provider, environmentId, now } = props;
200 const credits = provider.usageLimits?.resetCredits;
201 return (
202 <AccountLimits
203 label={DRIVER_LABEL[provider.driver] ?? String(provider.driver)}
204 instanceLabel={providerLimitsLabel(provider, (driver) => DRIVER_LABEL[driver])}
205 detail={provider.auth.label}
206 limits={provider.usageLimits}
207 now={now}
208 first={props.first}
209 footer={
210 credits ? (
211 <ResetCredits
212 environmentId={environmentId}
213 instanceId={provider.instanceId}
214 credits={credits}
215 now={now}
216 />
217 ) : undefined
218 }
219 />
220 );
222​
223/** Emails stay off the phone screen; the plan and driver identify the row. */
224function SourceAccountLimits(props: {
225 readonly account: UsageLimitSourceAccount;
226 readonly now: number;
227 readonly first: boolean;
228}) {
229 const { account } = props;
230 return (
231 <AccountLimits
232 label={DRIVER_LABEL[account.driver] ?? String(account.driver)}
233 instanceLabel="CLI Proxy"
234 detail={account.plan}
235 limits={account.usageLimits}
236 now={props.now}
237 first={props.first}
238 />
239 );
241​
242/**
243 * Subscription quota windows from every connected environment's providers,
244 * read from the config each environment already streams. Countdowns anchor to
245 * render time rather than ticking.
246 */
247export function UsageLimitsSection() {
248 const presentations = useAtomValue(environmentPresentations.presentationsAtom);
249 const groups = collectLimitsGroups(presentations);
250 const sources = collectLimitSources(presentations);
251 // Anchored once per mount on purpose: countdowns must not tick.
252 const [now] = useState(() => Date.now());
253 if (groups.length === 0 && sources.length === 0) return null;
254​
255 return (
256 <>
257 {sources.map((source) => (
258 <SettingsSection key={source.key} card>
259 {source.error ? (
260 <Text className="p-4 text-sm text-foreground-muted">{source.error}</Text>
261 ) : source.accounts.length === 0 ? (
262 <Text className="p-4 text-sm text-foreground-muted">
263 {source.hiddenAccountCount > 0
264 ? "All accounts are shown by connected providers."
265 : "No accounts reported."}
266 </Text>
267 ) : (
268 source.accounts.map((account, index) => (
269 <SourceAccountLimits
270 key={account.id}
271 account={account}
272 now={now}
273 first={index === 0}
274 />
275 ))
276 )}
277 </SettingsSection>
278 ))}
279 {groups.map((group) => (
280 <SettingsSection
281 key={group.environmentId}
282 title={group.environmentLabel ? `Limits · ${group.environmentLabel}` : "Limits"}
283 card
284 >
285 {group.providers.map((provider, index) => (
286 <ProviderLimits
287 key={provider.instanceId}
288 provider={provider}
289 environmentId={group.environmentId}
290 now={now}
291 first={index === 0}
292 />
293 ))}
294 </SettingsSection>
295 ))}
296 </>
297 );