TypeScript
fix(usage): deduplicate CLI proxy subscription accounts (#9584)
Julius Marmingeb34ff8f56469
diff --git a/apps/mobile/src/features/usage/UsageLimitsSection.tsx b/apps/mobile/src/features/usage/UsageLimitsSection.tsxindex 8ed89b1a94c..411fbc14551 100644--- a/apps/mobile/src/features/usage/UsageLimitsSection.tsx+++ b/apps/mobile/src/features/usage/UsageLimitsSection.tsx@@ -28,6 +28,7 @@ import { useAtomCommand } from "../../state/use-atom-command";import { SettingsSection } from "../settings/components/SettingsSection";const PACE_LABEL = { ahead: "ahead of pace", on: "on pace", under: "under pace" } as const;+const DRIVER_LABEL: Partial<Record<string, string>> = { codex: "Codex", claudeAgent: "Claude" };/*** One window as a bar spanning its whole duration: the fill is quota spent,@@ -74,6 +75,7 @@ function WindowBar(props: { readonly window: ServerProviderUsageWindow; readonlyfunction AccountLimits(props: {readonly label: string;+ readonly instanceLabel: string;readonly detail: string | undefined;readonly limits: ServerProvider["usageLimits"];readonly now: number;@@ -85,10 +87,13 @@ function AccountLimits(props: {const notice = limitsNotice(limits);return (<View className={props.first ? "gap-3 p-4" : "gap-3 border-t border-border-subtle p-4"}>- <View className="flex-row items-baseline gap-2">+ <View className="flex-row flex-wrap items-baseline gap-x-2 gap-y-1"><Text className="text-lg text-foreground">{props.label}</Text>+ {props.instanceLabel !== props.label ? (+ <Text className="shrink text-xs text-foreground-tertiary">· {props.instanceLabel}</Text>+ ) : null}{props.detail ? (- <Text className="text-sm text-foreground-muted">{props.detail}</Text>+ <Text className="shrink text-sm text-foreground-muted">· {props.detail}</Text>) : null}</View>{notice ? (@@ -195,7 +200,8 @@ function ProviderLimits(props: {const credits = provider.usageLimits?.resetCredits;return (<AccountLimits- label={providerLimitsLabel(provider, () => undefined)}+ label={DRIVER_LABEL[provider.driver] ?? String(provider.driver)}+ instanceLabel={providerLimitsLabel(provider, (driver) => DRIVER_LABEL[driver])}detail={provider.auth.label}limits={provider.usageLimits}now={now}@@ -214,8 +220,6 @@ function ProviderLimits(props: {);}-const DRIVER_LABEL: Partial<Record<string, string>> = { codex: "Codex", claudeAgent: "Claude" };-/** Emails stay off the phone screen; the plan and driver identify the row. */function SourceAccountLimits(props: {readonly account: UsageLimitSourceAccount;@@ -226,6 +230,7 @@ function SourceAccountLimits(props: {return (<AccountLimitslabel={DRIVER_LABEL[account.driver] ?? String(account.driver)}+ instanceLabel="CLI Proxy"detail={account.plan}limits={account.usageLimits}now={props.now}@@ -250,11 +255,15 @@ export function UsageLimitsSection() {return (<>{sources.map((source) => (- <SettingsSection key={source.key} title={`${source.label} · CLIProxyAPI`} card>+ <SettingsSection key={source.key} title={source.label} card>{source.error ? (<Text className="p-4 text-sm text-foreground-muted">{source.error}</Text>) : source.accounts.length === 0 ? (- <Text className="p-4 text-sm text-foreground-muted">No accounts reported.</Text>+ <Text className="p-4 text-sm text-foreground-muted">+ {source.hiddenAccountCount > 0+ ? "All accounts are shown by connected providers."+ : "No accounts reported."}+ </Text>) : (source.accounts.map((account, index) => (<SourceAccountLimitsdiff --git a/apps/web/src/components/usage/UsageLimits.tsx b/apps/web/src/components/usage/UsageLimits.tsxindex eff21977f65..8e626d0a526 100644--- a/apps/web/src/components/usage/UsageLimits.tsx+++ b/apps/web/src/components/usage/UsageLimits.tsx@@ -53,7 +53,6 @@ import {AlertDialogPopup,AlertDialogTitle,} from "../ui/alert-dialog";-import { Badge } from "../ui/badge";import { Button } from "../ui/button";import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select";import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";@@ -209,29 +208,29 @@ function LimitWindows({}/**- * Heading shared by local providers and source accounts: icon, name, plan,+ * Heading shared by local providers and source accounts: icon, driver, instance, plan,* and the signed-in email blurred until clicked, as provider settings do.*/function AccountHeading({driver,label,+ instanceLabel,plan,email,accentColor,- badge,}: {readonly driver: ServerProvider["driver"];readonly label: string;+ readonly instanceLabel: string;readonly plan: string | undefined;readonly email: string | undefined;readonly accentColor?: string | undefined;- readonly badge?: string | undefined;}) {return (- <h2 className="flex min-w-0 items-center gap-2 text-sm font-medium text-foreground">+ <h2 className="flex min-w-0 flex-wrap items-center gap-x-2 gap-y-1 text-sm font-medium text-foreground"><ProviderInstanceIcondriverKind={driver}- displayName={label}+ displayName={instanceLabel}accentColor={accentColor}showBadge={Boolean(accentColor)}indicatorBackground="var(--background)"@@ -239,7 +238,12 @@ function AccountHeading({iconClassName="size-4 text-foreground/80"/><span className="truncate">{label}</span>- {plan ? <span className="shrink-0 font-normal text-muted-foreground">· {plan}</span> : null}+ {instanceLabel !== label ? (+ <span className="min-w-0 truncate text-xs font-normal text-muted-foreground">+ · {instanceLabel}+ </span>+ ) : null}+ {plan ? <span className="font-normal text-muted-foreground">· {plan}</span> : null}{email ? (<RedactedSensitiveTextvalue={email}@@ -248,11 +252,6 @@ function AccountHeading({hideTooltip="Click to hide email"/>) : null}- {badge ? (- <Badge variant="outline" size="sm" className="ms-auto shrink-0 font-normal">- {badge}- </Badge>- ) : null}</h2>);}@@ -273,7 +272,8 @@ function ProviderLimits({<section className="flex flex-col gap-3"><AccountHeadingdriver={provider.driver}- label={providerLimitsLabel(provider, (driver) => getDriverOption(driver)?.label)}+ label={getDriverOption(provider.driver)?.label ?? String(provider.driver)}+ instanceLabel={providerLimitsLabel(provider, (driver) => getDriverOption(driver)?.label)}plan={provider.auth.label}email={provider.auth.email}accentColor={provider.accentColor}@@ -394,9 +394,9 @@ function SourceAccountLimits({<AccountHeadingdriver={account.driver}label={getDriverOption(account.driver)?.label ?? String(account.driver)}+ instanceLabel={sourceKind}plan={account.plan}email={account.email}- badge={`via ${sourceKind}`}/>{notice ? (<span className="text-xs text-muted-foreground">{notice}</span>@@ -413,9 +413,11 @@ function SourceAccountLimits({* environment can run a turn against them.*/const SOURCE_KIND_LABEL: Record<UsageLimitSourceSnapshot["kind"], string> = {- cliproxy: "CLIProxyAPI",+ 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@@ -467,7 +469,7 @@ function SourceLimits({now,onRemove,}: {- readonly source: UsageLimitSourceSnapshot;+ readonly source: LimitsSource;readonly now: number;readonly onRemove: (() => void) | null;}) {@@ -475,15 +477,17 @@ function SourceLimits({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} · {kind}- </h2>+ <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 ? (- <span className="text-xs text-muted-foreground">No accounts reported.</span>+ <span className="text-xs text-muted-foreground">+ {source.hiddenAccountCount > 0+ ? "All accounts are shown by connected providers."+ : "No accounts reported."}+ </span>) : (source.accounts.map((account) => (<SourceAccountLimits key={account.id} account={account} sourceKind={kind} now={now} />@@ -524,16 +528,7 @@ function useCanOperateEnvironment(environment: EnvironmentPresentation | null):}/** One source with a remove control bound to the environment it lives in. */-function SourceLimitsRow({- source,- now,-}: {- readonly source: UsageLimitSourceSnapshot & {- readonly key: string;- readonly environmentId: EnvironmentId;- };- readonly now: number;-}) {+function SourceLimitsRow({ source, now }: { readonly source: LimitsSource; readonly now: number }) {const updateSettings = useUpdateEnvironmentSettings(source.environmentId);const { environments } = useEnvironments();const environment =diff --git a/docs/user/usage.md b/docs/user/usage.mdindex 5b9e474c6aa..2fcb5c54210 100644--- a/docs/user/usage.md+++ b/docs/user/usage.md@@ -18,10 +18,13 @@ provider health-check interval and update live while a turn runs. API-key accounsubscription windows and say so; that includes a Claude Code that reaches Anthropic through a proxyvia `ANTHROPIC_AUTH_TOKEN`, since the CLI then treats itself as an API-key client.-If you pool accounts behind a CLIProxyAPI hub, **Add CLIProxyAPI hub** on the Limits view shows-every account the hub manages, each marked _via CLIProxyAPI_ so it is not mistaken for the provider-signed in on this machine. Enter the hub's URL and management key; the key is stored on the server-and never sent back to a client. Emails are blurred until clicked, as in provider settings.+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+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+is stored on the server and never sent back to a client. Emails are blurred until clicked, as in+provider settings.Use **Past 24h** for an hourly chart covering the exact rolling 24-hour period. The **7 days**,**30 days**, and **90 days** ranges use daily resolution. Cost and token toggles update both thediff --git a/packages/shared/src/usageLimits.test.ts b/packages/shared/src/usageLimits.test.tsindex 33f180ac9d6..83ac6906c61 100644--- a/packages/shared/src/usageLimits.test.ts+++ b/packages/shared/src/usageLimits.test.ts@@ -1,4 +1,11 @@-import { ProviderDriverKind, ProviderInstanceId, type ServerProvider } from "@t3tools/contracts";+import {+ EnvironmentId,+ ProviderDriverKind,+ ProviderInstanceId,+ type ServerProvider,+ type UsageLimitSourceAccount,+ UsageLimitSourceId,+} from "@t3tools/contracts";import { describe, expect, it } from "vite-plus/test";import {@@ -141,12 +148,130 @@ describe("collectLimitsGroups", () => {describe("collectLimitSources", () => {const source = {- id: "cliproxy-hub" as never,+ id: UsageLimitSourceId.make("cliproxy-hub"),kind: "cliproxy" as const,label: "hub",checkedAt: "2026-09-03T11:00:00.000Z",accounts: [],};+ const limits = { checkedAt: source.checkedAt, windows: [window] };+ const account: UsageLimitSourceAccount = {+ id: "codex-personal",+ driver: ProviderDriverKind.make("codex"),+ email: "[email protected]",+ plan: "ChatGPT Pro Subscription",+ usageLimits: limits,+ };+ const native = provider({+ displayName: "Personal",+ auth: { status: "authenticated", email: account.email },+ usageLimits: { ...limits, resetCredits: { availableCount: 2 } },+ });++ function presentations(+ providers: readonly ServerProvider[],+ accounts: readonly UsageLimitSourceAccount[] = [account],+ ) {+ return new Map([+ [+ EnvironmentId.make("env-a"),+ {+ entry: { target: { label: "Laptop" } },+ serverConfig: { providers, usageLimitSources: [{ ...source, accounts }] },+ },+ ],+ ]);+ }++ it.each(["codex", "claudeAgent"])(+ "prefers native %s limits by email without changing provider rows or source snapshots",+ (kind) => {+ const driver = ProviderDriverKind.make(kind);+ const first = { ...native, driver };+ const second = { ...first, instanceId: ProviderInstanceId.make("work") };+ const accounts = [{ ...account, driver, email: " [email protected] " }];+ const input = presentations([first, second], accounts);++ expect(collectLimitSources(input)).toMatchObject([{ accounts: [], hiddenAccountCount: 1 }]);+ expect(collectLimitsGroups(input)[0]?.providers).toEqual([first, second]);+ expect(accounts).toHaveLength(1);+ expect(first.usageLimits?.resetCredits?.availableCount).toBe(2);+ },+ );++ it("matches across environments even when the hub is visited before the native provider", () => {+ const input = presentations([]);+ input.set(EnvironmentId.make("env-b"), {+ entry: { target: { label: "Desktop" } },+ serverConfig: { providers: [native], usageLimitSources: [] },+ });++ expect(collectLimitSources(input)).toMatchObject([+ { accounts: [], hiddenAccountCount: 1, environmentId: "env-a" },+ ]);+ });++ it("keeps other providers, other emails, and unidentified accounts with the same plan", () => {+ const accounts = [+ account,+ { ...account, id: "other-provider", driver: ProviderDriverKind.make("claudeAgent") },+ { ...account, id: "other-email", email: "[email protected]" },+ { ...account, id: "unknown-email", email: undefined },+ ];++ expect(collectLimitSources(presentations([native], accounts))).toMatchObject([+ { accounts: accounts.slice(1), hiddenAccountCount: 1 },+ ]);+ expect(+ collectLimitSources(+ presentations([{ ...native, auth: { status: "authenticated" } }], accounts),+ )[0]?.accounts,+ ).toEqual(accounts);+ });++ it.each([+ { enabled: false },+ { installed: false },+ { availability: "unavailable" },+ { usageLimits: undefined },+ { usageLimits: { ...limits, windows: [] } },+ { usageLimits: { ...limits, unavailable: { reason: "probeFailed" } } },+ { usageLimits: { ...limits, unavailable: { reason: "unsupported" } } },+ ] satisfies Partial<ServerProvider>[])(+ "retains hub limits when the native provider cannot show them: %j",+ (overrides) => {+ expect(collectLimitSources(presentations([{ ...native, ...overrides }]))).toMatchObject([+ { accounts: [account], hiddenAccountCount: 0 },+ ]);+ },+ );++ it("restores the hub account when the matching provider disappears", () => {+ const input = presentations([native]);+ expect(collectLimitSources(input)[0]?.accounts).toEqual([]);+ input.delete(EnvironmentId.make("env-a"));+ for (const [id, entry] of presentations([])) input.set(id, entry);++ expect(collectLimitSources(input)[0]?.accounts).toEqual([account]);+ });++ it("keeps source errors and genuinely empty sources distinguishable from hidden accounts", () => {+ const input = new Map([+ [+ EnvironmentId.make("env-a"),+ {+ entry: { target: { label: "Laptop" } },+ serverConfig: {+ providers: [native],+ usageLimitSources: [{ ...source, error: "Hub unavailable" }],+ },+ },+ ],+ ]);+ expect(collectLimitSources(input)).toMatchObject([+ { accounts: [], hiddenAccountCount: 0, error: "Hub unavailable" },+ ]);+ });it("keys sources per environment and names the environment only when several have some", () => {const one = new Map([diff --git a/packages/shared/src/usageLimits.ts b/packages/shared/src/usageLimits.tsindex 3c5b39ea06a..8341796e39c 100644--- a/packages/shared/src/usageLimits.ts+++ b/packages/shared/src/usageLimits.ts@@ -70,6 +70,8 @@ export function collectLimitsGroups(* Every usage-limit source across connected environments, keyed so two* environments pointing at the same hub still get their own rows. The label* carries the environment only when more than one environment has sources.+ * A native provider with usable limits takes precedence over the same account+ * in a source, even when it belongs to another connected environment.*/export function collectLimitSources(presentations: ReadonlyMap<@@ -77,13 +79,31 @@ export function collectLimitSources({readonly entry: { readonly target: { readonly label: string } };readonly serverConfig: {+ readonly providers?: readonly ServerProvider[] | undefined;readonly usageLimitSources?: UsageLimitSourceSnapshots | undefined;} | null;}>,): ReadonlyArray<- UsageLimitSourceSnapshot & { readonly key: string; readonly environmentId: EnvironmentId }+ UsageLimitSourceSnapshot & {+ readonly key: string;+ readonly environmentId: EnvironmentId;+ readonly hiddenAccountCount: number;+ }> {+ const nativeAccounts = new Set<string>();+ for (const presentation of presentations.values()) {+ for (const provider of providersWithLimits(presentation.serverConfig?.providers ?? [])) {+ const key = accountKey(provider.driver, provider.auth.email);+ if (+ key !== null &&+ provider.usageLimits?.windows.length &&+ !provider.usageLimits.unavailable+ ) {+ nativeAccounts.add(key);+ }+ }+ }const perEnvironment: Array<{readonly environmentId: EnvironmentId;readonly environmentLabel: string;@@ -100,15 +120,28 @@ export function collectLimitSources(}const labelEnvironment = perEnvironment.length > 1;return perEnvironment.flatMap(({ environmentId, environmentLabel, sources }) =>- sources.map((source) => ({- ...source,- environmentId,- key: `${environmentId}:${source.id}`,- label: labelEnvironment ? `${environmentLabel} · ${source.label}` : source.label,- })),+ sources.map((source) => {+ const accounts = source.accounts.filter((account) => {+ const key = accountKey(account.driver, account.email);+ return key === null || !nativeAccounts.has(key);+ });+ return {+ ...source,+ accounts,+ hiddenAccountCount: source.accounts.length - accounts.length,+ environmentId,+ key: `${environmentId}:${source.id}`,+ label: labelEnvironment ? `${environmentLabel} · ${source.label}` : source.label,+ };+ }),);}+function accountKey(driver: ServerProvider["driver"], email: string | undefined): string | null {+ const normalizedEmail = email?.trim().toLowerCase();+ return normalizedEmail ? `${driver}:${normalizedEmail}` : null;+}+/** The instance's configured name, else the driver's, else its raw kind. */export function providerLimitsLabel(provider: ServerProvider,