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

UsageLimitsPooled.tsx

613 lines20.9 KB

1import {
2 collectLimitAccounts,
3 collectLimitNotices,
4 collectLimitPools,
5 cursorUsageWindowDetails,
6 displayLimitWindows,
7 formatResetsIn,
8 type LimitAccount,
9 type LimitPool,
10 type LimitPoolMember,
11 type LimitPoolWindow,
12 remainingPercent,
13} from "@t3tools/shared/usageLimits";
14import { AlertTriangleIcon, TicketIcon } from "lucide-react";
15import { Fragment, type ReactNode, useState } from "react";
16​
17import { usePrimarySettings } from "../../hooks/useSettings";
18import { cn } from "../../lib/utils";
19import { formatUpcomingTimestamp } from "../../timestampFormat";
20import { ProviderInstanceIcon } from "../chat/ProviderInstanceIcon";
21import { getDriverOption } from "../settings/providerDriverMeta";
22import { RedactedSensitiveText } from "../settings/RedactedSensitiveText";
23import { Button } from "../ui/button";
24import { Alert, AlertTitle } from "../ui/alert";
25import { Popover, PopoverPopup, PopoverTrigger } from "../ui/popover";
26import {
27 PaceIcon,
28 ResetCreditDialog,
29 barColor,
30 resetCreditsSummary,
31 useResetCredit,
32} from "./UsageLimits";
33​
34/** `someone@example.com` → `SE`: enough to tell accounts apart, too little to identify one. */
35function accountInitials(email: string): string {
36 const [local = "", domain = ""] = email.split("@");
37 return `${local[0] ?? ""}${domain[0] ?? ""}`.toUpperCase() || "?";
39​
40/** A stable hue per email, so the same account gets the same chip on every visit. */
41function accountHue(email: string): number {
42 let hash = 0;
43 for (let index = 0; index < email.length; index += 1) {
44 hash = (hash * 31 + email.charCodeAt(index)) | 0;
45 }
46 return Math.abs(hash) % 360;
48​
49/** The two-letter chip for an email, coloured by a stable hue per address. */
50function AccountChip({ email }: { readonly email: string }) {
51 const hue = accountHue(email);
52 return (
53 <span
54 role="img"
55 aria-label={`Account ${accountInitials(email)}`}
56 className="inline-flex size-4 shrink-0 items-center justify-center rounded-full text-3xs leading-none font-semibold"
57 style={{ backgroundColor: `oklch(0.85 0.08 ${hue})`, color: `oklch(0.35 0.1 ${hue})` }}
58 >
59 {accountInitials(email)}
60 </span>
61 );
63​
64/**
65 * The same mark the model picker uses for a native instance (provider glyph,
66 * initials badge, accent); hub accounts have no instance, so they get the chip.
67 */
68function AccountAvatar({
69 account,
70 className,
71}: {
72 readonly account: LimitAccount;
73 readonly className?: string;
74}) {
75 if (account.redeem) {
76 return (
77 <ProviderInstanceIcon
78 driverKind={account.driver}
79 displayName={
80 account.displayName ?? getDriverOption(account.driver)?.label ?? String(account.driver)
81 }
82 accentColor={account.accentColor}
83 showBadge={Boolean(account.displayName)}
84 indicatorBackground="var(--popover)"
85 className={cn("size-5", className)}
86 iconClassName="size-4 text-foreground/80"
87 />
88 );
89 }
90 return account.email ? <AccountChip email={account.email} /> : null;
92​
93/**
94 * Who an account is, without printing the email: the instance name when there
95 * is one, else a two-letter chip. The address itself is revealed on demand in
96 * the segment's popover.
97 */
98function AccountName({
99 account,
100 className,
101}: {
102 readonly account: LimitAccount;
103 readonly className?: string;
104}) {
105 if (account.displayName) return <span className={className}>{account.displayName}</span>;
106 if (account.email) {
107 return (
108 <span className={cn("inline-flex min-w-0 items-center", className)}>
109 <AccountChip email={account.email} />
110 </span>
111 );
112 }
113 return (
114 <span className={className}>
115 {getDriverOption(account.driver)?.label ?? String(account.driver)}
116 </span>
117 );
119​
120function Row({ label, children }: { readonly label: string; readonly children: ReactNode }) {
121 return (
122 <div className="grid grid-cols-[4.5rem_minmax(0,1fr)] gap-x-3">
123 <span className="text-muted-foreground">{label}</span>
124 <span className="min-w-0 text-foreground tabular-nums">{children}</span>
125 </div>
126 );
128​
129/**
130 * Everything about one account in one window: plan, where it is signed in,
131 * the email on request, reset time and share of the pool it restores, and the
132 * reset-credit action. Opens on hover for a glance, on click to act.
133 */
134function SegmentPopover({
135 account,
136 window,
137 reset,
138 now,
139 redeem,
140 onRedeem,
141}: {
142 readonly account: LimitAccount;
143 readonly window: LimitPoolMember["window"];
144 readonly reset: LimitPoolWindow["resets"][number] | undefined;
145 readonly now: number;
146 /** Redeem state owned by the segment, since the confirm lives outside this popover. */
147 readonly redeem: ReturnType<typeof useResetCredit> | null;
148 readonly onRedeem: () => void;
149}) {
150 const timestampFormat = usePrimarySettings((settings) => settings.timestampFormat);
151 const remaining = remainingPercent(window);
152 const resetsIn = formatResetsIn(window, now);
153 const where =
154 account.environments.length > 0
155 ? account.environments.map((environment) => environment.label).join(", ")
156 : account.sourceLabel;
157 const credits =
158 redeem && account.limits.resetCredits?.availableCount ? account.limits.resetCredits : null;
159 return (
160 <div className="flex w-72 max-w-[calc(100vw-3rem)] flex-col gap-2.5 text-xs">
161 <div className="flex min-w-0 flex-col gap-0.5">
162 <span className="flex items-center gap-2 text-sm font-medium text-foreground">
163 <AccountAvatar account={account} />
164 <span className="truncate">
165 {account.displayName ?? getDriverOption(account.driver)?.label ?? account.driver}
166 </span>
167 </span>
168 {account.email ? (
169 <RedactedSensitiveText
170 value={account.email}
171 ariaLabel="Toggle account email visibility"
172 revealTooltip="Click to reveal email"
173 hideTooltip="Click to hide email"
174 className="w-fit"
175 />
176 ) : null}
177 </div>
178 <div className="flex flex-col gap-1 border-t border-border/60 pt-2.5">
179 {account.plan ? <Row label="Plan">{account.plan}</Row> : null}
180 {where ? (
181 <Row label={account.environments.length > 0 ? "Signed in" : "Via"}>{where}</Row>
182 ) : null}
183 </div>
184 <div className="flex flex-col gap-1 border-t border-border/60 pt-2.5">
185 <Row label="Left">{remaining}%</Row>
186 {window.resetsAt ? (
187 <Row label="Resets">
188 {formatUpcomingTimestamp(window.resetsAt, timestampFormat, now)}
189 {resetsIn ? ` · ${resetsIn.replace("resets in ", "in ")}` : ""}
190 </Row>
191 ) : null}
192 {reset && reset.restoresPercent > 0 ? (
193 <Row label="Restores">+{reset.restoresPercent}% of pool</Row>
194 ) : null}
195 </div>
196 {credits && redeem ? (
197 <div className="border-t border-border/60 pt-2.5 text-muted-foreground">
198 <span className="flex items-center gap-3">
199 <span className="tabular-nums">{resetCreditsSummary(credits, now, true)}</span>
200 <Button
201 size="xs"
202 variant="outline"
203 disabled={redeem.busy}
204 className="ms-auto"
205 onClick={onRedeem}
206 >
207 {redeem.busy ? "Using…" : "Use reset"}
208 </Button>
209 </span>
210 </div>
211 ) : null}
212 </div>
213 );
215​
216/**
217 * One account's share of one pooled window: the segment, its popover, and the
218 * reset confirm. The confirm is a sibling of the popover, not a child: dialogs
219 * stack under popovers, and the popover closes as the confirm opens.
220 */
221function PoolSegment({
222 account,
223 window,
224 reset,
225 color,
226 now,
227 index,
228 showAccountName,
229}: {
230 readonly account: LimitAccount;
231 readonly window: LimitPoolMember["window"];
232 readonly reset: LimitPoolWindow["resets"][number] | undefined;
233 readonly color: string;
234 readonly now: number;
235 /** 1-based position in the bar, shown on the strip and its legend row to tie them together. */
236 readonly index: number;
237 readonly showAccountName: boolean;
238}) {
239 const [open, setOpen] = useState(false);
240 const remaining = remainingPercent(window);
241 const resetsIn = formatResetsIn(window, now);
242 const credits = account.limits.resetCredits?.availableCount ?? 0;
243 return (
244 <Popover open={open} onOpenChange={setOpen}>
245 <PopoverTrigger
246 openOnHover
247 render={
248 <button
249 type="button"
250 style={{ gridColumn: index, gridRow: 1 }}
251 aria-label={`${account.displayName ?? (account.email ? accountInitials(account.email) : account.driver)}: ${remaining}% left${resetsIn ? `, ${resetsIn}` : ""}${credits ? `, ${credits} reset ${credits === 1 ? "credit" : "credits"} banked` : ""}`}
252 className="relative h-5 min-w-0 cursor-pointer overflow-hidden rounded-md bg-muted text-start outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background data-[popup-open]:ring-1 data-[popup-open]:ring-border @2xl/pool:h-8"
253 />
254 }
255 >
256 {/* Translucent so the label reads over the fill for any provider colour and theme. */}
257 <div
258 aria-hidden
259 className="absolute inset-y-0 left-0 rounded-md opacity-35"
260 style={{ width: `${remaining}%`, backgroundColor: color }}
261 />
262 {/* The spent share is hatched, not blank: it is what the countdown restores. */}
263 {remaining < 100 && reset ? (
264 <div
265 aria-hidden
266 className="absolute inset-y-0 right-0 opacity-20"
267 style={{
268 width: `${100 - remaining}%`,
269 backgroundImage: `repeating-linear-gradient(135deg, ${color} 0 1px, transparent 1px 5px)`,
270 }}
271 />
272 ) : null}
273 <span
274 aria-hidden
275 className="absolute inset-0 flex items-center justify-center text-3xs leading-none font-semibold text-foreground/80 tabular-nums @2xl/pool:hidden"
276 >
277 {index}
278 </span>
279 <div className="relative hidden h-full min-w-0 items-center gap-1.5 px-2 text-xs @2xl/pool:flex">
280 {showAccountName ? (
281 <AccountName
282 account={account}
283 className="min-w-0 truncate font-medium text-foreground"
284 />
285 ) : null}
286 <span className="shrink-0 font-semibold text-foreground tabular-nums">{remaining}%</span>
287 {/* Countdown and badge get their own plate: fill and hatching run under them otherwise. */}
288 <span className="ms-auto flex shrink-0 items-center gap-1.5 rounded-sm bg-background/85 px-1.5 py-0.5 text-2xs text-foreground tabular-nums">
289 {resetsIn?.replace("resets in ", "↻ ") ?? ""}
290 {credits ? (
291 <>
292 {resetsIn ? (
293 <span aria-hidden className="text-muted-foreground">
294 ·
295 </span>
296 ) : null}
297 <span aria-hidden className="inline-flex items-center gap-0.5 font-semibold">
298 <TicketIcon className="size-3" aria-hidden />
299 {credits}
300 </span>
301 </>
302 ) : null}
303 </span>
304 </div>
305 </PopoverTrigger>
306 <LegendRow account={account} window={window} color={color} now={now} index={index} />
307 {account.redeem ? (
308 <RedeemableSegmentPopup
309 account={account}
310 window={window}
311 reset={reset}
312 now={now}
313 redeemAt={account.redeem}
314 closePopover={() => setOpen(false)}
315 />
316 ) : (
317 <PopoverPopup side="top" sideOffset={6}>
318 <SegmentPopover
319 account={account}
320 window={window}
321 reset={reset}
322 now={now}
323 redeem={null}
324 onRedeem={() => {}}
325 />
326 </PopoverPopup>
327 )}
328 </Popover>
329 );
331​
332/**
333 * Below the strip at narrow widths: one row per account in bar order, carrying
334 * the text the segment has no room for. Tapping a row opens the same popover
335 * as its segment, so the two are one control with two handles.
336 */
337function LegendRow({
338 account,
339 window,
340 color,
341 now,
342 index,
343}: {
344 readonly account: LimitAccount;
345 readonly window: LimitPoolMember["window"];
346 readonly color: string;
347 readonly now: number;
348 readonly index: number;
349}) {
350 const remaining = remainingPercent(window);
351 const resetsIn = formatResetsIn(window, now);
352 const credits = account.limits.resetCredits?.availableCount ?? 0;
353 return (
354 <PopoverTrigger
355 style={{ gridColumn: "1 / -1", gridRow: index + 1 }}
356 render={<Button variant="ghost" size="compact" />}
357 className="min-w-0 @2xl/pool:hidden"
358 >
359 <span className="relative inline-flex size-4 shrink-0 items-center justify-center rounded-sm text-3xs leading-none font-semibold text-foreground/80 tabular-nums">
360 <span
361 aria-hidden
362 className="absolute inset-0 rounded-sm opacity-35"
363 style={{ backgroundColor: color }}
364 />
365 <span className="sr-only">Segment </span>
366 <span className="relative">{index}</span>
367 </span>
368 <AccountName account={account} className="min-w-0 truncate font-medium text-foreground" />
369 <span className="shrink-0 font-semibold text-foreground tabular-nums">{remaining}%</span>
370 <span className="ms-auto flex shrink-0 items-center gap-1.5 text-2xs text-muted-foreground tabular-nums">
371 {resetsIn?.replace("resets in ", "↻ ") ?? ""}
372 {credits ? (
373 <>
374 {resetsIn ? <span aria-hidden>·</span> : null}
375 <span
376 aria-hidden
377 className="inline-flex items-center gap-0.5 font-semibold text-foreground"
378 >
379 <TicketIcon className="size-3" aria-hidden />
380 {credits}
381 </span>
382 <span className="sr-only">
383 {credits} reset {credits === 1 ? "credit" : "credits"} banked
384 </span>
385 </>
386 ) : null}
387 </span>
388 </PopoverTrigger>
389 );
391​
392/** Split out so the redeem hook only runs for accounts that can redeem. */
393function RedeemableSegmentPopup({
394 account,
395 window,
396 reset,
397 now,
398 redeemAt,
399 closePopover,
400}: {
401 readonly account: LimitAccount;
402 readonly window: LimitPoolMember["window"];
403 readonly reset: LimitPoolWindow["resets"][number] | undefined;
404 readonly now: number;
405 readonly redeemAt: NonNullable<LimitAccount["redeem"]>;
406 readonly closePopover: () => void;
407}) {
408 const redeem = useResetCredit(redeemAt.environmentId, redeemAt.input);
409 return (
410 <>
411 <PopoverPopup side="top" sideOffset={6}>
412 <SegmentPopover
413 account={account}
414 window={window}
415 reset={reset}
416 now={now}
417 redeem={redeem}
418 onRedeem={() => {
419 closePopover();
420 redeem.setConfirming(true);
421 }}
422 />
423 </PopoverPopup>
424 <ResetCreditDialog
425 open={redeem.confirming}
426 onOpenChange={redeem.setConfirming}
427 onConfirm={() => void redeem.redeem()}
428 />
429 {/* The popover closed before the confirm, so the outcome needs a home outside it. */}
430 {redeem.status ? (
431 <span role="status" className="col-span-full text-xs text-muted-foreground">
432 <AccountName account={account} className="font-medium text-foreground" /> {redeem.status}
433 </span>
434 ) : null}
435 </>
436 );
438​
439/**
440 * One pooled window as equal-width segments, one per account, each filled by
441 * the share of that account's quota still open. Equal widths are honest: every
442 * account contributes the same share of the pool, whatever its plan.
443 *
444 * Wide, each segment carries its own label. Narrow, the bar is a bare strip
445 * and a legend below lists the accounts in the same order; both open the
446 * same popover.
447 */
448function PoolBar({
449 pool,
450 color,
451 now,
452}: {
453 readonly pool: LimitPoolWindow;
454 readonly color: string;
455 readonly now: number;
456}) {
457 const restores = new Map(pool.resets.map((reset) => [reset.member.account.key, reset]));
458 return (
459 <div className="@container/pool min-w-0">
460 <div
461 className="grid gap-x-1 gap-y-1"
462 style={{ gridTemplateColumns: `repeat(${pool.columns.length}, minmax(0, 1fr))` }}
463 >
464 {pool.columns.map((member, position) =>
465 member.window ? (
466 <PoolSegment
467 key={member.account.key}
468 account={member.account}
469 window={member.window}
470 reset={restores.get(member.account.key)}
471 color={color}
472 now={now}
473 index={position + 1}
474 showAccountName={pool.columns.length > 1}
475 />
476 ) : null,
477 )}
478 </div>
479 </div>
480 );
482​
483/**
484 * Big pooled number and the segment bar. Accounts keep the same column across
485 * windows; each segment's popover shows its own reset time and share restored.
486 */
487function PoolWindowCard({
488 pool,
489 color,
490 now,
491 label,
492 description,
493}: {
494 readonly pool: LimitPoolWindow;
495 readonly color: string;
496 readonly now: number;
497 readonly label?: string | undefined;
498 readonly description?: string | undefined;
499}) {
500 // The soonest reset that hands anything back; an untouched account resets to no effect.
501 const nextRefill = pool.resets.find((reset) => reset.restoresPercent > 0);
502 return (
503 <div className="grid items-center gap-x-6 gap-y-3 rounded-lg border border-border/60 p-4 md:grid-cols-[11rem_minmax(0,1fr)]">
504 <div className="flex flex-col gap-1">
505 <span className="text-sm font-medium text-foreground">{label ?? pool.label}</span>
506 <span className="flex items-baseline gap-2">
507 <span className="text-3xl font-semibold text-foreground tabular-nums">
508 {pool.remainingPercent}%
509 </span>
510 <span className="text-sm text-muted-foreground">left</span>
511 {pool.pace ? <PaceIcon pace={pool.pace} /> : null}
512 </span>
513 {nextRefill && pool.columns.length > 1 ? (
514 <span className="text-xs font-medium text-foreground tabular-nums">
515 ↻ +{nextRefill.restoresPercent}%
516 </span>
517 ) : null}
518 </div>
519 <PoolBar pool={pool} color={color} now={now} />
520 {description ? (
521 <p className="text-xs text-muted-foreground md:col-span-2">{description}</p>
522 ) : null}
523 </div>
524 );
526​
527function PoolSection({ pool, now }: { readonly pool: LimitPool; readonly now: number }) {
528 const color = barColor(pool.driver);
529 const label = getDriverOption(pool.driver)?.label ?? String(pool.driver);
530 const windows = displayLimitWindows(pool);
531 return (
532 <section className="flex flex-col gap-3">
533 <h2 className="flex items-center gap-2 text-sm font-medium text-foreground">
534 <ProviderInstanceIcon
535 driverKind={pool.driver}
536 displayName={label}
537 indicatorBackground="var(--background)"
538 className="size-5"
539 iconClassName="size-4 text-foreground/80"
540 />
541 {label}
542 </h2>
543 {windows.map((window) => {
544 const details = pool.driver === "cursor" ? cursorUsageWindowDetails(window.id) : undefined;
545 return (
546 <PoolWindowCard
547 key={`${window.kind}:${window.id}`}
548 pool={window}
549 color={color}
550 now={now}
551 label={details?.label}
552 description={details?.description}
553 />
554 );
555 })}
556 </section>
557 );
559​
560/**
561 * Accounts pooled per provider: what is open across all of them, who resets
562 * next, and how much of the pool that hands back. Answers "can I keep going"
563 * before "on which account".
564 */
565export function UsageLimitsPooled({
566 presentations,
567 now,
568 cursorPrompt,
569}: {
570 readonly presentations: Parameters<typeof collectLimitAccounts>[0];
571 readonly now: number;
572 readonly cursorPrompt?: ReactNode;
573}) {
574 const pools = collectLimitPools(collectLimitAccounts(presentations), now);
575 const notices = collectLimitNotices(presentations);
576 const cursorPromptAt =
577 Math.max(
578 pools.findIndex((pool) => pool.driver === "codex"),
579 pools.findIndex((pool) => pool.driver === "claudeAgent"),
580 ) + 1;
581 return (
582 <div className="flex flex-col gap-8">
583 {pools.length === 0 && notices.length === 0 && !cursorPrompt ? (
584 <p className="text-sm text-muted-foreground">
585 No provider on the selected environments reports subscription limits.
586 </p>
587 ) : null}
588 {pools.map((pool, index) => (
589 <Fragment key={pool.driver}>
590 {index === cursorPromptAt ? cursorPrompt : null}
591 <PoolSection pool={pool} now={now} />
592 </Fragment>
593 ))}
594 {cursorPromptAt === pools.length ? cursorPrompt : null}
595 <LimitNotices notices={notices} />
596 </div>
597 );
599​
600/** Sources and providers that could not be read, so a missing bar is not mistaken for a full one. */
601function LimitNotices({ notices }: { readonly notices: readonly string[] }) {
602 if (notices.length === 0) return null;
603 return (
604 <Alert variant="warning" controlAlignment="first-line">
605 <AlertTriangleIcon />
606 {notices.map((notice) => (
607 <AlertTitle key={notice} className="break-words">
608 {notice}
609 </AlertTitle>
610 ))}
611 </Alert>
612 );