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

UsageLimitsSection.tsx

362 lines12.5 KB

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​
37function useBarColor(driver: Driver): string | null {
38 const colors = useProviderColors();
39 const kind: UsageProviderKind | null =
40 driver === "codex" ? "codex" : driver === "claudeAgent" ? "claude" : null;
41 return kind ? colors[kind] : null;
43​
44function WindowRow(props: {
45 readonly window: ServerProviderUsageWindow;
46 readonly color: string | null;
47 readonly now: number;
48}) {
49 const { window, now } = props;
50 const remaining = remainingPercent(window);
51 const elapsed = elapsedShare(window, now);
52 const timeLeft = elapsed === null ? null : Math.round((1 - elapsed) * 100);
53 const pace = paceOf(window, now);
54 const resetsIn = formatResetsIn(window, now);
55 return (
56 <View className="gap-1">
57 <View className="flex-row items-baseline justify-between gap-3">
58 <Text className="text-sm text-foreground">{window.label}</Text>
59 <Text className="text-sm font-t3-medium tabular-nums text-foreground">
60 {remaining}% left
61 </Text>
62 </View>
63 <View className="h-3 justify-center">
64 <View className="h-1.5 flex-row overflow-hidden rounded-full bg-subtle">
65 <View
66 className={
67 remaining <= 10
68 ? "h-full rounded-full bg-red-500"
69 : remaining <= 30
70 ? "h-full rounded-full bg-amber-500"
71 : "h-full rounded-full bg-foreground"
72 }
73 style={[
74 { flex: remaining },
75 remaining > 30 && props.color ? { backgroundColor: props.color } : null,
76 ]}
77 />
78 <View style={{ flex: 100 - remaining }} />
79 </View>
80 {timeLeft !== null ? (
81 <View
82 className="absolute top-0 bottom-0 w-px bg-foreground"
83 style={{ left: `${timeLeft}%`, opacity: 0.6 }}
84 />
85 ) : null}
86 </View>
87 {pace || resetsIn ? (
88 <View className="flex-row justify-between gap-3">
89 <Text className="text-xs text-foreground-tertiary">{pace ? PACE_LABEL[pace] : ""}</Text>
90 <Text className="text-xs tabular-nums text-foreground-tertiary">{resetsIn ?? ""}</Text>
91 </View>
92 ) : null}
93 </View>
94 );
96​
97function AccountInstanceLabel({ value }: { readonly value: string }) {
98 const [revealed, setRevealed] = useState(false);
99 if (!value.includes("@")) {
100 return (
101 <Text className="shrink text-xs text-foreground-tertiary" numberOfLines={1}>
102 · {value}
103 </Text>
104 );
105 }
106 return (
107 <Pressable
108 className="shrink active:opacity-60"
109 accessibilityRole="button"
110 accessibilityLabel={revealed ? "Hide account label" : "Reveal account label"}
111 onPress={() => setRevealed((current) => !current)}
112 >
113 <Text className="text-xs text-foreground-tertiary" numberOfLines={1}>
114 · {revealed ? value : "••••••@••••••"}
115 </Text>
116 </Pressable>
117 );
119​
120export function AccountLimits(props: {
121 readonly driver: Driver;
122 readonly label: string;
123 readonly instanceLabel: string;
124 readonly detail: string | undefined;
125 readonly limits: ServerProvider["usageLimits"];
126 readonly now: number;
127 readonly first: boolean;
128 readonly dense?: boolean;
129 readonly trailing?: ReactNode;
130 readonly footer?: ReactNode;
131}) {
132 const { limits, now, dense = false } = props;
133 const color = useBarColor(props.driver);
134 if (!limits) return null;
135 const notice = limitsNotice(limits);
136 const externalUsage = limits.externalUsage;
137 const padding = dense ? "px-4 py-3" : "p-4";
138 return (
139 <View
140 className={
141 props.first ? `gap-3 ${padding}` : `gap-3 border-t border-border-subtle ${padding}`
142 }
143 >
144 <View className="flex-row items-center gap-2">
145 <ProviderIcon provider={props.driver} size={16} />
146 <View className="min-w-0 flex-1 flex-row items-baseline gap-2">
147 <Text className="text-base font-t3-medium text-foreground">{props.label}</Text>
148 {props.instanceLabel !== props.label ? (
149 <AccountInstanceLabel key={props.instanceLabel} value={props.instanceLabel} />
150 ) : null}
151 {props.detail ? (
152 <Text className="shrink text-sm text-foreground-muted" numberOfLines={1}>
153 · {props.detail}
154 </Text>
155 ) : null}
156 </View>
157 {props.trailing}
158 </View>
159 {notice ? (
160 <Text className="text-sm text-foreground-muted">{notice}</Text>
161 ) : (
162 <View className="gap-3">
163 {limits.windows.map((window) => (
164 <WindowRow key={window.id} window={window} color={color} now={now} />
165 ))}
166 </View>
167 )}
168 {externalUsage ? (
169 <Pressable
170 accessibilityRole="link"
171 className="min-h-11 justify-center"
172 onPress={() => void Linking.openURL(externalUsage.url).catch(() => undefined)}
173 >
174 <Text className="text-sm font-t3-medium text-primary">Manage usage</Text>
175 </Pressable>
176 ) : null}
177 {props.footer}
178 </View>
179 );
181​
182const OUTCOME_TEXT: Record<ProviderConsumeResetCreditOutcome, string> = {
183 reset: "Reset applied. Your windows have cleared.",
184 nothingToReset: "Nothing to reset right now.",
185 noCredit: "No reset credit left.",
186 alreadyRedeemed: "That credit was already redeemed.",
187};
188​
189export function ResetCredits(props: {
190 readonly environmentId: EnvironmentId;
191 readonly input: ProviderConsumeResetCreditInput;
192 readonly credits: ServerProviderResetCredits;
193 readonly now: number;
194 readonly dense?: boolean;
195}) {
196 const { environmentId, input, credits, now, dense = false } = props;
197 const canManageProviders = useEnvironmentScope(environmentId, AuthProvidersManageScope);
198 const consume = useAtomCommand(serverEnvironment.consumeResetCredit, {
199 reportFailure: false,
200 });
201 const [busy, setBusy] = useState(false);
202 const [status, setStatus] = useState<string | null>(null);
203 if (dense && credits.availableCount === 0 && status === null) return null;
204​
205 const expiresIn = credits.nextExpiresAt
206 ? formatDuration(Date.parse(credits.nextExpiresAt) - now)
207 : null;
208 const summary =
209 credits.availableCount === 0
210 ? "No reset credits banked"
211 : `${credits.availableCount} ${credits.availableCount === 1 ? "reset credit" : "reset credits"} banked${
212 expiresIn ? ` · next expires in ${expiresIn}` : ""
213 }`;
214​
215 const redeem = async () => {
216 if (!readEnvironmentScope(environmentId, AuthProvidersManageScope)) return;
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 if (!readEnvironmentScope(environmentId, AuthProvidersManageScope)) return;
234 Dialog.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 || !canManageProviders }}
251 disabled={busy || !canManageProviders}
252 onPress={confirm}
253 className={
254 dense
255 ? "rounded-full bg-subtle-strong px-2.5 py-1 disabled:opacity-[0.45]"
256 : "min-h-[44px] justify-center rounded-full bg-subtle-strong px-3 py-1.5 disabled:opacity-[0.45]"
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 {!canManageProviders ? (
271 <Text className="text-xs text-foreground-tertiary">
272 This connection cannot manage provider accounts.
273 </Text>
274 ) : null}
275 {status ? <Text className="text-sm text-foreground">{status}</Text> : null}
276 </View>
277 );
279​
280export function useRefreshLimits(
281 selectedEnvironmentIds: ReadonlySet<EnvironmentId> | null = null,
282 active = false,
283) {
284 const presentations = useAtomValue(environmentPresentations.presentationsAtom);
285 const refreshProviders = useAtomCommand(serverEnvironment.refreshProviders, {
286 reportFailure: false,
287 });
288 const [now, setNow] = useState(() => Date.now());
289 const [refreshing, setRefreshing] = useState(false);
290 const refreshingRef = useRef(false);
291 const [failedEnvironments, setFailedEnvironments] = useState<
292 readonly { environmentId: EnvironmentId; label: string }[]
293 >([]);
294 const refresh = async (automatic = false, afterPending = false) => {
295 const connected = [...presentations].filter(
296 ([environmentId, presentation]) =>
297 presentation.connection.phase === "connected" &&
298 (selectedEnvironmentIds === null || selectedEnvironmentIds.has(environmentId)),
299 );
300 try {
301 await Promise.all(
302 connected.map(async ([environmentId, presentation]) => {
303 const result = await refreshUsageLimits(
304 environmentId,
305 () => refreshProviders({ environmentId, input: {} }),
306 automatic,
307 afterPending,
308 );
309 if (result === undefined) return;
310 setFailedEnvironments((previous) => [
311 ...previous.filter((failed) => failed.environmentId !== environmentId),
312 ...(result._tag === "Failure"
313 ? [{ environmentId, label: presentation.entry.target.label }]
314 : []),
315 ]);
316 }),
317 );
318 } finally {
319 setNow(Date.now());
320 }
321 };
322 // Always toggles `refreshing`, even with nothing to probe: Android's
323 // RefreshControl keeps its spinner up until it sees true then false.
324 const refreshManually = async () => {
325 if (refreshingRef.current) return;
326 refreshingRef.current = true;
327 setRefreshing(true);
328 try {
329 await refresh();
330 } finally {
331 refreshingRef.current = false;
332 setRefreshing(false);
333 }
334 };
335 const connectedLimitsEnvironments = [...presentations]
336 .filter(
337 ([environmentId, presentation]) =>
338 presentation.connection.phase === "connected" &&
339 (selectedEnvironmentIds === null || selectedEnvironmentIds.has(environmentId)),
340 )
341 .map(([environmentId]) => environmentId)
342 .sort()
343 .join(",");
344 const autoRefreshLimits = useEffectEvent(() => refresh(true));
345 useEffect(() => {
346 if (active && connectedLimitsEnvironments) void autoRefreshLimits();
347 }, [active, connectedLimitsEnvironments]);
348​
349 const failedLabels = failedEnvironments
350 .filter(
351 ({ environmentId }) =>
352 selectedEnvironmentIds === null || selectedEnvironmentIds.has(environmentId),
353 )
354 .map(({ label }) => label);
355 return {
356 now,
357 refreshing,
358 failedLabels,
359 refresh: refreshManually,
360 refreshAfterEnable: () => refresh(false, true),
361 };