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

UsageLimitsPooled.tsx

795 lines27.4 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, useGT, useMessages } 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 formatResetsIn,
47 resetCreditChoices,
48} from "@t3tools/shared/usageLimitsCopy";
49​
50function accountInitials(email: string): string {
51 const [local = "", domain = ""] = email.split("@");
52 return `${local[0] ?? ""}${domain[0] ?? ""}`.toUpperCase() || "?";
54​
55function accountHue(email: string): number {
56 let hash = 0;
57 for (let index = 0; index < email.length; index += 1) {
58 hash = (hash * 31 + email.charCodeAt(index)) | 0;
59 }
60 return Math.abs(hash) % 360;
62​
63function AccountChip({ email }: { readonly email: string }) {
64 const hue = accountHue(email);
65 const gt = useGT();
66 return (
67 <span
68 role="img"
69 aria-label={gt("Account {initials}", { initials: accountInitials(email) })}
70 className="inline-flex size-4 shrink-0 items-center justify-center rounded-full text-3xs leading-none font-semibold"
71 style={{ backgroundColor: `oklch(0.85 0.08 ${hue})`, color: `oklch(0.35 0.1 ${hue})` }}
72 >
73 {accountInitials(email)}
74 </span>
75 );
77​
78function AccountAvatar({
79 account,
80 className,
81}: {
82 readonly account: LimitAccount;
83 readonly className?: string;
84}) {
85 if (account.redeem) {
86 return (
87 <ProviderInstanceIcon
88 driverKind={account.driver}
89 displayName={
90 account.displayName ??
91 providerClients.get(account.driver)?.label ??
92 String(account.driver)
93 }
94 accentColor={account.accentColor}
95 showBadge={Boolean(account.displayName)}
96 indicatorBackground="var(--popover)"
97 className={cn("size-5", className)}
98 iconClassName="size-4 text-foreground/80"
99 />
100 );
101 }
102 return account.email ? <AccountChip email={account.email} /> : null;
104​
105function AccountName({
106 account,
107 className,
108}: {
109 readonly account: LimitAccount;
110 readonly className?: string;
111}) {
112 if (account.displayName) return <span className={className}>{account.displayName}</span>;
113 if (account.email) {
114 return (
115 <span className={cn("inline-flex min-w-0 items-center", className)}>
116 <AccountChip email={account.email} />
117 </span>
118 );
119 }
120 return (
121 <span className={className}>
122 {providerClients.get(account.driver)?.label ?? String(account.driver)}
123 </span>
124 );
126​
127function Row({ label, children }: { readonly label: string; readonly children: ReactNode }) {
128 return (
129 <div className="grid grid-cols-[4.5rem_minmax(0,1fr)] gap-x-3">
130 <span className="text-muted-foreground">{label}</span>
131 <span className="min-w-0 text-foreground tabular-nums">{children}</span>
132 </div>
133 );
135​
136function SegmentPopover({
137 account,
138 window,
139 reset,
140 now,
141 redeem,
142 onRedeem,
143}: {
144 readonly account: LimitAccount;
145 readonly window: LimitPoolMember["window"];
146 readonly reset: LimitPoolWindow["resets"][number] | undefined;
147 readonly now: number;
148 readonly redeem: ReturnType<typeof useResetCredit> | null;
149 readonly onRedeem: (choice: ResetCreditChoice) => void;
150}) {
151 const timestampFormat = usePrimarySettings((settings) => settings.timestampFormat);
152 const gt = useGT();
153 const m = useMessages();
154 const remaining = remainingPercent(window);
155 const timeLeft = paceRemainingPercent(window, now);
156 const resetsIn = formatResetsIn(window, now, m, "in");
157 const where =
158 account.environments.length > 0
159 ? account.environments.map((environment) => environment.label).join(", ")
160 : account.sourceLabel;
161 const choices =
162 redeem && account.redeem && account.limits.resetCredits?.availableCount
163 ? resetCreditChoices(account.limits.resetCredits, account.redeem.input, now, true, m)
164 : [];
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={gt("Toggle account email visibility")}
178 revealTooltip={gt("Click to reveal email")}
179 hideTooltip={gt("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 ? (
186 <Row label={gt("Plan", { $context: "subscription plan" })}>{account.plan}</Row>
187 ) : null}
188 {where ? (
189 <Row
190 label={
191 account.environments.length > 0
192 ? gt("Signed in")
193 : gt("Via", { $context: "signed in through a source" })
194 }
195 >
196 {where}
197 </Row>
198 ) : null}
199 </div>
200 <div className="flex flex-col gap-1 border-t border-border/60 pt-2.5">
201 <Row label={gt("Left", { $context: "remaining usage" })}>{remaining}%</Row>
202 {window.resetsAt ? (
203 <Row label={gt("Resets", { $context: "when the usage window resets" })}>
204 {formatUpcomingTimestamp(window.resetsAt, timestampFormat, now, undefined, m)}
205 {resetsIn ? ` · ${resetsIn}` : ""}
206 </Row>
207 ) : null}
208 {timeLeft !== null ? (
209 <Row label={gt("Even pace")}>{gt("{timeLeft}% left by now", { timeLeft })}</Row>
210 ) : null}
211 {reset && reset.restoresPercent > 0 ? (
212 <Row label={gt("Restores", { $context: "a reset credit restores part of the pool" })}>
213 {gt("+{percent}% of pool", { percent: reset.restoresPercent })}
214 </Row>
215 ) : null}
216 </div>
217 {choices.length > 0 && redeem ? (
218 <div className="flex flex-col gap-1.5 border-t border-border/60 pt-2.5 text-muted-foreground">
219 {choices.map((choice) => (
220 <span key={choice.key} className="flex items-center gap-3">
221 <span className="tabular-nums">{choice.summary}</span>
222 {choice.availableCount > 0 ? (
223 <Button
224 size="xs"
225 variant="outline"
226 disabled={redeem.busy || !redeem.canManageProviders}
227 className="ms-auto"
228 onClick={() => onRedeem(choice)}
229 >
230 {redeem.busy ? gt("Using…") : choice.actionLabel}
231 </Button>
232 ) : null}
233 </span>
234 ))}
235 </div>
236 ) : null}
237 </div>
238 );
240​
241/**
242 * Every segment on the page shares one popover, so hovering or clicking another
243 * segment moves it instead of opening a second one. The payload is the segment
244 * it currently describes.
245 */
246type SegmentPayload = Omit<Parameters<typeof SegmentPopover>[0], "now" | "onRedeem">;
247const SegmentPopoverContext = createContext<ReturnType<
248 typeof PopoverCreateHandle<SegmentPayload>
249> | null>(null);
250​
251function ActiveSegmentPopover({
252 handle,
253 actions,
254 payload,
255 pools,
256 now,
257}: {
258 readonly handle: ReturnType<typeof PopoverCreateHandle<SegmentPayload>>;
259 readonly actions: RefObject<PopoverPrimitive.Root.Actions | null>;
260 readonly payload: SegmentPayload;
261 readonly pools: readonly LimitPool[];
262 readonly now: number;
263}) {
264 const available = pools.some((pool) =>
265 displayLimitWindows(pool).some((window) =>
266 window.members.some(
267 (member) =>
268 member.account.key === payload.account.key &&
269 member.window.id === payload.window.id &&
270 member.window.kind === payload.window.kind &&
271 Boolean(member.account.redeem) === Boolean(payload.redeem),
272 ),
273 ),
274 );
275 // The trigger is gone, so the popup has nothing to anchor to: an exit transition would
276 // slide it to the viewport origin. Unmount it outright, which also clears Base UI's
277 // active-trigger bookkeeping so the segment can open again when it comes back.
278 // 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
279 useLayoutEffect(() => {
280 if (available) return;
281 handle.close();
282 actions.current?.unmount();
283 }, [available, handle, actions]);
284 return (
285 <PopoverPopup side="top" sideOffset={6}>
286 <SegmentPopover
287 {...payload}
288 now={now}
289 onRedeem={(choice) => {
290 handle.close();
291 payload.redeem?.confirm(choice);
292 }}
293 />
294 </PopoverPopup>
295 );
297​
298/**
299 * The confirm is a sibling of the popover, not a child: dialogs stack under
300 * popovers, and the popover closes as the confirm opens.
301 */
302function PoolSegment({
303 account,
304 ...props
305}: {
306 readonly account: LimitAccount;
307 readonly window: LimitPoolMember["window"];
308 readonly reset: LimitPoolWindow["resets"][number] | undefined;
309 readonly refillPercent: number;
310 readonly color: string;
311 readonly now: number;
312 readonly index: number;
313 readonly showAccountName: boolean;
314}) {
315 return account.redeem ? (
316 <RedeemableSegment account={account} redeemAt={account.redeem} {...props} />
317 ) : (
318 <SegmentTriggers account={account} redeem={null} {...props} />
319 );
321​
322function RedeemableSegment({
323 redeemAt,
324 ...props
325}: Omit<Parameters<typeof SegmentTriggers>[0], "redeem"> & {
326 readonly redeemAt: NonNullable<LimitAccount["redeem"]>;
327}) {
328 const redeem = useResetCredit(redeemAt.environmentId);
329 const gt = useGT();
330 return (
331 <>
332 <SegmentTriggers redeem={redeem} {...props} />
333 <ResetCreditDialog
334 open={redeem.confirming}
335 onOpenChange={redeem.setConfirming}
336 choice={redeem.choice}
337 onConfirm={() => void redeem.redeem()}
338 disabled={!redeem.canManageProviders}
339 />
340 {/* The popover closed before the confirm, so progress and the outcome need a home outside it. */}
341 {redeem.busy || redeem.status ? (
342 <span role="status" className="col-span-full text-xs text-muted-foreground">
343 <AccountName account={props.account} className="font-medium text-foreground" />{" "}
344 {redeem.busy ? gt("Using reset credit…") : redeem.status}
345 </span>
346 ) : null}
347 </>
348 );
350​
351function SegmentTriggers({
352 account,
353 window,
354 reset,
355 redeem,
356 refillPercent,
357 color,
358 now,
359 index,
360 showAccountName,
361}: SegmentPayload & {
362 readonly refillPercent: number;
363 readonly color: string;
364 readonly now: number;
365 readonly index: number;
366 readonly showAccountName: boolean;
367}) {
368 const popover = use(SegmentPopoverContext) ?? undefined;
369 const payload: SegmentPayload = { account, window, reset, redeem };
370 const remaining = remainingPercent(window);
371 const timeLeft = paceRemainingPercent(window, now);
372 const [segmentRef, paceMark] = usePaceMark(timeLeft);
373 const m = useMessages();
374 const resetsIn = formatResetsIn(window, now, m);
375 const refillIn = formatResetsIn(window, now, m, "refill");
376 const credits = account.limits.resetCredits?.availableCount ?? 0;
377 const gt = useGT();
378 const segmentLabel = [
379 gt("{name}: {remaining}% left", {
380 name:
381 account.displayName ?? (account.email ? accountInitials(account.email) : account.driver),
382 remaining,
383 }),
384 resetsIn,
385 timeLeft === null ? null : gt("{timeLeft}% of the window left", { timeLeft }),
386 credits
387 ? gt(
388 "{count, plural, one {{count} reset credit banked} other {{count} reset credits banked}}",
389 { count: credits },
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(
535 "{count, plural, one {{count} reset credit banked} other {{count} reset credits banked}}",
536 { count: credits },
537 )}
538 </span>
539 </>
540 ) : null}
541 </span>
542 </PopoverTrigger>
543 );
545​
546function PoolBar({
547 pool,
548 color,
549 now,
550}: {
551 readonly pool: LimitPoolWindow;
552 readonly color: string;
553 readonly now: number;
554}) {
555 const restores = new Map(pool.resets.map((reset) => [reset.member.account.key, reset]));
556 const gt = useGT();
557 return (
558 <div className="@container/pool min-w-0">
559 <div
560 className="grid gap-x-1 gap-y-1"
561 style={{ gridTemplateColumns: `repeat(${pool.columns.length}, minmax(0, 1fr))` }}
562 >
563 {pool.columns.map((member, position) =>
564 member.window ? (
565 <PoolSegment
566 key={member.account.key}
567 account={member.account}
568 window={member.window}
569 reset={restores.get(member.account.key)}
570 refillPercent={member.refillPercent}
571 color={normalizeProviderAccentColor(member.account.accentColor) ?? color}
572 now={now}
573 index={position + 1}
574 showAccountName={pool.columns.length > 1}
575 />
576 ) : pool.kind === "monthly" && member.account.limits.zeroSpendCap ? (
577 <div
578 key={member.account.key}
579 style={{ gridColumn: position + 1, gridRow: 1 }}
580 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"
581 >
582 <AccountName
583 account={member.account}
584 className="hidden min-w-0 truncate @2xl/pool:inline-flex"
585 />
586 {gt("$0 cap")}
587 </div>
588 ) : null,
589 )}
590 </div>
591 </div>
592 );
594​
595function PoolWindowCard({
596 pool,
597 color,
598 now,
599 label,
600 description,
601}: {
602 readonly pool: LimitPoolWindow;
603 readonly color: string;
604 readonly now: number;
605 readonly label?: string | null | undefined;
606 readonly description?: string | undefined;
607}) {
608 const nextRefill = pool.resets.find((reset) => reset.at > now && reset.restoresPercent > 0);
609 return (
610 <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)]">
611 <div className="flex flex-col gap-1">
612 {label !== null ? (
613 <span className="text-sm font-medium text-foreground">{label ?? pool.label}</span>
614 ) : null}
615 <span className="flex items-baseline gap-2">
616 <span className="text-3xl font-semibold text-foreground tabular-nums">
617 {pool.remainingPercent}%
618 </span>
619 <span className="inline-flex items-center gap-2 text-sm text-muted-foreground">
620 <span>
621 <T context="remaining usage percentage">left</T>
622 </span>
623 {pool.pace ? <PaceIcon pace={pool.pace} /> : null}
624 </span>
625 </span>
626 {nextRefill && pool.columns.length > 1 ? (
627 <span className="text-xs font-medium text-foreground tabular-nums">
628 ↻ +{nextRefill.restoresPercent}%
629 </span>
630 ) : null}
631 </div>
632 <PoolBar pool={pool} color={color} now={now} />
633 {description ? (
634 <p className="text-xs text-muted-foreground md:col-span-2">{description}</p>
635 ) : null}
636 </div>
637 );
639​
640function PoolSection({ pool, now }: { readonly pool: LimitPool; readonly now: number }) {
641 const color = barColor(pool.driver);
642 const label = providerClients.get(pool.driver)?.label ?? String(pool.driver);
643 const windows = displayLimitWindows(pool);
644 const m = useMessages();
645 return (
646 <section className="flex flex-col gap-3">
647 <h2 className="flex items-center gap-2 text-sm font-medium text-foreground">
648 <ProviderInstanceIcon
649 driverKind={pool.driver}
650 displayName={label}
651 indicatorBackground="var(--background)"
652 className="size-5"
653 iconClassName="size-4 text-foreground/80"
654 />
655 {label}
656 </h2>
657 {windows.map((window) => {
658 const details =
659 pool.driver === "cursor" ? cursorUsageWindowDetails(window.id, pool, m) : undefined;
660 return (
661 <PoolWindowCard
662 key={`${window.kind}:${window.id}`}
663 pool={window}
664 color={color}
665 now={now}
666 label={details?.label}
667 description={details?.description}
668 />
669 );
670 })}
671 </section>
672 );
674​
675export function UsageLimitsPooled({
676 presentations,
677 now,
678}: {
679 readonly presentations: Parameters<typeof collectLimitAccounts>[0];
680 readonly now: number;
681}) {
682 const gt = useGT();
683 const m = useMessages();
684 const [segmentPopover] = useState(() => PopoverCreateHandle<SegmentPayload>());
685 const segmentPopoverActions = useRef<PopoverPrimitive.Root.Actions | null>(null);
686 const pools = collectLimitPools(collectLimitAccounts(presentations), now);
687 const quotaSources = collectHttpQuotaSources(presentations);
688 const notices = collectLimitNotices(presentations, m);
689 const externalLinks = collectExternalUsageLinks(presentations, m);
690 return (
691 <div className="flex flex-col gap-8">
692 {pools.length === 0 &&
693 notices.length === 0 &&
694 externalLinks.length === 0 &&
695 quotaSources.length === 0 ? (
696 <p className="text-sm text-muted-foreground">
697 <T>No provider on the selected environments reports subscription limits.</T>
698 </p>
699 ) : null}
700 <SegmentPopoverContext value={segmentPopover}>
701 {pools.map((pool) => (
702 <Fragment key={pool.driver}>
703 <PoolSection pool={pool} now={now} />
704 </Fragment>
705 ))}
706 </SegmentPopoverContext>
707 <Popover handle={segmentPopover} actionsRef={segmentPopoverActions}>
708 {({ payload }) =>
709 payload ? (
710 <ActiveSegmentPopover
711 handle={segmentPopover}
712 actions={segmentPopoverActions}
713 payload={payload}
714 pools={pools}
715 now={now}
716 />
717 ) : null
718 }
719 </Popover>
720 {quotaSources.map((source) => (
721 <section key={source.key} className="space-y-3 rounded-xl border p-4">
722 <h2 className="text-sm font-medium">{source.label}</h2>
723 {source.quotaAccounts?.map((account) => (
724 <div key={account.id} className="space-y-1">
725 <h3 className="text-sm font-medium">{account.label}</h3>
726 {account.windows.map((window) => {
727 const reset = formatResetsIn(window, now, m);
728 return (
729 <div
730 key={window.id}
731 className="flex justify-between gap-3 text-sm text-muted-foreground"
732 >
733 <span>{window.label}</span>
734 <span>
735 {gt("{remaining}% left", { remaining: remainingPercent(window) })}
736 {reset ? ` · ${reset}` : ""}
737 </span>
738 </div>
739 );
740 })}
741 </div>
742 ))}
743 </section>
744 ))}
745 {externalLinks.map((link) => (
746 <section
747 key={link.url}
748 className="flex flex-wrap items-center justify-between gap-3 rounded-xl border p-4"
749 >
750 <div className="flex min-w-0 flex-1 items-center gap-3">
751 {link.url === CHATGPT_USAGE_URL ? (
752 <OpenAI className="size-5 shrink-0" aria-hidden="true" />
753 ) : null}
754 <div className="min-w-0 space-y-1">
755 <h2 className="text-sm font-medium">{link.label}</h2>
756 <p className="text-xs break-words text-muted-foreground">
757 {link.accounts.join(", ")}
758 </p>
759 {link.url === CHATGPT_USAGE_URL ? (
760 <p className="text-xs text-muted-foreground">
761 <T>View usage in ChatGPT with your connected account.</T>
762 </p>
763 ) : link.message ? (
764 <p className="max-w-xl text-xs text-muted-foreground">{link.message}</p>
765 ) : null}
766 </div>
767 </div>
768 <Button
769 variant="ghost-muted"
770 size="xs"
771 onClick={() => void ensureLocalApi().shell.openExternal(link.url)}
772 >
773 {gt("Manage usage")}
774 <ExternalLinkIcon className="size-3.5" aria-hidden="true" />
775 </Button>
776 </section>
777 ))}
778 <LimitNotices notices={notices} />
779 </div>
780 );
782​
783function LimitNotices({ notices }: { readonly notices: readonly string[] }) {
784 if (notices.length === 0) return null;
785 return (
786 <Alert variant="warning" controlAlignment="first-line">
787 <AlertTriangleIcon />
788 {notices.map((notice) => (
789 <AlertTitle key={notice} className="break-words">
790 {notice}
791 </AlertTitle>
792 ))}
793 </Alert>
794 );