Open History to see the last commit
1import {
2 collectLimitAccounts,
3 collectLimitNotices,
4 collectLimitPools,
5 formatDuration,
6 formatResetsIn,
7 type LimitAccount,
8 type LimitPool,
9 type LimitPoolMember,
10 type LimitPoolWindow,
11 remainingPercent,
12} from "@t3tools/shared/usageLimits";
13import { AlertTriangleIcon, TicketIcon } from "lucide-react";
14import { type ReactNode, useState } from "react";
15
16import { usePrimarySettings } from "../../hooks/useSettings";
17import { cn } from "../../lib/utils";
18import { formatUpcomingTimestamp } from "../../timestampFormat";
19import { ProviderInstanceIcon } from "../chat/ProviderInstanceIcon";
20import { getDriverOption } from "../settings/providerDriverMeta";
21import { RedactedSensitiveText } from "../settings/RedactedSensitiveText";
22import { Button } from "../ui/button";
23import { Alert, AlertTitle } from "../ui/alert";
24import { Popover, PopoverPopup, PopoverTrigger } from "../ui/popover";
25import {
26 PaceIcon,
27 ResetCreditDialog,
28 barColor,
29 resetCreditsSummary,
30 useResetCredit,
31} from "./UsageLimits";
32
33/** `someone@example.com` → `SE`: enough to tell accounts apart, too little to identify one. */
34function accountInitials(email: string): string {
35 const [local = "", domain = ""] = email.split("@");
36 return `${local[0] ?? ""}${domain[0] ?? ""}`.toUpperCase() || "?";
37}
38
39/** A stable hue per email, so the same account gets the same chip on every visit. */
40function accountHue(email: string): number {
41 let hash = 0;
42 for (let index = 0; index < email.length; index += 1) {
43 hash = (hash * 31 + email.charCodeAt(index)) | 0;
44 }
45 return Math.abs(hash) % 360;
46}
47
48/** The two-letter chip for an email, coloured by a stable hue per address. */
49function AccountChip({ email }: { readonly email: string }) {
50 const hue = accountHue(email);
51 return (
52 <span
53 role="img"
54 aria-label={`Account ${accountInitials(email)}`}
55 className="inline-flex size-4 shrink-0 items-center justify-center rounded-full text-[9px] leading-none font-semibold"
56 style={{ backgroundColor: `oklch(0.85 0.08 ${hue})`, color: `oklch(0.35 0.1 ${hue})` }}
57 >
58 {accountInitials(email)}
59 </span>
60 );
61}
62
63/**
64 * The same mark the model picker uses for a native instance (provider glyph,
65 * initials badge, accent); hub accounts have no instance, so they get the chip.
66 */
67function AccountAvatar({
68 account,
69 className,
70}: {
71 readonly account: LimitAccount;
72 readonly className?: string;
73}) {
74 if (account.redeem) {
75 return (
76 <ProviderInstanceIcon
77 driverKind={account.driver}
78 displayName={
79 account.displayName ?? getDriverOption(account.driver)?.label ?? String(account.driver)
80 }
81 accentColor={account.accentColor}
82 showBadge={Boolean(account.displayName)}
83 indicatorBackground="var(--popover)"
84 className={cn("size-5", className)}
85 iconClassName="size-4 text-foreground/80"
86 />
87 );
88 }
89 return account.email ? <AccountChip email={account.email} /> : null;
90}
91
92/**
93 * Who an account is, without printing the email: the instance name when there
94 * is one, else a two-letter chip. The address itself is revealed on demand in
95 * the segment's popover.
96 */
97function AccountName({
98 account,
99 className,
100}: {
101 readonly account: LimitAccount;
102 readonly className?: string;
103}) {
104 if (account.displayName) return <span className={className}>{account.displayName}</span>;
105 if (account.email) {
106 return (
107 <span className={cn("inline-flex min-w-0 items-center", className)}>
108 <AccountChip email={account.email} />
109 </span>
110 );
111 }
112 return (
113 <span className={className}>
114 {getDriverOption(account.driver)?.label ?? String(account.driver)}
115 </span>
116 );
117}
118
119function Row({ label, children }: { readonly label: string; readonly children: ReactNode }) {
120 return (
121 <div className="grid grid-cols-[4.5rem_minmax(0,1fr)] gap-x-3">
122 <span className="text-muted-foreground">{label}</span>
123 <span className="min-w-0 text-foreground tabular-nums">{children}</span>
124 </div>
125 );
126}
127
128/**
129 * Everything about one account in one window: plan, where it is signed in,
130 * the email on request, reset time and share of the pool it restores, and the
131 * reset-credit action. Opens on hover for a glance, on click to act.
132 */
133function SegmentPopover({
134 account,
135 window,
136 reset,
137 now,
138 redeem,
139 onRedeem,
140}: {
141 readonly account: LimitAccount;
142 readonly window: LimitPoolMember["window"];
143 readonly reset: LimitPoolWindow["resets"][number] | undefined;
144 readonly now: number;
145 /** Redeem state owned by the segment, since the confirm lives outside this popover. */
146 readonly redeem: ReturnType<typeof useResetCredit> | null;
147 readonly onRedeem: () => void;
148}) {
149 const timestampFormat = usePrimarySettings((settings) => settings.timestampFormat);
150 const remaining = remainingPercent(window);
151 const resetsIn = formatResetsIn(window, now);
152 const where =
153 account.environments.length > 0
154 ? account.environments.map((environment) => environment.label).join(", ")
155 : account.sourceLabel;
156 const credits =
157 redeem && account.limits.resetCredits?.availableCount ? account.limits.resetCredits : null;
158 return (
159 <div className="flex w-72 max-w-[calc(100vw-3rem)] flex-col gap-2.5 text-xs">
160 <div className="flex min-w-0 flex-col gap-0.5">
161 <span className="flex items-center gap-2 text-sm font-medium text-foreground">
162 <AccountAvatar account={account} />
163 <span className="truncate">
164 {account.displayName ?? getDriverOption(account.driver)?.label ?? account.driver}
165 </span>
166 </span>
167 {account.email ? (
168 <RedactedSensitiveText
169 value={account.email}
170 ariaLabel="Toggle account email visibility"
171 revealTooltip="Click to reveal email"
172 hideTooltip="Click to hide email"
173 className="w-fit"
174 />
175 ) : null}
176 </div>
177 <div className="flex flex-col gap-1 border-t border-border/60 pt-2.5">
178 {account.plan ? <Row label="Plan">{account.plan}</Row> : null}
179 {where ? (
180 <Row label={account.environments.length > 0 ? "Signed in" : "Via"}>{where}</Row>
181 ) : null}
182 </div>
183 <div className="flex flex-col gap-1 border-t border-border/60 pt-2.5">
184 <Row label="Left">{remaining}%</Row>
185 {window.resetsAt ? (
186 <Row label="Resets">
187 {formatUpcomingTimestamp(window.resetsAt, timestampFormat, now)}
188 {resetsIn ? ` · ${resetsIn.replace("resets in ", "in ")}` : ""}
189 </Row>
190 ) : null}
191 {reset && reset.restoresPercent > 0 ? (
192 <Row label="Restores">+{reset.restoresPercent}% of pool</Row>
193 ) : null}
194 </div>
195 {credits && redeem ? (
196 <div className="border-t border-border/60 pt-2.5 text-muted-foreground">
197 <span className="flex items-center gap-3">
198 <span className="tabular-nums">{resetCreditsSummary(credits, now, true)}</span>
199 <Button
200 size="xs"
201 variant="outline"
202 disabled={redeem.busy}
203 className="ms-auto"
204 onClick={onRedeem}
205 >
206 {redeem.busy ? "Using…" : "Use reset"}
207 </Button>
208 </span>
209 </div>
210 ) : null}
211 </div>
212 );
213}
214
215/**
216 * One account's share of one pooled window: the segment, its popover, and the
217 * reset confirm. The confirm is a sibling of the popover, not a child: dialogs
218 * stack under popovers, and the popover closes as the confirm opens.
219 */
220function PoolSegment({
221 account,
222 window,
223 reset,
224 color,
225 now,
226 index,
227}: {
228 readonly account: LimitAccount;
229 readonly window: LimitPoolMember["window"];
230 readonly reset: LimitPoolWindow["resets"][number] | undefined;
231 readonly color: string;
232 readonly now: number;
233 /** 1-based position in the bar, shown on the strip and its legend row to tie them together. */
234 readonly index: number;
235}) {
236 const [open, setOpen] = useState(false);
237 const remaining = remainingPercent(window);
238 const resetsIn = formatResetsIn(window, now);
239 const credits = account.limits.resetCredits?.availableCount ?? 0;
240 return (
241 <Popover open={open} onOpenChange={setOpen}>
242 <PopoverTrigger
243 openOnHover
244 render={
245 <button
246 type="button"
247 style={{ gridColumn: index, gridRow: 1 }}
248 aria-label={`${account.displayName ?? (account.email ? accountInitials(account.email) : account.driver)}: ${remaining}% left${resetsIn ? `, ${resetsIn}` : ""}${credits ? `, ${credits} reset ${credits === 1 ? "credit" : "credits"} banked` : ""}`}
249 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"
250 />
251 }
252 >
253 {/* Translucent so the label reads over the fill for any provider colour and theme. */}
254 <div
255 aria-hidden
256 className="absolute inset-y-0 left-0 rounded-md opacity-35"
257 style={{ width: `${remaining}%`, backgroundColor: color }}
258 />
259 {/* The spent share is hatched, not blank: it is what the countdown restores. */}
260 {remaining < 100 && reset ? (
261 <div
262 aria-hidden
263 className="absolute inset-y-0 right-0 opacity-20"
264 style={{
265 width: `${100 - remaining}%`,
266 backgroundImage: `repeating-linear-gradient(135deg, ${color} 0 1px, transparent 1px 5px)`,
267 }}
268 />
269 ) : null}
270 <span
271 aria-hidden
272 className="absolute inset-0 flex items-center justify-center text-[10px] leading-none font-semibold text-foreground/80 tabular-nums @2xl/pool:hidden"
273 >
274 {index}
275 </span>
276 <div className="relative hidden h-full min-w-0 items-center gap-1.5 px-2 text-xs @2xl/pool:flex">
277 <AccountName account={account} className="min-w-0 truncate font-medium text-foreground" />
278 <span className="shrink-0 font-semibold text-foreground tabular-nums">{remaining}%</span>
279 {/* Countdown and badge get their own plate: fill and hatching run under them otherwise. */}
280 <span className="ms-auto flex shrink-0 items-center gap-1.5 rounded-sm bg-background/85 px-1.5 py-0.5 text-[11px] text-foreground tabular-nums">
281 {resetsIn?.replace("resets in ", "↻ ") ?? ""}
282 {credits ? (
283 <>
284 {resetsIn ? (
285 <span aria-hidden className="text-muted-foreground">
286 ·
287 </span>
288 ) : null}
289 <span aria-hidden className="inline-flex items-center gap-0.5 font-semibold">
290 <TicketIcon className="size-3" aria-hidden />
291 {credits}
292 </span>
293 </>
294 ) : null}
295 </span>
296 </div>
297 </PopoverTrigger>
298 <LegendRow account={account} window={window} color={color} now={now} index={index} />
299 {account.redeem ? (
300 <RedeemableSegmentPopup
301 account={account}
302 window={window}
303 reset={reset}
304 now={now}
305 redeemAt={account.redeem}
306 closePopover={() => setOpen(false)}
307 />
308 ) : (
309 <PopoverPopup side="top" sideOffset={6}>
310 <SegmentPopover
311 account={account}
312 window={window}
313 reset={reset}
314 now={now}
315 redeem={null}
316 onRedeem={() => {}}
317 />
318 </PopoverPopup>
319 )}
320 </Popover>
321 );
322}
323
324/**
325 * Below the strip at narrow widths: one row per account in bar order, carrying
326 * the text the segment has no room for. Tapping a row opens the same popover
327 * as its segment, so the two are one control with two handles.
328 */
329function LegendRow({
330 account,
331 window,
332 color,
333 now,
334 index,
335}: {
336 readonly account: LimitAccount;
337 readonly window: LimitPoolMember["window"];
338 readonly color: string;
339 readonly now: number;
340 readonly index: number;
341}) {
342 const remaining = remainingPercent(window);
343 const resetsIn = formatResetsIn(window, now);
344 const credits = account.limits.resetCredits?.availableCount ?? 0;
345 return (
346 <PopoverTrigger
347 style={{ gridColumn: "1 / -1", gridRow: index + 1 }}
348 render={<Button variant="ghost" size="compact" />}
349 className="min-w-0 @2xl/pool:hidden"
350 >
351 <span className="relative inline-flex size-4 shrink-0 items-center justify-center rounded-sm text-[10px] leading-none font-semibold text-foreground/80 tabular-nums">
352 <span
353 aria-hidden
354 className="absolute inset-0 rounded-sm opacity-35"
355 style={{ backgroundColor: color }}
356 />
357 <span className="sr-only">Segment </span>
358 <span className="relative">{index}</span>
359 </span>
360 <AccountName account={account} className="min-w-0 truncate font-medium text-foreground" />
361 <span className="shrink-0 font-semibold text-foreground tabular-nums">{remaining}%</span>
362 <span className="ms-auto flex shrink-0 items-center gap-1.5 text-[11px] text-muted-foreground tabular-nums">
363 {resetsIn?.replace("resets in ", "↻ ") ?? ""}
364 {credits ? (
365 <>
366 {resetsIn ? <span aria-hidden>·</span> : null}
367 <span
368 aria-hidden
369 className="inline-flex items-center gap-0.5 font-semibold text-foreground"
370 >
371 <TicketIcon className="size-3" aria-hidden />
372 {credits}
373 </span>
374 <span className="sr-only">
375 {credits} reset {credits === 1 ? "credit" : "credits"} banked
376 </span>
377 </>
378 ) : null}
379 </span>
380 </PopoverTrigger>
381 );
382}
383
384/** Split out so the redeem hook only runs for accounts that can redeem. */
385function RedeemableSegmentPopup({
386 account,
387 window,
388 reset,
389 now,
390 redeemAt,
391 closePopover,
392}: {
393 readonly account: LimitAccount;
394 readonly window: LimitPoolMember["window"];
395 readonly reset: LimitPoolWindow["resets"][number] | undefined;
396 readonly now: number;
397 readonly redeemAt: NonNullable<LimitAccount["redeem"]>;
398 readonly closePopover: () => void;
399}) {
400 const redeem = useResetCredit(redeemAt.environmentId, redeemAt.input);
401 return (
402 <>
403 <PopoverPopup side="top" sideOffset={6}>
404 <SegmentPopover
405 account={account}
406 window={window}
407 reset={reset}
408 now={now}
409 redeem={redeem}
410 onRedeem={() => {
411 closePopover();
412 redeem.setConfirming(true);
413 }}
414 />
415 </PopoverPopup>
416 <ResetCreditDialog
417 open={redeem.confirming}
418 onOpenChange={redeem.setConfirming}
419 onConfirm={() => void redeem.redeem()}
420 />
421 {/* The popover closed before the confirm, so the outcome needs a home outside it. */}
422 {redeem.status ? (
423 <span role="status" className="col-span-full text-xs text-muted-foreground">
424 <AccountName account={account} className="font-medium text-foreground" /> {redeem.status}
425 </span>
426 ) : null}
427 </>
428 );
429}
430
431/**
432 * One pooled window as equal-width segments, one per account, each filled by
433 * the share of that account's quota still open. Equal widths are honest: every
434 * account contributes the same share of the pool, whatever its plan.
435 *
436 * Wide, each segment carries its own label. Narrow, the bar is a bare strip
437 * and a legend below lists the accounts in the same order; both open the
438 * same popover.
439 */
440function PoolBar({
441 pool,
442 color,
443 now,
444}: {
445 readonly pool: LimitPoolWindow;
446 readonly color: string;
447 readonly now: number;
448}) {
449 const restores = new Map(pool.resets.map((reset) => [reset.member.account.key, reset]));
450 return (
451 <div className="@container/pool min-w-0">
452 <div
453 className="grid gap-x-1 gap-y-1"
454 style={{ gridTemplateColumns: `repeat(${pool.columns.length}, minmax(0, 1fr))` }}
455 >
456 {pool.columns.map((member, position) =>
457 member.window ? (
458 <PoolSegment
459 key={member.account.key}
460 account={member.account}
461 window={member.window}
462 reset={restores.get(member.account.key)}
463 color={color}
464 now={now}
465 index={position + 1}
466 />
467 ) : null,
468 )}
469 </div>
470 </div>
471 );
472}
473
474/**
475 * Big pooled number and the segment bar. Accounts keep the same column across
476 * windows; each segment's popover shows its own reset time and share restored.
477 */
478function PoolWindowCard({
479 pool,
480 color,
481 now,
482}: {
483 readonly pool: LimitPoolWindow;
484 readonly color: string;
485 readonly now: number;
486}) {
487 // The soonest reset that hands anything back; an untouched account resets to no effect.
488 const nextRefill = pool.resets.find((reset) => reset.restoresPercent > 0);
489 return (
490 <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)]">
491 <div className="flex flex-col gap-1">
492 <span className="text-sm font-medium text-foreground">{pool.label}</span>
493 <span className="flex items-baseline gap-2">
494 <span className="text-3xl font-semibold text-foreground tabular-nums">
495 {pool.remainingPercent}%
496 </span>
497 <span className="text-sm text-muted-foreground">left</span>
498 {pool.pace ? <PaceIcon pace={pool.pace} /> : null}
499 </span>
500 {nextRefill ? (
501 <span className="text-xs text-muted-foreground tabular-nums">
502 <span className="font-medium text-foreground">↻ +{nextRefill.restoresPercent}%</span>{" "}
503 {nextRefill.at <= now ? "now" : `in ${formatDuration(nextRefill.at - now)}`}
504 </span>
505 ) : null}
506 </div>
507 <PoolBar pool={pool} color={color} now={now} />
508 </div>
509 );
510}
511
512function PoolSection({ pool, now }: { readonly pool: LimitPool; readonly now: number }) {
513 const color = barColor(pool.driver);
514 const label = getDriverOption(pool.driver)?.label ?? String(pool.driver);
515 return (
516 <section className="flex flex-col gap-3">
517 <h2 className="flex items-center gap-2 text-sm font-medium text-foreground">
518 <ProviderInstanceIcon
519 driverKind={pool.driver}
520 displayName={label}
521 indicatorBackground="var(--background)"
522 className="size-5"
523 iconClassName="size-4 text-foreground/80"
524 />
525 {label}
526 </h2>
527 {pool.windows.map((window) => (
528 <PoolWindowCard key={`${window.kind}:${window.id}`} pool={window} color={color} now={now} />
529 ))}
530 </section>
531 );
532}
533
534/**
535 * Accounts pooled per provider: what is open across all of them, who resets
536 * next, and how much of the pool that hands back. Answers "can I keep going"
537 * before "on which account".
538 */
539export function UsageLimitsPooled({
540 presentations,
541 now,
542}: {
543 readonly presentations: Parameters<typeof collectLimitAccounts>[0];
544 readonly now: number;
545}) {
546 const pools = collectLimitPools(collectLimitAccounts(presentations), now);
547 const notices = collectLimitNotices(presentations);
548 return (
549 <div className="flex flex-col gap-8">
550 {pools.length === 0 && notices.length === 0 ? (
551 <p className="text-sm text-muted-foreground">
552 No provider on the selected environments reports subscription limits.
553 </p>
554 ) : null}
555 {pools.map((pool) => (
556 <PoolSection key={pool.driver} pool={pool} now={now} />
557 ))}
558 <LimitNotices notices={notices} />
559 </div>
560 );
561}
562
563/** Sources and providers that could not be read, so a missing bar is not mistaken for a full one. */
564function LimitNotices({ notices }: { readonly notices: readonly string[] }) {
565 if (notices.length === 0) return null;
566 return (
567 <Alert variant="warning" controlAlignment="first-line">
568 <AlertTriangleIcon />
569 {notices.map((notice) => (
570 <AlertTitle key={notice} className="break-words">
571 {notice}
572 </AlertTitle>
573 ))}
574 </Alert>
575 );
576}