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