1
-import type {
1
+import {
2
+ EnvironmentId,
3
+ type ProviderConsumeResetCreditOutcome,
4
+ ProviderInstanceId,
5
ServerProvider,
6
+ ServerProviderResetCredits,
7
ServerProviderUsageWindow,
8
UsageLimitSourceAccount,
5
- UsageLimitSourceId,
9
UsageLimitSourceSnapshot,
10
UsageProviderKind,
11
} from "@t3tools/contracts";
14
collectLimitSources,
15
collectLimitsGroups,
16
elapsedShare,
17
+ formatDuration,
18
formatResetsIn,
19
limitsNotice,
20
type LimitPace,
24
import { GaugeIcon, PlusIcon, TrendingDownIcon, TrendingUpIcon } from "lucide-react";
25
import { Fragment, useState } from "react";
26
27
+import { isElectron } from "../../env";
28
+import { usePrimarySessionState } from "../../environments/primary";
29
+import { usePrimarySettings, useUpdateEnvironmentSettings } from "../../hooks/useSettings";
30
import {
24
- usePrimarySettings,
25
- usePrimarySettingsAvailable,
26
- useUpdatePrimarySettings,
27
-} from "../../hooks/useSettings";
28
-import { usePrimaryEnvironmentId } from "../../state/environments";
31
+ type EnvironmentPresentation,
32
+ useEnvironments,
33
+ usePrimaryEnvironmentId,
34
+} from "../../state/environments";
35
+import { useEnvironmentSessionState } from "../../state/session";
36
import { environmentPresentations } from "../../state/presentation";
37
+import { serverEnvironment } from "../../state/server";
38
+import { useAtomCommand } from "../../state/use-atom-command";
39
import { formatUpcomingTimestamp } from "../../timestampFormat";
40
import { ProviderInstanceIcon } from "../chat/ProviderInstanceIcon";
41
import { getDriverOption } from "../settings/providerDriverMeta";
42
+import {
43
+ resolvePrimaryOperateAccess,
44
+ resolveRemoteOperateAccess,
45
+} from "../settings/ProviderSettingsPanel.logic";
46
import { RedactedSensitiveText } from "../settings/RedactedSensitiveText";
47
import {
48
AlertDialog,
55
} from "../ui/alert-dialog";
56
import { Badge } from "../ui/badge";
57
import { Button } from "../ui/button";
58
+import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select";
59
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
60
import { AddUsageLimitSourceDialog } from "./AddUsageLimitSourceDialog";
61
import { PROVIDER_PRESENTATION } from "./usageProviders";
259
260
function ProviderLimits({
261
provider,
262
+ environmentId,
263
now,
264
}: {
265
readonly provider: ServerProvider;
266
+ readonly environmentId: EnvironmentId;
267
readonly now: number;
268
}) {
269
const limits = provider.usageLimits;
283
) : (
284
<LimitWindows driver={provider.driver} windows={limits.windows} now={now} />
285
)}
286
+ {limits.resetCredits ? (
287
+ <ResetCredits
288
+ environmentId={environmentId}
289
+ instanceId={provider.instanceId}
290
+ credits={limits.resetCredits}
291
+ now={now}
292
+ />
293
+ ) : null}
294
</section>
295
);
296
}
297
298
+const OUTCOME_TEXT: Record<ProviderConsumeResetCreditOutcome, string> = {
299
+ reset: "Reset applied. Your windows have cleared.",
300
+ nothingToReset: "Nothing to reset right now.",
301
+ noCredit: "No reset credit left.",
302
+ alreadyRedeemed: "That credit was already redeemed.",
303
+};
304
+
305
+/**
306
+ * Banked reset credits with a confirmed redeem action. Redeeming spends a
307
+ * credit the provider granted the user, so it never fires on a bare click.
308
+ */
309
+function ResetCredits({
310
+ environmentId,
311
+ instanceId,
312
+ credits,
313
+ now,
314
+}: {
315
+ readonly environmentId: EnvironmentId;
316
+ readonly instanceId: ProviderInstanceId;
317
+ readonly credits: ServerProviderResetCredits;
318
+ readonly now: number;
319
+}) {
320
+ const consume = useAtomCommand(serverEnvironment.consumeResetCredit, { reportFailure: false });
321
+ const [confirming, setConfirming] = useState(false);
322
+ const [busy, setBusy] = useState(false);
323
+ const [status, setStatus] = useState<string | null>(null);
324
+ if (credits.availableCount === 0 && status === null) return null;
325
+
326
+ const expiresIn = credits.nextExpiresAt
327
+ ? formatDuration(Date.parse(credits.nextExpiresAt) - now)
328
+ : null;
329
+ const summary =
330
+ credits.availableCount === 0
331
+ ? "No reset credits banked"
332
+ : `${credits.availableCount} ${credits.availableCount === 1 ? "reset credit" : "reset credits"} banked${
333
+ expiresIn ? ` · next expires in ${expiresIn}` : ""
334
+ }`;
335
+
336
+ const redeem = async () => {
337
+ setConfirming(false);
338
+ setBusy(true);
339
+ setStatus(null);
340
+ const result = await consume({ environmentId, input: { instanceId } });
341
+ setBusy(false);
342
+ if (result._tag === "Success") {
343
+ setStatus(OUTCOME_TEXT[result.value.outcome]);
344
+ return;
345
+ }
346
+ setStatus(
347
+ "error" in result.cause && result.cause.error instanceof Error
348
+ ? result.cause.error.message
349
+ : "Could not use the reset credit.",
350
+ );
351
+ };
352
+
353
+ return (
354
+ <div className="flex flex-wrap items-center gap-x-3 gap-y-1 text-xs text-muted-foreground">
355
+ <span className="tabular-nums">{summary}</span>
356
+ {credits.availableCount > 0 ? (
357
+ <Button size="xs" variant="outline" disabled={busy} onClick={() => setConfirming(true)}>
358
+ {busy ? "Using credit…" : "Use a reset credit"}
359
+ </Button>
360
+ ) : null}
361
+ {status ? <span className="text-foreground">{status}</span> : null}
362
+ <AlertDialog open={confirming} onOpenChange={setConfirming}>
363
+ <AlertDialogPopup>
364
+ <AlertDialogHeader>
365
+ <AlertDialogTitle>Use a reset credit?</AlertDialogTitle>
366
+ <AlertDialogDescription>
367
+ This redeems one credit on your account and clears the current rate-limit windows. It
368
+ cannot be undone.
369
+ </AlertDialogDescription>
370
+ </AlertDialogHeader>
371
+ <AlertDialogFooter>
372
+ <AlertDialogClose render={<Button variant="outline" />}>Cancel</AlertDialogClose>
373
+ <Button onClick={() => void redeem()}>Use credit</Button>
374
+ </AlertDialogFooter>
375
+ </AlertDialogPopup>
376
+ </AlertDialog>
377
+ </div>
378
+ );
379
+}
380
+
381
/** One account pooled by a usage-limit source, drawn like a provider row. */
382
function SourceAccountLimits({
383
account,
493
);
494
}
495
496
+/**
497
+ * Whether this client's credential may write settings on an environment,
498
+ * resolved the way Settings → Providers does: the desktop app owns its
499
+ * primary outright; a browser session checks the scopes it was granted;
500
+ * a remote environment reports scopes over its own session endpoint.
501
+ */
502
+function useCanOperateEnvironment(environment: EnvironmentPresentation | null): boolean {
503
+ const isPrimary = environment?.entry.target._tag === "PrimaryConnectionTarget";
504
+ const primarySession = usePrimarySessionState();
505
+ const remoteSession = useEnvironmentSessionState(
506
+ environment?.environmentId ?? EnvironmentId.make("none"),
507
+ );
508
+ if (environment === null || environment.connection.phase !== "connected") return false;
509
+ if (isPrimary && isElectron) return true;
510
+ const access = isPrimary
511
+ ? resolvePrimaryOperateAccess({
512
+ isPrimary: true,
513
+ hasDesktopBridge: false,
514
+ session: primarySession.data,
515
+ isPending: primarySession.isPending,
516
+ hasError: primarySession.error !== null,
517
+ })
518
+ : resolveRemoteOperateAccess({
519
+ session: remoteSession.data,
520
+ isPending: remoteSession.isPending,
521
+ hasError: remoteSession.hasError,
522
+ });
523
+ return access === "granted";
524
+}
525
+
526
+/** One source with a remove control bound to the environment it lives in. */
527
+function SourceLimitsRow({
528
+ source,
529
+ now,
530
+}: {
531
+ readonly source: UsageLimitSourceSnapshot & {
532
+ readonly key: string;
533
+ readonly environmentId: EnvironmentId;
534
+ };
535
+ readonly now: number;
536
+}) {
537
+ const updateSettings = useUpdateEnvironmentSettings(source.environmentId);
538
+ const { environments } = useEnvironments();
539
+ const environment =
540
+ environments.find((entry) => entry.environmentId === source.environmentId) ?? null;
541
+ const canOperate = useCanOperateEnvironment(environment);
542
+ // The patch names only this entry, so two edits in flight cannot clobber
543
+ // each other's map.
544
+ const remove = () => updateSettings({ usageLimitSources: { [source.id]: null } });
545
+ return <SourceLimits source={source} now={now} onRemove={canOperate ? remove : null} />;
546
+}
547
+
548
/**
549
* Subscription quota windows from every connected environment's providers.
550
* Countdowns anchor to render time rather than ticking: a live clock would
554
const presentations = useAtomValue(environmentPresentations.presentationsAtom);
555
const groups = collectLimitsGroups(presentations);
556
const sources = collectLimitSources(presentations);
398
- const configuredSources = usePrimarySettings((settings) => settings.usageLimitSources);
399
- const canEditSources = usePrimarySettingsAvailable();
557
const primaryEnvironmentId = usePrimaryEnvironmentId();
401
- const updateSettings = useUpdatePrimarySettings();
558
+ const { environments } = useEnvironments();
559
const [adding, setAdding] = useState(false);
560
// Anchored once per mount on purpose: countdowns must not tick (see below).
561
const [now] = useState(() => Date.now());
562
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;
563
+ // Sources live in one environment's settings. Writing them needs only the
564
+ // operate scope, like any provider control, so a T3 Connect client can add
565
+ // a hub to whichever environment it is connected to: the primary when there
566
+ // is one, else the first connected environment, with a picker for more.
567
+ const connected = environments.filter(
568
+ (environment) => environment.connection.phase === "connected",
569
+ );
570
+ const [pickedEnvironmentId, setPickedEnvironmentId] = useState<EnvironmentId | null>(null);
571
+ const targetEnvironment =
572
+ (pickedEnvironmentId !== null
573
+ ? connected.find((environment) => environment.environmentId === pickedEnvironmentId)
574
+ : undefined) ??
575
+ (primaryEnvironmentId !== null
576
+ ? connected.find((environment) => environment.environmentId === primaryEnvironmentId)
577
+ : undefined) ??
578
+ connected[0] ??
579
+ null;
580
+ const canOperateTarget = useCanOperateEnvironment(targetEnvironment);
581
582
return (
583
<div className="flex flex-col gap-8">
584
+ {/* Sources first: they are the thing a user configures here, so the
585
+ control to add one sits at the top rather than after every row. */}
586
+ <div className="flex items-center justify-between gap-3">
587
+ <div className="flex flex-col gap-1">
588
+ <h2 className="text-sm font-medium text-foreground">Usage sources</h2>
589
+ <p className="text-xs text-muted-foreground">
590
+ Quota from a CLIProxyAPI hub shows beside the providers signed in on this machine.
591
+ </p>
592
+ </div>
593
+ {/* The picker stays whenever several environments are connected, so
594
+ a read-only default target does not hide the way to an operable
595
+ one; only the button follows the picked target's access. */}
596
+ {targetEnvironment ? (
597
+ <div className="flex items-center gap-2">
598
+ {connected.length > 1 ? (
599
+ <Select
600
+ value={targetEnvironment.environmentId}
601
+ onValueChange={(value) => {
602
+ if (value !== null) setPickedEnvironmentId(EnvironmentId.make(value));
603
+ }}
604
+ >
605
+ <SelectTrigger
606
+ aria-label="Environment to add the hub to"
607
+ size="compact"
608
+ variant="ghost"
609
+ className="w-auto min-w-0"
610
+ >
611
+ <SelectValue>{targetEnvironment.label}</SelectValue>
612
+ </SelectTrigger>
613
+ <SelectPopup align="end" alignItemWithTrigger={false}>
614
+ {connected.map((environment) => (
615
+ <SelectItem key={environment.environmentId} value={environment.environmentId}>
616
+ {environment.label}
617
+ </SelectItem>
618
+ ))}
619
+ </SelectPopup>
620
+ </Select>
621
+ ) : null}
622
+ {canOperateTarget ? (
623
+ <Button size="xs" variant="outline" onClick={() => setAdding(true)}>
624
+ <PlusIcon className="size-3" aria-hidden />
625
+ Add hub
626
+ </Button>
627
+ ) : (
628
+ <Tooltip>
629
+ <TooltipTrigger
630
+ render={
631
+ <span
632
+ tabIndex={0}
633
+ className="rounded-md outline-none focus-visible:ring-2 focus-visible:ring-ring"
634
+ />
635
+ }
636
+ >
637
+ <span className="inline-flex" inert>
638
+ <Button size="xs" variant="outline" disabled>
639
+ <PlusIcon className="size-3" aria-hidden />
640
+ Add hub
641
+ </Button>
642
+ </span>
643
+ </TooltipTrigger>
644
+ <TooltipPopup side="top" className="max-w-72">
645
+ Your session cannot change settings on {targetEnvironment.label}.
646
+ </TooltipPopup>
647
+ </Tooltip>
648
+ )}
649
+ </div>
650
+ ) : null}
651
+ </div>
652
{groups.length === 0 && sources.length === 0 ? (
653
<p className="text-sm text-muted-foreground">
654
No provider on a connected environment reports subscription limits.
655
</p>
656
) : null}
657
{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
- />
658
+ <SourceLimitsRow key={source.key} source={source} now={now} />
659
))}
660
{groups.map((group) => (
661
<div key={group.environmentId} className="flex flex-col gap-6">
665
</h2>
666
) : null}
667
{group.providers.map((provider) => (
450
- <ProviderLimits key={provider.instanceId} provider={provider} now={now} />
668
+ <ProviderLimits
669
+ key={provider.instanceId}
670
+ provider={provider}
671
+ environmentId={group.environmentId}
672
+ now={now}
673
+ />
674
))}
675
</div>
676
))}
454
- {addHubButton ? <div>{addHubButton}</div> : null}
455
- <AddUsageLimitSourceDialog open={adding} onOpenChange={setAdding} />
677
+ {targetEnvironment && canOperateTarget ? (
678
+ // Keyed on the target: if it disconnects or the primary changes while
679
+ // the dialog is open, a fresh dialog mounts empty rather than carrying
680
+ // a typed key over to a different environment.
681
+ <AddUsageLimitSourceDialog
682
+ key={targetEnvironment.environmentId}
683
+ open={adding}
684
+ onOpenChange={setAdding}
685
+ environmentId={targetEnvironment.environmentId}
686
+ environmentLabel={targetEnvironment.label}
687
+ />
688
+ ) : null}
689
</div>
690
);
691
}