From b90720ddfa5e7464b9ac15030efdcc0b9c9ac9ba Mon Sep 17 00:00:00 2001 From: daTuzzo <123642701+daTuzzo@users.noreply.github.com> Date: Wed, 25 Nov 2026 02:54:43 +0200 Subject: [PATCH] fix(web): hub account badges use the account name the picker uses A CLIProxyAPI hub account showed letters from its e-mail in Usage, while the model picker badges its provider instance from the instance name. One account showed two different badges. The hub keeps no name per account, so a usage limit source can now name its accounts: `accountNames` maps an e-mail to a name. The server puts the name on each hub account it reads, and the Usage chips take their letters from it with providerInstanceInitials, the function the picker uses. An account with no name keeps its e-mail letters. --- .../src/features/usage/UsageLimitsPooled.tsx | 19 +++-- apps/server/src/serverSettings.test.ts | 1 + .../src/usage/UsageLimitSources.test.ts | 58 ++++++++++++++ apps/server/src/usage/UsageLimitSources.ts | 22 +++++- .../settings/AddUsageLimitSourceDialog.tsx | 3 + .../usage/UsageLimitsPooled.browser.test.tsx | 59 ++++++++++++++ .../components/usage/UsageLimitsPooled.tsx | 24 +++--- packages/contracts/src/providerUsageLimits.ts | 2 + packages/contracts/src/settings.ts | 2 + packages/shared/src/usageLimits.test.ts | 76 +++++++++++++++++++ packages/shared/src/usageLimits.ts | 24 +++--- 11 files changed, 263 insertions(+), 27 deletions(-) diff --git a/apps/mobile/src/features/usage/UsageLimitsPooled.tsx b/apps/mobile/src/features/usage/UsageLimitsPooled.tsx index 869be3631f74c..a898d9230b288 100644 --- a/apps/mobile/src/features/usage/UsageLimitsPooled.tsx +++ b/apps/mobile/src/features/usage/UsageLimitsPooled.tsx @@ -2,7 +2,10 @@ import { useAtomValue } from "@effect/atom-react"; import { useNavigation, type StaticScreenProps } from "@react-navigation/native"; import { EnvironmentId } from "@t3tools/contracts"; import { providerClients } from "@t3tools/client-runtime/provider-clients"; -import { normalizeProviderAccentColor } from "@t3tools/client-runtime/state/provider-instance-display"; +import { + normalizeProviderAccentColor, + providerInstanceInitials, +} from "@t3tools/client-runtime/state/provider-instance-display"; import { collectHttpQuotaSources, collectLimitAccounts, @@ -63,8 +66,8 @@ function accountHue(email: string) { return Math.abs(hash) % 360; } -// Same hashed hue as the web account chip, so an account keeps its color across clients. -function AccountChip({ email }: { readonly email: string }) { +// Same hashed hue and letters as the web account chip, so an account looks alike across clients. +function AccountChip({ email, name }: { readonly email: string; readonly name: string | null }) { const hue = accountHue(email); return ( - {emailInitials(email)} + {(name ? providerInstanceInitials(name) : "") || emailInitials(email)} ); @@ -292,7 +295,13 @@ function PoolWindowCard({ className="absolute inset-0 flex-row items-center justify-between gap-2 overflow-hidden rounded-md px-2" > - {account.email ? : null} + {account.email ? ( + + ) : null} {account.email && !(account.displayName && inlineName) ? null : ( + Effect.gen(function* () { + const sources = yield* UsageLimitSources.make; + yield* sources.refresh; + const [source] = yield* sources.current; + expect(source?.accounts.map(({ email, displayName }) => ({ email, displayName }))).toEqual([ + { email: "alice@example.com", displayName: "work" }, + { email: "bob@example.com", displayName: undefined }, + ]); + }).pipe( + Effect.provide([ + ServerSettings.layerTest({ + usageLimitSources: { + [UsageLimitSourceId.make("hub")]: { + kind: "cliproxy", + url: "http://hub.test:8317", + managementKey: "management-secret", + enabled: true, + // Names match e-mails in any letter case; a name for an unlisted login is ignored. + accountNames: { "Alice@Example.com": "work", "carol@example.com": "personal" }, + }, + }, + }), + Layer.mock(BackgroundPolicy.BackgroundPolicy)({ + shouldRunScopeWork: () => Effect.succeed(false), + }), + Layer.succeed(SecretResolver.SecretResolver, { + label: (provider) => Effect.succeed(provider), + read: (references) => Effect.succeed(references.map(() => undefined)), + invalidate: () => Effect.void, + }), + Layer.succeed( + HttpClient.HttpClient, + HttpClient.make((request) => + Effect.sync(() => + HttpClientResponse.fromWeb( + request, + Response.json( + new URL(request.url).pathname.endsWith("/auth-files") + ? { + files: ["alice", "bob"].map((name) => ({ + id: `claude-${name}@example.com.json`, + auth_index: name, + provider: "claude", + email: `${name}@example.com`, + })), + } + : { status_code: 200, body: JSON.stringify({ five_hour: null }) }, + ), + ), + ), + ), + ), + NodeCrypto.layer, + ]), + ), +); + const NOW = Date.parse("2026-11-13T12:00:00.000Z"); const at = (hours: number) => DateTime.formatIso(DateTime.makeUnsafe(NOW + hours * 3_600_000)); const spent = (id: string, hours: number): ServerProviderUsageWindow => ({ diff --git a/apps/server/src/usage/UsageLimitSources.ts b/apps/server/src/usage/UsageLimitSources.ts index 21ca1fd39064f..d8540761a095f 100644 --- a/apps/server/src/usage/UsageLimitSources.ts +++ b/apps/server/src/usage/UsageLimitSources.ts @@ -8,6 +8,7 @@ import { type ServerSettings, UsageLimitSourceConfig, settingsSecretLiteral, + type UsageLimitSourceAccount, type UsageLimitSourceId, type UsageLimitSourceSnapshot, } from "@t3tools/contracts"; @@ -114,13 +115,28 @@ function keepLastGoodReadings( candidate.workspaceId === account.workspaceId, ); if (!last || last.usageLimits.unavailable) return account; - // Only the reading is lent; an unread model list stays unknown. - return { ...last, models: account.models }; + // Only the reading is lent; an unread model list stays unknown, and names follow settings. + return { ...last, models: account.models, displayName: account.displayName }; }), }; }); } +/** The hub keeps no usable name per account, so settings name them by e-mail. */ +function nameAccounts( + accounts: ReadonlyArray, + config: UsageLimitSourceConfig, +): ReadonlyArray { + const names = new Map( + Object.entries(config.accountNames ?? {}).map(([email, name]) => [email.toLowerCase(), name]), + ); + if (names.size === 0) return accounts; + return accounts.map((account) => { + const displayName = account.email ? names.get(account.email.toLowerCase()) : undefined; + return displayName ? { ...account, displayName } : account; + }); +} + function missingManagementKey(config: UsageLimitSourceConfig): string { return typeof config.managementKey === "string" ? "No management key configured." @@ -202,7 +218,7 @@ export const make = Effect.gen(function* () { yield* Effect.logDebug("usage limit source read failed", { id, cause: accounts.failure }); return { ...base, accounts: [], error: accounts.failure.detail }; } - return { ...base, accounts: accounts.success }; + return { ...base, accounts: nameAccounts(accounts.success, config) }; }); const publish = Effect.fn("UsageLimitSources.publish")(function* ( diff --git a/apps/web/src/components/settings/AddUsageLimitSourceDialog.tsx b/apps/web/src/components/settings/AddUsageLimitSourceDialog.tsx index e89e52d8ea8d0..d4de7829ab13f 100644 --- a/apps/web/src/components/settings/AddUsageLimitSourceDialog.tsx +++ b/apps/web/src/components/settings/AddUsageLimitSourceDialog.tsx @@ -65,6 +65,8 @@ export function AddUsageLimitSourceDialog({ const save = () => { if (!canSave) return; const id = sourceIdFromUrl(trimmedUrl, sources, kind); + // Adding a saved hub again replaces its entry, so it keeps the account names set for it. + const accountNames = sources[id]?.accountNames; updateSettings({ usageLimitSources: { [id]: { @@ -73,6 +75,7 @@ export function AddUsageLimitSourceDialog({ url: trimmedUrl, managementKey, enabled: true, + ...(accountNames ? { accountNames } : {}), }, }, }); diff --git a/apps/web/src/components/usage/UsageLimitsPooled.browser.test.tsx b/apps/web/src/components/usage/UsageLimitsPooled.browser.test.tsx index 886dc684a10d7..2cc27b86d8ae3 100644 --- a/apps/web/src/components/usage/UsageLimitsPooled.browser.test.tsx +++ b/apps/web/src/components/usage/UsageLimitsPooled.browser.test.tsx @@ -3,6 +3,7 @@ import { ProviderDriverKind, ProviderInstanceId, type ServerProvider, + UsageLimitSourceId, } from "@t3tools/contracts"; import { CHATGPT_USAGE_URL } from "@t3tools/shared/usageLimits"; import { describe, expect, it } from "vite-plus/test"; @@ -66,6 +67,64 @@ describe("UsageLimitsPooled ChatGPT usage card", () => { }); }); +describe("UsageLimitsPooled hub account badges", () => { + it("draws a named hub account with its picker initials and an unnamed one by e-mail", async () => { + const account = (email: string, usedPercent: number, displayName?: string) => ({ + id: `claude-${email}.json`, + driver: ProviderDriverKind.make("claudeAgent"), + email, + ...(displayName ? { displayName } : {}), + usageLimits: { + checkedAt, + windows: [ + { + id: "five_hour", + label: "Session", + kind: "session" as const, + usedPercent, + resetsAt: "2026-10-25T18:00:00.000Z", + }, + ], + }, + }); + const presentations = new Map([ + [ + EnvironmentId.make("desk"), + { + entry: { target: { label: "Desk" } }, + serverConfig: { + providers: [], + usageLimitSources: [ + { + id: UsageLimitSourceId.make("hub"), + kind: "cliproxy" as const, + label: "Hub", + checkedAt, + accounts: [ + account("alice@example.com", 20, "work"), + account("bob@example.com", 60), + ], + }, + ], + }, + }, + ], + ]); + await using screen = await render( + , + ); + + // The model picker badges an instance named "work" as WO. + await expect.element(screen.getByRole("img", { name: "Account WO" }).first()).toBeVisible(); + await expect.element(screen.getByRole("img", { name: "Account BE" }).first()).toBeVisible(); + await expect.element(screen.getByRole("img", { name: "Account AE" })).not.toBeInTheDocument(); + + await screen.getByRole("img", { name: "Account WO" }).first().click(); + await expect.element(screen.getByText("work", { exact: true })).toBeVisible(); + await expect.element(screen.getByLabelText("Toggle account email visibility")).toBeVisible(); + }); +}); + describe("UsageLimitsPooled next refill", () => { it("skips elapsed resets while waiting for refreshed account data", async () => { function account(instanceId: string, usedPercent: number, resetsAt: string): ServerProvider { diff --git a/apps/web/src/components/usage/UsageLimitsPooled.tsx b/apps/web/src/components/usage/UsageLimitsPooled.tsx index 144bab9a1a27b..04a4d2357eff0 100644 --- a/apps/web/src/components/usage/UsageLimitsPooled.tsx +++ b/apps/web/src/components/usage/UsageLimitsPooled.tsx @@ -14,7 +14,10 @@ import { } from "@t3tools/shared/usageLimits"; import { T, Var, useGT, useMessages } from "gt-react"; import type { Popover as PopoverPrimitive } from "@base-ui/react/popover"; -import { normalizeProviderAccentColor } from "@t3tools/client-runtime/state/provider-instance-display"; +import { + normalizeProviderAccentColor, + providerInstanceInitials, +} from "@t3tools/client-runtime/state/provider-instance-display"; import { AlertTriangleIcon, ExternalLinkIcon, TicketIcon } from "lucide-react"; import { createContext, @@ -61,17 +64,19 @@ function accountHue(email: string): number { return Math.abs(hash) % 360; } -function AccountChip({ email }: { readonly email: string }) { +// A named account reads as the picker's badge for that name; the e-mail keeps its color. +function AccountChip({ email, name }: { readonly email: string; readonly name: string | null }) { const hue = accountHue(email); + const initials = (name ? providerInstanceInitials(name) : "") || accountInitials(email); const gt = useGT(); return ( - {accountInitials(email)} + {initials} ); } @@ -100,7 +105,7 @@ function AccountAvatar({ /> ); } - return account.email ? : null; + return account.email ? : null; } function AccountName({ @@ -110,14 +115,15 @@ function AccountName({ readonly account: LimitAccount; readonly className?: string; }) { - if (account.displayName) return {account.displayName}; - if (account.email) { + // A hub account keeps its chip when named, so it matches its badge in the model picker. + if (account.email && (!account.displayName || account.environments.length === 0)) { return ( - + ); } + if (account.displayName) return {account.displayName}; return ( {providerClients.get(account.driver)?.label ?? String(account.driver)} diff --git a/packages/contracts/src/providerUsageLimits.ts b/packages/contracts/src/providerUsageLimits.ts index 342aa2660c9c4..ed571a0cbfdd7 100644 --- a/packages/contracts/src/providerUsageLimits.ts +++ b/packages/contracts/src/providerUsageLimits.ts @@ -76,6 +76,8 @@ export const UsageLimitSourceAccount = Schema.Struct({ id: TrimmedNonEmptyString, driver: ProviderDriverKind, email: Schema.optional(TrimmedNonEmptyString), + /** The source's name for this account (see UsageLimitSourceConfig.accountNames). */ + displayName: Schema.optional(TrimmedNonEmptyString), plan: Schema.optional(TrimmedNonEmptyString), workspaceId: Schema.optional(TrimmedNonEmptyString), /** The models the hub routes to this account. */ diff --git a/packages/contracts/src/settings.ts b/packages/contracts/src/settings.ts index 4922cceeda19f..97bef803271a9 100644 --- a/packages/contracts/src/settings.ts +++ b/packages/contracts/src/settings.ts @@ -957,6 +957,8 @@ export const UsageLimitSourceConfig = Schema.Struct({ secretSetting, ), enabled: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))), + /** Names for hub accounts, keyed by e-mail, so a hub account can carry its instance's name. */ + accountNames: Schema.optional(Schema.Record(TrimmedNonEmptyString, TrimmedNonEmptyString)), }); export type UsageLimitSourceConfig = typeof UsageLimitSourceConfig.Type; diff --git a/packages/shared/src/usageLimits.test.ts b/packages/shared/src/usageLimits.test.ts index 2aab03105b5d9..153ed60185088 100644 --- a/packages/shared/src/usageLimits.test.ts +++ b/packages/shared/src/usageLimits.test.ts @@ -294,6 +294,82 @@ describe("pools", () => { expect(accounts[0]?.limits.windows[0]?.usedPercent).toBe(55); }); + it("names hub accounts by the source's names and leaves unnamed ones to their e-mail", () => { + const hubAccount = (email: string, displayName?: string): UsageLimitSourceAccount => ({ + id: `claude-${email}.json`, + driver: claude, + email, + ...(displayName ? { displayName } : {}), + usageLimits: { checkedAt, windows: [window] }, + }); + const accounts = [ + hubAccount("alice@example.com", "work"), + hubAccount("bob@example.com"), + hubAccount("carol@example.com", "personal"), + ]; + // Carol is also signed in on the default instance, whose name is the driver's. + const native = provider({ + driver: claude, + instanceId: ProviderInstanceId.make("claudeAgent"), + displayName: "Claude", + auth: { status: "authenticated", email: "carol@example.com" }, + usageLimits: { checkedAt, windows: [window] }, + }); + const input = new Map([ + [ + EnvironmentId.make("env-a"), + { + ...laptop, + serverConfig: { providers: [native], usageLimitSources: [{ ...source, accounts }] }, + }, + ], + ]); + expect( + collectLimitAccounts(input).map(({ email, displayName }) => ({ email, displayName })), + ).toEqual([ + { email: "carol@example.com", displayName: "personal" }, + { email: "alice@example.com", displayName: "work" }, + { email: "bob@example.com", displayName: null }, + ]); + const routed = provider({ driver: claude, instanceId: ProviderInstanceId.make("work_claude") }); + const report = collectProviderUsageLimits( + routed.instanceId, + [routed], + [{ ...source, accounts }], + now, + ); + expect(report?.accounts.map((account) => account.label)).toEqual([ + "hub · work", + "hub · claude-bob@example.com", + "hub · personal", + ]); + const unread = (email: string, displayName?: string): UsageLimitSourceAccount => ({ + ...hubAccount(email, displayName), + usageLimits: { checkedAt, windows: [], unavailable: { reason: "probeFailed" } }, + }); + const failed = new Map([ + [ + EnvironmentId.make("env-a"), + { + ...laptop, + serverConfig: { + providers: [], + usageLimitSources: [ + { + ...source, + accounts: [unread("alice@example.com", "work"), unread("bob@example.com")], + }, + ], + }, + }, + ], + ]); + expect(collectLimitNotices(failed)).toEqual([ + "hub · work: Could not read limits.", + "hub · bob@example.com: Could not read limits.", + ]); + }); + it("uses the freshest reported plan even when the newest quota has no plan", () => { const snapshot = (label: string | undefined, checkedAt: string, usedPercent: number) => provider({ diff --git a/packages/shared/src/usageLimits.ts b/packages/shared/src/usageLimits.ts index 77710a8d5852d..3752174db82a2 100644 --- a/packages/shared/src/usageLimits.ts +++ b/packages/shared/src/usageLimits.ts @@ -385,18 +385,22 @@ export function collectLimitAccounts(presentations: LimitPresentations): readonl ]; const winner = fresher ? next : previous; const creditSource = creditSources.get(key); - // A hub e-mail names the account better than the driver's default instance name. + // A hub e-mail or name names the account better than the driver's default instance name. const hubEmail = [previous, next].some( (account) => account.environments.length === 0 && account.email, ); - const displayName = previous.displayName ?? next.displayName; + const displayName = + [previous.displayName, next.displayName].find( + (name) => + name && + !( + hubEmail && + name.toLowerCase() === PROVIDER_DISPLAY_NAMES[previous.driver]?.toLowerCase() + ), + ) ?? null; accounts.set(key, { ...previous, - displayName: - hubEmail && - displayName?.toLowerCase() === PROVIDER_DISPLAY_NAMES[previous.driver]?.toLowerCase() - ? null - : displayName, + displayName, plan: planSources.get(key)?.plan ?? previous.plan ?? next.plan, accentColor: previous.accentColor ?? next.accentColor, environments, @@ -446,7 +450,7 @@ export function collectLimitAccounts(presentations: LimitPresentations): readonl merge(hubRowKey(resolveKey, environmentId, source, account), { key, driver: account.driver, - displayName: account.email ? null : hubAccountName(account), + displayName: account.displayName ?? (account.email ? null : hubAccountName(account)), email: account.email, plan: account.plan, accentColor: undefined, @@ -496,7 +500,7 @@ export function unshownFailedHubAccounts( for (const account of source.accounts) { if (account.usageLimits.unavailable?.reason !== "probeFailed") continue; if (shownRows.has(hubRowKey(resolveKey, environmentId, source, account))) continue; - failed.set(account, account.email ?? hubAccountName(account)); + failed.set(account, account.displayName ?? account.email ?? hubAccountName(account)); } } } @@ -1106,7 +1110,7 @@ export function collectProviderUsageLimits( accounts.push({ id: `${source.id}:${account.id}`, driver: account.driver, - label: `${source.label} · ${hubAccountName(account)}`, + label: `${source.label} · ${account.displayName ?? hubAccountName(account)}`, sourceLabel: "CLI Proxy", ...(account.usageLimits.resetCredits?.nextCreditId ? {