Open History to see the last commit
1import * as Dialog from "../../components/ui/Dialog";
2import { RegistryContext, useAtomMount, useAtomValue } from "@effect/atom-react";
3import { normalizeProviderAccentColor } from "@t3tools/client-runtime/state/provider-instance-display";
4import {
5 AuthProvidersManageScope,
6 type EnvironmentId,
7 type ProviderConsumeResetCreditOutcome,
8 type ProviderConsumeResetCreditInput,
9 type ServerProvider,
10 type ServerProviderResetCredits,
11 type ServerProviderUsageWindow,
12} from "@t3tools/contracts";
13import {
14 formatDuration,
15 formatResetsIn,
16 limitsNotice,
17 paceOf,
18 paceRemainingPercent,
19 remainingPercent,
20} from "@t3tools/shared/usageLimits";
21import { type ReactNode, useContext, useRef, useState } from "react";
22import { Atom } from "effect/reactivity";
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 { useNowMinuteMs } from "../../lib/clock";
32import {
33 environmentIdsKey,
34 limitsAutoRefreshSetAtom,
35 limitsRefreshFailuresAtom,
36 refreshEnvironmentLimits,
37} from "./usageLimitsRefresh";
38import { usageProviderKind, useProviderColors } from "./usageProviders";
39
40const PACE_LABEL = { ahead: "ahead of pace", on: "on pace", under: "under pace" } as const;
41
42type Driver = ServerProvider["driver"];
43
44function useBarColor(driver: Driver): string | null {
45 const colors = useProviderColors();
46 const kind = usageProviderKind(driver);
47 return kind ? colors[kind] : null;
48}
49
50function WindowRow(props: {
51 readonly window: ServerProviderUsageWindow;
52 readonly color: string | null;
53 readonly now: number;
54}) {
55 const { window, now } = props;
56 const remaining = remainingPercent(window);
57 const timeLeft = paceRemainingPercent(window, now);
58 const pace = paceOf(window, now);
59 const resetsIn = formatResetsIn(window, now);
60 const [barWidth, setBarWidth] = useState(0);
61 const tickX =
62 timeLeft === null || barWidth < 6
63 ? null
64 : Math.min(Math.max((barWidth * timeLeft) / 100, 3), barWidth - 3);
65 const bar = (
66 <View
67 className="h-1.5 flex-row overflow-hidden rounded-full bg-subtle"
68 style={barWidth > 0 ? { width: barWidth } : undefined}
69 >
70 <View
71 className={
72 remaining <= 10
73 ? "h-full rounded-full bg-red-500"
74 : remaining <= 30
75 ? "h-full rounded-full bg-amber-500"
76 : "h-full rounded-full bg-foreground"
77 }
78 style={[
79 { flex: remaining },
80 remaining > 30 && props.color ? { backgroundColor: props.color } : null,
81 ]}
82 />
83 <View style={{ flex: 100 - remaining }} />
84 </View>
85 );
86 return (
87 <View className="gap-1">
88 <View className="flex-row items-baseline justify-between gap-3">
89 <Text className="text-sm text-foreground">{window.label}</Text>
90 <Text className="text-sm font-t3-medium tabular-nums text-foreground">
91 {remaining}% left
92 </Text>
93 </View>
94 <View
95 className="h-3 justify-center"
96 onLayout={(event) => setBarWidth(event.nativeEvent.layout.width)}
97 >
98 {tickX === null ? (
99 bar
100 ) : (
101 <View className="h-1.5">
102 {/* Clip the same full-width bar so neither fill proportions nor corner radii change. */}
103 {(
104 [
105 [0, tickX - 3],
106 [tickX + 3, barWidth],
107 ] as const
108 ).map(([start, end]) => (
109 <View
110 key={start}
111 className="absolute top-0 bottom-0 overflow-hidden"
112 style={{ left: start, width: end - start }}
113 >
114 <View style={{ marginLeft: -start }}>{bar}</View>
115 </View>
116 ))}
117 </View>
118 )}
119 {tickX !== null ? (
120 <View
121 className="absolute top-px bottom-px w-0.5 rounded-full bg-foreground"
122 style={{ left: tickX - 1 }}
123 />
124 ) : null}
125 </View>
126 {pace || resetsIn ? (
127 <View className="flex-row justify-between gap-3">
128 <Text className="text-xs text-foreground-tertiary">{pace ? PACE_LABEL[pace] : ""}</Text>
129 <Text className="text-xs tabular-nums text-foreground-tertiary">{resetsIn ?? ""}</Text>
130 </View>
131 ) : null}
132 </View>
133 );
134}
135
136function AccountInstanceLabel({ value }: { readonly value: string }) {
137 const [revealed, setRevealed] = useState(false);
138 if (!value.includes("@")) {
139 return (
140 <Text className="shrink text-xs text-foreground-tertiary" numberOfLines={1}>
141 · {value}
142 </Text>
143 );
144 }
145 return (
146 <Pressable
147 className="shrink active:opacity-60"
148 accessibilityRole="button"
149 accessibilityLabel={revealed ? "Hide account label" : "Reveal account label"}
150 onPress={() => setRevealed((current) => !current)}
151 >
152 <Text className="text-xs text-foreground-tertiary" numberOfLines={1}>
153 · {revealed ? value : "••••••@••••••"}
154 </Text>
155 </Pressable>
156 );
157}
158
159export function AccountLimits(props: {
160 readonly driver: Driver;
161 readonly accentColor?: string | undefined;
162 readonly label: string;
163 readonly instanceLabel: string;
164 readonly detail: string | undefined;
165 readonly limits: ServerProvider["usageLimits"];
166 readonly now: number;
167 readonly first: boolean;
168 readonly dense?: boolean;
169 readonly trailing?: ReactNode;
170 readonly footer?: ReactNode;
171}) {
172 const { limits, now, dense = false } = props;
173 const providerColor = useBarColor(props.driver);
174 const color = normalizeProviderAccentColor(props.accentColor) ?? providerColor;
175 if (!limits) return null;
176 const notice = limitsNotice(limits);
177 const externalUsage = limits.externalUsage;
178 const padding = dense ? "px-4 py-3" : "p-4";
179 return (
180 <View
181 className={
182 props.first ? `gap-3 ${padding}` : `gap-3 border-t border-border-subtle ${padding}`
183 }
184 >
185 <View className="flex-row items-center gap-2">
186 <ProviderIcon provider={props.driver} size={16} />
187 <View className="min-w-0 flex-1 flex-row items-baseline gap-2">
188 <Text className="text-base font-t3-medium text-foreground">{props.label}</Text>
189 {props.instanceLabel !== props.label ? (
190 <AccountInstanceLabel key={props.instanceLabel} value={props.instanceLabel} />
191 ) : null}
192 {props.detail ? (
193 <Text className="shrink text-sm text-foreground-muted" numberOfLines={1}>
194 · {props.detail}
195 </Text>
196 ) : null}
197 </View>
198 {props.trailing}
199 </View>
200 {notice ? (
201 <Text className="text-sm text-foreground-muted">{notice}</Text>
202 ) : (
203 <View className="gap-3">
204 {limits.windows.map((window) => (
205 <WindowRow key={window.id} window={window} color={color} now={now} />
206 ))}
207 </View>
208 )}
209 {externalUsage ? (
210 <Pressable
211 accessibilityRole="link"
212 className="min-h-11 justify-center"
213 onPress={() => void Linking.openURL(externalUsage.url).catch(() => undefined)}
214 >
215 <Text className="text-sm font-t3-medium text-primary">Manage usage</Text>
216 </Pressable>
217 ) : null}
218 {props.footer}
219 </View>
220 );
221}
222
223const OUTCOME_TEXT: Record<ProviderConsumeResetCreditOutcome, string> = {
224 reset: "Reset applied. Your windows have cleared.",
225 nothingToReset: "Nothing to reset right now.",
226 noCredit: "No reset credit left.",
227 alreadyRedeemed: "That credit was already redeemed.",
228};
229
230export function ResetCredits(props: {
231 readonly environmentId: EnvironmentId;
232 readonly input: ProviderConsumeResetCreditInput;
233 readonly credits: ServerProviderResetCredits;
234 readonly now: number;
235 readonly dense?: boolean;
236}) {
237 const { environmentId, input, credits, now, dense = false } = props;
238 const canManageProviders = useEnvironmentScope(environmentId, AuthProvidersManageScope);
239 const consume = useAtomCommand(serverEnvironment.consumeResetCredit, {
240 reportFailure: false,
241 });
242 const [busy, setBusy] = useState(false);
243 const [status, setStatus] = useState<string | null>(null);
244 if (dense && credits.availableCount === 0 && status === null) return null;
245
246 const expiresIn = credits.nextExpiresAt
247 ? formatDuration(Date.parse(credits.nextExpiresAt) - now)
248 : null;
249 const summary =
250 credits.availableCount === 0
251 ? "No reset credits banked"
252 : `${credits.availableCount} ${credits.availableCount === 1 ? "reset credit" : "reset credits"} banked${
253 expiresIn ? ` · next expires in ${expiresIn}` : ""
254 }`;
255
256 const redeem = async () => {
257 if (!readEnvironmentScope(environmentId, AuthProvidersManageScope)) return;
258 setBusy(true);
259 setStatus(null);
260 const result = await consume({ environmentId, input });
261 setBusy(false);
262 if (result._tag === "Success") {
263 setStatus(result.value.warning ?? OUTCOME_TEXT[result.value.outcome]);
264 return;
265 }
266 setStatus(
267 "error" in result.cause && result.cause.error instanceof Error
268 ? result.cause.error.message
269 : "Could not use the reset credit.",
270 );
271 };
272
273 const confirm = () => {
274 if (!readEnvironmentScope(environmentId, AuthProvidersManageScope)) return;
275 Dialog.alert(
276 "Use a reset credit?",
277 "This redeems one credit on your account and clears the current rate-limit windows. It cannot be undone.",
278 [
279 { text: "Cancel", style: "cancel" },
280 { text: "Use credit", onPress: () => void redeem() },
281 ],
282 );
283 };
284
285 return (
286 <View className="flex-row flex-wrap items-center gap-x-3 gap-y-1">
287 <Text className="text-xs tabular-nums text-foreground-tertiary">{summary}</Text>
288 {credits.availableCount > 0 ? (
289 <Pressable
290 accessibilityRole="button"
291 accessibilityState={{ disabled: busy || !canManageProviders }}
292 disabled={busy || !canManageProviders}
293 onPress={confirm}
294 className={
295 dense
296 ? "rounded-full bg-subtle-strong px-2.5 py-1 disabled:opacity-[0.45]"
297 : "min-h-[44px] justify-center rounded-full bg-subtle-strong px-3 py-1.5 disabled:opacity-[0.45]"
298 }
299 >
300 <Text
301 className={
302 dense
303 ? "text-xs font-t3-medium text-foreground"
304 : "text-sm font-t3-medium text-foreground"
305 }
306 >
307 {busy ? "Using…" : "Use reset"}
308 </Text>
309 </Pressable>
310 ) : null}
311 {!canManageProviders ? (
312 <Text className="text-xs text-foreground-tertiary">
313 This connection cannot manage provider accounts.
314 </Text>
315 ) : null}
316 {status ? <Text className="text-sm text-foreground">{status}</Text> : null}
317 </View>
318 );
319}
320
321const IDLE_ATOM = Atom.make(undefined);
322
323export function useRefreshLimits(
324 selectedEnvironmentIds: ReadonlySet<EnvironmentId> | null = null,
325 active = false,
326) {
327 const registry = useContext(RegistryContext);
328 const presentations = useAtomValue(environmentPresentations.presentationsAtom);
329 const now = useNowMinuteMs();
330 const [refreshing, setRefreshing] = useState(false);
331 const refreshingRef = useRef(false);
332 const selected = [...presentations].filter(
333 ([environmentId]) =>
334 selectedEnvironmentIds === null || selectedEnvironmentIds.has(environmentId),
335 );
336 const connectedIds = selected
337 .filter(([, presentation]) => presentation.connection.phase === "connected")
338 .map(([environmentId]) => environmentId);
339 const connectedKey = environmentIdsKey(connectedIds);
340 useAtomMount(active && connectedKey !== "" ? limitsAutoRefreshSetAtom(connectedKey) : IDLE_ATOM);
341 const failedIds = new Set(
342 useAtomValue(limitsRefreshFailuresAtom(environmentIdsKey(selected.map(([id]) => id)))),
343 );
344 const failedLabels = selected
345 .filter(([environmentId]) => failedIds.has(environmentId))
346 .map(([, presentation]) => presentation.entry.target.label);
347
348 const refresh = (afterPending: boolean) =>
349 Promise.all(
350 connectedIds.map((environmentId) =>
351 refreshEnvironmentLimits(registry, environmentId, { afterPending }),
352 ),
353 );
354 // Android RefreshControl needs a true-to-false cycle to stop, even with nothing to probe.
355 const refreshManually = async () => {
356 if (refreshingRef.current) return;
357 refreshingRef.current = true;
358 setRefreshing(true);
359 await refresh(false).finally(() => {
360 refreshingRef.current = false;
361 setRefreshing(false);
362 });
363 };
364 return {
365 now,
366 refreshing,
367 failedLabels,
368 refresh: refreshManually,
369 refreshAfterEnable: () => refresh(true),
370 };
371}