diff --git a/apps/mobile/src/features/threads/ComposerUsageLimits.tsx b/apps/mobile/src/features/threads/ComposerUsageLimits.tsx index 49f43cc2161b2..eddd018a2d81a 100644 --- a/apps/mobile/src/features/threads/ComposerUsageLimits.tsx +++ b/apps/mobile/src/features/threads/ComposerUsageLimits.tsx @@ -37,6 +37,18 @@ export function ComposerUsageLimits({ account.resetCreditInput ?? (account.instanceId ? { instanceId: account.instanceId } : undefined); const driverLabel = providerClients.get(account.driver)?.label ?? account.driver; + const statusSuffix = + account.status === "held" + ? " · Held" + : account.status === "signed-out" + ? " · Sign in" + : ""; + const instanceLabel = account.instanceId + ? account.displayName?.trim() || + (String(account.instanceId) !== String(account.driver) + ? account.instanceId + : driverLabel) + : account.label; return ( ); const { account, window } = member; + const segmentCaption = pooledSegmentCaption(account, accountName(account), inlineName); const timeLeft = paceRemainingPercent(window, now); const credits = account.limits.resetCredits?.availableCount ?? 0; const resetsIn = formatResetsIn(window, now)?.replace("resets in ", ""); @@ -264,14 +271,14 @@ function PoolWindowCard({ > {account.email ? : null} - {account.email && !(account.displayName && inlineName) ? null : ( + {segmentCaption ? ( - {accountName(account)} + {segmentCaption} - )} + ) : null} {remainingPercent(window)}% @@ -590,6 +597,9 @@ export function UsageLimitAccountScreen({ route }: AccountScreenProps) { {account.plan} ) : null} + {account.statusDetail ? ( + {account.statusDetail} + ) : null} {window.label} diff --git a/apps/mobile/src/features/usage/pooledSegmentCaption.test.ts b/apps/mobile/src/features/usage/pooledSegmentCaption.test.ts new file mode 100644 index 0000000000000..fb5e9163b372d --- /dev/null +++ b/apps/mobile/src/features/usage/pooledSegmentCaption.test.ts @@ -0,0 +1,32 @@ +import { describe, expect, it } from "@effect/vitest"; + +import { pooledSegmentCaption } from "./pooledSegmentCaption"; + +describe("pooledSegmentCaption", () => { + const held = { + email: "a@example.com", + displayName: null, + status: "held" as const, + }; + + it("keeps Held on a wide bar when the emailed name is hidden", () => { + expect(pooledSegmentCaption(held, "AE · Held", false)).toBe("Held"); + expect(pooledSegmentCaption({ ...held, status: "signed-out" }, "AE · Sign in", false)).toBe( + "Sign in", + ); + }); + + it("leaves an unnamed emailed seat as the chip", () => { + expect(pooledSegmentCaption({ ...held, status: null }, "AE", false)).toBeNull(); + }); + + it("shows the full name once the segment is wide enough", () => { + expect( + pooledSegmentCaption( + { ...held, displayName: "A Person · SuperGrok" }, + "A Person · SuperGrok · Held", + true, + ), + ).toBe("A Person · SuperGrok · Held"); + }); +}); diff --git a/apps/mobile/src/features/usage/pooledSegmentCaption.ts b/apps/mobile/src/features/usage/pooledSegmentCaption.ts new file mode 100644 index 0000000000000..1bb63dbf17a7b --- /dev/null +++ b/apps/mobile/src/features/usage/pooledSegmentCaption.ts @@ -0,0 +1,16 @@ +/** What a wide pooled segment may print beside its chip. */ +export function pooledSegmentCaption( + account: { + readonly email: string | undefined; + readonly displayName: string | null; + readonly status: "held" | "signed-out" | null; + }, + fullName: string, + showFullName: boolean, +): string | null { + const showName = !account.email || (!!account.displayName && showFullName); + if (showName) return fullName; + if (account.status === "held") return "Held"; + if (account.status === "signed-out") return "Sign in"; + return null; +} diff --git a/apps/server/src/usage/magpieQuotas.test.ts b/apps/server/src/usage/magpieQuotas.test.ts index b11ac499b1035..e0b6a47efb749 100644 --- a/apps/server/src/usage/magpieQuotas.test.ts +++ b/apps/server/src/usage/magpieQuotas.test.ts @@ -137,6 +137,8 @@ describe("magpieQuotasToAccounts", () => { "magpie-go:oc-billed", "magpie-go:oc-other", "claude:second@example.com", + "grok:jeffrey.smith@closura.ai", + "grok:kameron.smith@closura.ai", ]); const team = accounts[2]!; const billed = accounts[3]!; @@ -173,6 +175,129 @@ describe("magpieQuotasToAccounts", () => { "weekly", "monthly", ]); + // Both seats share the product name "Grok" and neither has an alias. + expect(grok.map((account) => account.displayName)).toEqual(["Jeffrey Smith", "Kameron Smith"]); + }); + + it("prefers an alias, splits a shared product name, and keeps held and lapsed seats", () => { + const labeled = magpieQuotasToAccounts( + [ + { + provider: "claude", + name: "Claude Code", + plan: "max", + user: "a@example.com", + alias: "Kameron · Claude work", + windows: [{ name: "5 hours", used: 0 }], + }, + { + provider: "claude", + name: "Claude Code", + plan: "max", + user: "bee.person@example.com", + alias: null, + windows: [{ name: "5 hours", used: 10 }], + }, + { + provider: "grok", + name: "Grok (SuperGrok)", + user: "jeffrey.smith@example.com", + alias: null, + windows: [{ name: "7 days", used: 65 }], + }, + { + provider: "grok", + name: "Grok (SuperGrok)", + user: "kameron.smith@example.com", + windows: [{ name: "7 days", used: 7 }], + }, + { + provider: "codex", + name: "Codex", + plan: "pro", + user: "a@example.com", + held: true, + until: "2026-12-02T00:00:00Z", + windows: [{ name: "7 days", used: 100 }], + }, + { + provider: "claude", + user: "old@example.com", + lapsed: "Claude Code is no longer signed in", + windows: [{ name: "7 days", used: 100 }], + }, + ], + checkedAt, + ); + expect(labeled.find((account) => account.email === "a@example.com")?.displayName).toBe( + "Kameron · Claude work", + ); + // The second Claude seat shares the product name and has no alias. + expect(labeled.find((account) => account.email === "bee.person@example.com")?.displayName).toBe( + "Bee Person", + ); + expect( + labeled.filter((account) => account.driver === "grok").map((account) => account.displayName), + ).toEqual(["Jeffrey Smith · SuperGrok", "Kameron Smith · SuperGrok"]); + const held = labeled.find((account) => account.driver === "codex"); + expect(held?.status).toBe("held"); + expect(held?.statusDetail).toBe("Held until 2026-12-02."); + const lapsed = labeled.find((account) => account.email === "old@example.com"); + expect(lapsed?.status).toBe("signed-out"); + expect(lapsed?.statusDetail).toBe("Claude Code is no longer signed in."); + expect(lapsed?.usageLimits.windows).toHaveLength(1); + }); + + it("leaves one emailed seat unnamed, including a duplicate row, and keeps a colliding alias", () => { + const lone = magpieQuotasToAccounts( + [ + { + provider: "grok", + name: "Grok (SuperGrok)", + user: "only@example.com", + alias: null, + held: null, + lapsed: null, + windows: [{ name: "7 days", used: 10 }], + }, + { + provider: "grok", + name: "Grok (SuperGrok)", + user: "only@example.com", + windows: [{ name: "7 days", used: 12 }], + }, + { + provider: "claude", + name: "Claude Code", + user: "a@example.com", + alias: "Bee Person", + windows: [{ name: "5 hours", used: 1 }], + }, + { + provider: "claude", + name: "Claude Code", + user: "bee.person@example.com", + alias: null, + windows: [{ name: "5 hours", used: 2 }], + }, + { + provider: "claude", + name: "Claude Code", + user: "c@example.com", + windows: [{ name: "5 hours", used: 3 }], + }, + ], + checkedAt, + ); + const grok = lone.filter((account) => account.driver === "grok"); + expect(grok.map((account) => account.email)).toEqual(["only@example.com"]); + expect(grok[0]?.displayName).toBeUndefined(); + expect(lone.find((account) => account.email === "a@example.com")?.displayName).toBe( + "Bee Person", + ); + expect(lone.find((account) => account.email === "bee.person@example.com")?.displayName).toBe( + "Bee Person · example", + ); }); }); @@ -327,6 +452,45 @@ describe("makeMagpieApi", () => { }), ); + it.effect("accepts null alias, held, and lapsed on a quota row", () => + Effect.gen(function* () { + const http = HttpClient.make((request) => + Effect.sync(() => + HttpClientResponse.fromWeb( + request, + Response.json({ + object: "list", + data: [ + { + provider: "grok", + name: "Grok (SuperGrok)", + user: "only@example.com", + alias: null, + held: null, + until: null, + lapsed: null, + windows: [{ name: "7 days", used: 4, resetsAt: null }], + }, + ], + }), + ), + ), + ); + const result = yield* makeMagpieApi.pipe( + Effect.flatMap((api) => + api.readAccounts({ url: "http://127.0.0.1:3425", managementKey: "" }), + ), + Effect.result, + Effect.provideService(HttpClient.HttpClient, http), + ); + expect(result._tag).toBe("Success"); + if (result._tag !== "Success") return; + expect(result.success.map((account) => account.id)).toEqual(["grok:only@example.com"]); + expect(result.success[0]?.displayName).toBeUndefined(); + expect(result.success[0]?.status).toBeUndefined(); + }), + ); + it.effect("sends a configured gateway key and explains a refusal", () => Effect.gen(function* () { const { result, seen } = yield* run("gateway-key", 401); diff --git a/apps/server/src/usage/magpieQuotas.ts b/apps/server/src/usage/magpieQuotas.ts index 322bbaa1cfe8e..3a1cd1f50644d 100644 --- a/apps/server/src/usage/magpieQuotas.ts +++ b/apps/server/src/usage/magpieQuotas.ts @@ -40,6 +40,11 @@ const QuotaEntry = Schema.Struct({ kind: Schema.optional(Schema.String), plan: Schema.optional(Schema.String), user: Schema.optional(Schema.String), + // Null is a present-but-empty alias. Omitting the key and rejecting null would drop the whole read. + alias: Schema.optional(Schema.NullOr(Schema.String)), + held: Schema.optional(Schema.NullOr(Schema.Boolean)), + until: Schema.optional(Schema.NullOr(Schema.String)), + lapsed: Schema.optional(Schema.NullOr(Schema.Union([Schema.Boolean, Schema.String]))), windows: Schema.optional(Schema.Array(QuotaWindow)), readAt: Schema.optional(Schema.String), error: Schema.optional(Schema.String), @@ -95,9 +100,7 @@ function magpieWindow( const [span = window.name, ...scopeParts] = window.name.split("·").map((part) => part.trim()); const scope = scopeParts.join(" · "); const match = /^(?:(\d+(?:\.\d+)?)\s+)?(minute|hour|day|week|month)s?$/i.exec(span); - const mins = match - ? Number(match[1] ?? 1) * MINUTES[match[2]!.toLowerCase()]! - : undefined; + const mins = match ? Number(match[1] ?? 1) * MINUTES[match[2]!.toLowerCase()]! : undefined; const kind: ServerProviderUsageWindow["kind"] = mins === undefined ? "other" @@ -169,13 +172,93 @@ function shortReason(error: string): string { return sentence.endsWith(".") ? sentence : `${sentence}.`; } +function trimmed(value: string | null | undefined): string | undefined { + const text = value?.trim(); + return text ? text : undefined; +} + +function emailAddress(user: string): string | undefined { + const head = user.split(" · ")[0]?.trim() ?? ""; + return /^[^\s@]+@[^\s@]+$/.test(head) ? head : undefined; +} + +function personFromEmail(email: string): string { + const local = email.split("@")[0] ?? email; + const parts = local.split(/[._+-]+/).filter(Boolean); + if (parts.length === 0) return local; + return parts.map((part) => part.charAt(0).toUpperCase() + part.slice(1).toLowerCase()).join(" "); +} + +/** + * Seats that share one product name (both Grok rows are "Grok (SuperGrok)", + * and grok has no native alias) need a label that is not that shared name. + * A real alias always wins. A unique emailed seat stays unnamed so the chip + * can stand in for the address. + */ +function displayNamesFor( + entries: ReadonlyArray, +): ReadonlyArray { + const draft = entries.map((entry) => { + const alias = trimmed(entry.alias); + if (alias) return { name: alias, fromAlias: true }; + const user = trimmed(entry.user) ?? ""; + const email = emailAddress(user); + if (!email) return { name: undefined, fromAlias: false }; + const nameKey = (entry.name ?? "").trim().toLowerCase(); + const sharedEmails = new Set(); + for (const other of entries) { + if (other.provider !== entry.provider) continue; + if ((other.name ?? "").trim().toLowerCase() !== nameKey) continue; + const otherEmail = emailAddress(trimmed(other.user) ?? ""); + if (otherEmail) sharedEmails.add(otherEmail.toLowerCase()); + } + // A repeated payload for one address is still one seat. + if (sharedEmails.size < 2) return { name: undefined, fromAlias: false }; + const seat = user.includes(" · ") ? user.split(" · ").slice(1).join(" · ").trim() : ""; + const person = personFromEmail(email); + const who = seat ? `${person} · ${seat}` : person; + const product = trimmed(entry.name?.match(/\(([^)]+)\)/)?.[1]); + return { name: product ? `${who} · ${product}` : who, fromAlias: false }; + }); + const counts = new Map(); + for (const item of draft) { + if (item.name) counts.set(item.name, (counts.get(item.name) ?? 0) + 1); + } + return draft.map((item, index) => { + // An alias is the operator's label. Only a derived name gets a domain suffix. + if (!item.name || item.fromAlias || (counts.get(item.name) ?? 0) < 2) return item.name; + const email = emailAddress(trimmed(entries[index]?.user) ?? ""); + const domain = email?.split("@")[1]?.split(".")[0]; + return domain ? `${item.name} · ${domain}` : item.name; + }); +} + +function accountFlags(entry: MagpieQuotaEntry): { + readonly status?: "held" | "signed-out"; + readonly statusDetail?: string; +} { + const lapsed = entry.lapsed; + if (typeof lapsed === "string" && lapsed.trim()) { + return { status: "signed-out", statusDetail: shortReason(lapsed) }; + } + if (lapsed === true) { + return { status: "signed-out", statusDetail: "Sign-in required." }; + } + if (entry.held === true) { + const day = /^\d{4}-\d{2}-\d{2}/.exec(trimmed(entry.until) ?? "")?.[0]; + return { status: "held", statusDetail: day ? `Held until ${day}.` : "Held." }; + } + return {}; +} + export function magpieQuotasToAccounts( entries: ReadonlyArray, checkedAt: string, ): ReadonlyArray { const accounts: UsageLimitSourceAccount[] = []; const seen = new Set(); - for (const entry of entries) { + const names = displayNamesFor(entries); + for (const [index, entry] of entries.entries()) { const driver = driverFor(entry.provider); if (!driver) continue; if (driver === "opencode" && entry.error && isDeadGoSubscription(entry.error)) { @@ -194,12 +277,16 @@ export function magpieQuotasToAccounts( message: shortReason(entry.error), }) : makeUsageLimits({ checkedAt: entry.readAt ?? checkedAt, windows }); + const displayName = names[index]; + const flags = accountFlags(entry); accounts.push({ id, driver, // Only a real address is an email; Go keys carry a key name instead. ...(/^[^\s@]+@[^\s@]+$/.test(user.split(" · ")[0]!) ? { email: user } : {}), ...(plan ? { plan } : {}), + ...(displayName ? { displayName } : {}), + ...flags, usageLimits, }); } diff --git a/apps/web/src/components/chat/ComposerUsageLimits.tsx b/apps/web/src/components/chat/ComposerUsageLimits.tsx index b46614a8b418d..76da7b3959d72 100644 --- a/apps/web/src/components/chat/ComposerUsageLimits.tsx +++ b/apps/web/src/components/chat/ComposerUsageLimits.tsx @@ -40,6 +40,11 @@ function AccountSummary({ account }: { readonly account: UsageLimitsReport["acco label )} {account.plan ? ` · ${account.plan}` : null} + {account.status === "held" + ? " · Held" + : account.status === "signed-out" + ? " · Sign in" + : null} ); } diff --git a/apps/web/src/components/usage/UsageLimitsPooled.browser.test.tsx b/apps/web/src/components/usage/UsageLimitsPooled.browser.test.tsx index 3c2cfcc40ed89..fc761b9cfcf45 100644 --- a/apps/web/src/components/usage/UsageLimitsPooled.browser.test.tsx +++ b/apps/web/src/components/usage/UsageLimitsPooled.browser.test.tsx @@ -2,6 +2,7 @@ import { EnvironmentId, ProviderDriverKind, ProviderInstanceId, + UsageLimitSourceId, type ServerProvider, } from "@t3tools/contracts"; import { CHATGPT_USAGE_URL } from "@t3tools/shared/usageLimits"; @@ -155,3 +156,87 @@ describe("UsageLimitsPooled quiet states", () => { await expect.element(screen.getByText("(primary-r720)")).toBeVisible(); }); }); + +describe("UsageLimitsPooled Grok accounts", () => { + it("shows the emergency route and the other SuperGrok seat as named rows", async () => { + const grok = ProviderDriverKind.make("grok"); + const limits = (usedPercent: number) => ({ + checkedAt, + windows: [ + { + id: "subscription", + kind: "weekly" as const, + label: "Weekly", + usedPercent, + windowDurationMins: 7 * 24 * 60, + resetsAt: "2026-11-27T00:00:00.000Z", + }, + ], + }); + const emergency: ServerProvider = { + instanceId: ProviderInstanceId.make("grok-direct"), + driver: grok, + displayName: "Grok · Emergency (direct)", + enabled: true, + installed: true, + version: "1.0.0", + status: "ready", + auth: { status: "authenticated", email: "a@example.com" }, + checkedAt, + models: [], + slashCommands: [], + skills: [], + usageLimits: limits(7), + }; + const presentations = new Map([ + [ + EnvironmentId.make("desk"), + { + entry: { target: { label: "Desk" } }, + serverConfig: { + providers: [emergency], + usageLimitSources: [ + { + id: UsageLimitSourceId.make("magpie"), + kind: "magpie" as const, + label: "Magpie", + checkedAt, + accounts: [ + { + id: "grok:a@example.com", + driver: grok, + email: "a@example.com", + displayName: "A Person · SuperGrok", + plan: "SuperGrok", + status: "held" as const, + statusDetail: "Held.", + usageLimits: limits(7), + }, + { + id: "grok:b@example.com", + driver: grok, + email: "b@example.com", + displayName: "B Person · SuperGrok", + plan: "SuperGrok", + usageLimits: limits(65), + }, + ], + }, + ], + }, + }, + ], + ]); + await using screen = await render( + , + ); + + await expect.element(screen.getByText("Grok · Emergency (direct)")).toBeVisible(); + await expect.element(screen.getByText("B Person · SuperGrok")).toBeVisible(); + await expect.element(screen.getByText("Held")).toBeVisible(); + expect(screen.container.textContent).not.toContain("A Person · SuperGrok"); + }); +}); diff --git a/apps/web/src/components/usage/UsageLimitsPooled.tsx b/apps/web/src/components/usage/UsageLimitsPooled.tsx index a436eedf1cda6..0cc3b5f8e85ea 100644 --- a/apps/web/src/components/usage/UsageLimitsPooled.tsx +++ b/apps/web/src/components/usage/UsageLimitsPooled.tsx @@ -110,6 +110,24 @@ function AccountAvatar({ return account.email ? : null; } +function accountAccessibleName(account: LimitAccount): string { + const name = + account.displayName ?? + (account.email ? accountInitials(account.email) : String(account.driver)); + if (account.status === "held") return `${name}, held`; + if (account.status === "signed-out") return `${name}, sign-in required`; + return name; +} + +function AccountStatus({ status }: { readonly status: LimitAccount["status"] }) { + if (!status) return null; + return ( + + {status === "held" ? "Held" : "Sign in"} + + ); +} + function AccountName({ account, className, @@ -117,17 +135,29 @@ function AccountName({ readonly account: LimitAccount; readonly className?: string; }) { - if (account.displayName) return {account.displayName}; + const status = ; + if (account.displayName) { + return ( + + {account.displayName} + {status} + + ); + } if (account.email) { return ( - + + {status} ); } return ( - - {providerClients.get(account.driver)?.label ?? String(account.driver)} + + + {providerClients.get(account.driver)?.label ?? String(account.driver)} + + {status} ); } @@ -173,10 +203,16 @@ function SegmentPopover({
- - {account.displayName ?? providerClients.get(account.driver)?.label ?? account.driver} + + + {account.displayName ?? providerClients.get(account.driver)?.label ?? account.driver} + + + {account.statusDetail ? ( + {account.statusDetail} + ) : null} {account.email ? ( } @@ -413,13 +449,7 @@ function SegmentTriggers({ {index}
- {showAccountName ? ( - - ) : null} - {/* A single-account bar repeats the headline percentage. */} + {/* Names live in the legend. A half-width segment truncates them into the reset chip. */} {showAccountName ? ( {remaining}% @@ -445,7 +475,13 @@ function SegmentTriggers({ ) : null}
- + ); } @@ -455,11 +491,13 @@ function LegendRow({ color, now, index, + showAccountName, }: { readonly payload: SegmentPayload; readonly color: string; readonly now: number; readonly index: number; + readonly showAccountName: boolean; }) { const popover = use(SegmentPopoverContext) ?? undefined; const { account, window } = payload; @@ -472,7 +510,7 @@ function LegendRow({ payload={payload} style={{ gridColumn: "1 / -1", gridRow: index + 1 }} render={