Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

UsageLimits.tsx

392 lines13.6 KB

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