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

UsageLimitsSection.tsx

325 lines11.4 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, 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;
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 );
99​
100function AccountInstanceLabel({ value }: { readonly value: string }) {
101 const [revealed, setRevealed] = useState(false);
102 if (!value.includes("@")) {
103 return (
104 <Text className="shrink text-xs text-foreground-tertiary" numberOfLines={1}>
105 · {value}
106 </Text>
107 );
108 }
109 return (
110 <Pressable
111 className="shrink active:opacity-60"
112 accessibilityRole="button"
113 accessibilityLabel={revealed ? "Hide account label" : "Reveal account label"}
114 onPress={() => setRevealed((current) => !current)}
115 >
116 <Text className="text-xs text-foreground-tertiary" numberOfLines={1}>
117 · {revealed ? value : "••••••@••••••"}
118 </Text>
119 </Pressable>
120 );
122​
123/** One account: icon, name and plan on a single line, then its windows. */
124export function AccountLimits(props: {
125 readonly driver: Driver;
126 readonly label: string;
127 readonly instanceLabel: string;
128 readonly detail: string | undefined;
129 readonly limits: ServerProvider["usageLimits"];
130 readonly now: number;
131 readonly first: boolean;
132 /** Tighter padding for the composer card. */
133 readonly dense?: boolean;
134 /** Sits at the end of the heading row, such as a close control. */
135 readonly trailing?: ReactNode;
136 readonly footer?: ReactNode;
137}) {
138 const { limits, now, dense = false } = props;
139 const color = useBarColor(props.driver);
140 if (!limits) return null;
141 const notice = limitsNotice(limits);
142 const padding = dense ? "px-4 py-3" : "p-4";
143 return (
144 <View
145 className={
146 props.first ? `gap-3 ${padding}` : `gap-3 border-t border-border-subtle ${padding}`
147 }
148 >
149 <View className="flex-row items-center gap-2">
150 <ProviderIcon provider={props.driver} size={16} />
151 <View className="min-w-0 flex-1 flex-row items-baseline gap-2">
152 <Text className="text-base font-t3-medium text-foreground">{props.label}</Text>
153 {props.instanceLabel !== props.label ? (
154 <AccountInstanceLabel key={props.instanceLabel} value={props.instanceLabel} />
155 ) : null}
156 {props.detail ? (
157 <Text className="shrink text-sm text-foreground-muted" numberOfLines={1}>
158 · {props.detail}
159 </Text>
160 ) : null}
161 </View>
162 {props.trailing}
163 </View>
164 {notice ? (
165 <Text className="text-sm text-foreground-muted">{notice}</Text>
166 ) : (
167 <View className="gap-3">
168 {limits.windows.map((window) => (
169 <WindowRow key={window.id} window={window} color={color} now={now} />
170 ))}
171 </View>
172 )}
173 {props.footer}
174 </View>
175 );
177​
178const OUTCOME_TEXT: Record<ProviderConsumeResetCreditOutcome, string> = {
179 reset: "Reset applied. Your windows have cleared.",
180 nothingToReset: "Nothing to reset right now.",
181 noCredit: "No reset credit left.",
182 alreadyRedeemed: "That credit was already redeemed.",
183};
184​
185/**
186 * Banked reset credits with a confirmed redeem action. Redeeming spends a
187 * credit the provider granted the user, so it goes through the native
188 * confirm alert rather than firing on a bare tap.
189 */
190export function ResetCredits(props: {
191 readonly environmentId: EnvironmentId;
192 readonly input: ProviderConsumeResetCreditInput;
193 readonly credits: ServerProviderResetCredits;
194 readonly now: number;
195 /** A smaller pill for the composer card. */
196 readonly dense?: boolean;
197}) {
198 const { environmentId, input, credits, now, dense = false } = props;
199 const consume = useAtomCommand(serverEnvironment.consumeResetCredit, {
200 reportFailure: false,
201 });
202 const [busy, setBusy] = useState(false);
203 const [status, setStatus] = useState<string | null>(null);
204 if (dense && credits.availableCount === 0 && status === null) return null;
205​
206 const expiresIn = credits.nextExpiresAt
207 ? formatDuration(Date.parse(credits.nextExpiresAt) - now)
208 : null;
209 const summary =
210 credits.availableCount === 0
211 ? "No reset credits banked"
212 : `${credits.availableCount} ${credits.availableCount === 1 ? "reset credit" : "reset credits"} banked${
213 expiresIn ? ` · next expires in ${expiresIn}` : ""
214 }`;
215​
216 const redeem = async () => {
217 setBusy(true);
218 setStatus(null);
219 const result = await consume({ environmentId, input });
220 setBusy(false);
221 if (result._tag === "Success") {
222 setStatus(result.value.warning ?? OUTCOME_TEXT[result.value.outcome]);
223 return;
224 }
225 setStatus(
226 "error" in result.cause && result.cause.error instanceof Error
227 ? result.cause.error.message
228 : "Could not use the reset credit.",
229 );
230 };
231​
232 const confirm = () => {
233 Alert.alert(
234 "Use a reset credit?",
235 "This redeems one credit on your account and clears the current rate-limit windows. It cannot be undone.",
236 [
237 { text: "Cancel", style: "cancel" },
238 { text: "Use credit", onPress: () => void redeem() },
239 ],
240 );
241 };
242​
243 return (
244 <View className="flex-row flex-wrap items-center gap-x-3 gap-y-1">
245 <Text className="text-xs tabular-nums text-foreground-tertiary">{summary}</Text>
246 {credits.availableCount > 0 ? (
247 <Pressable
248 accessibilityRole="button"
249 accessibilityState={{ disabled: busy }}
250 disabled={busy}
251 onPress={confirm}
252 className={
253 dense
254 ? "rounded-full bg-subtle-strong px-2.5 py-1"
255 : "min-h-[44px] justify-center rounded-full bg-subtle-strong px-3 py-1.5"
256 }
257 >
258 <Text
259 className={
260 dense
261 ? "text-xs font-t3-medium text-foreground"
262 : "text-sm font-t3-medium text-foreground"
263 }
264 >
265 {busy ? "Using…" : "Use reset"}
266 </Text>
267 </Pressable>
268 ) : null}
269 {status ? <Text className="text-sm text-foreground">{status}</Text> : null}
270 </View>
271 );
273​
274/**
275 * Re-probes every provider (and usage-limit source) on each connected
276 * environment; the fresh snapshots then arrive over the config stream.
277 * Countdowns and pace anchor to `now` rather than ticking, so a refresh also
278 * re-anchors the clock: quota and elapsed time move together, or not at all.
279 * Environments whose probe failed are named, since their rows keep showing
280 * the previous quota with nothing else to say so.
281 */
282export function useRefreshLimits(selectedEnvironmentIds: ReadonlySet<EnvironmentId> | null = null) {
283 const presentations = useAtomValue(environmentPresentations.presentationsAtom);
284 const refreshProviders = useAtomCommand(serverEnvironment.refreshProviders, {
285 reportFailure: false,
286 });
287 const [now, setNow] = useState(() => Date.now());
288 const [refreshing, setRefreshing] = useState(false);
289 const [failedEnvironments, setFailedEnvironments] = useState<
290 readonly { environmentId: EnvironmentId; label: string }[]
291 >([]);
292 // Always toggles `refreshing`, even with nothing to probe: Android's
293 // RefreshControl keeps its spinner up until it sees true then false.
294 const refresh = async () => {
295 const connected = [...presentations].filter(
296 ([environmentId, presentation]) =>
297 presentation.connection.phase === "connected" &&
298 (selectedEnvironmentIds === null || selectedEnvironmentIds.has(environmentId)),
299 );
300 setRefreshing(true);
301 try {
302 const results = await Promise.all(
303 connected.map(([environmentId]) => refreshProviders({ environmentId, input: {} })),
304 );
305 setFailedEnvironments(
306 connected
307 .filter((_, index) => results[index]?._tag === "Failure")
308 .map(([environmentId, presentation]) => ({
309 environmentId,
310 label: presentation.entry.target.label,
311 })),
312 );
313 } finally {
314 setNow(Date.now());
315 setRefreshing(false);
316 }
317 };
318 const failedLabels = failedEnvironments
319 .filter(
320 ({ environmentId }) =>
321 selectedEnvironmentIds === null || selectedEnvironmentIds.has(environmentId),
322 )
323 .map(({ label }) => label);
324 return { now, refreshing, failedLabels, refresh };