Open History to see the last commit
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 } 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() || "?";
54}
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;
62}
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}", { 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 );
77}
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;
104}
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 );
126}
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 );
135}
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("Plan", { $context: "subscription plan" })}>{account.plan}</Row>
188 ) : null}
189 {where ? (
190 <Row
191 label={
192 account.environments.length > 0
193 ? gt("Signed in")
194 : gt("Via", { $context: "signed in through a source" })
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("Left", { $context: "remaining usage" })}>{remaining}%</Row>
203 {window.resetsAt ? (
204 <Row label={gt("Resets", { $context: "when the usage window 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", { timeLeft })}</Row>
211 ) : null}
212 {reset && reset.restoresPercent > 0 ? (
213 <Row label={gt("Restores", { $context: "a reset credit restores part of the pool" })}>
214 {gt("+{percent}% of pool", { percent: reset.restoresPercent })}
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 );
240}
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 );
297}
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 );
321}
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 );
350}
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}: {remaining}% left", {
381 name:
382 account.displayName ?? (account.email ? accountInitials(account.email) : account.driver),
383 remaining,
384 }),
385 resetsIn,
386 timeLeft === null ? null : gt("{timeLeft}% of the window left", { timeLeft }),
387 credits
388 ? gt(
389 "{count, plural, one {{count} reset credit banked} other {{count} reset credits banked}}",
390 { count: credits },
391 )
392 : null,
393 ]
394 .filter(Boolean)
395 .join(", ");
396 return (
397 <>
398 <PopoverTrigger
399 handle={popover}
400 payload={payload}
401 openOnHover
402 render={
403 <button
404 ref={segmentRef}
405 type="button"
406 style={{ gridColumn: index, gridRow: 1, ...paceMark?.gappedTrack }}
407 aria-label={segmentLabel}
408 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"
409 />
410 }
411 >
412 <div aria-hidden className="absolute inset-0 overflow-hidden rounded-md">
413 {/* Clipped inside the rounded clip so the bar's own corners keep their antialiasing. */}
414 <div className="absolute inset-0" style={paceMark?.gap}>
415 <div
416 aria-hidden
417 className="absolute inset-y-0 left-0 rounded-md opacity-35"
418 style={{ width: `${remaining}%`, backgroundColor: color }}
419 />
420 {remaining < 100 && reset && refillPercent > 0 ? (
421 <div
422 aria-hidden
423 className="absolute inset-y-0 right-0 opacity-20"
424 style={{
425 width: `${Math.min(100 - remaining, refillPercent)}%`,
426 // A bare 45° gradient repeats every 5√2px, so some stripes rasterize thinner; a whole-pixel tile doesn't.
427 backgroundImage: `repeating-linear-gradient(135deg, transparent 0 1px, ${color} 1px 2px, transparent 2px 50%)`,
428 backgroundSize: "7px 7px",
429 }}
430 />
431 ) : null}
432 </div>
433 </div>
434 {paceMark ? (
435 <span
436 aria-hidden
437 className="absolute inset-y-0.5 w-0.5 -translate-x-1/2 rounded-full bg-foreground"
438 style={paceMark.tick}
439 />
440 ) : null}
441 <span
442 aria-hidden
443 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"
444 >
445 {index}
446 </span>
447 <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">
448 {showAccountName ? (
449 <AccountName
450 account={account}
451 className="min-w-0 truncate font-medium text-foreground"
452 />
453 ) : null}
454 {/* A single-account bar repeats the headline percentage. */}
455 {showAccountName ? (
456 <span className="shrink-0 font-semibold text-foreground tabular-nums">
457 {remaining}%
458 </span>
459 ) : null}
460 {resetsIn || credits ? (
461 <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">
462 {refillIn ?? ""}
463 {credits ? (
464 <>
465 {resetsIn ? (
466 <span aria-hidden className="text-muted-foreground">
467 ·
468 </span>
469 ) : null}
470 <span aria-hidden className="inline-flex items-center gap-0.5 font-semibold">
471 <TicketIcon className="size-3" aria-hidden />
472 {credits}
473 </span>
474 </>
475 ) : null}
476 </span>
477 ) : null}
478 </div>
479 </PopoverTrigger>
480 <LegendRow payload={payload} color={color} now={now} index={index} />
481 </>
482 );
483}
484
485function LegendRow({
486 payload,
487 color,
488 now,
489 index,
490}: {
491 readonly payload: SegmentPayload;
492 readonly color: string;
493 readonly now: number;
494 readonly index: number;
495}) {
496 const popover = use(SegmentPopoverContext) ?? undefined;
497 const { account, window } = payload;
498 const remaining = remainingPercent(window);
499 const m = useMessages();
500 const resetsIn = formatResetsIn(window, now, m, "refill");
501 const credits = account.limits.resetCredits?.availableCount ?? 0;
502 const gt = useGT();
503 return (
504 <PopoverTrigger
505 handle={popover}
506 payload={payload}
507 style={{ gridColumn: "1 / -1", gridRow: index + 1 }}
508 render={<Button variant="ghost" size="compact" />}
509 className="min-w-0 @2xl/pool:hidden"
510 >
511 <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">
512 <span
513 aria-hidden
514 className="absolute inset-0 rounded-sm opacity-35"
515 style={{ backgroundColor: color }}
516 />
517 <span className="sr-only">{`${gt("Segment")} `}</span>
518 <span className="relative">{index}</span>
519 </span>
520 <AccountName account={account} className="min-w-0 truncate font-medium text-foreground" />
521 <span className="shrink-0 font-semibold text-foreground tabular-nums">{remaining}%</span>
522 <span className="ms-auto flex shrink-0 items-center gap-1.5 text-2xs text-muted-foreground tabular-nums">
523 {resetsIn ?? ""}
524 {credits ? (
525 <>
526 {resetsIn ? <span aria-hidden>·</span> : null}
527 <span
528 aria-hidden
529 className="inline-flex items-center gap-0.5 font-semibold text-foreground"
530 >
531 <TicketIcon className="size-3" aria-hidden />
532 {credits}
533 </span>
534 <span className="sr-only">
535 {gt(
536 "{count, plural, one {{count} reset credit banked} other {{count} reset credits banked}}",
537 { count: credits },
538 )}
539 </span>
540 </>
541 ) : null}
542 </span>
543 </PopoverTrigger>
544 );
545}
546
547function PoolBar({
548 pool,
549 color,
550 now,
551}: {
552 readonly pool: LimitPoolWindow;
553 readonly color: string;
554 readonly now: number;
555}) {
556 const restores = new Map(pool.resets.map((reset) => [reset.member.account.key, reset]));
557 const gt = useGT();
558 return (
559 <div className="@container/pool min-w-0">
560 <div
561 className="grid gap-x-1 gap-y-1"
562 style={{ gridTemplateColumns: `repeat(${pool.columns.length}, minmax(0, 1fr))` }}
563 >
564 {pool.columns.map((member, position) =>
565 member.window ? (
566 <PoolSegment
567 key={member.account.key}
568 account={member.account}
569 window={member.window}
570 reset={restores.get(member.account.key)}
571 refillPercent={member.refillPercent}
572 color={normalizeProviderAccentColor(member.account.accentColor) ?? color}
573 now={now}
574 index={position + 1}
575 showAccountName={pool.columns.length > 1}
576 />
577 ) : pool.kind === "monthly" && member.account.limits.zeroSpendCap ? (
578 <div
579 key={member.account.key}
580 style={{ gridColumn: position + 1, gridRow: 1 }}
581 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"
582 >
583 <AccountName
584 account={member.account}
585 className="hidden min-w-0 truncate @2xl/pool:inline-flex"
586 />
587 {gt("$0 cap")}
588 </div>
589 ) : null,
590 )}
591 </div>
592 </div>
593 );
594}
595
596function PoolWindowCard({
597 pool,
598 color,
599 now,
600 label,
601 description,
602}: {
603 readonly pool: LimitPoolWindow;
604 readonly color: string;
605 readonly now: number;
606 readonly label?: string | null | undefined;
607 readonly description?: string | undefined;
608}) {
609 const m = useMessages();
610 const nextRefill = pool.resets.find((reset) => reset.at > now && reset.restoresPercent > 0);
611 return (
612 <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)]">
613 <div className="flex flex-col gap-1">
614 {label !== null ? (
615 <span className="text-sm font-medium text-foreground">{label ?? pool.label}</span>
616 ) : null}
617 <span className="flex items-baseline gap-2">
618 <span className="text-3xl font-semibold text-foreground tabular-nums">
619 {pool.remainingPercent}%
620 </span>
621 <span className="inline-flex items-center gap-2 text-sm text-muted-foreground">
622 <span>
623 <T context="remaining usage percentage">left</T>
624 </span>
625 {pool.pace ? <PaceIcon pace={pool.pace} /> : null}
626 </span>
627 </span>
628 {nextRefill && pool.columns.length > 1 ? (
629 <span className="text-xs text-muted-foreground tabular-nums">
630 <T context="usage limit refill">
631 <span className="font-medium text-foreground">
632 ↻ +<Var>{nextRefill.restoresPercent}</Var>%
633 </span>{" "}
634 in <Var>{formatDuration(nextRefill.at - now, m)}</Var>
635 </T>
636 </span>
637 ) : null}
638 </div>
639 <PoolBar pool={pool} color={color} now={now} />
640 {description ? (
641 <p className="text-xs text-muted-foreground md:col-span-2">{description}</p>
642 ) : null}
643 </div>
644 );
645}
646
647function PoolSection({ pool, now }: { readonly pool: LimitPool; readonly now: number }) {
648 const color = barColor(pool.driver);
649 const label = providerClients.get(pool.driver)?.label ?? String(pool.driver);
650 const windows = displayLimitWindows(pool);
651 const m = useMessages();
652 return (
653 <section className="flex flex-col gap-3">
654 <h2 className="flex items-center gap-2 text-sm font-medium text-foreground">
655 <ProviderInstanceIcon
656 driverKind={pool.driver}
657 displayName={label}
658 indicatorBackground="var(--background)"
659 className="size-5"
660 iconClassName="size-4 text-foreground/80"
661 />
662 {label}
663 </h2>
664 {windows.map((window) => {
665 const details =
666 pool.driver === "cursor" ? cursorUsageWindowDetails(window.id, pool, m) : undefined;
667 return (
668 <PoolWindowCard
669 key={`${window.kind}:${window.id}`}
670 pool={window}
671 color={color}
672 now={now}
673 label={details?.label}
674 description={details?.description}
675 />
676 );
677 })}
678 </section>
679 );
680}
681
682export function UsageLimitsPooled({
683 presentations,
684 now,
685}: {
686 readonly presentations: Parameters<typeof collectLimitAccounts>[0];
687 readonly now: number;
688}) {
689 const gt = useGT();
690 const m = useMessages();
691 const [segmentPopover] = useState(() => PopoverCreateHandle<SegmentPayload>());
692 const segmentPopoverActions = useRef<PopoverPrimitive.Root.Actions | null>(null);
693 const pools = collectLimitPools(collectLimitAccounts(presentations), now);
694 const quotaSources = collectHttpQuotaSources(presentations);
695 const notices = collectLimitNotices(presentations, m);
696 const externalLinks = collectExternalUsageLinks(presentations, m);
697 return (
698 <div className="flex flex-col gap-8">
699 {pools.length === 0 &&
700 notices.length === 0 &&
701 externalLinks.length === 0 &&
702 quotaSources.length === 0 ? (
703 <p className="text-sm text-muted-foreground">
704 <T>No provider on the selected environments reports subscription limits.</T>
705 </p>
706 ) : null}
707 <SegmentPopoverContext value={segmentPopover}>
708 {pools.map((pool) => (
709 <Fragment key={pool.driver}>
710 <PoolSection pool={pool} now={now} />
711 </Fragment>
712 ))}
713 </SegmentPopoverContext>
714 <Popover handle={segmentPopover} actionsRef={segmentPopoverActions}>
715 {({ payload }) =>
716 payload ? (
717 <ActiveSegmentPopover
718 handle={segmentPopover}
719 actions={segmentPopoverActions}
720 payload={payload}
721 pools={pools}
722 now={now}
723 />
724 ) : null
725 }
726 </Popover>
727 {quotaSources.map((source) => (
728 <section key={source.key} className="space-y-3 rounded-xl border p-4">
729 <h2 className="text-sm font-medium">{source.label}</h2>
730 {source.quotaAccounts?.map((account) => (
731 <div key={account.id} className="space-y-1">
732 <h3 className="text-sm font-medium">{account.label}</h3>
733 {account.windows.map((window) => {
734 const reset = formatResetsIn(window, now, m);
735 return (
736 <div
737 key={window.id}
738 className="flex justify-between gap-3 text-sm text-muted-foreground"
739 >
740 <span>{window.label}</span>
741 <span>
742 {gt("{remaining}% left", { remaining: remainingPercent(window) })}
743 {reset ? ` · ${reset}` : ""}
744 </span>
745 </div>
746 );
747 })}
748 </div>
749 ))}
750 </section>
751 ))}
752 {externalLinks.map((link) => (
753 <section
754 key={link.url}
755 className="flex flex-wrap items-center justify-between gap-3 rounded-xl border p-4"
756 >
757 <div className="flex min-w-0 flex-1 items-center gap-3">
758 {link.url === CHATGPT_USAGE_URL ? (
759 <OpenAI className="size-5 shrink-0" aria-hidden="true" />
760 ) : null}
761 <div className="min-w-0 space-y-1">
762 <h2 className="text-sm font-medium">{link.label}</h2>
763 <p className="text-xs break-words text-muted-foreground">
764 {link.accounts.join(", ")}
765 </p>
766 {link.url === CHATGPT_USAGE_URL ? (
767 <p className="text-xs text-muted-foreground">
768 <T>View usage in ChatGPT with your connected account.</T>
769 </p>
770 ) : link.message ? (
771 <p className="max-w-xl text-xs text-muted-foreground">{link.message}</p>
772 ) : null}
773 </div>
774 </div>
775 <Button
776 variant="ghost-muted"
777 size="xs"
778 onClick={() => void ensureLocalApi().shell.openExternal(link.url)}
779 >
780 {gt("Manage usage")}
781 <ExternalLinkIcon className="size-3.5" aria-hidden="true" />
782 </Button>
783 </section>
784 ))}
785 <LimitNotices notices={notices} />
786 </div>
787 );
788}
789
790function LimitNotices({ notices }: { readonly notices: readonly string[] }) {
791 if (notices.length === 0) return null;
792 return (
793 <Alert variant="warning" controlAlignment="first-line">
794 <AlertTriangleIcon />
795 {notices.map((notice) => (
796 <AlertTitle key={notice} className="break-words">
797 {notice}
798 </AlertTitle>
799 ))}
800 </Alert>
801 );
802}