Open History to see the last commit
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, 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;
40}
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 );
99}
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 );
122}
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 padding = dense ? "px-4 py-3" : "p-4";
144 return (
145 <View
146 className={
147 props.first ? `gap-3 ${padding}` : `gap-3 border-t border-border-subtle ${padding}`
148 }
149 >
150 <View className="flex-row items-center gap-2">
151 <ProviderIcon provider={props.driver} size={16} />
152 <View className="min-w-0 flex-1 flex-row items-baseline gap-2">
153 <Text className="text-base font-t3-medium text-foreground">{props.label}</Text>
154 {props.instanceLabel !== props.label ? (
155 <AccountInstanceLabel key={props.instanceLabel} value={props.instanceLabel} />
156 ) : null}
157 {props.detail ? (
158 <Text className="shrink text-sm text-foreground-muted" numberOfLines={1}>
159 · {props.detail}
160 </Text>
161 ) : null}
162 </View>
163 {props.trailing}
164 </View>
165 {notice ? (
166 <Text className="text-sm text-foreground-muted">{notice}</Text>
167 ) : (
168 <View className="gap-3">
169 {limits.windows.map((window) => (
170 <WindowRow key={window.id} window={window} color={color} now={now} />
171 ))}
172 </View>
173 )}
174 {props.footer}
175 </View>
176 );
177}
178
179const OUTCOME_TEXT: Record<ProviderConsumeResetCreditOutcome, string> = {
180 reset: "Reset applied. Your windows have cleared.",
181 nothingToReset: "Nothing to reset right now.",
182 noCredit: "No reset credit left.",
183 alreadyRedeemed: "That credit was already redeemed.",
184};
185
186/**
187 * Banked reset credits with a confirmed redeem action. Redeeming spends a
188 * credit the provider granted the user, so it goes through the native
189 * confirm alert rather than firing on a bare tap.
190 */
191export function ResetCredits(props: {
192 readonly environmentId: EnvironmentId;
193 readonly input: ProviderConsumeResetCreditInput;
194 readonly credits: ServerProviderResetCredits;
195 readonly now: number;
196 /** A smaller pill for the composer card. */
197 readonly dense?: boolean;
198}) {
199 const { environmentId, input, credits, now, dense = false } = props;
200 const consume = useAtomCommand(serverEnvironment.consumeResetCredit, {
201 reportFailure: false,
202 });
203 const [busy, setBusy] = useState(false);
204 const [status, setStatus] = useState<string | null>(null);
205 if (dense && credits.availableCount === 0 && status === null) return null;
206
207 const expiresIn = credits.nextExpiresAt
208 ? formatDuration(Date.parse(credits.nextExpiresAt) - now)
209 : null;
210 const summary =
211 credits.availableCount === 0
212 ? "No reset credits banked"
213 : `${credits.availableCount} ${credits.availableCount === 1 ? "reset credit" : "reset credits"} banked${
214 expiresIn ? ` · next expires in ${expiresIn}` : ""
215 }`;
216
217 const redeem = async () => {
218 setBusy(true);
219 setStatus(null);
220 const result = await consume({ environmentId, input });
221 setBusy(false);
222 if (result._tag === "Success") {
223 setStatus(result.value.warning ?? OUTCOME_TEXT[result.value.outcome]);
224 return;
225 }
226 setStatus(
227 "error" in result.cause && result.cause.error instanceof Error
228 ? result.cause.error.message
229 : "Could not use the reset credit.",
230 );
231 };
232
233 const confirm = () => {
234 Alert.alert(
235 "Use a reset credit?",
236 "This redeems one credit on your account and clears the current rate-limit windows. It cannot be undone.",
237 [
238 { text: "Cancel", style: "cancel" },
239 { text: "Use credit", onPress: () => void redeem() },
240 ],
241 );
242 };
243
244 return (
245 <View className="flex-row flex-wrap items-center gap-x-3 gap-y-1">
246 <Text className="text-xs tabular-nums text-foreground-tertiary">{summary}</Text>
247 {credits.availableCount > 0 ? (
248 <Pressable
249 accessibilityRole="button"
250 accessibilityState={{ disabled: busy }}
251 disabled={busy}
252 onPress={confirm}
253 className={
254 dense
255 ? "rounded-full bg-subtle-strong px-2.5 py-1"
256 : "min-h-[44px] justify-center rounded-full bg-subtle-strong px-3 py-1.5"
257 }
258 >
259 <Text
260 className={
261 dense
262 ? "text-xs font-t3-medium text-foreground"
263 : "text-sm font-t3-medium text-foreground"
264 }
265 >
266 {busy ? "Using…" : "Use reset"}
267 </Text>
268 </Pressable>
269 ) : null}
270 {status ? <Text className="text-sm text-foreground">{status}</Text> : null}
271 </View>
272 );
273}
274
275/**
276 * Re-probes every provider (and usage-limit source) on each connected
277 * environment; the fresh snapshots then arrive over the config stream.
278 * Countdowns and pace anchor to `now` rather than ticking, so a refresh also
279 * re-anchors the clock: quota and elapsed time move together, or not at all.
280 * Environments whose probe failed are named, since their rows keep showing
281 * the previous quota with nothing else to say so.
282 */
283export function useRefreshLimits(
284 selectedEnvironmentIds: ReadonlySet<EnvironmentId> | null = null,
285 active = false,
286) {
287 const presentations = useAtomValue(environmentPresentations.presentationsAtom);
288 const refreshProviders = useAtomCommand(serverEnvironment.refreshProviders, {
289 reportFailure: false,
290 });
291 const [now, setNow] = useState(() => Date.now());
292 const [refreshing, setRefreshing] = useState(false);
293 const refreshingRef = useRef(false);
294 const [failedEnvironments, setFailedEnvironments] = useState<
295 readonly { environmentId: EnvironmentId; label: string }[]
296 >([]);
297 const refresh = async (automatic = false, afterPending = false) => {
298 const connected = [...presentations].filter(
299 ([environmentId, presentation]) =>
300 presentation.connection.phase === "connected" &&
301 (selectedEnvironmentIds === null || selectedEnvironmentIds.has(environmentId)),
302 );
303 try {
304 await Promise.all(
305 connected.map(async ([environmentId, presentation]) => {
306 const result = await refreshUsageLimits(
307 environmentId,
308 () => refreshProviders({ environmentId, input: {} }),
309 automatic,
310 afterPending,
311 );
312 if (result === undefined) return;
313 setFailedEnvironments((previous) => [
314 ...previous.filter((failed) => failed.environmentId !== environmentId),
315 ...(result._tag === "Failure"
316 ? [{ environmentId, label: presentation.entry.target.label }]
317 : []),
318 ]);
319 }),
320 );
321 } finally {
322 setNow(Date.now());
323 }
324 };
325 // Always toggles `refreshing`, even with nothing to probe: Android's
326 // RefreshControl keeps its spinner up until it sees true then false.
327 const refreshManually = async () => {
328 if (refreshingRef.current) return;
329 refreshingRef.current = true;
330 setRefreshing(true);
331 try {
332 await refresh();
333 } finally {
334 refreshingRef.current = false;
335 setRefreshing(false);
336 }
337 };
338 const connectedLimitsEnvironments = [...presentations]
339 .filter(
340 ([environmentId, presentation]) =>
341 presentation.connection.phase === "connected" &&
342 (selectedEnvironmentIds === null || selectedEnvironmentIds.has(environmentId)),
343 )
344 .map(([environmentId]) => environmentId)
345 .sort()
346 .join(",");
347 const autoRefreshLimits = useEffectEvent(() => refresh(true));
348 useEffect(() => {
349 if (active && connectedLimitsEnvironments) void autoRefreshLimits();
350 }, [active, connectedLimitsEnvironments]);
351
352 const failedLabels = failedEnvironments
353 .filter(
354 ({ environmentId }) =>
355 selectedEnvironmentIds === null || selectedEnvironmentIds.has(environmentId),
356 )
357 .map(({ label }) => label);
358 return {
359 now,
360 refreshing,
361 failedLabels,
362 refresh: refreshManually,
363 refreshAfterEnable: () => refresh(false, true),
364 };
365}