Open History to see the last commit
1import {
2 AuthProvidersManageScope,
3 type EnvironmentId,
4 type ProviderConsumeResetCreditOutcome,
5 ProviderConsumeResetCreditInput,
6 ServerProvider,
7 ServerProviderResetCredits,
8 ServerProviderUsageWindow,
9 UsageProviderKind,
10} from "@t3tools/contracts";
11import { useAtomValue } from "@effect/atom-react";
12import {
13 formatDuration,
14 formatResetsIn,
15 type LimitPace,
16 paceOf,
17 paceRemainingPercent,
18 remainingPercent,
19} from "@t3tools/shared/usageLimits";
20import { GaugeIcon, TrendingDownIcon, TrendingUpIcon } from "lucide-react";
21import { Fragment, type ReactNode, useLayoutEffect, useState } from "react";
22
23import { usePrimarySettings } from "../../hooks/useSettings";
24import { observeResize } from "../../lib/observeResize";
25import { environmentPresentations } from "../../state/presentation";
26import { useEnvironmentScope, readEnvironmentScope } from "../../state/session";
27import { serverEnvironment } from "../../state/server";
28import { useAtomCommand } from "../../state/use-atom-command";
29import { formatUpcomingTimestamp } from "../../timestampFormat";
30import {
31 AlertDialog,
32 AlertDialogClose,
33 AlertDialogDescription,
34 AlertDialogFooter,
35 AlertDialogHeader,
36 AlertDialogPopup,
37 AlertDialogTitle,
38} from "../ui/alert-dialog";
39import { Button } from "../ui/button";
40import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
41import { UsageLimitsPooled } from "./UsageLimitsPooled";
42import { PROVIDER_PRESENTATION } from "./usageProviders";
43
44const PACE: Record<LimitPace, { readonly label: string; readonly icon: typeof GaugeIcon }> = {
45 ahead: { label: "Ahead of pace: spending faster than the window elapses", icon: TrendingUpIcon },
46 on: { label: "On pace with the window", icon: GaugeIcon },
47 under: { label: "Under pace: headroom left for the rest of the window", icon: TrendingDownIcon },
48};
49
50export function barColor(driver: ServerProvider["driver"]): string {
51 const presentation = Object.values(PROVIDER_PRESENTATION).find(
52 (entry) => entry.driverKind === driver,
53 );
54 return presentation?.color ?? "var(--foreground)";
55}
56
57export function PaceIcon({ pace }: { readonly pace: LimitPace }) {
58 const Icon = PACE[pace].icon;
59 return (
60 <Tooltip>
61 <TooltipTrigger
62 render={
63 <span
64 role="img"
65 aria-label={PACE[pace].label}
66 className="inline-flex text-muted-foreground"
67 />
68 }
69 >
70 <Icon className="size-3.5" aria-hidden />
71 </TooltipTrigger>
72 <TooltipPopup side="top">{PACE[pace].label}</TooltipPopup>
73 </Tooltip>
74 );
75}
76
77// The tick sits in a transparent gap cut from the bar, clamped so it stays inside at 0% and 100%.
78// The gap is a clip-path slot rather than a mask: a mask composites its layer and re-antialiases
79// the bar's rounded ends, and the polygon reaches 1px past the box so only the slot edges clip.
80function paceMarkStyles(timeLeft: number | null) {
81 if (timeLeft === null) return null;
82 const at = `clamp(3px, ${timeLeft}%, calc(100% - 3px))`;
83 const [left, right] = [`calc(${at} - 3px)`, `calc(${at} + 3px)`];
84 const [near, far] = ["-1px", "calc(100% + 1px)"];
85 return {
86 tick: { left: at },
87 gap: {
88 clipPath: `polygon(${near} ${near}, ${left} ${near}, ${left} ${far}, ${right} ${far}, ${right} ${near}, ${far} ${near}, ${far} ${far}, ${near} ${far})`,
89 },
90 // For a track painted on an element that also draws focus rings, which a clip would cut.
91 gappedTrack: {
92 backgroundColor: "transparent",
93 backgroundImage: `linear-gradient(to right, var(--color-muted) ${left}, transparent ${left}, transparent ${right}, var(--color-muted) ${right})`,
94 },
95 };
96}
97
98/**
99 * Pace mark styles for the bar given the returned ref. Below 6px there is no room for the gap
100 * and tick, so the bar draws neither, as the mobile bars do.
101 */
102export function usePaceMark(timeLeft: number | null) {
103 const [bar, setBar] = useState<HTMLElement | null>(null);
104 const [roomy, setRoomy] = useState(false);
105 useLayoutEffect(() => {
106 if (!bar) return;
107 const measure = () => setRoomy(bar.getBoundingClientRect().width >= 6);
108 measure();
109 return observeResize(bar, measure);
110 }, [bar]);
111 return [setBar, roomy ? paceMarkStyles(timeLeft) : null] as const;
112}
113
114function WindowBar({
115 color,
116 window,
117 now,
118}: {
119 readonly color: string;
120 readonly window: ServerProviderUsageWindow;
121 readonly now: number;
122}) {
123 const timestampFormat = usePrimarySettings((settings) => settings.timestampFormat);
124 const remaining = remainingPercent(window);
125 const timeLeft = paceRemainingPercent(window, now);
126 const [barRef, paceMark] = usePaceMark(timeLeft);
127 const resetsIn = formatResetsIn(window, now);
128 const resetsAt = window.resetsAt
129 ? formatUpcomingTimestamp(window.resetsAt, timestampFormat, now)
130 : null;
131 const summary = `${window.label}: ${remaining}% left${
132 timeLeft === null ? "" : `, ${timeLeft}% of the window left`
133 }${resetsIn ? `, ${resetsIn}` : ""}`;
134
135 return (
136 <Tooltip>
137 <TooltipTrigger
138 render={
139 <div
140 ref={barRef}
141 role="img"
142 aria-label={summary}
143 tabIndex={0}
144 className="relative h-6 cursor-default rounded-full outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background"
145 />
146 }
147 >
148 {/* Clip both layers so the gap exposes even a translucent composer surface. */}
149 <div className="absolute inset-0" style={paceMark?.gap}>
150 <div className="absolute inset-x-0 inset-y-1.5 rounded-full bg-muted" />
151 {remaining > 0 ? (
152 <div
153 className="absolute inset-y-1.5 left-0 rounded-full"
154 style={{ width: `${remaining}%`, backgroundColor: color }}
155 />
156 ) : null}
157 </div>
158 {paceMark ? (
159 <span
160 aria-hidden
161 className="absolute inset-y-1 w-0.5 -translate-x-1/2 rounded-full bg-foreground"
162 style={paceMark.tick}
163 />
164 ) : null}
165 </TooltipTrigger>
166 <TooltipPopup side="top">
167 <div className="flex flex-col gap-0.5">
168 <span className="text-foreground">
169 {remaining}% left{timeLeft !== null ? ` · ${timeLeft}% of the window left` : ""}
170 </span>
171 {timeLeft !== null ? (
172 <span className="text-muted-foreground">The line is where even spending would be.</span>
173 ) : null}
174 {resetsAt ? (
175 <span className="text-muted-foreground">
176 Resets {resetsAt}
177 {resetsIn ? ` · ${resetsIn}` : ""}
178 </span>
179 ) : null}
180 </div>
181 </TooltipPopup>
182 </Tooltip>
183 );
184}
185
186export function LimitWindows({
187 driver,
188 windows,
189 now,
190 compact = false,
191}: {
192 readonly driver: ServerProvider["driver"];
193 readonly windows: ReadonlyArray<ServerProviderUsageWindow>;
194 readonly now: number;
195 readonly compact?: boolean;
196}) {
197 const color = barColor(driver);
198 return (
199 <div
200 className={
201 compact
202 ? "grid grid-cols-[minmax(0,9rem)_minmax(3rem,1fr)_auto] gap-x-3 gap-y-0.5"
203 : "grid grid-cols-[11rem_minmax(0,1fr)_7rem] gap-x-4 gap-y-1"
204 }
205 >
206 {windows.map((window) => {
207 const pace = paceOf(window, now);
208 const resetsIn = formatResetsIn(window, now);
209 return (
210 <Fragment key={window.id}>
211 <span className="flex min-w-0 items-center gap-2 text-xs">
212 <span className="truncate text-muted-foreground">{window.label}</span>
213 <span className="ms-auto shrink-0 font-medium text-foreground tabular-nums">
214 {remainingPercent(window)}% left
215 </span>
216 </span>
217 <WindowBar color={color} window={window} now={now} />
218 <span className="flex items-center gap-2 text-xs whitespace-nowrap text-muted-foreground tabular-nums">
219 {pace ? <PaceIcon pace={pace} /> : null}
220 <span className="ms-auto shrink-0">{resetsIn ?? ""}</span>
221 </span>
222 </Fragment>
223 );
224 })}
225 </div>
226 );
227}
228
229const OUTCOME_TEXT: Record<ProviderConsumeResetCreditOutcome, string> = {
230 reset: "Reset applied. Your windows have cleared.",
231 nothingToReset: "Nothing to reset right now.",
232 noCredit: "No reset credit left.",
233 alreadyRedeemed: "That credit was already redeemed.",
234};
235
236export function useResetCredit(
237 environmentId: EnvironmentId,
238 input: ProviderConsumeResetCreditInput,
239) {
240 const canManageProviders = useEnvironmentScope(environmentId, AuthProvidersManageScope);
241 const consume = useAtomCommand(serverEnvironment.consumeResetCredit, { reportFailure: false });
242 const [confirming, setConfirming] = useState(false);
243 const [busy, setBusy] = useState(false);
244 const [status, setStatus] = useState<string | null>(null);
245
246 const redeem = async () => {
247 setConfirming(false);
248 if (!readEnvironmentScope(environmentId, AuthProvidersManageScope)) return;
249 setBusy(true);
250 setStatus(null);
251 const result = await consume({ environmentId, input });
252 setBusy(false);
253 if (result._tag === "Success") {
254 setStatus(result.value.warning ?? OUTCOME_TEXT[result.value.outcome]);
255 return;
256 }
257 setStatus(
258 "error" in result.cause && result.cause.error instanceof Error
259 ? result.cause.error.message
260 : "Could not use the reset credit.",
261 );
262 };
263
264 return { canManageProviders, confirming, setConfirming, busy, status, redeem };
265}
266
267/**
268 * Redeeming spends a credit the provider granted the user, so it never fires on a bare click.
269 * Mount it outside any popover that holds the button: dialogs stack under popovers, and closing
270 * the popover would unmount a dialog rendered inside it.
271 */
272export function ResetCreditDialog({
273 open,
274 onOpenChange,
275 onConfirm,
276 disabled = false,
277}: {
278 readonly open: boolean;
279 readonly onOpenChange: (open: boolean) => void;
280 readonly onConfirm: () => void;
281 readonly disabled?: boolean;
282}) {
283 return (
284 <AlertDialog open={open} onOpenChange={onOpenChange}>
285 <AlertDialogPopup>
286 <AlertDialogHeader>
287 <AlertDialogTitle>Use a reset credit?</AlertDialogTitle>
288 <AlertDialogDescription>
289 This redeems one credit on your account and clears the current rate-limit windows. It
290 cannot be undone.
291 </AlertDialogDescription>
292 </AlertDialogHeader>
293 <AlertDialogFooter>
294 <AlertDialogClose render={<Button variant="outline" />}>Cancel</AlertDialogClose>
295 <Button disabled={disabled} onClick={onConfirm}>
296 Use credit
297 </Button>
298 </AlertDialogFooter>
299 </AlertDialogPopup>
300 </AlertDialog>
301 );
302}
303
304export function resetCreditsSummary(
305 credits: ServerProviderResetCredits,
306 now: number,
307 compact = false,
308): string {
309 const expiresIn = credits.nextExpiresAt
310 ? formatDuration(Date.parse(credits.nextExpiresAt) - now)
311 : null;
312 if (credits.availableCount === 0) return "No reset credits banked";
313 if (compact)
314 return `${credits.availableCount} banked${expiresIn ? ` · expires in ${expiresIn}` : ""}`;
315 return `${credits.availableCount} ${credits.availableCount === 1 ? "reset credit" : "reset credits"} banked${
316 expiresIn ? ` · next expires in ${expiresIn}` : ""
317 }`;
318}
319
320export function ResetCredits({
321 environmentId,
322 input,
323 credits,
324 now,
325}: {
326 readonly environmentId: EnvironmentId;
327 readonly input: ProviderConsumeResetCreditInput;
328 readonly credits: ServerProviderResetCredits;
329 readonly now: number;
330}) {
331 const { canManageProviders, confirming, setConfirming, busy, status, redeem } = useResetCredit(
332 environmentId,
333 input,
334 );
335 if (credits.availableCount === 0 && status === null) return null;
336 return (
337 <div className="flex flex-wrap items-center gap-x-3 gap-y-1 text-xs text-muted-foreground">
338 <span className="tabular-nums">{resetCreditsSummary(credits, now)}</span>
339 {credits.availableCount > 0 ? (
340 <Button
341 size="xs"
342 variant="outline"
343 disabled={busy || !canManageProviders}
344 onClick={() => {
345 if (readEnvironmentScope(environmentId, AuthProvidersManageScope)) setConfirming(true);
346 }}
347 >
348 {busy ? "Using…" : "Use reset"}
349 </Button>
350 ) : null}
351 {status ? <span className="text-foreground">{status}</span> : null}
352 <ResetCreditDialog
353 open={confirming}
354 onOpenChange={setConfirming}
355 onConfirm={() => void redeem()}
356 disabled={!canManageProviders}
357 />
358 </div>
359 );
360}
361
362/**
363 * The page advances `now` on explicit refresh rather than ticking: a live clock would repaint the
364 * page for no decision-changing gain.
365 */
366export function UsageLimitsSection({
367 selectedEnvironmentIds,
368 hiddenProviders,
369 now,
370 cursorPrompt,
371}: {
372 readonly selectedEnvironmentIds: ReadonlySet<EnvironmentId> | null;
373 readonly hiddenProviders: ReadonlySet<UsageProviderKind>;
374 readonly now: number;
375 readonly cursorPrompt?: ReactNode;
376}) {
377 const presentations = useAtomValue(environmentPresentations.presentationsWithProvidersAtom);
378 const hiddenDrivers = new Set<ServerProvider["driver"]>(
379 [...hiddenProviders].map((provider) => PROVIDER_PRESENTATION[provider].driverKind),
380 );
381 const isVisible = (driver: ServerProvider["driver"]) => !hiddenDrivers.has(driver);
382 const selected = new Map(
383 [...presentations].flatMap(([id, presentation]) => {
384 if (selectedEnvironmentIds !== null && !selectedEnvironmentIds.has(id)) return [];
385 const config = presentation.serverConfig;
386 if (hiddenDrivers.size === 0 || config === null) return [[id, presentation] as const];
387 return [
388 [
389 id,
390 {
391 ...presentation,
392 serverConfig: {
393 ...config,
394 providers: config.providers.filter((provider) => isVisible(provider.driver)),
395 usageLimitSources: config.usageLimitSources?.flatMap((source) => {
396 const accounts = source.accounts.filter((account) => isVisible(account.driver));
397 return accounts.length === 0 && source.accounts.length > 0
398 ? []
399 : [{ ...source, accounts }];
400 }),
401 },
402 },
403 ] as const,
404 ];
405 }),
406 );
407 return <UsageLimitsPooled presentations={selected} now={now} cursorPrompt={cursorPrompt} />;
408}