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

UsageLimitsPooled.tsx

648 lines22.3 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}
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 />
433 {/* The popover closed before the confirm, so the outcome needs a home outside it. */}
434 {redeem.status ? (
435 <span role="status" className="col-span-full text-xs text-muted-foreground">
436 <AccountName account={account} className="font-medium text-foreground" /> {redeem.status}
437 </span>
438 ) : null}
439 </>
440 );
442​
443/**
444 * One pooled window as equal-width segments, one per account, each filled by
445 * the share of that account's quota still open. Equal widths are honest: every
446 * account contributes the same share of the pool, whatever its plan.
447 *
448 * Wide, each segment carries its own label. Narrow, the bar is a bare strip
449 * and a legend below lists the accounts in the same order; both open the
450 * same popover.
451 */
452function PoolBar({
453 pool,
454 color,
455 now,
456}: {
457 readonly pool: LimitPoolWindow;
458 readonly color: string;
459 readonly now: number;
460}) {
461 const restores = new Map(pool.resets.map((reset) => [reset.member.account.key, reset]));
462 return (
463 <div className="@container/pool min-w-0">
464 <div
465 className="grid gap-x-1 gap-y-1"
466 style={{ gridTemplateColumns: `repeat(${pool.columns.length}, minmax(0, 1fr))` }}
467 >
468 {pool.columns.map((member, position) =>
469 member.window ? (
470 <PoolSegment
471 key={member.account.key}
472 account={member.account}
473 window={member.window}
474 reset={restores.get(member.account.key)}
475 color={color}
476 now={now}
477 index={position + 1}
478 showAccountName={pool.columns.length > 1}
479 />
480 ) : null,
481 )}
482 </div>
483 </div>
484 );
486​
487/**
488 * Big pooled number and the segment bar. Accounts keep the same column across
489 * windows; each segment's popover shows its own reset time and share restored.
490 */
491function PoolWindowCard({
492 pool,
493 color,
494 now,
495 label,
496 description,
497}: {
498 readonly pool: LimitPoolWindow;
499 readonly color: string;
500 readonly now: number;
501 readonly label?: string | undefined;
502 readonly description?: string | undefined;
503}) {
504 // The soonest reset that hands anything back; an untouched account resets to no effect.
505 const nextRefill = pool.resets.find((reset) => reset.restoresPercent > 0);
506 return (
507 <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)]">
508 <div className="flex flex-col gap-1">
509 <span className="text-sm font-medium text-foreground">{label ?? pool.label}</span>
510 <span className="flex items-baseline gap-2">
511 <span className="text-3xl font-semibold text-foreground tabular-nums">
512 {pool.remainingPercent}%
513 </span>
514 <span className="text-sm text-muted-foreground">left</span>
515 {pool.pace ? <PaceIcon pace={pool.pace} /> : null}
516 </span>
517 {nextRefill && pool.columns.length > 1 ? (
518 <span className="text-xs font-medium text-foreground tabular-nums">
519 ↻ +{nextRefill.restoresPercent}%
520 </span>
521 ) : null}
522 </div>
523 <PoolBar pool={pool} color={color} now={now} />
524 {description ? (
525 <p className="text-xs text-muted-foreground md:col-span-2">{description}</p>
526 ) : null}
527 </div>
528 );
530​
531function PoolSection({ pool, now }: { readonly pool: LimitPool; readonly now: number }) {
532 const color = barColor(pool.driver);
533 const label = getDriverOption(pool.driver)?.label ?? String(pool.driver);
534 const windows = displayLimitWindows(pool);
535 return (
536 <section className="flex flex-col gap-3">
537 <h2 className="flex items-center gap-2 text-sm font-medium text-foreground">
538 <ProviderInstanceIcon
539 driverKind={pool.driver}
540 displayName={label}
541 indicatorBackground="var(--background)"
542 className="size-5"
543 iconClassName="size-4 text-foreground/80"
544 />
545 {label}
546 </h2>
547 {windows.map((window) => {
548 const details = pool.driver === "cursor" ? cursorUsageWindowDetails(window.id) : undefined;
549 return (
550 <PoolWindowCard
551 key={`${window.kind}:${window.id}`}
552 pool={window}
553 color={color}
554 now={now}
555 label={details?.label}
556 description={details?.description}
557 />
558 );
559 })}
560 </section>
561 );
563​
564/**
565 * Accounts pooled per provider: what is open across all of them, who resets
566 * next, and how much of the pool that hands back. Answers "can I keep going"
567 * before "on which account".
568 */
569export function UsageLimitsPooled({
570 presentations,
571 now,
572 cursorPrompt,
573}: {
574 readonly presentations: Parameters<typeof collectLimitAccounts>[0];
575 readonly now: number;
576 readonly cursorPrompt?: ReactNode;
577}) {
578 const pools = collectLimitPools(collectLimitAccounts(presentations), now);
579 const notices = collectLimitNotices(presentations);
580 const externalLinks = collectExternalUsageLinks(presentations);
581 const cursorPromptAt =
582 Math.max(
583 pools.findIndex((pool) => pool.driver === "codex"),
584 pools.findIndex((pool) => pool.driver === "claudeAgent"),
585 ) + 1;
586 return (
587 <div className="flex flex-col gap-8">
588 {pools.length === 0 && notices.length === 0 && !cursorPrompt && externalLinks.length === 0 ? (
589 <p className="text-sm text-muted-foreground">
590 No provider on the selected environments reports subscription limits.
591 </p>
592 ) : null}
593 {pools.map((pool, index) => (
594 <Fragment key={pool.driver}>
595 {index === cursorPromptAt ? cursorPrompt : null}
596 <PoolSection pool={pool} now={now} />
597 </Fragment>
598 ))}
599 {cursorPromptAt === pools.length ? cursorPrompt : null}
600 {externalLinks.map((link) => (
601 <section
602 key={link.url}
603 className="flex flex-wrap items-center justify-between gap-3 rounded-xl border p-4"
604 >
605 <div className="flex min-w-0 flex-1 items-center gap-3">
606 {link.url === CHATGPT_USAGE_URL ? (
607 <OpenAI className="size-5 shrink-0" aria-hidden="true" />
608 ) : null}
609 <div className="min-w-0 space-y-1">
610 <h2 className="text-sm font-medium">{link.label}</h2>
611 {link.url === CHATGPT_USAGE_URL ? (
612 <p className="text-xs text-muted-foreground">
613 View usage in ChatGPT with your connected account.
614 </p>
615 ) : link.message ? (
616 <p className="max-w-xl text-xs text-muted-foreground">{link.message}</p>
617 ) : null}
618 </div>
619 </div>
620 <Button
621 variant="ghost-muted"
622 size="xs"
623 onClick={() => void ensureLocalApi().shell.openExternal(link.url)}
624 >
625 Manage usage
626 <ExternalLinkIcon className="size-3.5" aria-hidden="true" />
627 </Button>
628 </section>
629 ))}
630 <LimitNotices notices={notices} />
631 </div>
632 );
634​
635/** Sources and providers that could not be read, so a missing bar is not mistaken for a full one. */
636function LimitNotices({ notices }: { readonly notices: readonly string[] }) {
637 if (notices.length === 0) return null;
638 return (
639 <Alert variant="warning" controlAlignment="first-line">
640 <AlertTriangleIcon />
641 {notices.map((notice) => (
642 <AlertTitle key={notice} className="break-words">
643 {notice}
644 </AlertTitle>
645 ))}
646 </Alert>
647 );