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

UsageLimitsSection.tsx

375 lines13.1 KB

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