Skip to content

Commit 077eb5b

Browse files
committed
fix(usage): reconcile legacy reports and distinguish workspaces
1 parent 58a911b commit 077eb5b

4 files changed

Lines changed: 286 additions & 9 deletions

File tree

‎apps/web/src/components/usage/UsageLimitsPooled.tsx‎

Lines changed: 32 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -121,6 +121,35 @@ function AccountName({
121121
);
122122
}
123123

124+
/** A visible label key; initials chips can collide even when the emails differ. */
125+
function accountNameKey(account: LimitAccount): string {
126+
return (
127+
account.displayName ?? (account.email ? accountInitials(account.email) : String(account.driver))
128+
);
129+
}
130+
131+
/** Preserve distinct labels and allocate collision-free suffixes in stable key order. */
132+
function disambiguateAccountNames(accounts: readonly LimitAccount[]): readonly LimitAccount[] {
133+
const names = accounts.map(accountNameKey);
134+
const used = new Set(names);
135+
const labels = new Map<string, string>();
136+
accounts
137+
.toSorted((left, right) => left.key.localeCompare(right.key))
138+
.forEach((account, index) => {
139+
const name = accountNameKey(account);
140+
if (names.indexOf(name) === names.lastIndexOf(name)) return;
141+
let suffix = index + 1;
142+
let label = `${account.displayName ?? "Account"} ${suffix}`;
143+
while (used.has(label)) label = `${account.displayName ?? "Account"} ${++suffix}`;
144+
used.add(label);
145+
labels.set(account.key, label);
146+
});
147+
return accounts.map((account) => {
148+
const displayName = labels.get(account.key);
149+
return displayName ? { ...account, displayName } : account;
150+
});
151+
}
152+
124153
function Row({ label, children }: { readonly label: string; readonly children: ReactNode }) {
125154
return (
126155
<div className="grid grid-cols-[4.5rem_minmax(0,1fr)] gap-x-3">
@@ -543,7 +572,9 @@ function PoolSection({ pool, now }: { readonly pool: LimitPool; readonly now: nu
543572
// Codex workspaces can share an email but have independent subscription quotas.
544573
const separateAccounts = pool.driver === "codex" && pool.accounts.length > 1;
545574
const windows = separateAccounts
546-
? pool.accounts.flatMap((account) => displayLimitWindows(collectLimitPools([account], now)[0]!))
575+
? disambiguateAccountNames(pool.accounts).flatMap((account) =>
576+
displayLimitWindows(collectLimitPools([account], now)[0]!),
577+
)
547578
: displayLimitWindows(pool);
548579
return (
549580
<section className="flex flex-col gap-3">

‎apps/web/src/components/usage/UsagePage.refresh.test.tsx‎

Lines changed: 65 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -180,7 +180,13 @@ it.each([0, 1])(
180180
},
181181
);
182182

183-
it.each(["codex", "claudeAgent", "cursor"])("shows account quotas for %s", async (driver) => {
183+
it.each([
184+
["codex", "named"],
185+
["codex", "unnamed"],
186+
["codex", "duplicate"],
187+
["claudeAgent", "named"],
188+
["cursor", "named"],
189+
])("shows account quotas for %s with %s labels", async (driver, labels) => {
184190
const [id, presentation] = [...state.presentations][0]!;
185191
const provider = presentation.serverConfig.providers[0];
186192
state.presentations = new Map([
@@ -197,7 +203,8 @@ it.each(["codex", "claudeAgent", "cursor"])("shows account quotas for %s", async
197203
...provider,
198204
driver,
199205
instanceId: ProviderInstanceId.make(accountId),
200-
displayName,
206+
displayName:
207+
labels === "unnamed" ? undefined : labels === "duplicate" ? "Codex" : displayName,
201208
auth: { status: "authenticated", email: "[email protected]" },
202209
usageLimits: {
203210
...provider.usageLimits,
@@ -219,14 +226,68 @@ it.each(["codex", "claudeAgent", "cursor"])("shows account quotas for %s", async
219226
)
220227
.map((node) => node.children.join(""))
221228
.join("\n");
222-
expect(text).toContain("Personal");
223-
expect(text).toContain("Corebio");
229+
if (labels === "named") {
230+
expect(text).toContain("Personal");
231+
expect(text).toContain("Corebio");
232+
} else {
233+
const name = labels === "duplicate" ? "Codex" : "Account";
234+
expect(text).toContain(`${name} 1`);
235+
expect(text).toContain(`${name} 2`);
236+
}
224237
expect(text).toContain("67%");
225238
expect(text).toContain("91%");
226239
if (driver === "codex") expect(text).not.toContain("79%");
227240
else expect(text).toContain("79%");
228241
});
229242

243+
it.each([
244+
{
245+
names: [undefined, undefined, undefined, undefined],
246+
expected: ["Account 1", "Account 2", "Account 3", "Account 4"],
247+
},
248+
{ names: ["Codex", "Codex", "Codex 1"], expected: ["Codex 2", "Codex 3", "Codex 1"] },
249+
])("keeps generated quota labels unique across the pool: $names", async ({ names, expected }) => {
250+
const [id, presentation] = [...state.presentations][0]!;
251+
const provider = presentation.serverConfig.providers[0];
252+
const providers = names.map((displayName, index) => ({
253+
...provider,
254+
instanceId: ProviderInstanceId.make(`account-${index}`),
255+
displayName,
256+
auth: { status: "authenticated", email: `${index < 2 ? "a" : "b"}@example.com` },
257+
usageLimits: {
258+
...provider.usageLimits,
259+
accountId: `workspace-${index}`,
260+
windows: [{ ...provider.usageLimits.windows[0], usedPercent: (index + 1) * 10 }],
261+
},
262+
}));
263+
for (const [position, ordered] of [providers, providers.toReversed()].entries()) {
264+
state.presentations = new Map([
265+
[
266+
id,
267+
{
268+
...presentation,
269+
serverConfig: { ...presentation.serverConfig, providers: ordered },
270+
},
271+
],
272+
]);
273+
await act(() => {
274+
if (position === 0) renderer = create(<UsagePage />);
275+
else renderer.update(<UsagePage />);
276+
});
277+
const text = renderer.root
278+
.findAll(
279+
(node) =>
280+
typeof node.type === "string" &&
281+
node.children.every((child) => typeof child === "string"),
282+
)
283+
.map((node) => node.children.join(""))
284+
.join("\n");
285+
expected.forEach((label, index) => {
286+
expect(text).toContain(`${label}\n· Session\n${100 - (index + 1) * 10}%`);
287+
});
288+
}
289+
});
290+
230291
it("uses the current time when returning to limits from tokens", async () => {
231292
await act(() => {
232293
renderer = create(<UsagePage />);

‎packages/shared/src/usageLimits.test.ts‎

Lines changed: 139 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -224,6 +224,145 @@ describe("pools", () => {
224224
expect(collectLimitAccounts(input)[0]?.environments).toHaveLength(2);
225225
});
226226

227+
it.each([true, false])(
228+
"reconciles a unique legacy report with an account ID (native ID: %s)",
229+
(nativeId) => {
230+
const native = provider({
231+
auth: { status: "authenticated", email: "[email protected]" },
232+
usageLimits: {
233+
checkedAt,
234+
...(nativeId ? { accountId: "workspace" } : {}),
235+
windows: [window],
236+
},
237+
});
238+
const hub = {
239+
...source,
240+
accounts: [
241+
{
242+
id: "hub-account",
243+
driver: native.driver,
244+
245+
usageLimits: {
246+
checkedAt,
247+
...(!nativeId ? { accountId: "workspace" } : {}),
248+
windows: [window],
249+
resetCredits: { availableCount: 2, nextCreditId: "credit" },
250+
},
251+
},
252+
],
253+
};
254+
const input = new Map([
255+
[
256+
EnvironmentId.make("env-a"),
257+
{
258+
...laptop,
259+
serverConfig: { providers: [native], usageLimitSources: [hub] },
260+
},
261+
],
262+
]);
263+
const accounts = collectLimitAccounts(input);
264+
expect(accounts).toHaveLength(1);
265+
expect(accounts[0]?.limits.resetCredits?.availableCount).toBe(2);
266+
expect(accounts[0]?.redeem?.input).toEqual({
267+
sourceId: "hub",
268+
accountId: "hub-account",
269+
creditId: "credit",
270+
});
271+
const report = collectProviderUsageLimits(native.instanceId, [native], [hub], now);
272+
expect(report?.accounts).toHaveLength(1);
273+
expect(report?.accounts[0]?.limits.resetCredits?.availableCount).toBe(2);
274+
expect(report?.accounts[0]?.resetCreditInput).toEqual(accounts[0]?.redeem?.input);
275+
},
276+
);
277+
278+
it("keeps hub workspace quotas separate when environments reuse the same source account name", () => {
279+
const input = new Map(
280+
[33, 9].map(
281+
(usedPercent, index) =>
282+
[
283+
EnvironmentId.make(`env-${index}`),
284+
{
285+
...laptop,
286+
serverConfig: {
287+
providers: [],
288+
usageLimitSources: [
289+
{
290+
...source,
291+
accounts: [
292+
{
293+
id: "same-account.json",
294+
driver: ProviderDriverKind.make("codex"),
295+
296+
usageLimits: {
297+
checkedAt,
298+
accountId: `workspace-${index}`,
299+
windows: [{ ...window, usedPercent }],
300+
},
301+
},
302+
],
303+
},
304+
],
305+
},
306+
},
307+
] as const,
308+
),
309+
);
310+
const accounts = collectLimitAccounts(input);
311+
expect(accounts).toHaveLength(2);
312+
expect(
313+
collectLimitPools(accounts, now)[0]
314+
?.windows[0]?.columns.map((column) => column.window!.usedPercent)
315+
.toSorted((left, right) => left - right),
316+
).toEqual([9, 33]);
317+
});
318+
319+
it("does not assign an ambiguous legacy report to either workspace sharing its email", () => {
320+
const natives = ["personal", "business"].map((accountId) =>
321+
provider({
322+
instanceId: ProviderInstanceId.make(accountId),
323+
auth: { status: "authenticated", email: "[email protected]" },
324+
usageLimits: { checkedAt, accountId, windows: [window] },
325+
}),
326+
);
327+
const hub = {
328+
...source,
329+
accounts: [
330+
{
331+
id: "legacy",
332+
driver: natives[0]!.driver,
333+
334+
usageLimits: {
335+
checkedAt,
336+
windows: [window],
337+
resetCredits: { availableCount: 2, nextCreditId: "credit" },
338+
},
339+
},
340+
],
341+
};
342+
const accounts = collectLimitAccounts(
343+
new Map([
344+
[
345+
EnvironmentId.make("env-a"),
346+
{
347+
...laptop,
348+
serverConfig: { providers: natives, usageLimitSources: [hub] },
349+
},
350+
],
351+
]),
352+
);
353+
expect(accounts).toHaveLength(3);
354+
expect(accounts.slice(0, 2).map((account) => account.limits.resetCredits)).toEqual([
355+
undefined,
356+
undefined,
357+
]);
358+
const report = collectProviderUsageLimits(natives[0]!.instanceId, natives, [hub], now);
359+
expect(report?.accounts).toHaveLength(3);
360+
expect(report?.accounts.slice(0, 2).map((account) => account.resetCreditInput)).toEqual([
361+
{ instanceId: "personal" },
362+
{ instanceId: "business" },
363+
]);
364+
});
365+
227366
it("merges one account reported natively on two environments and by a hub into one entry", () => {
228367
const native = provider({
229368
driver: claude,

‎packages/shared/src/usageLimits.ts‎

Lines changed: 50 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -112,20 +112,56 @@ export function collectExternalUsageLinks(presentations: LimitPresentations) {
112112
return [...links.values()];
113113
}
114114

115-
/** Workspace identity takes precedence: one email can own several separate quotas. */
116-
function accountKey(
115+
function fallbackAccountKey(
117116
driver: ServerProvider["driver"],
118117
email: string | undefined,
119118
limits?: ServerProviderUsageLimits,
120119
): string | null {
121-
if (limits?.accountId) return `${driver}:account:${limits.accountId}`;
122120
const normalizedEmail = email?.trim().toLowerCase();
123121
if (normalizedEmail) return `${driver}:${normalizedEmail}`;
124122
return limits?.credentialFingerprint
125123
? `${driver}:credential:${limits.credentialFingerprint}`
126124
: null;
127125
}
128126

127+
/** Resolve legacy reports only when their fallback identifies one explicit account. */
128+
function accountKeyResolver(
129+
providers: readonly ServerProvider[],
130+
sources: UsageLimitSourceSnapshots,
131+
) {
132+
const reports = [
133+
...providersWithLimits(providers).map((provider) => ({
134+
driver: provider.driver,
135+
email: provider.auth.email,
136+
limits: provider.usageLimits,
137+
})),
138+
...sources.flatMap((source) =>
139+
source.accounts.map((account) => ({
140+
driver: account.driver,
141+
email: account.email,
142+
limits: account.usageLimits,
143+
})),
144+
),
145+
];
146+
const aliases = new Map<string, string | null>();
147+
for (const { driver, email, limits } of reports) {
148+
if (!limits?.accountId || limitsNotice(limits) !== null) continue;
149+
const fallback = fallbackAccountKey(driver, email, limits);
150+
if (!fallback) continue;
151+
const key = `${driver}:account:${limits.accountId}`;
152+
aliases.set(fallback, aliases.has(fallback) && aliases.get(fallback) !== key ? null : key);
153+
}
154+
return (
155+
driver: ServerProvider["driver"],
156+
email: string | undefined,
157+
limits?: ServerProviderUsageLimits,
158+
) => {
159+
if (limits?.accountId) return `${driver}:account:${limits.accountId}`;
160+
const fallback = fallbackAccountKey(driver, email, limits);
161+
return fallback ? (aliases.get(fallback) ?? fallback) : null;
162+
};
163+
}
164+
129165
/**
130166
* One subscription account as the pooled views see it, whichever way it was
131167
* reported. Matching account ids, or emails and credentials when no id is
@@ -161,6 +197,14 @@ export interface LimitAccount {
161197
* native instances supply names and environment labels.
162198
*/
163199
export function collectLimitAccounts(presentations: LimitPresentations): readonly LimitAccount[] {
200+
const accountKey = accountKeyResolver(
201+
[...presentations.values()].flatMap(
202+
(presentation) => presentation.serverConfig?.providers ?? [],
203+
),
204+
[...presentations.values()].flatMap(
205+
(presentation) => presentation.serverConfig?.usageLimitSources ?? [],
206+
),
207+
);
164208
const accounts = new Map<string, LimitAccount>();
165209
const creditSources = new Map<string, LimitAccount>();
166210
const hubRedeems = new Map<string, LimitAccount>();
@@ -188,7 +232,7 @@ export function collectLimitAccounts(presentations: LimitPresentations): readonl
188232
}
189233
const previous = accounts.get(key);
190234
if (!previous) {
191-
accounts.set(key, next);
235+
accounts.set(key, { ...next, key: next.limits.accountId ? key : next.key });
192236
return;
193237
}
194238
const fresher = Date.parse(next.limits.checkedAt) > Date.parse(previous.limits.checkedAt);
@@ -206,6 +250,7 @@ export function collectLimitAccounts(presentations: LimitPresentations): readonl
206250
const creditSource = creditSources.get(key);
207251
accounts.set(key, {
208252
...previous,
253+
key: next.limits.accountId ? key : previous.key,
209254
displayName: previous.displayName ?? next.displayName,
210255
plan: previous.plan ?? next.plan,
211256
accentColor: previous.accentColor ?? next.accentColor,
@@ -634,6 +679,7 @@ export function collectProviderUsageLimits(
634679
const native = providersWithLimits(providers).filter(
635680
(provider) => provider.driver === selected.driver,
636681
);
682+
const accountKey = accountKeyResolver(native, sources);
637683
const nativeAccounts = new Set(
638684
native.flatMap((provider) => {
639685
const key = accountKey(provider.driver, provider.auth.email, provider.usageLimits);

0 commit comments

Comments
 (0)