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

UsageLimitsPooled.tsx

649 lines22.4 KB

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