1
+import type {
2
+ ServerProvider,
3
+ ServerProviderUsageWindow,
4
+ UsageLimitSourceAccount,
5
+ UsageLimitSourceId,
6
+ UsageLimitSourceSnapshot,
7
+ UsageProviderKind,
8
+} from "@t3tools/contracts";
9
+import { useAtomValue } from "@effect/atom-react";
10
+import {
11
+ collectLimitSources,
12
+ collectLimitsGroups,
13
+ elapsedShare,
14
+ formatResetsIn,
15
+ limitsNotice,
16
+ type LimitPace,
17
+ paceOf,
18
+ providerLimitsLabel,
19
+} from "@t3tools/shared/usageLimits";
20
+import { GaugeIcon, PlusIcon, TrendingDownIcon, TrendingUpIcon } from "lucide-react";
21
+import { Fragment, useState } from "react";
22
+
23
+import {
24
+ usePrimarySettings,
25
+ usePrimarySettingsAvailable,
26
+ useUpdatePrimarySettings,
27
+} from "../../hooks/useSettings";
28
+import { usePrimaryEnvironmentId } from "../../state/environments";
29
+import { environmentPresentations } from "../../state/presentation";
30
+import { formatUpcomingTimestamp } from "../../timestampFormat";
31
+import { ProviderInstanceIcon } from "../chat/ProviderInstanceIcon";
32
+import { getDriverOption } from "../settings/providerDriverMeta";
33
+import { RedactedSensitiveText } from "../settings/RedactedSensitiveText";
34
+import {
35
+ AlertDialog,
36
+ AlertDialogClose,
37
+ AlertDialogDescription,
38
+ AlertDialogFooter,
39
+ AlertDialogHeader,
40
+ AlertDialogPopup,
41
+ AlertDialogTitle,
42
+} from "../ui/alert-dialog";
43
+import { Badge } from "../ui/badge";
44
+import { Button } from "../ui/button";
45
+import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
46
+import { AddUsageLimitSourceDialog } from "./AddUsageLimitSourceDialog";
47
+import { PROVIDER_PRESENTATION } from "./usageProviders";
48
+
49
+const PACE: Record<LimitPace, { readonly label: string; readonly icon: typeof GaugeIcon }> = {
50
+ ahead: { label: "Ahead of pace: spending faster than the window elapses", icon: TrendingUpIcon },
51
+ on: { label: "On pace with the window", icon: GaugeIcon },
52
+ under: { label: "Under pace: headroom left for the rest of the window", icon: TrendingDownIcon },
53
+};
54
+
55
+/** The series colour the cost chart uses for this driver, so the two views read as one. */
56
+function barColor(driver: ServerProvider["driver"]): string {
57
+ const kind: UsageProviderKind | undefined =
58
+ driver === "codex" ? "codex" : driver === "claudeAgent" ? "claude" : undefined;
59
+ return kind ? PROVIDER_PRESENTATION[kind].color : "var(--foreground)";
60
+}
61
+
62
+/** Pace as a glyph with the words on hover. */
63
+function PaceIcon({ pace }: { readonly pace: LimitPace }) {
64
+ const Icon = PACE[pace].icon;
65
+ return (
66
+ <Tooltip>
67
+ <TooltipTrigger
68
+ render={
69
+ <span
70
+ role="img"
71
+ aria-label={PACE[pace].label}
72
+ className="inline-flex text-muted-foreground"
73
+ />
74
+ }
75
+ >
76
+ <Icon className="size-3.5" aria-hidden />
77
+ </TooltipTrigger>
78
+ <TooltipPopup side="top">{PACE[pace].label}</TooltipPopup>
79
+ </Tooltip>
80
+ );
81
+}
82
+
83
+/**
84
+ * One window as a full-width bar from the moment it opened to its reset.
85
+ * The fill is the share of quota spent; the hairline is how far into the
86
+ * window the clock is, which is also where even spending would have put the
87
+ * fill. Hover for the exact figures and reset time.
88
+ */
89
+function WindowBar({
90
+ color,
91
+ window,
92
+ now,
93
+}: {
94
+ readonly color: string;
95
+ readonly window: ServerProviderUsageWindow;
96
+ readonly now: number;
97
+}) {
98
+ const timestampFormat = usePrimarySettings((settings) => settings.timestampFormat);
99
+ const used = Math.max(0, Math.min(100, window.usedPercent));
100
+ const elapsed = elapsedShare(window, now);
101
+ const resetsIn = formatResetsIn(window, now);
102
+ const resetsAt = window.resetsAt
103
+ ? formatUpcomingTimestamp(window.resetsAt, timestampFormat, now)
104
+ : null;
105
+ const summary = `${window.label}: ${Math.round(used)}% used${
106
+ elapsed === null ? "" : `, ${Math.round(elapsed * 100)}% of the window elapsed`
107
+ }${resetsIn ? `, ${resetsIn}` : ""}`;
108
+
109
+ return (
110
+ <Tooltip>
111
+ <TooltipTrigger
112
+ render={
113
+ <div
114
+ role="img"
115
+ aria-label={summary}
116
+ tabIndex={0}
117
+ className="relative h-6 cursor-default rounded-full outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background"
118
+ />
119
+ }
120
+ >
121
+ <div className="absolute inset-x-0 inset-y-1.5 rounded-full bg-muted" />
122
+ {used > 0 ? (
123
+ <div
124
+ className="absolute inset-y-1.5 left-0 rounded-full"
125
+ style={{ width: `${used}%`, backgroundColor: color }}
126
+ />
127
+ ) : null}
128
+ {elapsed !== null ? (
129
+ <span
130
+ aria-hidden
131
+ className="absolute inset-y-0.5 w-px -translate-x-1/2 bg-foreground/60"
132
+ style={{ left: `${elapsed * 100}%` }}
133
+ />
134
+ ) : null}
135
+ </TooltipTrigger>
136
+ <TooltipPopup side="top" className="max-w-72 text-xs">
137
+ <div className="flex flex-col gap-0.5">
138
+ <span className="text-foreground">
139
+ {Math.round(used)}% used
140
+ {elapsed !== null ? ` · ${Math.round(elapsed * 100)}% of the window elapsed` : ""}
141
+ </span>
142
+ {elapsed !== null ? (
143
+ <span className="text-muted-foreground">The line is where even spending would be.</span>
144
+ ) : null}
145
+ {resetsAt ? (
146
+ <span className="text-muted-foreground">
147
+ Resets {resetsAt}
148
+ {resetsIn ? ` · ${resetsIn}` : ""}
149
+ </span>
150
+ ) : null}
151
+ </div>
152
+ </TooltipPopup>
153
+ </Tooltip>
154
+ );
155
+}
156
+
157
+/** One account's windows as rows: label and percent, bar, pace and countdown. */
158
+function LimitWindows({
159
+ driver,
160
+ windows,
161
+ now,
162
+}: {
163
+ readonly driver: ServerProvider["driver"];
164
+ readonly windows: ReadonlyArray<ServerProviderUsageWindow>;
165
+ readonly now: number;
166
+}) {
167
+ const color = barColor(driver);
168
+ return (
169
+ <div className="grid grid-cols-[11rem_minmax(0,1fr)_7rem] gap-x-4 gap-y-1">
170
+ {windows.map((window, index) => {
171
+ // Windows that reset together show the countdown once.
172
+ const previous = windows[index - 1];
173
+ const sharesReset =
174
+ previous?.resetsAt !== undefined && previous.resetsAt === window.resetsAt;
175
+ const pace = paceOf(window, now);
176
+ const resetsIn = formatResetsIn(window, now);
177
+ return (
178
+ <Fragment key={window.id}>
179
+ <span className="flex min-w-0 items-center gap-2 text-xs">
180
+ <span className="truncate text-muted-foreground">{window.label}</span>
181
+ <span className="ms-auto shrink-0 font-medium text-foreground tabular-nums">
182
+ {Math.round(window.usedPercent)}%
183
+ </span>
184
+ </span>
185
+ <WindowBar color={color} window={window} now={now} />
186
+ <span className="flex items-center gap-2 text-xs text-muted-foreground tabular-nums">
187
+ {pace ? <PaceIcon pace={pace} /> : null}
188
+ <span className="ms-auto shrink-0">{sharesReset ? "" : (resetsIn ?? "")}</span>
189
+ </span>
190
+ </Fragment>
191
+ );
192
+ })}
193
+ </div>
194
+ );
195
+}
196
+
197
+/**
198
+ * Heading shared by local providers and source accounts: icon, name, plan,
199
+ * and the signed-in email blurred until clicked, as provider settings do.
200
+ */
201
+function AccountHeading({
202
+ driver,
203
+ label,
204
+ plan,
205
+ email,
206
+ accentColor,
207
+ badge,
208
+}: {
209
+ readonly driver: ServerProvider["driver"];
210
+ readonly label: string;
211
+ readonly plan: string | undefined;
212
+ readonly email: string | undefined;
213
+ readonly accentColor?: string | undefined;
214
+ readonly badge?: string | undefined;
215
+}) {
216
+ return (
217
+ <h2 className="flex min-w-0 items-center gap-2 text-sm font-medium text-foreground">
218
+ <ProviderInstanceIcon
219
+ driverKind={driver}
220
+ displayName={label}
221
+ accentColor={accentColor}
222
+ showBadge={Boolean(accentColor)}
223
+ indicatorBackground="var(--background)"
224
+ className="size-5"
225
+ iconClassName="size-4 text-foreground/80"
226
+ />
227
+ <span className="truncate">{label}</span>
228
+ {plan ? <span className="shrink-0 font-normal text-muted-foreground">· {plan}</span> : null}
229
+ {email ? (
230
+ <RedactedSensitiveText
231
+ value={email}
232
+ ariaLabel="Toggle account email visibility"
233
+ revealTooltip="Click to reveal email"
234
+ hideTooltip="Click to hide email"
235
+ />
236
+ ) : null}
237
+ {badge ? (
238
+ <Badge variant="outline" size="sm" className="ms-auto shrink-0 font-normal">
239
+ {badge}
240
+ </Badge>
241
+ ) : null}
242
+ </h2>
243
+ );
244
+}
245
+
246
+function ProviderLimits({
247
+ provider,
248
+ now,
249
+}: {
250
+ readonly provider: ServerProvider;
251
+ readonly now: number;
252
+}) {
253
+ const limits = provider.usageLimits;
254
+ if (!limits) return null;
255
+ const notice = limitsNotice(limits);
256
+ return (
257
+ <section className="flex flex-col gap-3">
258
+ <AccountHeading
259
+ driver={provider.driver}
260
+ label={providerLimitsLabel(provider, (driver) => getDriverOption(driver)?.label)}
261
+ plan={provider.auth.label}
262
+ email={provider.auth.email}
263
+ accentColor={provider.accentColor}
264
+ />
265
+ {notice ? (
266
+ <span className="text-xs text-muted-foreground">{notice}</span>
267
+ ) : (
268
+ <LimitWindows driver={provider.driver} windows={limits.windows} now={now} />
269
+ )}
270
+ </section>
271
+ );
272
+}
273
+
274
+/** One account pooled by a usage-limit source, drawn like a provider row. */
275
+function SourceAccountLimits({
276
+ account,
277
+ sourceKind,
278
+ now,
279
+}: {
280
+ readonly account: UsageLimitSourceAccount;
281
+ readonly sourceKind: string;
282
+ readonly now: number;
283
+}) {
284
+ const notice = limitsNotice(account.usageLimits);
285
+ return (
286
+ <section className="flex flex-col gap-3">
287
+ <AccountHeading
288
+ driver={account.driver}
289
+ label={getDriverOption(account.driver)?.label ?? String(account.driver)}
290
+ plan={account.plan}
291
+ email={account.email}
292
+ badge={`via ${sourceKind}`}
293
+ />
294
+ {notice ? (
295
+ <span className="text-xs text-muted-foreground">{notice}</span>
296
+ ) : (
297
+ <LimitWindows driver={account.driver} windows={account.usageLimits.windows} now={now} />
298
+ )}
299
+ </section>
300
+ );
301
+}
302
+
303
+/**
304
+ * Accounts a configured source (a CLIProxyAPI hub) pools, grouped under the
305
+ * source's name. Unlike provider rows these are read-only: nothing on this
306
+ * environment can run a turn against them.
307
+ */
308
+const SOURCE_KIND_LABEL: Record<UsageLimitSourceSnapshot["kind"], string> = {
309
+ cliproxy: "CLIProxyAPI",
310
+};
311
+
312
+/**
313
+ * Removing a hub also deletes its management key from the server, so it
314
+ * asks first and says so. A bare icon that acted on click was too easy to
315
+ * hit while reaching for the row beside it.
316
+ */
317
+function RemoveSourceButton({
318
+ source,
319
+ onConfirm,
320
+}: {
321
+ readonly source: UsageLimitSourceSnapshot;
322
+ readonly onConfirm: () => void;
323
+}) {
324
+ const [open, setOpen] = useState(false);
325
+ return (
326
+ <>
327
+ <Button size="xs" variant="ghost" onClick={() => setOpen(true)}>
328
+ Remove
329
+ </Button>
330
+ <AlertDialog open={open} onOpenChange={setOpen}>
331
+ <AlertDialogPopup>
332
+ <AlertDialogHeader>
333
+ <AlertDialogTitle>Remove {source.label}?</AlertDialogTitle>
334
+ <AlertDialogDescription>
335
+ The hub's management key is deleted from this server. Its accounts leave the Limits
336
+ view; the hub itself is untouched. Add it again with the URL and key to bring them
337
+ back.
338
+ </AlertDialogDescription>
339
+ </AlertDialogHeader>
340
+ <AlertDialogFooter>
341
+ <AlertDialogClose render={<Button variant="outline" />}>Cancel</AlertDialogClose>
342
+ <Button
343
+ variant="destructive"
344
+ onClick={() => {
345
+ setOpen(false);
346
+ onConfirm();
347
+ }}
348
+ >
349
+ Remove hub
350
+ </Button>
351
+ </AlertDialogFooter>
352
+ </AlertDialogPopup>
353
+ </AlertDialog>
354
+ </>
355
+ );
356
+}
357
+
358
+function SourceLimits({
359
+ source,
360
+ now,
361
+ onRemove,
362
+}: {
363
+ readonly source: UsageLimitSourceSnapshot;
364
+ readonly now: number;
365
+ readonly onRemove: (() => void) | null;
366
+}) {
367
+ const kind = SOURCE_KIND_LABEL[source.kind];
368
+ return (
369
+ <div className="flex flex-col gap-6">
370
+ <div className="flex items-center justify-between gap-3">
371
+ <h2 className="text-xs tracking-wide text-muted-foreground uppercase">
372
+ {source.label} · {kind}
373
+ </h2>
374
+ {onRemove ? <RemoveSourceButton source={source} onConfirm={onRemove} /> : null}
375
+ </div>
376
+ {source.error ? (
377
+ <span className="text-xs text-muted-foreground">{source.error}</span>
378
+ ) : source.accounts.length === 0 ? (
379
+ <span className="text-xs text-muted-foreground">No accounts reported.</span>
380
+ ) : (
381
+ source.accounts.map((account) => (
382
+ <SourceAccountLimits key={account.id} account={account} sourceKind={kind} now={now} />
383
+ ))
384
+ )}
385
+ </div>
386
+ );
387
+}
388
+
389
+/**
390
+ * Subscription quota windows from every connected environment's providers.
391
+ * Countdowns anchor to render time rather than ticking: a live clock would
392
+ * repaint the page every minute for no decision-changing gain.
393
+ */
394
+export function UsageLimitsSection() {
395
+ const presentations = useAtomValue(environmentPresentations.presentationsAtom);
396
+ const groups = collectLimitsGroups(presentations);
397
+ const sources = collectLimitSources(presentations);
398
+ const configuredSources = usePrimarySettings((settings) => settings.usageLimitSources);
399
+ const canEditSources = usePrimarySettingsAvailable();
400
+ const primaryEnvironmentId = usePrimaryEnvironmentId();
401
+ const updateSettings = useUpdatePrimarySettings();
402
+ const [adding, setAdding] = useState(false);
403
+ // Anchored once per mount on purpose: countdowns must not tick (see below).
404
+ const [now] = useState(() => Date.now());
405
+
406
+ // The patch names only this entry, so two edits in flight cannot clobber
407
+ // each other's map.
408
+ const removeSource = (id: UsageLimitSourceId) => {
409
+ updateSettings({ usageLimitSources: { [id]: null } });
410
+ };
411
+
412
+ const addHubButton = canEditSources ? (
413
+ <Button size="xs" variant="outline" onClick={() => setAdding(true)}>
414
+ <PlusIcon className="size-3" aria-hidden />
415
+ Add CLIProxyAPI hub
416
+ </Button>
417
+ ) : null;
418
+
419
+ return (
420
+ <div className="flex flex-col gap-8">
421
+ {groups.length === 0 && sources.length === 0 ? (
422
+ <p className="text-sm text-muted-foreground">
423
+ No provider on a connected environment reports subscription limits.
424
+ </p>
425
+ ) : null}
426
+ {sources.map((source) => (
427
+ <SourceLimits
428
+ key={source.key}
429
+ source={source}
430
+ now={now}
431
+ // Only the primary environment's own sources can be edited from
432
+ // here; a remote environment's row with the same id is read-only.
433
+ onRemove={
434
+ canEditSources &&
435
+ source.environmentId === primaryEnvironmentId &&
436
+ source.id in configuredSources
437
+ ? () => removeSource(source.id)
438
+ : null
439
+ }
440
+ />
441
+ ))}
442
+ {groups.map((group) => (
443
+ <div key={group.environmentId} className="flex flex-col gap-6">
444
+ {group.environmentLabel ? (
445
+ <h2 className="text-xs tracking-wide text-muted-foreground uppercase">
446
+ {group.environmentLabel}
447
+ </h2>
448
+ ) : null}
449
+ {group.providers.map((provider) => (
450
+ <ProviderLimits key={provider.instanceId} provider={provider} now={now} />
451
+ ))}
452
+ </div>
453
+ ))}
454
+ {addHubButton ? <div>{addHubButton}</div> : null}
455
+ <AddUsageLimitSourceDialog open={adding} onOpenChange={setAdding} />
456
+ </div>
457
+ );
458
+}