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 elapsedShare,
14 formatDuration,
15 formatResetsIn,
16 type LimitPace,
17 paceOf,
18 remainingPercent,
19} from "@t3tools/shared/usageLimits";
20import { GaugeIcon, TrendingDownIcon, TrendingUpIcon } from "lucide-react";
21import { Fragment, type ReactNode, useState } from "react";
22
23import { usePrimarySettings } from "../../hooks/useSettings";
24import { environmentPresentations } from "../../state/presentation";
25import { useEnvironmentScope, readEnvironmentScope } from "../../state/session";
26import { serverEnvironment } from "../../state/server";
27import { useAtomCommand } from "../../state/use-atom-command";
28import { formatUpcomingTimestamp } from "../../timestampFormat";
29import {
30 AlertDialog,
31 AlertDialogClose,
32 AlertDialogDescription,
33 AlertDialogFooter,
34 AlertDialogHeader,
35 AlertDialogPopup,
36 AlertDialogTitle,
37} from "../ui/alert-dialog";
38import { Button } from "../ui/button";
39import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
40import { UsageLimitsPooled } from "./UsageLimitsPooled";
41import { PROVIDER_PRESENTATION } from "./usageProviders";
42
43const PACE: Record<LimitPace, { readonly label: string; readonly icon: typeof GaugeIcon }> = {
44 ahead: { label: "Ahead of pace: spending faster than the window elapses", icon: TrendingUpIcon },
45 on: { label: "On pace with the window", icon: GaugeIcon },
46 under: { label: "Under pace: headroom left for the rest of the window", icon: TrendingDownIcon },
47};
48
49/** The series colour the cost chart uses for this driver, so the two views read as one. */
50export function barColor(driver: ServerProvider["driver"]): string {
51 const kind: UsageProviderKind | undefined =
52 driver === "codex" ? "codex" : driver === "claudeAgent" ? "claude" : undefined;
53 return kind ? PROVIDER_PRESENTATION[kind].color : "var(--foreground)";
54}
55
56/** Pace as a glyph with the words on hover. */
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/**
78 * One window as a full-width bar from the moment it opened to its reset.
79 * The fill is the share of quota spent; the hairline is how far into the
80 * window the clock is, which is also where even spending would have put the
81 * fill. Hover for the exact figures and reset time.
82 */
83function WindowBar({
84 color,
85 window,
86 now,
87}: {
88 readonly color: string;
89 readonly window: ServerProviderUsageWindow;
90 readonly now: number;
91}) {
92 const timestampFormat = usePrimarySettings((settings) => settings.timestampFormat);
93 const remaining = remainingPercent(window);
94 const elapsed = elapsedShare(window, now);
95 // The fill is quota left, so the even-spending mark is the time left.
96 const timeLeft = elapsed === null ? null : Math.round((1 - elapsed) * 100);
97 const resetsIn = formatResetsIn(window, now);
98 const resetsAt = window.resetsAt
99 ? formatUpcomingTimestamp(window.resetsAt, timestampFormat, now)
100 : null;
101 const summary = `${window.label}: ${remaining}% left${
102 timeLeft === null ? "" : `, ${timeLeft}% of the window left`
103 }${resetsIn ? `, ${resetsIn}` : ""}`;
104
105 return (
106 <Tooltip>
107 <TooltipTrigger
108 render={
109 <div
110 role="img"
111 aria-label={summary}
112 tabIndex={0}
113 className="relative h-6 cursor-default rounded-full outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background"
114 />
115 }
116 >
117 <div className="absolute inset-x-0 inset-y-1.5 rounded-full bg-muted" />
118 {remaining > 0 ? (
119 <div
120 className="absolute inset-y-1.5 left-0 rounded-full"
121 style={{ width: `${remaining}%`, backgroundColor: color }}
122 />
123 ) : null}
124 {timeLeft !== null ? (
125 <span
126 aria-hidden
127 className="absolute inset-y-0.5 w-px -translate-x-1/2 bg-foreground/60"
128 style={{ left: `${timeLeft}%` }}
129 />
130 ) : null}
131 </TooltipTrigger>
132 <TooltipPopup side="top">
133 <div className="flex flex-col gap-0.5">
134 <span className="text-foreground">
135 {remaining}% left{timeLeft !== null ? ` · ${timeLeft}% of the window left` : ""}
136 </span>
137 {timeLeft !== null ? (
138 <span className="text-muted-foreground">The line is where even spending would be.</span>
139 ) : null}
140 {resetsAt ? (
141 <span className="text-muted-foreground">
142 Resets {resetsAt}
143 {resetsIn ? ` · ${resetsIn}` : ""}
144 </span>
145 ) : null}
146 </div>
147 </TooltipPopup>
148 </Tooltip>
149 );
150}
151
152/**
153 * One account's windows as rows: label and percent, bar, pace and countdown.
154 * Compact rows fit the composer panel with narrower columns.
155 */
156export function LimitWindows({
157 driver,
158 windows,
159 now,
160 compact = false,
161}: {
162 readonly driver: ServerProvider["driver"];
163 readonly windows: ReadonlyArray<ServerProviderUsageWindow>;
164 readonly now: number;
165 readonly compact?: boolean;
166}) {
167 const color = barColor(driver);
168 return (
169 <div
170 className={
171 compact
172 ? "grid grid-cols-[minmax(0,9rem)_minmax(3rem,1fr)_auto] gap-x-3 gap-y-0.5"
173 : "grid grid-cols-[11rem_minmax(0,1fr)_7rem] gap-x-4 gap-y-1"
174 }
175 >
176 {windows.map((window) => {
177 const pace = paceOf(window, now);
178 const resetsIn = formatResetsIn(window, now);
179 return (
180 <Fragment key={window.id}>
181 <span className="flex min-w-0 items-center gap-2 text-xs">
182 <span className="truncate text-muted-foreground">{window.label}</span>
183 <span className="ms-auto shrink-0 font-medium text-foreground tabular-nums">
184 {remainingPercent(window)}% left
185 </span>
186 </span>
187 <WindowBar color={color} window={window} now={now} />
188 <span className="flex items-center gap-2 text-xs whitespace-nowrap text-muted-foreground tabular-nums">
189 {pace ? <PaceIcon pace={pace} /> : null}
190 <span className="ms-auto shrink-0">{resetsIn ?? ""}</span>
191 </span>
192 </Fragment>
193 );
194 })}
195 </div>
196 );
197}
198
199const OUTCOME_TEXT: Record<ProviderConsumeResetCreditOutcome, string> = {
200 reset: "Reset applied. Your windows have cleared.",
201 nothingToReset: "Nothing to reset right now.",
202 noCredit: "No reset credit left.",
203 alreadyRedeemed: "That credit was already redeemed.",
204};
205
206/** Everything a redeem needs: where to send it and what to say afterwards. */
207export function useResetCredit(
208 environmentId: EnvironmentId,
209 input: ProviderConsumeResetCreditInput,
210) {
211 const canManageProviders = useEnvironmentScope(environmentId, AuthProvidersManageScope);
212 const consume = useAtomCommand(serverEnvironment.consumeResetCredit, { reportFailure: false });
213 const [confirming, setConfirming] = useState(false);
214 const [busy, setBusy] = useState(false);
215 const [status, setStatus] = useState<string | null>(null);
216
217 const redeem = async () => {
218 setConfirming(false);
219 if (!readEnvironmentScope(environmentId, AuthProvidersManageScope)) return;
220 setBusy(true);
221 setStatus(null);
222 const result = await consume({ environmentId, input });
223 setBusy(false);
224 if (result._tag === "Success") {
225 setStatus(result.value.warning ?? OUTCOME_TEXT[result.value.outcome]);
226 return;
227 }
228 setStatus(
229 "error" in result.cause && result.cause.error instanceof Error
230 ? result.cause.error.message
231 : "Could not use the reset credit.",
232 );
233 };
234
235 return { canManageProviders, confirming, setConfirming, busy, status, redeem };
236}
237
238/**
239 * The confirm for a redeem. Redeeming spends a credit the provider granted the
240 * user, so it never fires on a bare click. Mount it outside any popover that
241 * holds the button: dialogs stack under popovers, and closing the popover
242 * would unmount a dialog rendered inside it.
243 */
244export function ResetCreditDialog({
245 open,
246 onOpenChange,
247 onConfirm,
248 disabled = false,
249}: {
250 readonly open: boolean;
251 readonly onOpenChange: (open: boolean) => void;
252 readonly onConfirm: () => void;
253 readonly disabled?: boolean;
254}) {
255 return (
256 <AlertDialog open={open} onOpenChange={onOpenChange}>
257 <AlertDialogPopup>
258 <AlertDialogHeader>
259 <AlertDialogTitle>Use a reset credit?</AlertDialogTitle>
260 <AlertDialogDescription>
261 This redeems one credit on your account and clears the current rate-limit windows. It
262 cannot be undone.
263 </AlertDialogDescription>
264 </AlertDialogHeader>
265 <AlertDialogFooter>
266 <AlertDialogClose render={<Button variant="outline" />}>Cancel</AlertDialogClose>
267 <Button disabled={disabled} onClick={onConfirm}>
268 Use credit
269 </Button>
270 </AlertDialogFooter>
271 </AlertDialogPopup>
272 </AlertDialog>
273 );
274}
275
276/** `2 reset credits banked · next expires in 27d 23h`, or the short form for a popover. */
277export function resetCreditsSummary(
278 credits: ServerProviderResetCredits,
279 now: number,
280 compact = false,
281): string {
282 const expiresIn = credits.nextExpiresAt
283 ? formatDuration(Date.parse(credits.nextExpiresAt) - now)
284 : null;
285 if (credits.availableCount === 0) return "No reset credits banked";
286 if (compact)
287 return `${credits.availableCount} banked${expiresIn ? ` · expires in ${expiresIn}` : ""}`;
288 return `${credits.availableCount} ${credits.availableCount === 1 ? "reset credit" : "reset credits"} banked${
289 expiresIn ? ` · next expires in ${expiresIn}` : ""
290 }`;
291}
292
293/** Banked reset credits with the redeem button and its confirm, self-contained. */
294export function ResetCredits({
295 environmentId,
296 input,
297 credits,
298 now,
299}: {
300 readonly environmentId: EnvironmentId;
301 readonly input: ProviderConsumeResetCreditInput;
302 readonly credits: ServerProviderResetCredits;
303 readonly now: number;
304}) {
305 const { canManageProviders, confirming, setConfirming, busy, status, redeem } = useResetCredit(
306 environmentId,
307 input,
308 );
309 if (credits.availableCount === 0 && status === null) return null;
310 return (
311 <div className="flex flex-wrap items-center gap-x-3 gap-y-1 text-xs text-muted-foreground">
312 <span className="tabular-nums">{resetCreditsSummary(credits, now)}</span>
313 {credits.availableCount > 0 ? (
314 <Button
315 size="xs"
316 variant="outline"
317 disabled={busy || !canManageProviders}
318 onClick={() => {
319 if (readEnvironmentScope(environmentId, AuthProvidersManageScope)) setConfirming(true);
320 }}
321 >
322 {busy ? "Using…" : "Use reset"}
323 </Button>
324 ) : null}
325 {status ? <span className="text-foreground">{status}</span> : null}
326 <ResetCreditDialog
327 open={confirming}
328 onOpenChange={setConfirming}
329 onConfirm={() => void redeem()}
330 disabled={!canManageProviders}
331 />
332 </div>
333 );
334}
335
336/**
337 * Subscription quota across every connected environment's providers and hubs,
338 * pooled per provider. The page advances `now` on explicit refresh rather than
339 * ticking: a live clock would repaint the page for no decision-changing gain.
340 */
341export function UsageLimitsSection({
342 selectedEnvironmentIds,
343 hiddenProviders,
344 now,
345 cursorPrompt,
346}: {
347 readonly selectedEnvironmentIds: ReadonlySet<EnvironmentId> | null;
348 readonly hiddenProviders: ReadonlySet<UsageProviderKind>;
349 readonly now: number;
350 readonly cursorPrompt?: ReactNode;
351}) {
352 const presentations = useAtomValue(environmentPresentations.presentationsAtom);
353 const hiddenDrivers = new Set<ServerProvider["driver"]>(
354 [...hiddenProviders].map((provider) => PROVIDER_PRESENTATION[provider].driverKind),
355 );
356 const isVisible = (driver: ServerProvider["driver"]) => !hiddenDrivers.has(driver);
357 // Hidden drivers leave both native accounts and hub accounts, so their
358 // bars, notices, and external links all drop out together.
359 const selected = new Map(
360 [...presentations].flatMap(([id, presentation]) => {
361 if (selectedEnvironmentIds !== null && !selectedEnvironmentIds.has(id)) return [];
362 const config = presentation.serverConfig;
363 if (hiddenDrivers.size === 0 || config === null) return [[id, presentation] as const];
364 return [
365 [
366 id,
367 {
368 ...presentation,
369 serverConfig: {
370 ...config,
371 providers: config.providers.filter((provider) => isVisible(provider.driver)),
372 // A hub left with no visible accounts is dropped, not reported as empty.
373 usageLimitSources: config.usageLimitSources?.flatMap((source) => {
374 const accounts = source.accounts.filter((account) => isVisible(account.driver));
375 return accounts.length === 0 && source.accounts.length > 0
376 ? []
377 : [{ ...source, accounts }];
378 }),
379 },
380 },
381 ] as const,
382 ];
383 }),
384 );
385 return <UsageLimitsPooled presentations={selected} now={now} cursorPrompt={cursorPrompt} />;
386}