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