refactor(web): move usage provider controls to settings (#9599)

This commit is contained in:
Julius Marminge authored and GitHub committed 2026-09-03 23:56:23 -07:00
1 parent caab2fdbac
commit f1e90e388b
9 files changed
+176 -234

No files matched your search

@@ -4,14 +4,16 @@ import { View } from "react-native";
import { AppText as Text } from "../../../components/AppText";
export function SettingsSection(props: {
readonly title: string;
readonly title?: string;
readonly children: ReactNode;
/** Force the grouped card background; Android otherwise lists options flat. */
readonly card?: boolean;
}) {
return (
<View className="gap-2">
<Text className="px-2 text-sm font-t3-medium text-foreground-muted">{props.title}</Text>
{props.title ? (
<Text className="px-2 text-sm font-t3-medium text-foreground-muted">{props.title}</Text>
) : null}
<View
className={
props.card
@@ -255,7 +255,7 @@ export function UsageLimitsSection() {
return (
<>
{sources.map((source) => (
<SettingsSection key={source.key} title={source.label} card>
<SettingsSection key={source.key} card>
{source.error ? (
<Text className="p-4 text-sm text-foreground-muted">{source.error}</Text>
) : source.accounts.length === 0 ? (
@@ -35,7 +35,7 @@ function sourceIdFromUrl(url: string): UsageLimitSourceId {
}
/**
* Adds a CLIProxyAPI hub as a usage-limit source on one environment. The
* Adds a CLIProxyAPI hub from provider settings on one environment. The
* management key is sent once and kept in that server's secret store;
* settings only ever carry a redaction marker for it afterwards.
*/
@@ -68,6 +68,7 @@ import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
import { stackedThreadToast, toastManager } from "../ui/toast";
import { AddProviderInstanceDialog } from "./AddProviderInstanceDialog";
import { ProviderInstanceCard } from "./ProviderInstanceCard";
import { UsageProviderSettings } from "./UsageProviderSettings";
import { ProviderSetupSection, readAntigravityAuthMethod } from "./ProviderSetupSection";
import { DRIVER_OPTIONS, getDriverOption } from "./providerDriverMeta";
import { providerSettingsTabClassName } from "./providerSettingsTabs";
@@ -241,7 +242,8 @@ function ProviderSettingsPanelContent(target: ProviderSettingsTarget) {
)?.environmentId;
useEffect(() => {
if (
searchTargetId === searchableSetting("provider-health-check-interval").id &&
(searchTargetId === searchableSetting("provider-health-check-interval").id ||
searchTargetId === searchableSetting("usage-providers").id) &&
!selectedEnvironmentCanRenderSettings &&
searchableEnvironmentId !== undefined
) {
@@ -997,6 +999,14 @@ export function EnvironmentProviderSettings({
</div>
</SettingsSection>
<UsageProviderSettings
key={environmentId}
environmentId={environmentId}
environmentLabel={environmentLabel}
sources={settings.usageLimitSources}
readOnly={readOnly}
/>
<SettingsSection title="Advanced">
<SettingsRow
id={searchableSetting("provider-health-check-interval").id}
@@ -0,0 +1,130 @@
import type { EnvironmentId, UnifiedSettings } from "@t3tools/contracts";
import { PlusIcon } from "lucide-react";
import { useState } from "react";
import { useUpdateEnvironmentSettings } from "../../hooks/useSettings";
import {
AlertDialog,
AlertDialogClose,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogPopup,
AlertDialogTitle,
} from "../ui/alert-dialog";
import { Button } from "../ui/button";
import { AddUsageLimitSourceDialog } from "./AddUsageLimitSourceDialog";
import { searchableSetting } from "./settingsSearch";
import { SettingsRow, SettingsSection } from "./settingsLayout";
/** Hub management follows the selected device and access rules of provider settings. */
export function UsageProviderSettings({
environmentId,
environmentLabel,
sources,
readOnly,
}: {
readonly environmentId: EnvironmentId;
readonly environmentLabel: string;
readonly sources: UnifiedSettings["usageLimitSources"];
readonly readOnly: boolean;
}) {
const updateSettings = useUpdateEnvironmentSettings(environmentId);
const [adding, setAdding] = useState(false);
const entries = Object.entries(sources);
return (
<>
<SettingsSection
{...searchableSetting("usage-providers")}
description="Connect a CLIProxyAPI hub to show its accounts on Usage → Limits."
headerAction={
!readOnly ? (
<Button size="xs" variant="outline" onClick={() => setAdding(true)}>
<PlusIcon className="size-3" aria-hidden />
Add hub
</Button>
) : null
}
>
{entries.length === 0 ? (
<SettingsRow title="No usage providers configured." />
) : (
entries.map(([id, source]) => {
const label = source.label?.trim() || source.url;
return (
<SettingsRow
key={id}
title={label}
description={
<span className="break-all">
CLI Proxy{source.enabled ? "" : " · Disabled"}
{label !== source.url ? ` · ${source.url}` : ""}
</span>
}
control={
!readOnly ? (
<RemoveUsageProviderButton
label={label}
onConfirm={() => updateSettings({ usageLimitSources: { [id]: null } })}
/>
) : null
}
/>
);
})
)}
</SettingsSection>
{adding && !readOnly ? (
<AddUsageLimitSourceDialog
open
onOpenChange={setAdding}
environmentId={environmentId}
environmentLabel={environmentLabel}
/>
) : null}
</>
);
}
/** Removing a hub deletes its stored management key, so it requires confirmation. */
function RemoveUsageProviderButton({
label,
onConfirm,
}: {
readonly label: string;
readonly onConfirm: () => void;
}) {
const [open, setOpen] = useState(false);
return (
<>
<Button size="xs" variant="ghost" onClick={() => setOpen(true)}>
Remove
</Button>
<AlertDialog open={open} onOpenChange={setOpen}>
<AlertDialogPopup>
<AlertDialogHeader>
<AlertDialogTitle>Remove {label}?</AlertDialogTitle>
<AlertDialogDescription>
The hub's management key is deleted from this server. Its accounts leave the Limits
view; the hub itself is untouched. Add it again with the URL and key to bring them
back.
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogClose render={<Button variant="outline" />}>Cancel</AlertDialogClose>
<Button
variant="destructive"
onClick={() => {
setOpen(false);
onConfirm();
}}
>
Remove hub
</Button>
</AlertDialogFooter>
</AlertDialogPopup>
</AlertDialog>
</>
);
}
@@ -101,6 +101,16 @@ describe("searchSettings", () => {
]);
});
it.each(["usage providers", "CLIProxyAPI", "CLI proxy hub", "management key"])(
"finds usage-provider management by %s",
(query) => {
expect(searchSettings(query)[0]).toMatchObject({
id: "usage-providers",
to: "/settings/providers",
});
},
);
it("returns no results for an empty query", () => {
expect(searchSettings(" ", ITEMS)).toEqual([]);
});
@@ -324,6 +324,15 @@ export const SETTINGS_SEARCH_ITEMS = [
"agents cli codex claude cursor grok opencode antigravity google sign in sign out install subscription instances authentication api key models configuration binary path config directory endpoint arguments environment variables display name accent color custom favorite hidden auto compact",
],
},
{
id: "usage-providers",
title: "Usage providers",
to: "/settings/providers",
searchTerms: [
"usage sources CLIProxyAPI CLI proxy hub quota subscription limits management key add remove",
],
providerSettingsOnly: true,
},
{
id: "provider-health-check-interval",
title: "Health check interval",
+6 -227
View File
@@ -1,5 +1,5 @@
import {
EnvironmentId,
type EnvironmentId,
type ProviderConsumeResetCreditOutcome,
ProviderInstanceId,
ServerProvider,
@@ -21,28 +21,16 @@ import {
paceOf,
providerLimitsLabel,
} from "@t3tools/shared/usageLimits";
import { GaugeIcon, PlusIcon, TrendingDownIcon, TrendingUpIcon } from "lucide-react";
import { GaugeIcon, TrendingDownIcon, TrendingUpIcon } from "lucide-react";
import { Fragment, useState } from "react";
import { isElectron } from "../../env";
import { usePrimarySessionState } from "../../environments/primary";
import { usePrimarySettings, useUpdateEnvironmentSettings } from "../../hooks/useSettings";
import {
type EnvironmentPresentation,
useEnvironments,
usePrimaryEnvironmentId,
} from "../../state/environments";
import { useEnvironmentSessionState } from "../../state/session";
import { usePrimarySettings } from "../../hooks/useSettings";
import { environmentPresentations } from "../../state/presentation";
import { serverEnvironment } from "../../state/server";
import { useAtomCommand } from "../../state/use-atom-command";
import { formatUpcomingTimestamp } from "../../timestampFormat";
import { ProviderInstanceIcon } from "../chat/ProviderInstanceIcon";
import { getDriverOption } from "../settings/providerDriverMeta";
import {
resolvePrimaryOperateAccess,
resolveRemoteOperateAccess,
} from "../settings/ProviderSettingsPanel.logic";
import { RedactedSensitiveText } from "../settings/RedactedSensitiveText";
import {
AlertDialog,
@@ -54,9 +42,7 @@ import {
AlertDialogTitle,
} from "../ui/alert-dialog";
import { Button } from "../ui/button";
import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select";
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
import { AddUsageLimitSourceDialog } from "./AddUsageLimitSourceDialog";
import { PROVIDER_PRESENTATION } from "./usageProviders";
const PACE: Record<LimitPace, { readonly label: string; readonly icon: typeof GaugeIcon }> = {
@@ -407,79 +393,17 @@ function SourceAccountLimits({
);
}
/**
* Accounts a configured source (a CLIProxyAPI hub) pools, grouped under the
* source's name. Unlike provider rows these are read-only: nothing on this
* environment can run a turn against them.
*/
const SOURCE_KIND_LABEL: Record<UsageLimitSourceSnapshot["kind"], string> = {
cliproxy: "CLI Proxy",
};
type LimitsSource = ReturnType<typeof collectLimitSources>[number];
/**
* Removing a hub also deletes its management key from the server, so it
* asks first and says so. A bare icon that acted on click was too easy to
* hit while reaching for the row beside it.
*/
function RemoveSourceButton({
source,
onConfirm,
}: {
readonly source: UsageLimitSourceSnapshot;
readonly onConfirm: () => void;
}) {
const [open, setOpen] = useState(false);
return (
<>
<Button size="xs" variant="ghost" onClick={() => setOpen(true)}>
Remove
</Button>
<AlertDialog open={open} onOpenChange={setOpen}>
<AlertDialogPopup>
<AlertDialogHeader>
<AlertDialogTitle>Remove {source.label}?</AlertDialogTitle>
<AlertDialogDescription>
The hub's management key is deleted from this server. Its accounts leave the Limits
view; the hub itself is untouched. Add it again with the URL and key to bring them
back.
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogClose render={<Button variant="outline" />}>Cancel</AlertDialogClose>
<Button
variant="destructive"
onClick={() => {
setOpen(false);
onConfirm();
}}
>
Remove hub
</Button>
</AlertDialogFooter>
</AlertDialogPopup>
</AlertDialog>
</>
);
}
function SourceLimits({
source,
now,
onRemove,
}: {
readonly source: LimitsSource;
readonly now: number;
readonly onRemove: (() => void) | null;
}) {
/** Read-only accounts pooled by a configured usage source. */
function SourceLimits({ source, now }: { readonly source: LimitsSource; readonly now: number }) {
const kind = SOURCE_KIND_LABEL[source.kind];
return (
<div className="flex flex-col gap-6">
<div className="flex items-center justify-between gap-3">
<h2 className="text-xs tracking-wide text-muted-foreground uppercase">{source.label}</h2>
{onRemove ? <RemoveSourceButton source={source} onConfirm={onRemove} /> : null}
</div>
{source.error ? (
<span className="text-xs text-muted-foreground">{source.error}</span>
) : source.accounts.length === 0 ? (
@@ -497,49 +421,6 @@ function SourceLimits({
);
}
/**
* Whether this client's credential may write settings on an environment,
* resolved the way Settings → Providers does: the desktop app owns its
* primary outright; a browser session checks the scopes it was granted;
* a remote environment reports scopes over its own session endpoint.
*/
function useCanOperateEnvironment(environment: EnvironmentPresentation | null): boolean {
const isPrimary = environment?.entry.target._tag === "PrimaryConnectionTarget";
const primarySession = usePrimarySessionState();
const remoteSession = useEnvironmentSessionState(
environment?.environmentId ?? EnvironmentId.make("none"),
);
if (environment === null || environment.connection.phase !== "connected") return false;
if (isPrimary && isElectron) return true;
const access = isPrimary
? resolvePrimaryOperateAccess({
isPrimary: true,
hasDesktopBridge: false,
session: primarySession.data,
isPending: primarySession.isPending,
hasError: primarySession.error !== null,
})
: resolveRemoteOperateAccess({
session: remoteSession.data,
isPending: remoteSession.isPending,
hasError: remoteSession.hasError,
});
return access === "granted";
}
/** One source with a remove control bound to the environment it lives in. */
function SourceLimitsRow({ source, now }: { readonly source: LimitsSource; readonly now: number }) {
const updateSettings = useUpdateEnvironmentSettings(source.environmentId);
const { environments } = useEnvironments();
const environment =
environments.find((entry) => entry.environmentId === source.environmentId) ?? null;
const canOperate = useCanOperateEnvironment(environment);
// The patch names only this entry, so two edits in flight cannot clobber
// each other's map.
const remove = () => updateSettings({ usageLimitSources: { [source.id]: null } });
return <SourceLimits source={source} now={now} onRemove={canOperate ? remove : null} />;
}
/**
* Subscription quota windows from every connected environment's providers.
* Countdowns anchor to render time rather than ticking: a live clock would
@@ -549,108 +430,18 @@ export function UsageLimitsSection() {
const presentations = useAtomValue(environmentPresentations.presentationsAtom);
const groups = collectLimitsGroups(presentations);
const sources = collectLimitSources(presentations);
const primaryEnvironmentId = usePrimaryEnvironmentId();
const { environments } = useEnvironments();
const [adding, setAdding] = useState(false);
// Anchored once per mount on purpose: countdowns must not tick (see below).
const [now] = useState(() => Date.now());
// Sources live in one environment's settings. Writing them needs only the
// operate scope, like any provider control, so a T3 Connect client can add
// a hub to whichever environment it is connected to: the primary when there
// is one, else the first connected environment, with a picker for more.
const connected = environments.filter(
(environment) => environment.connection.phase === "connected",
);
const [pickedEnvironmentId, setPickedEnvironmentId] = useState<EnvironmentId | null>(null);
const targetEnvironment =
(pickedEnvironmentId !== null
? connected.find((environment) => environment.environmentId === pickedEnvironmentId)
: undefined) ??
(primaryEnvironmentId !== null
? connected.find((environment) => environment.environmentId === primaryEnvironmentId)
: undefined) ??
connected[0] ??
null;
const canOperateTarget = useCanOperateEnvironment(targetEnvironment);
return (
<div className="flex flex-col gap-8">
{/* Sources first: they are the thing a user configures here, so the
control to add one sits at the top rather than after every row. */}
<div className="flex items-center justify-between gap-3">
<div className="flex flex-col gap-1">
<h2 className="text-sm font-medium text-foreground">Usage sources</h2>
<p className="text-xs text-muted-foreground">
Quota from a CLIProxyAPI hub shows beside the providers signed in on this machine.
</p>
</div>
{/* The picker stays whenever several environments are connected, so
a read-only default target does not hide the way to an operable
one; only the button follows the picked target's access. */}
{targetEnvironment ? (
<div className="flex items-center gap-2">
{connected.length > 1 ? (
<Select
value={targetEnvironment.environmentId}
onValueChange={(value) => {
if (value !== null) setPickedEnvironmentId(EnvironmentId.make(value));
}}
>
<SelectTrigger
aria-label="Environment to add the hub to"
size="compact"
variant="ghost"
className="w-auto min-w-0"
>
<SelectValue>{targetEnvironment.label}</SelectValue>
</SelectTrigger>
<SelectPopup align="end" alignItemWithTrigger={false}>
{connected.map((environment) => (
<SelectItem key={environment.environmentId} value={environment.environmentId}>
{environment.label}
</SelectItem>
))}
</SelectPopup>
</Select>
) : null}
{canOperateTarget ? (
<Button size="xs" variant="outline" onClick={() => setAdding(true)}>
<PlusIcon className="size-3" aria-hidden />
Add hub
</Button>
) : (
<Tooltip>
<TooltipTrigger
render={
<span
tabIndex={0}
className="rounded-md outline-none focus-visible:ring-2 focus-visible:ring-ring"
/>
}
>
<span className="inline-flex" inert>
<Button size="xs" variant="outline" disabled>
<PlusIcon className="size-3" aria-hidden />
Add hub
</Button>
</span>
</TooltipTrigger>
<TooltipPopup side="top" className="max-w-72">
Your session cannot change settings on {targetEnvironment.label}.
</TooltipPopup>
</Tooltip>
)}
</div>
) : null}
</div>
{groups.length === 0 && sources.length === 0 ? (
<p className="text-sm text-muted-foreground">
No provider on a connected environment reports subscription limits.
</p>
) : null}
{sources.map((source) => (
<SourceLimitsRow key={source.key} source={source} now={now} />
<SourceLimits key={source.key} source={source} now={now} />
))}
{groups.map((group) => (
<div key={group.environmentId} className="flex flex-col gap-6">
@@ -669,18 +460,6 @@ export function UsageLimitsSection() {
))}
</div>
))}
{targetEnvironment && canOperateTarget ? (
// Keyed on the target: if it disconnects or the primary changes while
// the dialog is open, a fresh dialog mounts empty rather than carrying
// a typed key over to a different environment.
<AddUsageLimitSourceDialog
key={targetEnvironment.environmentId}
open={adding}
onOpenChange={setAdding}
environmentId={targetEnvironment.environmentId}
environmentLabel={targetEnvironment.label}
/>
) : null}
</div>
);
}
+4 -2
View File
@@ -18,8 +18,10 @@ provider health-check interval and update live while a turn runs. API-key accoun
subscription windows and say so; that includes a Claude Code that reaches Anthropic through a proxy
via `ANTHROPIC_AUTH_TOKEN`, since the CLI then treats itself as an API-key client.
If you pool accounts behind a CLIProxyAPI hub, **Add hub** on the Limits view shows the accounts
the hub manages. Each row shows its provider and instance name, or a small _CLI Proxy_ label for
If you pool accounts behind a CLIProxyAPI hub, open **Settings → Providers → Usage providers**
and choose **Add hub**. Select the device that should connect to the hub; its accounts appear on
the Limits view. Remove hubs from the same settings section. Each limits row shows its provider
and instance name, or a small _CLI Proxy_ label for
hub accounts. When a connected provider reports limits for the same provider and email, its row
replaces the hub copy, keeping details such as banked reset credits. The hub copy remains visible
if the connected provider cannot report limits. Enter the hub's URL and management key; the key