Skip to content

Commit 94e40ad

Browse files
committed
fix(codex): fence stale main usage responses
1 parent ed7147f commit 94e40ad

2 files changed

Lines changed: 76 additions & 5 deletions

File tree

‎src/codex/auth-api.ts‎

Lines changed: 30 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ import {
1010
TokenRefreshError,
1111
} from "./account-store";
1212
import { deleteCodexAccount, reconcileMainCodexAccountRuntimeState } from "./account-lifecycle";
13-
import { checkAccountIdCollision, readCodexTokens } from "./auth-collision";
13+
import { checkAccountIdCollision, getMainChatgptAccountId, readCodexTokens } from "./auth-collision";
1414
export { checkAccountIdCollision, getMainChatgptAccountId } from "./auth-collision";
1515
export { clearAccountNeedsReauth, isAccountNeedsReauth, markAccountNeedsReauth } from "./account-runtime-state";
1616
import { clearAccountNeedsReauth, isAccountNeedsReauth, markAccountNeedsReauth } from "./account-runtime-state";
@@ -252,12 +252,31 @@ async function isTerminalMainAuthResponse(resp: Response): Promise<boolean> {
252252
}
253253

254254
export async function fetchMainAccountInfo(forceRefresh = false): Promise<MainAccountInfo> {
255+
return fetchMainAccountInfoAttempt(forceRefresh, 1);
256+
}
257+
258+
const EMPTY_MAIN_ACCOUNT_INFO: MainAccountInfo = { email: null, plan: null, quota: null };
259+
260+
async function retryMainAccountInfoIfIdentityChanged(
261+
requestAccountId: string | null,
262+
retriesRemaining: number,
263+
): Promise<MainAccountInfo | null> {
264+
if (getMainChatgptAccountId() === requestAccountId) return null;
265+
reconcileMainCodexAccountRuntimeState();
266+
return retriesRemaining > 0
267+
? fetchMainAccountInfoAttempt(true, retriesRemaining - 1)
268+
: EMPTY_MAIN_ACCOUNT_INFO;
269+
}
270+
271+
async function fetchMainAccountInfoAttempt(forceRefresh: boolean, retriesRemaining: number): Promise<MainAccountInfo> {
272+
reconcileMainCodexAccountRuntimeState();
255273
const tokens = readCodexTokens();
256274
if (!tokens) {
257275
clearMainAccountInfoCache();
258276
markAccountNeedsReauth(MAIN_CODEX_ACCOUNT_ID);
259-
return { email: null, plan: null, quota: null };
277+
return EMPTY_MAIN_ACCOUNT_INFO;
260278
}
279+
const requestAccountId = extractAccountId(tokens.id_token, tokens.access_token) ?? (tokens.account_id || null);
261280
const cached = getMainAccountInfoCache();
262281
if (!forceRefresh && cached && Date.now() - cached.ts < MAIN_CACHE_TTL) {
263282
return cached;
@@ -268,13 +287,18 @@ export async function fetchMainAccountInfo(forceRefresh = false): Promise<MainAc
268287
signal: AbortSignal.timeout(8000),
269288
});
270289
if (!resp.ok) {
271-
if (await isTerminalMainAuthResponse(resp)) {
290+
const terminalAuthFailure = await isTerminalMainAuthResponse(resp);
291+
const retried = await retryMainAccountInfoIfIdentityChanged(requestAccountId, retriesRemaining);
292+
if (retried) return retried;
293+
if (terminalAuthFailure) {
272294
clearMainAccountInfoCache();
273295
markAccountNeedsReauth(MAIN_CODEX_ACCOUNT_ID);
274296
}
275-
return { email: null, plan: null, quota: null };
297+
return EMPTY_MAIN_ACCOUNT_INFO;
276298
}
277299
const data = (await resp.json()) as WhamUsageResponse;
300+
const retried = await retryMainAccountInfoIfIdentityChanged(requestAccountId, retriesRemaining);
301+
if (retried) return retried;
278302
const result = {
279303
email: data.email ?? null,
280304
plan: data.plan_type ?? null,
@@ -298,7 +322,8 @@ export async function fetchMainAccountInfo(forceRefresh = false): Promise<MainAc
298322
}
299323
return result;
300324
} catch {
301-
return { email: null, plan: null, quota: null };
325+
const retried = await retryMainAccountInfoIfIdentityChanged(requestAccountId, retriesRemaining);
326+
return retried ?? EMPTY_MAIN_ACCOUNT_INFO;
302327
}
303328
}
304329

‎tests/codex-main-rotation.test.ts‎

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -263,6 +263,52 @@ describe("main account rotation (Option A)", () => {
263263
}
264264
});
265265

266+
test("discards an in-flight usage response after the main identity changes", async () => {
267+
expect(reconcileMainCodexAccountRuntimeState()).toBe(false);
268+
const originalFetch = globalThis.fetch;
269+
let resolveFirstUsage!: (response: Response) => void;
270+
const requestedAccountIds: string[] = [];
271+
globalThis.fetch = (async (input, init) => {
272+
if (!String(input).includes("/backend-api/wham/usage")) return originalFetch(input, init);
273+
requestedAccountIds.push(new Headers(init?.headers).get("ChatGPT-Account-Id") ?? "");
274+
if (requestedAccountIds.length === 1) {
275+
return new Promise<Response>(resolve => { resolveFirstUsage = resolve; });
276+
}
277+
return new Response(JSON.stringify({
278+
279+
plan_type: "pro",
280+
rate_limit: { primary_window: { used_percent: 12, reset_at: 1_789_000_000 } },
281+
}), { status: 200 });
282+
}) as typeof fetch;
283+
try {
284+
const infoPromise = fetchMainAccountInfo(true);
285+
expect(requestedAccountIds).toEqual(["main_acct"]);
286+
287+
writeFileSync(
288+
join(CODEX_DIR, "auth.json"),
289+
JSON.stringify({ tokens: { access_token: "replacement_access", account_id: "replacement_acct" } }),
290+
);
291+
expect(reconcileMainCodexAccountRuntimeState()).toBe(true);
292+
resolveFirstUsage(new Response(JSON.stringify({
293+
294+
plan_type: "plus",
295+
rate_limit: { primary_window: { used_percent: 91, reset_at: 1_788_000_000 } },
296+
}), { status: 200 }));
297+
298+
await expect(infoPromise).resolves.toMatchObject({
299+
300+
plan: "pro",
301+
quota: { weeklyPercent: 12 },
302+
});
303+
expect(requestedAccountIds).toEqual(["main_acct", "replacement_acct"]);
304+
expect(getAccountQuota(MAIN_CODEX_ACCOUNT_ID)).toMatchObject({ weeklyPercent: 12 });
305+
expect((await fetchMainAccountInfo(false)).email).toBe("[email protected]");
306+
expect(requestedAccountIds).toHaveLength(2);
307+
} finally {
308+
globalThis.fetch = originalFetch;
309+
}
310+
});
311+
266312
test("no active id selects from main plus added accounts and binds main affinity", async () => {
267313
const config = makeConfig({ activeCodexAccountId: undefined, autoSwitchThreshold: 0 });
268314
updateAccountQuota(MAIN_CODEX_ACCOUNT_ID, 5, 0);

0 commit comments

Comments
 (0)