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 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- measures the bar DOM width before paint and remeasures through a ResizeObserver
106 useLayoutEffect(() => {
107 if (!bar) return;
108 const measure = () => setRoomy(bar.getBoundingClientRect().width >= 6);
109 measure();
110 return observeResize(bar, measure);
111 }, [bar]);
112 return [setBar, roomy ? paceMarkStyles(timeLeft) : null] as const;
113}
114
115function WindowBar({
116 color,
117 window,
118 now,
119}: {
120 readonly color: string;
121 readonly window: ServerProviderUsageWindow;
122 readonly now: number;
123}) {
124 const timestampFormat = usePrimarySettings((settings) => settings.timestampFormat);
125 const remaining = remainingPercent(window);
126 const timeLeft = paceRemainingPercent(window, now);
127 const [barRef, paceMark] = usePaceMark(timeLeft);
128 const resetsIn = formatResetsIn(window, now);
129 const resetsAt = window.resetsAt
130 ? formatUpcomingTimestamp(window.resetsAt, timestampFormat, now)
131 : null;
132 const summary = `${window.label}: ${remaining}% left${
133 timeLeft === null ? "" : `, ${timeLeft}% of the window left`
134 }${resetsIn ? `, ${resetsIn}` : ""}`;
135
136 return (
137 <Tooltip>
138 <TooltipTrigger
139 render={
140 <div
141 ref={barRef}
142 role="img"
143 aria-label={summary}
144 tabIndex={0}
145 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"
146 />
147 }
148 >
149 {/* Clip both layers so the gap exposes even a translucent composer surface. */}
150 <div className="absolute inset-0" style={paceMark?.gap}>
151 <div className="absolute inset-x-0 inset-y-1.5 rounded-full bg-muted" />
152 {remaining > 0 ? (
153 <div
154 className="absolute inset-y-1.5 left-0 rounded-full"
155 style={{ width: `${remaining}%`, backgroundColor: color }}
156 />
157 ) : null}
158 </div>
159 {paceMark ? (
160 <span
161 aria-hidden
162 className="absolute inset-y-1 w-0.5 -translate-x-1/2 rounded-full bg-foreground"
163 style={paceMark.tick}
164 />
165 ) : null}
166 </TooltipTrigger>
167 <TooltipPopup side="top">
168 <div className="flex flex-col gap-0.5">
169 <span className="text-foreground">
170 {remaining}% left{timeLeft !== null ? ` · ${timeLeft}% of the window left` : ""}
171 </span>
172 {timeLeft !== null ? (
173 <span className="text-muted-foreground">The line is where even spending would be.</span>
174 ) : null}
175 {resetsAt ? (
176 <span className="text-muted-foreground">
177 Resets {resetsAt}
178 {resetsIn ? ` · ${resetsIn}` : ""}
179 </span>
180 ) : null}
181 </div>
182 </TooltipPopup>
183 </Tooltip>
184 );
185}
186
187export function LimitWindows({
188 driver,
189 windows,
190 now,
191 compact = false,
192}: {
193 readonly driver: ServerProvider["driver"];
194 readonly windows: ReadonlyArray<ServerProviderUsageWindow>;
195 readonly now: number;
196 readonly compact?: boolean;
197}) {
198 const color = barColor(driver);
199 return (
200 <div
201 className={
202 compact
203 ? "grid grid-cols-[minmax(0,9rem)_minmax(3rem,1fr)_auto] gap-x-3 gap-y-0.5"
204 : "grid grid-cols-[11rem_minmax(0,1fr)_7rem] gap-x-4 gap-y-1"
205 }
206 >
207 {windows.map((window) => {
208 const pace = paceOf(window, now);
209 const resetsIn = formatResetsIn(window, now);
210 return (
211 <Fragment key={window.id}>
212 <span className="flex min-w-0 items-center gap-2 text-xs">
213 <span className="truncate text-muted-foreground">{window.label}</span>
214 <span className="ms-auto shrink-0 font-medium text-foreground tabular-nums">
215 {remainingPercent(window)}% left
216 </span>
217 </span>
218 <WindowBar color={color} window={window} now={now} />
219 <span className="flex items-center gap-2 text-xs whitespace-nowrap text-muted-foreground tabular-nums">
220 {pace ? <PaceIcon pace={pace} /> : null}
221 <span className="ms-auto shrink-0">{resetsIn ?? ""}</span>
222 </span>
223 </Fragment>
224 );
225 })}
226 </div>
227 );
228}
229
230const OUTCOME_TEXT: Record<ProviderConsumeResetCreditOutcome, string> = {
231 reset: "Reset applied. Your windows have cleared.",
232 nothingToReset: "Nothing to reset right now.",
233 noCredit: "No reset credit left.",
234 alreadyRedeemed: "That credit was already redeemed.",
235};
236
237export function useResetCredit(
238 environmentId: EnvironmentId,
239 input: ProviderConsumeResetCreditInput,
240) {
241 const canManageProviders = useEnvironmentScope(environmentId, AuthProvidersManageScope);
242 const consume = useAtomCommand(serverEnvironment.consumeResetCredit, { reportFailure: false });
243 const [confirming, setConfirming] = useState(false);
244 const [busy, setBusy] = useState(false);
245 const [status, setStatus] = useState<string | null>(null);
246
247 const redeem = async () => {
248 setConfirming(false);
249 if (!readEnvironmentScope(environmentId, AuthProvidersManageScope)) return;
250 setBusy(true);
251 setStatus(null);
252 const result = await consume({ environmentId, input });
253 setBusy(false);
254 if (result._tag === "Success") {
255 setStatus(result.value.warning ?? OUTCOME_TEXT[result.value.outcome]);
256 return;
257 }
258 setStatus(
259 "error" in result.cause && result.cause.error instanceof Error
260 ? result.cause.error.message
261 : "Could not use the reset credit.",
262 );
263 };
264
265 return { canManageProviders, confirming, setConfirming, busy, status, redeem };
266}
267
268/** Require confirmation because redemption spends credits. Mount outside popovers, which stack above
269 * dialogs and unmount on close. */
270export function ResetCreditDialog({
271 open,
272 onOpenChange,
273 onConfirm,
274 disabled = false,
275}: {
276 readonly open: boolean;
277 readonly onOpenChange: (open: boolean) => void;
278 readonly onConfirm: () => void;
279 readonly disabled?: boolean;
280}) {
281 return (
282 <AlertDialog open={open} onOpenChange={onOpenChange}>
283 <AlertDialogPopup>
284 <AlertDialogHeader>
285 <AlertDialogTitle>Use a reset credit?</AlertDialogTitle>
286 <AlertDialogDescription>
287 This redeems one credit on your account and clears the current rate-limit windows. It
288 cannot be undone.
289 </AlertDialogDescription>
290 </AlertDialogHeader>
291 <AlertDialogFooter>
292 <AlertDialogClose render={<Button variant="outline" />}>Cancel</AlertDialogClose>
293 <Button disabled={disabled} onClick={onConfirm}>
294 Use credit
295 </Button>
296 </AlertDialogFooter>
297 </AlertDialogPopup>
298 </AlertDialog>
299 );
300}
301
302export function resetCreditsSummary(
303 credits: ServerProviderResetCredits,
304 now: number,
305 compact = false,
306): string {
307 const expiresIn = credits.nextExpiresAt
308 ? formatDuration(Date.parse(credits.nextExpiresAt) - now)
309 : null;
310 if (credits.availableCount === 0) return "No reset credits banked";
311 if (compact)
312 return `${credits.availableCount} banked${expiresIn ? ` · expires in ${expiresIn}` : ""}`;
313 return `${credits.availableCount} ${credits.availableCount === 1 ? "reset credit" : "reset credits"} banked${
314 expiresIn ? ` · next expires in ${expiresIn}` : ""
315 }`;
316}
317
318export function ResetCredits({
319 environmentId,
320 input,
321 credits,
322 now,
323}: {
324 readonly environmentId: EnvironmentId;
325 readonly input: ProviderConsumeResetCreditInput;
326 readonly credits: ServerProviderResetCredits;
327 readonly now: number;
328}) {
329 const { canManageProviders, confirming, setConfirming, busy, status, redeem } = useResetCredit(
330 environmentId,
331 input,
332 );
333 if (credits.availableCount === 0 && status === null) return null;
334 return (
335 <div className="flex flex-wrap items-center gap-x-3 gap-y-1 text-xs text-muted-foreground">
336 <span className="tabular-nums">{resetCreditsSummary(credits, now)}</span>
337 {credits.availableCount > 0 ? (
338 <Button
339 size="xs"
340 variant="outline"
341 disabled={busy || !canManageProviders}
342 onClick={() => {
343 if (readEnvironmentScope(environmentId, AuthProvidersManageScope)) setConfirming(true);
344 }}
345 >
346 {busy ? "Using…" : "Use reset"}
347 </Button>
348 ) : null}
349 {status ? <span className="text-foreground">{status}</span> : null}
350 <ResetCreditDialog
351 open={confirming}
352 onOpenChange={setConfirming}
353 onConfirm={() => void redeem()}
354 disabled={!canManageProviders}
355 />
356 </div>
357 );
358}
359
360/** Advance now only on explicit refresh to avoid page repaints from ticking. */
361export function UsageLimitsSection({
362 selectedEnvironmentIds,
363 hiddenProviders,
364 now,
365 cursorPrompt,
366}: {
367 readonly selectedEnvironmentIds: ReadonlySet<EnvironmentId> | null;
368 readonly hiddenProviders: ReadonlySet<UsageProviderKind>;
369 readonly now: number;
370 readonly cursorPrompt?: ReactNode;
371}) {
372 const presentations = useAtomValue(environmentPresentations.presentationsWithProvidersAtom);
373 const hiddenDrivers = new Set<ServerProvider["driver"]>(
374 [...hiddenProviders].map((provider) => PROVIDER_PRESENTATION[provider].driverKind),
375 );
376 const isVisible = (driver: ServerProvider["driver"]) => !hiddenDrivers.has(driver);
377 const selected = new Map(
378 [...presentations].flatMap(([id, presentation]) => {
379 if (selectedEnvironmentIds !== null && !selectedEnvironmentIds.has(id)) return [];
380 const config = presentation.serverConfig;
381 if (hiddenDrivers.size === 0 || config === null) return [[id, presentation] as const];
382 return [
383 [
384 id,
385 {
386 ...presentation,
387 serverConfig: {
388 ...config,
389 providers: config.providers.filter((provider) => isVisible(provider.driver)),
390 usageLimitSources: config.usageLimitSources?.flatMap((source) => {
391 const accounts = source.accounts.filter((account) => isVisible(account.driver));
392 return accounts.length === 0 && source.accounts.length > 0
393 ? []
394 : [{ ...source, accounts }];
395 }),
396 },
397 },
398 ] as const,
399 ];
400 }),
401 );
402 return <UsageLimitsPooled presentations={selected} now={now} cursorPrompt={cursorPrompt} />;
403}