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

UsageLimitsPooled.tsx

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