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

UsageLimitsPooled.tsx

804 lines27.7 KB

1import {
2 CHATGPT_USAGE_URL,
3 collectHttpQuotaSources,
4 collectLimitAccounts,
5 collectLimitPools,
6 displayLimitWindows,
7 type LimitAccount,
8 type LimitPool,
9 type LimitPoolMember,
10 type LimitPoolWindow,
11 paceRemainingPercent,
12 remainingPercent,
13 type ResetCreditChoice,
14} from "@t3tools/shared/usageLimits";
15import { T, Var, useGT, useMessages, plural, part } from "gt-react";
16import type { Popover as PopoverPrimitive } from "@base-ui/react/popover";
17import { normalizeProviderAccentColor } from "@t3tools/client-runtime/state/provider-instance-display";
18import { AlertTriangleIcon, ExternalLinkIcon, TicketIcon } from "lucide-react";
19import {
20 createContext,
21 Fragment,
22 type ReactNode,
23 type RefObject,
24 use,
25 useLayoutEffect,
26 useRef,
27 useState,
28} from "react";
29​
30import { ensureLocalApi } from "../../localApi";
31import { usePrimarySettings } from "../../hooks/useSettings";
32import { cn } from "../../lib/utils";
33import { formatUpcomingTimestamp } from "../../timestampFormat";
34import { ProviderInstanceIcon } from "../chat/ProviderInstanceIcon";
35import { providerClients } from "../settings/providerDriverMeta";
36import { RedactedSensitiveText } from "../settings/RedactedSensitiveText";
37import { Button } from "../ui/button";
38import { OpenAI } from "../Icons";
39import { Alert, AlertTitle } from "../ui/alert";
40import { Popover, PopoverCreateHandle, PopoverPopup, PopoverTrigger } from "../ui/popover";
41import { PaceIcon, ResetCreditDialog, barColor, usePaceMark, useResetCredit } from "./UsageLimits";
42import {
43 collectExternalUsageLinks,
44 collectLimitNotices,
45 cursorUsageWindowDetails,
46 formatDuration,
47 formatResetsIn,
48 resetCreditChoices,
49} from "@t3tools/shared/usageLimitsCopy";
50​
51function accountInitials(email: string): string {
52 const [local = "", domain = ""] = email.split("@");
53 return `${local[0] ?? ""}${domain[0] ?? ""}`.toUpperCase() || "?";
55​
56function accountHue(email: string): number {
57 let hash = 0;
58 for (let index = 0; index < email.length; index += 1) {
59 hash = (hash * 31 + email.charCodeAt(index)) | 0;
60 }
61 return Math.abs(hash) % 360;
63​
64function AccountChip({ email }: { readonly email: string }) {
65 const hue = accountHue(email);
66 const gt = useGT();
67 return (
68 <span
69 role="img"
70 aria-label={gt`Account ${{ initials: accountInitials(email) }}`}
71 className="inline-flex size-4 shrink-0 items-center justify-center rounded-full text-3xs leading-none font-semibold"
72 style={{ backgroundColor: `oklch(0.85 0.08 ${hue})`, color: `oklch(0.35 0.1 ${hue})` }}
73 >
74 {accountInitials(email)}
75 </span>
76 );
78​
79function AccountAvatar({
80 account,
81 className,
82}: {
83 readonly account: LimitAccount;
84 readonly className?: string;
85}) {
86 if (account.redeem) {
87 return (
88 <ProviderInstanceIcon
89 driverKind={account.driver}
90 displayName={
91 account.displayName ??
92 providerClients.get(account.driver)?.label ??
93 String(account.driver)
94 }
95 accentColor={account.accentColor}
96 showBadge={Boolean(account.displayName)}
97 indicatorBackground="var(--popover)"
98 className={cn("size-5", className)}
99 iconClassName="size-4 text-foreground/80"
100 />
101 );
102 }
103 return account.email ? <AccountChip email={account.email} /> : null;
105​
106function AccountName({
107 account,
108 className,
109}: {
110 readonly account: LimitAccount;
111 readonly className?: string;
112}) {
113 if (account.displayName) return <span className={className}>{account.displayName}</span>;
114 if (account.email) {
115 return (
116 <span className={cn("inline-flex min-w-0 items-center", className)}>
117 <AccountChip email={account.email} />
118 </span>
119 );
120 }
121 return (
122 <span className={className}>
123 {providerClients.get(account.driver)?.label ?? String(account.driver)}
124 </span>
125 );
127​
128function Row({ label, children }: { readonly label: string; readonly children: ReactNode }) {
129 return (
130 <div className="grid grid-cols-[4.5rem_minmax(0,1fr)] gap-x-3">
131 <span className="text-muted-foreground">{label}</span>
132 <span className="min-w-0 text-foreground tabular-nums">{children}</span>
133 </div>
134 );
136​
137function SegmentPopover({
138 account,
139 window,
140 reset,
141 now,
142 redeem,
143 onRedeem,
144}: {
145 readonly account: LimitAccount;
146 readonly window: LimitPoolMember["window"];
147 readonly reset: LimitPoolWindow["resets"][number] | undefined;
148 readonly now: number;
149 readonly redeem: ReturnType<typeof useResetCredit> | null;
150 readonly onRedeem: (choice: ResetCreditChoice) => void;
151}) {
152 const timestampFormat = usePrimarySettings((settings) => settings.timestampFormat);
153 const gt = useGT();
154 const m = useMessages();
155 const remaining = remainingPercent(window);
156 const timeLeft = paceRemainingPercent(window, now);
157 const resetsIn = formatResetsIn(window, now, m, "in");
158 const where =
159 account.environments.length > 0
160 ? account.environments.map((environment) => environment.label).join(", ")
161 : account.sourceLabel;
162 const choices =
163 redeem && account.redeem && account.limits.resetCredits?.availableCount
164 ? resetCreditChoices(account.limits.resetCredits, account.redeem.input, now, true, m)
165 : [];
166 return (
167 <div className="flex w-72 max-w-[calc(100vw-3rem)] flex-col gap-2.5 text-xs">
168 <div className="flex min-w-0 flex-col gap-0.5">
169 <span className="flex items-center gap-2 text-sm font-medium text-foreground">
170 <AccountAvatar account={account} />
171 <span className="truncate">
172 {account.displayName ?? providerClients.get(account.driver)?.label ?? account.driver}
173 </span>
174 </span>
175 {account.email ? (
176 <RedactedSensitiveText
177 value={account.email}
178 ariaLabel={gt`Toggle account email visibility`}
179 revealTooltip={gt`Click to reveal email`}
180 hideTooltip={gt`Click to hide email`}
181 className="w-fit"
182 />
183 ) : null}
184 </div>
185 <div className="flex flex-col gap-1 border-t border-border/60 pt-2.5">
186 {account.plan ? (
187 <Row label={gt({ context: "subscription plan" })`Plan`}>{account.plan}</Row>
188 ) : null}
189 {where ? (
190 <Row
191 label={
192 account.environments.length > 0
193 ? gt`Signed in`
194 : gt({ context: "signed in through a source" })`Via`
195 }
196 >
197 {where}
198 </Row>
199 ) : null}
200 </div>
201 <div className="flex flex-col gap-1 border-t border-border/60 pt-2.5">
202 <Row label={gt({ context: "remaining usage" })`Left`}>{remaining}%</Row>
203 {window.resetsAt ? (
204 <Row label={gt({ context: "when the usage window resets" })`Resets`}>
205 {formatUpcomingTimestamp(window.resetsAt, timestampFormat, now, undefined, m)}
206 {resetsIn ? ` · ${resetsIn}` : ""}
207 </Row>
208 ) : null}
209 {timeLeft !== null ? (
210 <Row label={gt`Even pace`}>{gt`${{ timeLeft }}% left by now`}</Row>
211 ) : null}
212 {reset && reset.restoresPercent > 0 ? (
213 <Row label={gt({ context: "a reset credit restores part of the pool" })`Restores`}>
214 {gt`+${{ percent: reset.restoresPercent }}% of pool`}
215 </Row>
216 ) : null}
217 </div>
218 {choices.length > 0 && redeem ? (
219 <div className="flex flex-col gap-1.5 border-t border-border/60 pt-2.5 text-muted-foreground">
220 {choices.map((choice) => (
221 <span key={choice.key} className="flex items-center gap-3">
222 <span className="tabular-nums">{choice.summary}</span>
223 {choice.availableCount > 0 ? (
224 <Button
225 size="xs"
226 variant="outline"
227 disabled={redeem.busy || !redeem.canManageProviders}
228 className="ms-auto"
229 onClick={() => onRedeem(choice)}
230 >
231 {redeem.busy ? gt`Using…` : choice.actionLabel}
232 </Button>
233 ) : null}
234 </span>
235 ))}
236 </div>
237 ) : null}
238 </div>
239 );
241​
242/**
243 * Every segment on the page shares one popover, so hovering or clicking another
244 * segment moves it instead of opening a second one. The payload is the segment
245 * it currently describes.
246 */
247type SegmentPayload = Omit<Parameters<typeof SegmentPopover>[0], "now" | "onRedeem">;
248const SegmentPopoverContext = createContext<ReturnType<
249 typeof PopoverCreateHandle<SegmentPayload>
250> | null>(null);
251​
252function ActiveSegmentPopover({
253 handle,
254 actions,
255 payload,
256 pools,
257 now,
258}: {
259 readonly handle: ReturnType<typeof PopoverCreateHandle<SegmentPayload>>;
260 readonly actions: RefObject<PopoverPrimitive.Root.Actions | null>;
261 readonly payload: SegmentPayload;
262 readonly pools: readonly LimitPool[];
263 readonly now: number;
264}) {
265 const available = pools.some((pool) =>
266 displayLimitWindows(pool).some((window) =>
267 window.members.some(
268 (member) =>
269 member.account.key === payload.account.key &&
270 member.window.id === payload.window.id &&
271 member.window.kind === payload.window.kind &&
272 Boolean(member.account.redeem) === Boolean(payload.redeem),
273 ),
274 ),
275 );
276 // The trigger is gone, so the popup has nothing to anchor to: an exit transition would
277 // slide it to the viewport origin. Unmount it outright, which also clears Base UI's
278 // active-trigger bookkeeping so the segment can open again when it comes back.
279 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- closes the popover handle and unmounts the Base UI popup before paint when its trigger is gone
280 useLayoutEffect(() => {
281 if (available) return;
282 handle.close();
283 actions.current?.unmount();
284 }, [available, handle, actions]);
285 return (
286 <PopoverPopup side="top" sideOffset={6}>
287 <SegmentPopover
288 {...payload}
289 now={now}
290 onRedeem={(choice) => {
291 handle.close();
292 payload.redeem?.confirm(choice);
293 }}
294 />
295 </PopoverPopup>
296 );
298​
299/**
300 * The confirm is a sibling of the popover, not a child: dialogs stack under
301 * popovers, and the popover closes as the confirm opens.
302 */
303function PoolSegment({
304 account,
305 ...props
306}: {
307 readonly account: LimitAccount;
308 readonly window: LimitPoolMember["window"];
309 readonly reset: LimitPoolWindow["resets"][number] | undefined;
310 readonly refillPercent: number;
311 readonly color: string;
312 readonly now: number;
313 readonly index: number;
314 readonly showAccountName: boolean;
315}) {
316 return account.redeem ? (
317 <RedeemableSegment account={account} redeemAt={account.redeem} {...props} />
318 ) : (
319 <SegmentTriggers account={account} redeem={null} {...props} />
320 );
322​
323function RedeemableSegment({
324 redeemAt,
325 ...props
326}: Omit<Parameters<typeof SegmentTriggers>[0], "redeem"> & {
327 readonly redeemAt: NonNullable<LimitAccount["redeem"]>;
328}) {
329 const redeem = useResetCredit(redeemAt.environmentId);
330 const gt = useGT();
331 return (
332 <>
333 <SegmentTriggers redeem={redeem} {...props} />
334 <ResetCreditDialog
335 open={redeem.confirming}
336 onOpenChange={redeem.setConfirming}
337 choice={redeem.choice}
338 onConfirm={() => void redeem.redeem()}
339 disabled={!redeem.canManageProviders}
340 />
341 {/* The popover closed before the confirm, so progress and the outcome need a home outside it. */}
342 {redeem.busy || redeem.status ? (
343 <span role="status" className="col-span-full text-xs text-muted-foreground">
344 <AccountName account={props.account} className="font-medium text-foreground" />{" "}
345 {redeem.busy ? gt`Using reset credit…` : redeem.status}
346 </span>
347 ) : null}
348 </>
349 );
351​
352function SegmentTriggers({
353 account,
354 window,
355 reset,
356 redeem,
357 refillPercent,
358 color,
359 now,
360 index,
361 showAccountName,
362}: SegmentPayload & {
363 readonly refillPercent: number;
364 readonly color: string;
365 readonly now: number;
366 readonly index: number;
367 readonly showAccountName: boolean;
368}) {
369 const popover = use(SegmentPopoverContext) ?? undefined;
370 const payload: SegmentPayload = { account, window, reset, redeem };
371 const remaining = remainingPercent(window);
372 const timeLeft = paceRemainingPercent(window, now);
373 const [segmentRef, paceMark] = usePaceMark(timeLeft);
374 const m = useMessages();
375 const resetsIn = formatResetsIn(window, now, m);
376 const refillIn = formatResetsIn(window, now, m, "refill");
377 const credits = account.limits.resetCredits?.availableCount ?? 0;
378 const gt = useGT();
379 const segmentLabel = [
380 gt`${{ name: account.displayName ?? (account.email ? accountInitials(account.email) : account.driver) }}: ${{ remaining }}% left`,
381 resetsIn,
382 timeLeft === null ? null : gt`${{ timeLeft }}% of the window left`,
383 credits
384 ? gt`${plural(
385 { count: credits },
386 {
387 one: part`${{ count: credits }} reset credit banked`,
388 other: part`${{ count: credits }} reset credits banked`,
389 },
390 )}`
391 : null,
392 ]
393 .filter(Boolean)
394 .join(", ");
395 return (
396 <>
397 <PopoverTrigger
398 handle={popover}
399 payload={payload}
400 openOnHover
401 render={
402 <button
403 ref={segmentRef}
404 type="button"
405 style={{ gridColumn: index, gridRow: 1, ...paceMark?.gappedTrack }}
406 aria-label={segmentLabel}
407 className="relative h-5 min-w-0 cursor-pointer rounded-md bg-muted text-start outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background data-[popup-open]:ring-1 data-[popup-open]:ring-inset data-[popup-open]:ring-border @2xl/pool:h-8"
408 />
409 }
410 >
411 <div aria-hidden className="absolute inset-0 overflow-hidden rounded-md">
412 {/* Clipped inside the rounded clip so the bar's own corners keep their antialiasing. */}
413 <div className="absolute inset-0" style={paceMark?.gap}>
414 <div
415 aria-hidden
416 className="absolute inset-y-0 left-0 rounded-md opacity-35"
417 style={{ width: `${remaining}%`, backgroundColor: color }}
418 />
419 {remaining < 100 && reset && refillPercent > 0 ? (
420 <div
421 aria-hidden
422 className="absolute inset-y-0 right-0 opacity-20"
423 style={{
424 width: `${Math.min(100 - remaining, refillPercent)}%`,
425 // A bare 45° gradient repeats every 5√2px, so some stripes rasterize thinner; a whole-pixel tile doesn't.
426 backgroundImage: `repeating-linear-gradient(135deg, transparent 0 1px, ${color} 1px 2px, transparent 2px 50%)`,
427 backgroundSize: "7px 7px",
428 }}
429 />
430 ) : null}
431 </div>
432 </div>
433 {paceMark ? (
434 <span
435 aria-hidden
436 className="absolute inset-y-0.5 w-0.5 -translate-x-1/2 rounded-full bg-foreground"
437 style={paceMark.tick}
438 />
439 ) : null}
440 <span
441 aria-hidden
442 className="absolute inset-0 flex items-center justify-center overflow-hidden rounded-md text-3xs leading-none font-semibold text-foreground/80 tabular-nums @2xl/pool:hidden"
443 >
444 {index}
445 </span>
446 <div className="relative hidden h-full min-w-0 items-center gap-1.5 overflow-hidden rounded-md px-2 text-xs @2xl/pool:flex">
447 {showAccountName ? (
448 <AccountName
449 account={account}
450 className="min-w-0 truncate font-medium text-foreground"
451 />
452 ) : null}
453 {/* A single-account bar repeats the headline percentage. */}
454 {showAccountName ? (
455 <span className="shrink-0 font-semibold text-foreground tabular-nums">
456 {remaining}%
457 </span>
458 ) : null}
459 {resetsIn || credits ? (
460 <span className="ms-auto flex min-w-0 items-center gap-1.5 overflow-hidden rounded-sm bg-background/85 px-1.5 py-0.5 text-2xs whitespace-nowrap text-foreground tabular-nums">
461 {refillIn ?? ""}
462 {credits ? (
463 <>
464 {resetsIn ? (
465 <span aria-hidden className="text-muted-foreground">
466 ·
467 </span>
468 ) : null}
469 <span aria-hidden className="inline-flex items-center gap-0.5 font-semibold">
470 <TicketIcon className="size-3" aria-hidden />
471 {credits}
472 </span>
473 </>
474 ) : null}
475 </span>
476 ) : null}
477 </div>
478 </PopoverTrigger>
479 <LegendRow payload={payload} color={color} now={now} index={index} />
480 </>
481 );
483​
484function LegendRow({
485 payload,
486 color,
487 now,
488 index,
489}: {
490 readonly payload: SegmentPayload;
491 readonly color: string;
492 readonly now: number;
493 readonly index: number;
494}) {
495 const popover = use(SegmentPopoverContext) ?? undefined;
496 const { account, window } = payload;
497 const remaining = remainingPercent(window);
498 const m = useMessages();
499 const resetsIn = formatResetsIn(window, now, m, "refill");
500 const credits = account.limits.resetCredits?.availableCount ?? 0;
501 const gt = useGT();
502 return (
503 <PopoverTrigger
504 handle={popover}
505 payload={payload}
506 style={{ gridColumn: "1 / -1", gridRow: index + 1 }}
507 render={<Button variant="ghost" size="compact" />}
508 className="min-w-0 @2xl/pool:hidden"
509 >
510 <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">
511 <span
512 aria-hidden
513 className="absolute inset-0 rounded-sm opacity-35"
514 style={{ backgroundColor: color }}
515 />
516 <span className="sr-only">{`${gt`Segment`} `}</span>
517 <span className="relative">{index}</span>
518 </span>
519 <AccountName account={account} className="min-w-0 truncate font-medium text-foreground" />
520 <span className="shrink-0 font-semibold text-foreground tabular-nums">{remaining}%</span>
521 <span className="ms-auto flex shrink-0 items-center gap-1.5 text-2xs text-muted-foreground tabular-nums">
522 {resetsIn ?? ""}
523 {credits ? (
524 <>
525 {resetsIn ? <span aria-hidden>·</span> : null}
526 <span
527 aria-hidden
528 className="inline-flex items-center gap-0.5 font-semibold text-foreground"
529 >
530 <TicketIcon className="size-3" aria-hidden />
531 {credits}
532 </span>
533 <span className="sr-only">
534 {gt`${plural(
535 { count: credits },
536 {
537 one: part`${{ count: credits }} reset credit banked`,
538 other: part`${{ count: credits }} reset credits banked`,
539 },
540 )}`}
541 </span>
542 </>
543 ) : null}
544 </span>
545 </PopoverTrigger>
546 );
548​
549function PoolBar({
550 pool,
551 color,
552 now,
553}: {
554 readonly pool: LimitPoolWindow;
555 readonly color: string;
556 readonly now: number;
557}) {
558 const restores = new Map(pool.resets.map((reset) => [reset.member.account.key, reset]));
559 const gt = useGT();
560 return (
561 <div className="@container/pool min-w-0">
562 <div
563 className="grid gap-x-1 gap-y-1"
564 style={{ gridTemplateColumns: `repeat(${pool.columns.length}, minmax(0, 1fr))` }}
565 >
566 {pool.columns.map((member, position) =>
567 member.window ? (
568 <PoolSegment
569 key={member.account.key}
570 account={member.account}
571 window={member.window}
572 reset={restores.get(member.account.key)}
573 refillPercent={member.refillPercent}
574 color={normalizeProviderAccentColor(member.account.accentColor) ?? color}
575 now={now}
576 index={position + 1}
577 showAccountName={pool.columns.length > 1}
578 />
579 ) : pool.kind === "monthly" && member.account.limits.zeroSpendCap ? (
580 <div
581 key={member.account.key}
582 style={{ gridColumn: position + 1, gridRow: 1 }}
583 className="flex h-5 min-w-0 items-center justify-center gap-1.5 overflow-hidden rounded-md border border-dashed border-border text-3xs whitespace-nowrap text-muted-foreground @2xl/pool:h-8 @2xl/pool:justify-start @2xl/pool:px-2 @2xl/pool:text-xs"
584 >
585 <AccountName
586 account={member.account}
587 className="hidden min-w-0 truncate @2xl/pool:inline-flex"
588 />
589 {gt`$0 cap`}
590 </div>
591 ) : null,
592 )}
593 </div>
594 </div>
595 );
597​
598function PoolWindowCard({
599 pool,
600 color,
601 now,
602 label,
603 description,
604}: {
605 readonly pool: LimitPoolWindow;
606 readonly color: string;
607 readonly now: number;
608 readonly label?: string | null | undefined;
609 readonly description?: string | undefined;
610}) {
611 const m = useMessages();
612 const nextRefill = pool.resets.find((reset) => reset.at > now && reset.restoresPercent > 0);
613 return (
614 <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)]">
615 <div className="flex flex-col gap-1">
616 {label !== null ? (
617 <span className="text-sm font-medium text-foreground">{label ?? pool.label}</span>
618 ) : null}
619 <span className="flex items-baseline gap-2">
620 <span className="text-3xl font-semibold text-foreground tabular-nums">
621 {pool.remainingPercent}%
622 </span>
623 <span className="inline-flex items-center gap-2 text-sm text-muted-foreground">
624 <span>
625 <T context="remaining usage percentage">left</T>
626 </span>
627 {pool.pace ? <PaceIcon pace={pool.pace} /> : null}
628 </span>
629 </span>
630 {nextRefill && pool.columns.length > 1 ? (
631 <span className="text-xs text-muted-foreground tabular-nums">
632 <T context="usage limit refill">
633 <span className="font-medium text-foreground">
634 ↻ +<Var>{nextRefill.restoresPercent}</Var>%
635 </span>{" "}
636 in <Var>{formatDuration(nextRefill.at - now, m)}</Var>
637 </T>
638 </span>
639 ) : null}
640 </div>
641 <PoolBar pool={pool} color={color} now={now} />
642 {description ? (
643 <p className="text-xs text-muted-foreground md:col-span-2">{description}</p>
644 ) : null}
645 </div>
646 );
648​
649function PoolSection({ pool, now }: { readonly pool: LimitPool; readonly now: number }) {
650 const color = barColor(pool.driver);
651 const label = providerClients.get(pool.driver)?.label ?? String(pool.driver);
652 const windows = displayLimitWindows(pool);
653 const m = useMessages();
654 return (
655 <section className="flex flex-col gap-3">
656 <h2 className="flex items-center gap-2 text-sm font-medium text-foreground">
657 <ProviderInstanceIcon
658 driverKind={pool.driver}
659 displayName={label}
660 indicatorBackground="var(--background)"
661 className="size-5"
662 iconClassName="size-4 text-foreground/80"
663 />
664 {label}
665 </h2>
666 {windows.map((window) => {
667 const details =
668 pool.driver === "cursor" ? cursorUsageWindowDetails(window.id, pool, m) : undefined;
669 return (
670 <PoolWindowCard
671 key={`${window.kind}:${window.id}`}
672 pool={window}
673 color={color}
674 now={now}
675 label={details?.label}
676 description={details?.description}
677 />
678 );
679 })}
680 </section>
681 );
683​
684export function UsageLimitsPooled({
685 presentations,
686 now,
687}: {
688 readonly presentations: Parameters<typeof collectLimitAccounts>[0];
689 readonly now: number;
690}) {
691 const gt = useGT();
692 const m = useMessages();
693 const [segmentPopover] = useState(() => PopoverCreateHandle<SegmentPayload>());
694 const segmentPopoverActions = useRef<PopoverPrimitive.Root.Actions | null>(null);
695 const pools = collectLimitPools(collectLimitAccounts(presentations), now);
696 const quotaSources = collectHttpQuotaSources(presentations);
697 const notices = collectLimitNotices(presentations, m);
698 const externalLinks = collectExternalUsageLinks(presentations, m);
699 return (
700 <div className="flex flex-col gap-8">
701 {pools.length === 0 &&
702 notices.length === 0 &&
703 externalLinks.length === 0 &&
704 quotaSources.length === 0 ? (
705 <p className="text-sm text-muted-foreground">
706 <T>No provider on the selected environments reports subscription limits.</T>
707 </p>
708 ) : null}
709 <SegmentPopoverContext value={segmentPopover}>
710 {pools.map((pool) => (
711 <Fragment key={pool.driver}>
712 <PoolSection pool={pool} now={now} />
713 </Fragment>
714 ))}
715 </SegmentPopoverContext>
716 <Popover handle={segmentPopover} actionsRef={segmentPopoverActions}>
717 {({ payload }) =>
718 payload ? (
719 <ActiveSegmentPopover
720 handle={segmentPopover}
721 actions={segmentPopoverActions}
722 payload={payload}
723 pools={pools}
724 now={now}
725 />
726 ) : null
727 }
728 </Popover>
729 {quotaSources.map((source) => (
730 <section key={source.key} className="space-y-3 rounded-xl border p-4">
731 <h2 className="text-sm font-medium">{source.label}</h2>
732 {source.quotaAccounts?.map((account) => (
733 <div key={account.id} className="space-y-1">
734 <h3 className="text-sm font-medium">{account.label}</h3>
735 {account.windows.map((window) => {
736 const reset = formatResetsIn(window, now, m);
737 return (
738 <div
739 key={window.id}
740 className="flex justify-between gap-3 text-sm text-muted-foreground"
741 >
742 <span>{window.label}</span>
743 <span>
744 {gt`${{ remaining: remainingPercent(window) }}% left`}
745 {reset ? ` · ${reset}` : ""}
746 </span>
747 </div>
748 );
749 })}
750 </div>
751 ))}
752 </section>
753 ))}
754 {externalLinks.map((link) => (
755 <section
756 key={link.url}
757 className="flex flex-wrap items-center justify-between gap-3 rounded-xl border p-4"
758 >
759 <div className="flex min-w-0 flex-1 items-center gap-3">
760 {link.url === CHATGPT_USAGE_URL ? (
761 <OpenAI className="size-5 shrink-0" aria-hidden="true" />
762 ) : null}
763 <div className="min-w-0 space-y-1">
764 <h2 className="text-sm font-medium">{link.label}</h2>
765 <p className="text-xs break-words text-muted-foreground">
766 {link.accounts.join(", ")}
767 </p>
768 {link.url === CHATGPT_USAGE_URL ? (
769 <p className="text-xs text-muted-foreground">
770 <T>View usage in ChatGPT with your connected account.</T>
771 </p>
772 ) : link.message ? (
773 <p className="max-w-xl text-xs text-muted-foreground">{link.message}</p>
774 ) : null}
775 </div>
776 </div>
777 <Button
778 variant="ghost-muted"
779 size="xs"
780 onClick={() => void ensureLocalApi().shell.openExternal(link.url)}
781 >
782 {gt`Manage usage`}
783 <ExternalLinkIcon className="size-3.5" aria-hidden="true" />
784 </Button>
785 </section>
786 ))}
787 <LimitNotices notices={notices} />
788 </div>
789 );
791​
792function LimitNotices({ notices }: { readonly notices: readonly string[] }) {
793 if (notices.length === 0) return null;
794 return (
795 <Alert variant="warning" controlAlignment="first-line">
796 <AlertTriangleIcon />
797 {notices.map((notice) => (
798 <AlertTitle key={notice} className="break-words">
799 {notice}
800 </AlertTitle>
801 ))}
802 </Alert>
803 );