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

UsageLimits.tsx

473 lines15.9 KB

1import {
2 type EnvironmentId,
3 type ProviderConsumeResetCreditOutcome,
4 ProviderInstanceId,
5 ServerProvider,
6 ServerProviderResetCredits,
7 ServerProviderUsageWindow,
8 UsageLimitSourceAccount,
9 UsageLimitSourceSnapshot,
10 UsageProviderKind,
11} from "@t3tools/contracts";
12import { useAtomValue } from "@effect/atom-react";
13import {
14 collectLimitSources,
15 collectLimitsGroups,
16 elapsedShare,
17 formatDuration,
18 formatResetsIn,
19 limitsNotice,
20 type LimitPace,
21 paceOf,
22 providerLimitsLabel,
23} from "@t3tools/shared/usageLimits";
24import { GaugeIcon, TrendingDownIcon, TrendingUpIcon } from "lucide-react";
25import { Fragment, useState } from "react";
26​
27import { usePrimarySettings } from "../../hooks/useSettings";
28import { environmentPresentations } from "../../state/presentation";
29import { serverEnvironment } from "../../state/server";
30import { useAtomCommand } from "../../state/use-atom-command";
31import { formatUpcomingTimestamp } from "../../timestampFormat";
32import { ProviderInstanceIcon } from "../chat/ProviderInstanceIcon";
33import { getDriverOption } from "../settings/providerDriverMeta";
34import { RedactedSensitiveText } from "../settings/RedactedSensitiveText";
35import {
36 AlertDialog,
37 AlertDialogClose,
38 AlertDialogDescription,
39 AlertDialogFooter,
40 AlertDialogHeader,
41 AlertDialogPopup,
42 AlertDialogTitle,
43} from "../ui/alert-dialog";
44import { Button } from "../ui/button";
45import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
46import { PROVIDER_PRESENTATION } from "./usageProviders";
47​
48const PACE: Record<LimitPace, { readonly label: string; readonly icon: typeof GaugeIcon }> = {
49 ahead: { label: "Ahead of pace: spending faster than the window elapses", icon: TrendingUpIcon },
50 on: { label: "On pace with the window", icon: GaugeIcon },
51 under: { label: "Under pace: headroom left for the rest of the window", icon: TrendingDownIcon },
52};
53​
54/** The series colour the cost chart uses for this driver, so the two views read as one. */
55function barColor(driver: ServerProvider["driver"]): string {
56 const kind: UsageProviderKind | undefined =
57 driver === "codex" ? "codex" : driver === "claudeAgent" ? "claude" : undefined;
58 return kind ? PROVIDER_PRESENTATION[kind].color : "var(--foreground)";
60​
61/** Pace as a glyph with the words on hover. */
62function PaceIcon({ pace }: { readonly pace: LimitPace }) {
63 const Icon = PACE[pace].icon;
64 return (
65 <Tooltip>
66 <TooltipTrigger
67 render={
68 <span
69 role="img"
70 aria-label={PACE[pace].label}
71 className="inline-flex text-muted-foreground"
72 />
73 }
74 >
75 <Icon className="size-3.5" aria-hidden />
76 </TooltipTrigger>
77 <TooltipPopup side="top">{PACE[pace].label}</TooltipPopup>
78 </Tooltip>
79 );
81​
82/**
83 * One window as a full-width bar from the moment it opened to its reset.
84 * The fill is the share of quota spent; the hairline is how far into the
85 * window the clock is, which is also where even spending would have put the
86 * fill. Hover for the exact figures and reset time.
87 */
88function WindowBar({
89 color,
90 window,
91 now,
92}: {
93 readonly color: string;
94 readonly window: ServerProviderUsageWindow;
95 readonly now: number;
96}) {
97 const timestampFormat = usePrimarySettings((settings) => settings.timestampFormat);
98 const used = Math.max(0, Math.min(100, window.usedPercent));
99 const elapsed = elapsedShare(window, now);
100 const resetsIn = formatResetsIn(window, now);
101 const resetsAt = window.resetsAt
102 ? formatUpcomingTimestamp(window.resetsAt, timestampFormat, now)
103 : null;
104 const summary = `${window.label}: ${Math.round(used)}% used${
105 elapsed === null ? "" : `, ${Math.round(elapsed * 100)}% of the window elapsed`
106 }${resetsIn ? `, ${resetsIn}` : ""}`;
107​
108 return (
109 <Tooltip>
110 <TooltipTrigger
111 render={
112 <div
113 role="img"
114 aria-label={summary}
115 tabIndex={0}
116 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"
117 />
118 }
119 >
120 <div className="absolute inset-x-0 inset-y-1.5 rounded-full bg-muted" />
121 {used > 0 ? (
122 <div
123 className="absolute inset-y-1.5 left-0 rounded-full"
124 style={{ width: `${used}%`, backgroundColor: color }}
125 />
126 ) : null}
127 {elapsed !== null ? (
128 <span
129 aria-hidden
130 className="absolute inset-y-0.5 w-px -translate-x-1/2 bg-foreground/60"
131 style={{ left: `${elapsed * 100}%` }}
132 />
133 ) : null}
134 </TooltipTrigger>
135 <TooltipPopup side="top" className="max-w-72 text-xs">
136 <div className="flex flex-col gap-0.5">
137 <span className="text-foreground">
138 {Math.round(used)}% used
139 {elapsed !== null ? ` · ${Math.round(elapsed * 100)}% of the window elapsed` : ""}
140 </span>
141 {elapsed !== null ? (
142 <span className="text-muted-foreground">The line is where even spending would be.</span>
143 ) : null}
144 {resetsAt ? (
145 <span className="text-muted-foreground">
146 Resets {resetsAt}
147 {resetsIn ? ` · ${resetsIn}` : ""}
148 </span>
149 ) : null}
150 </div>
151 </TooltipPopup>
152 </Tooltip>
153 );
155​
156/** One account's windows as rows: label and percent, bar, pace and countdown. */
157function LimitWindows({
158 driver,
159 windows,
160 now,
161}: {
162 readonly driver: ServerProvider["driver"];
163 readonly windows: ReadonlyArray<ServerProviderUsageWindow>;
164 readonly now: number;
165}) {
166 const color = barColor(driver);
167 return (
168 <div className="grid grid-cols-[11rem_minmax(0,1fr)_7rem] gap-x-4 gap-y-1">
169 {windows.map((window, index) => {
170 // Windows that reset together show the countdown once.
171 const previous = windows[index - 1];
172 const sharesReset =
173 previous?.resetsAt !== undefined && previous.resetsAt === window.resetsAt;
174 const pace = paceOf(window, now);
175 const resetsIn = formatResetsIn(window, now);
176 return (
177 <Fragment key={window.id}>
178 <span className="flex min-w-0 items-center gap-2 text-xs">
179 <span className="truncate text-muted-foreground">{window.label}</span>
180 <span className="ms-auto shrink-0 font-medium text-foreground tabular-nums">
181 {Math.round(window.usedPercent)}%
182 </span>
183 </span>
184 <WindowBar color={color} window={window} now={now} />
185 <span className="flex items-center gap-2 text-xs text-muted-foreground tabular-nums">
186 {pace ? <PaceIcon pace={pace} /> : null}
187 <span className="ms-auto shrink-0">{sharesReset ? "" : (resetsIn ?? "")}</span>
188 </span>
189 </Fragment>
190 );
191 })}
192 </div>
193 );
195​
196/**
197 * Heading shared by local providers and source accounts: icon, driver, instance, plan,
198 * and the signed-in email blurred until clicked, as provider settings do.
199 */
200function AccountHeading({
201 driver,
202 label,
203 instanceLabel,
204 plan,
205 email,
206 accentColor,
207}: {
208 readonly driver: ServerProvider["driver"];
209 readonly label: string;
210 readonly instanceLabel: string;
211 readonly plan: string | undefined;
212 readonly email: string | undefined;
213 readonly accentColor?: string | undefined;
214}) {
215 return (
216 <h2 className="flex min-w-0 flex-wrap items-center gap-x-2 gap-y-1 text-sm font-medium text-foreground">
217 <ProviderInstanceIcon
218 driverKind={driver}
219 displayName={instanceLabel}
220 accentColor={accentColor}
221 showBadge={Boolean(accentColor)}
222 indicatorBackground="var(--background)"
223 className="size-5"
224 iconClassName="size-4 text-foreground/80"
225 />
226 <span className="truncate">{label}</span>
227 {instanceLabel !== label ? (
228 <span className="min-w-0 truncate text-xs font-normal text-muted-foreground">
229 · {instanceLabel}
230 </span>
231 ) : null}
232 {plan ? <span className="font-normal text-muted-foreground">· {plan}</span> : null}
233 {email ? (
234 <RedactedSensitiveText
235 value={email}
236 ariaLabel="Toggle account email visibility"
237 revealTooltip="Click to reveal email"
238 hideTooltip="Click to hide email"
239 />
240 ) : null}
241 </h2>
242 );
244​
245function ProviderLimits({
246 provider,
247 environmentId,
248 now,
249}: {
250 readonly provider: ServerProvider;
251 readonly environmentId: EnvironmentId;
252 readonly now: number;
253}) {
254 const limits = provider.usageLimits;
255 if (!limits) return null;
256 const notice = limitsNotice(limits);
257 return (
258 <section className="flex flex-col gap-3">
259 <AccountHeading
260 driver={provider.driver}
261 label={getDriverOption(provider.driver)?.label ?? String(provider.driver)}
262 instanceLabel={providerLimitsLabel(provider, (driver) => getDriverOption(driver)?.label)}
263 plan={provider.auth.label}
264 email={provider.auth.email}
265 accentColor={provider.accentColor}
266 />
267 {notice ? (
268 <span className="text-xs text-muted-foreground">{notice}</span>
269 ) : (
270 <LimitWindows driver={provider.driver} windows={limits.windows} now={now} />
271 )}
272 {limits.resetCredits ? (
273 <ResetCredits
274 environmentId={environmentId}
275 instanceId={provider.instanceId}
276 credits={limits.resetCredits}
277 now={now}
278 />
279 ) : null}
280 </section>
281 );
283​
284const OUTCOME_TEXT: Record<ProviderConsumeResetCreditOutcome, string> = {
285 reset: "Reset applied. Your windows have cleared.",
286 nothingToReset: "Nothing to reset right now.",
287 noCredit: "No reset credit left.",
288 alreadyRedeemed: "That credit was already redeemed.",
289};
290​
291/**
292 * Banked reset credits with a confirmed redeem action. Redeeming spends a
293 * credit the provider granted the user, so it never fires on a bare click.
294 */
295function ResetCredits({
296 environmentId,
297 instanceId,
298 credits,
299 now,
300}: {
301 readonly environmentId: EnvironmentId;
302 readonly instanceId: ProviderInstanceId;
303 readonly credits: ServerProviderResetCredits;
304 readonly now: number;
305}) {
306 const consume = useAtomCommand(serverEnvironment.consumeResetCredit, { reportFailure: false });
307 const [confirming, setConfirming] = useState(false);
308 const [busy, setBusy] = useState(false);
309 const [status, setStatus] = useState<string | null>(null);
310 if (credits.availableCount === 0 && status === null) return null;
311​
312 const expiresIn = credits.nextExpiresAt
313 ? formatDuration(Date.parse(credits.nextExpiresAt) - now)
314 : null;
315 const summary =
316 credits.availableCount === 0
317 ? "No reset credits banked"
318 : `${credits.availableCount} ${credits.availableCount === 1 ? "reset credit" : "reset credits"} banked${
319 expiresIn ? ` · next expires in ${expiresIn}` : ""
320 }`;
321​
322 const redeem = async () => {
323 setConfirming(false);
324 setBusy(true);
325 setStatus(null);
326 const result = await consume({ environmentId, input: { instanceId } });
327 setBusy(false);
328 if (result._tag === "Success") {
329 setStatus(OUTCOME_TEXT[result.value.outcome]);
330 return;
331 }
332 setStatus(
333 "error" in result.cause && result.cause.error instanceof Error
334 ? result.cause.error.message
335 : "Could not use the reset credit.",
336 );
337 };
338​
339 return (
340 <div className="flex flex-wrap items-center gap-x-3 gap-y-1 text-xs text-muted-foreground">
341 <span className="tabular-nums">{summary}</span>
342 {credits.availableCount > 0 ? (
343 <Button size="xs" variant="outline" disabled={busy} onClick={() => setConfirming(true)}>
344 {busy ? "Using credit…" : "Use a reset credit"}
345 </Button>
346 ) : null}
347 {status ? <span className="text-foreground">{status}</span> : null}
348 <AlertDialog open={confirming} onOpenChange={setConfirming}>
349 <AlertDialogPopup>
350 <AlertDialogHeader>
351 <AlertDialogTitle>Use a reset credit?</AlertDialogTitle>
352 <AlertDialogDescription>
353 This redeems one credit on your account and clears the current rate-limit windows. It
354 cannot be undone.
355 </AlertDialogDescription>
356 </AlertDialogHeader>
357 <AlertDialogFooter>
358 <AlertDialogClose render={<Button variant="outline" />}>Cancel</AlertDialogClose>
359 <Button onClick={() => void redeem()}>Use credit</Button>
360 </AlertDialogFooter>
361 </AlertDialogPopup>
362 </AlertDialog>
363 </div>
364 );
366​
367/** One account pooled by a usage-limit source, drawn like a provider row. */
368function SourceAccountLimits({
369 account,
370 sourceKind,
371 now,
372}: {
373 readonly account: UsageLimitSourceAccount;
374 readonly sourceKind: string;
375 readonly now: number;
376}) {
377 const notice = limitsNotice(account.usageLimits);
378 return (
379 <section className="flex flex-col gap-3">
380 <AccountHeading
381 driver={account.driver}
382 label={getDriverOption(account.driver)?.label ?? String(account.driver)}
383 instanceLabel={sourceKind}
384 plan={account.plan}
385 email={account.email}
386 />
387 {notice ? (
388 <span className="text-xs text-muted-foreground">{notice}</span>
389 ) : (
390 <LimitWindows driver={account.driver} windows={account.usageLimits.windows} now={now} />
391 )}
392 </section>
393 );
395​
396const SOURCE_KIND_LABEL: Record<UsageLimitSourceSnapshot["kind"], string> = {
397 cliproxy: "CLI Proxy",
398};
399​
400type LimitsSource = ReturnType<typeof collectLimitSources>[number];
401​
402/** Read-only accounts pooled by a configured usage source. */
403function SourceLimits({ source, now }: { readonly source: LimitsSource; readonly now: number }) {
404 const kind = SOURCE_KIND_LABEL[source.kind];
405 return (
406 <div className="flex flex-col gap-6">
407 {source.error ? (
408 <span className="text-xs text-muted-foreground">{source.error}</span>
409 ) : source.accounts.length === 0 ? (
410 <span className="text-xs text-muted-foreground">
411 {source.hiddenAccountCount > 0
412 ? "All accounts are shown by connected providers."
413 : "No accounts reported."}
414 </span>
415 ) : (
416 source.accounts.map((account) => (
417 <SourceAccountLimits key={account.id} account={account} sourceKind={kind} now={now} />
418 ))
419 )}
420 </div>
421 );
423​
424/**
425 * Subscription quota windows from every connected environment's providers.
426 * Countdowns anchor to render time rather than ticking: a live clock would
427 * repaint the page every minute for no decision-changing gain.
428 */
429export function UsageLimitsSection({
430 selectedEnvironmentIds,
431}: {
432 readonly selectedEnvironmentIds: ReadonlySet<EnvironmentId> | null;
433}) {
434 const presentations = useAtomValue(environmentPresentations.presentationsAtom);
435 const selected =
436 selectedEnvironmentIds === null
437 ? presentations
438 : new Map([...presentations].filter(([id]) => selectedEnvironmentIds.has(id)));
439 const groups = collectLimitsGroups(selected);
440 const sources = collectLimitSources(selected);
441 // Anchored once per mount on purpose: countdowns must not tick (see below).
442 const [now] = useState(() => Date.now());
443​
444 return (
445 <div className="flex flex-col gap-8">
446 {groups.length === 0 && sources.length === 0 ? (
447 <p className="text-sm text-muted-foreground">
448 No provider on the selected environments reports subscription limits.
449 </p>
450 ) : null}
451 {sources.map((source) => (
452 <SourceLimits key={source.key} source={source} now={now} />
453 ))}
454 {groups.map((group) => (
455 <div key={group.environmentId} className="flex flex-col gap-6">
456 {group.environmentLabel ? (
457 <h2 className="text-xs tracking-wide text-muted-foreground uppercase">
458 {group.environmentLabel}
459 </h2>
460 ) : null}
461 {group.providers.map((provider) => (
462 <ProviderLimits
463 key={provider.instanceId}
464 provider={provider}
465 environmentId={group.environmentId}
466 now={now}
467 />
468 ))}
469 </div>
470 ))}
471 </div>
472 );