Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 14 additions & 5 deletions apps/mobile/src/features/usage/UsageLimitsPooled.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -63,16 +66,16 @@ 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 (
<View
className="size-5 items-center justify-center rounded-full"
style={{ backgroundColor: `hsl(${hue}, 45%, 82%)` }}
>
<Text className="text-[9px] font-t3-bold" style={{ color: `hsl(${hue}, 45%, 28%)` }}>
{emailInitials(email)}
{(name ? providerInstanceInitials(name) : "") || emailInitials(email)}
</Text>
</View>
);
Expand Down Expand Up @@ -292,7 +295,13 @@ function PoolWindowCard({
className="absolute inset-0 flex-row items-center justify-between gap-2 overflow-hidden rounded-md px-2"
>
<View className="min-w-0 shrink flex-row items-center gap-1.5">
{account.email ? <AccountChip email={account.email} /> : null}
{account.email ? (
<AccountChip
email={account.email}
// As on the web, only a named hub account's chip shows its name's letters.
name={account.environments.length === 0 ? account.displayName : null}
/>
) : null}
{account.email && !(account.displayName && inlineName) ? null : (
<Text
numberOfLines={1}
Expand Down
1 change: 1 addition & 0 deletions apps/server/src/serverSettings.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -650,6 +650,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("server settings"
url: "https://hub.example.test",
managementKey: "",
enabled: true,
accountNames: { "alice@example.com": "work" },
},
};
const saved = yield* serverSettings.updateSettings({
Expand Down
58 changes: 58 additions & 0 deletions apps/server/src/usage/UsageLimitSources.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -352,6 +352,64 @@ it.effect("keeps an account's last good reading when the hub's next read of it i
);
});

it.effect("names hub accounts by e-mail from the source's account names", () =>
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 => ({
Expand Down
22 changes: 19 additions & 3 deletions apps/server/src/usage/UsageLimitSources.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {
type ServerSettings,
UsageLimitSourceConfig,
settingsSecretLiteral,
type UsageLimitSourceAccount,
type UsageLimitSourceId,
type UsageLimitSourceSnapshot,
} from "@t3tools/contracts";
Expand Down Expand Up @@ -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<UsageLimitSourceAccount>,
config: UsageLimitSourceConfig,
): ReadonlyArray<UsageLimitSourceAccount> {
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."
Expand Down Expand Up @@ -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* (
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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]: {
Expand All @@ -73,6 +75,7 @@ export function AddUsageLimitSourceDialog({
url: trimmedUrl,
managementKey,
enabled: true,
...(accountNames ? { accountNames } : {}),
},
},
});
Expand Down
59 changes: 59 additions & 0 deletions apps/web/src/components/usage/UsageLimitsPooled.browser.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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(
<UsageLimitsPooled presentations={presentations} now={Date.parse(checkedAt)} />,
);

// 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 {
Expand Down
24 changes: 15 additions & 9 deletions apps/web/src/components/usage/UsageLimitsPooled.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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 (
<span
role="img"
aria-label={gt("Account {initials}", { initials: accountInitials(email) })}
className="inline-flex size-4 shrink-0 items-center justify-center rounded-full text-3xs leading-none font-semibold"
aria-label={gt("Account {initials}", { initials })}
className="inline-flex h-4 min-w-4 shrink-0 items-center justify-center rounded-full px-0.5 text-3xs leading-none font-semibold"
style={{ backgroundColor: `oklch(0.85 0.08 ${hue})`, color: `oklch(0.35 0.1 ${hue})` }}
>
{accountInitials(email)}
{initials}
</span>
);
}
Expand Down Expand Up @@ -100,7 +105,7 @@ function AccountAvatar({
/>
);
}
return account.email ? <AccountChip email={account.email} /> : null;
return account.email ? <AccountChip email={account.email} name={account.displayName} /> : null;
}

function AccountName({
Expand All @@ -110,14 +115,15 @@ function AccountName({
readonly account: LimitAccount;
readonly className?: string;
}) {
if (account.displayName) return <span className={className}>{account.displayName}</span>;
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 (
<span className={cn("inline-flex min-w-0 items-center", className)}>
<AccountChip email={account.email} />
<AccountChip email={account.email} name={account.displayName} />
</span>
);
}
if (account.displayName) return <span className={className}>{account.displayName}</span>;
return (
<span className={className}>
{providerClients.get(account.driver)?.label ?? String(account.driver)}
Expand Down
2 changes: 2 additions & 0 deletions packages/contracts/src/providerUsageLimits.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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. */
Expand Down
2 changes: 2 additions & 0 deletions packages/contracts/src/settings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down
Loading
Loading