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