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

UsageLimitsPooled.tsx

575 lines19.9 KB

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() || "?";
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;
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 );
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;
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 );
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 );
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 );
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 );
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 className="flex min-h-7 min-w-0 cursor-pointer items-center gap-2 rounded-md px-1 py-0.5 text-start text-xs outline-none focus-visible:ring-2 focus-visible:ring-ring @2xl/pool:hidden"
349 >
350 <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">
351 <span
352 aria-hidden
353 className="absolute inset-0 rounded-sm opacity-35"
354 style={{ backgroundColor: color }}
355 />
356 <span className="sr-only">Segment </span>
357 <span className="relative">{index}</span>
358 </span>
359 <AccountName account={account} className="min-w-0 truncate font-medium text-foreground" />
360 <span className="shrink-0 font-semibold text-foreground tabular-nums">{remaining}%</span>
361 <span className="ms-auto flex shrink-0 items-center gap-1.5 text-[11px] text-muted-foreground tabular-nums">
362 {resetsIn?.replace("resets in ", "↻ ") ?? ""}
363 {credits ? (
364 <>
365 {resetsIn ? <span aria-hidden>·</span> : null}
366 <span
367 aria-hidden
368 className="inline-flex items-center gap-0.5 font-semibold text-foreground"
369 >
370 <TicketIcon className="size-3" aria-hidden />
371 {credits}
372 </span>
373 <span className="sr-only">
374 {credits} reset {credits === 1 ? "credit" : "credits"} banked
375 </span>
376 </>
377 ) : null}
378 </span>
379 </PopoverTrigger>
380 );
382​
383/** Split out so the redeem hook only runs for accounts that can redeem. */
384function RedeemableSegmentPopup({
385 account,
386 window,
387 reset,
388 now,
389 redeemAt,
390 closePopover,
391}: {
392 readonly account: LimitAccount;
393 readonly window: LimitPoolMember["window"];
394 readonly reset: LimitPoolWindow["resets"][number] | undefined;
395 readonly now: number;
396 readonly redeemAt: NonNullable<LimitAccount["redeem"]>;
397 readonly closePopover: () => void;
398}) {
399 const redeem = useResetCredit(redeemAt.environmentId, redeemAt.input);
400 return (
401 <>
402 <PopoverPopup side="top" sideOffset={6}>
403 <SegmentPopover
404 account={account}
405 window={window}
406 reset={reset}
407 now={now}
408 redeem={redeem}
409 onRedeem={() => {
410 closePopover();
411 redeem.setConfirming(true);
412 }}
413 />
414 </PopoverPopup>
415 <ResetCreditDialog
416 open={redeem.confirming}
417 onOpenChange={redeem.setConfirming}
418 onConfirm={() => void redeem.redeem()}
419 />
420 {/* The popover closed before the confirm, so the outcome needs a home outside it. */}
421 {redeem.status ? (
422 <span role="status" className="col-span-full text-xs text-muted-foreground">
423 <AccountName account={account} className="font-medium text-foreground" /> {redeem.status}
424 </span>
425 ) : null}
426 </>
427 );
429​
430/**
431 * One pooled window as equal-width segments, one per account, each filled by
432 * the share of that account's quota still open. Equal widths are honest: every
433 * account contributes the same share of the pool, whatever its plan.
434 *
435 * Wide, each segment carries its own label. Narrow, the bar is a bare strip
436 * and a legend below lists the accounts in the same order; both open the
437 * same popover.
438 */
439function PoolBar({
440 pool,
441 color,
442 now,
443}: {
444 readonly pool: LimitPoolWindow;
445 readonly color: string;
446 readonly now: number;
447}) {
448 const restores = new Map(pool.resets.map((reset) => [reset.member.account.key, reset]));
449 return (
450 <div className="@container/pool min-w-0">
451 <div
452 className="grid gap-x-1 gap-y-1"
453 style={{ gridTemplateColumns: `repeat(${pool.columns.length}, minmax(0, 1fr))` }}
454 >
455 {pool.columns.map((member, position) =>
456 member.window ? (
457 <PoolSegment
458 key={member.account.key}
459 account={member.account}
460 window={member.window}
461 reset={restores.get(member.account.key)}
462 color={color}
463 now={now}
464 index={position + 1}
465 />
466 ) : null,
467 )}
468 </div>
469 </div>
470 );
472​
473/**
474 * Big pooled number and the segment bar. Accounts keep the same column across
475 * windows; each segment's popover shows its own reset time and share restored.
476 */
477function PoolWindowCard({
478 pool,
479 color,
480 now,
481}: {
482 readonly pool: LimitPoolWindow;
483 readonly color: string;
484 readonly now: number;
485}) {
486 // The soonest reset that hands anything back; an untouched account resets to no effect.
487 const nextRefill = pool.resets.find((reset) => reset.restoresPercent > 0);
488 return (
489 <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)]">
490 <div className="flex flex-col gap-1">
491 <span className="text-sm font-medium text-foreground">{pool.label}</span>
492 <span className="flex items-baseline gap-2">
493 <span className="text-3xl font-semibold text-foreground tabular-nums">
494 {pool.remainingPercent}%
495 </span>
496 <span className="text-sm text-muted-foreground">left</span>
497 {pool.pace ? <PaceIcon pace={pool.pace} /> : null}
498 </span>
499 {nextRefill ? (
500 <span className="text-xs text-muted-foreground tabular-nums">
501 <span className="font-medium text-foreground">↻ +{nextRefill.restoresPercent}%</span>{" "}
502 {nextRefill.at <= now ? "now" : `in ${formatDuration(nextRefill.at - now)}`}
503 </span>
504 ) : null}
505 </div>
506 <PoolBar pool={pool} color={color} now={now} />
507 </div>
508 );
510​
511function PoolSection({ pool, now }: { readonly pool: LimitPool; readonly now: number }) {
512 const color = barColor(pool.driver);
513 const label = getDriverOption(pool.driver)?.label ?? String(pool.driver);
514 return (
515 <section className="flex flex-col gap-3">
516 <h2 className="flex items-center gap-2 text-sm font-medium text-foreground">
517 <ProviderInstanceIcon
518 driverKind={pool.driver}
519 displayName={label}
520 indicatorBackground="var(--background)"
521 className="size-5"
522 iconClassName="size-4 text-foreground/80"
523 />
524 {label}
525 </h2>
526 {pool.windows.map((window) => (
527 <PoolWindowCard key={`${window.kind}:${window.id}`} pool={window} color={color} now={now} />
528 ))}
529 </section>
530 );
532​
533/**
534 * Accounts pooled per provider: what is open across all of them, who resets
535 * next, and how much of the pool that hands back. Answers "can I keep going"
536 * before "on which account".
537 */
538export function UsageLimitsPooled({
539 presentations,
540 now,
541}: {
542 readonly presentations: Parameters<typeof collectLimitAccounts>[0];
543 readonly now: number;
544}) {
545 const pools = collectLimitPools(collectLimitAccounts(presentations), now);
546 const notices = collectLimitNotices(presentations);
547 return (
548 <div className="flex flex-col gap-8">
549 {pools.length === 0 && notices.length === 0 ? (
550 <p className="text-sm text-muted-foreground">
551 No provider on the selected environments reports subscription limits.
552 </p>
553 ) : null}
554 {pools.map((pool) => (
555 <PoolSection key={pool.driver} pool={pool} now={now} />
556 ))}
557 <LimitNotices notices={notices} />
558 </div>
559 );
561​
562/** Sources and providers that could not be read, so a missing bar is not mistaken for a full one. */
563function LimitNotices({ notices }: { readonly notices: readonly string[] }) {
564 if (notices.length === 0) return null;
565 return (
566 <Alert variant="warning" controlAlignment="first-line">
567 <AlertTriangleIcon />
568 {notices.map((notice) => (
569 <AlertTitle key={notice} className="break-words">
570 {notice}
571 </AlertTitle>
572 ))}
573 </Alert>
574 );