Skip to content

Commit 2245961

Browse files
committed
fix(codex): reset main runtime state after account switch
1 parent 4c8b09a commit 2245961

3 files changed

Lines changed: 59 additions & 0 deletions

File tree

‎src/codex/account-lifecycle.ts‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,43 @@
11
import { removeCodexAccountCredential } from "./account-store";
22
import { clearAccountNeedsReauth } from "./account-runtime-state";
3+
import { getMainChatgptAccountId } from "./auth-collision";
4+
import { MAIN_CODEX_ACCOUNT_ID, setMainAccountPlan } from "./main-account";
35
import { clearAccountQuota } from "./quota";
46
import { clearCodexUpstreamHealthForAccount, clearThreadAccountMapForAccount } from "./routing";
57
import { invalidateCodexWebSocketsForAccount } from "./websocket-registry";
68
import type { OcxConfig } from "../types";
79

10+
let observedMainChatgptAccountId: string | null | undefined;
11+
812
export function purgeCodexAccountRuntimeState(accountId: string): void {
913
clearAccountNeedsReauth(accountId);
1014
clearAccountQuota(accountId);
1115
clearThreadAccountMapForAccount(accountId);
1216
clearCodexUpstreamHealthForAccount(accountId);
1317
}
1418

19+
/**
20+
* The main Codex login is stored under the stable `__main__` alias, while
21+
* `~/.codex/auth.json` can be replaced with credentials for another physical
22+
* ChatGPT account. Drop alias-keyed runtime state when that identity changes so
23+
* cooldown, quota, reauth, and thread affinity do not leak across accounts.
24+
*/
25+
export function reconcileMainCodexAccountRuntimeState(): boolean {
26+
const currentAccountId = getMainChatgptAccountId();
27+
const previousAccountId = observedMainChatgptAccountId;
28+
observedMainChatgptAccountId = currentAccountId;
29+
if (previousAccountId === undefined || previousAccountId === currentAccountId) return false;
30+
31+
purgeCodexAccountRuntimeState(MAIN_CODEX_ACCOUNT_ID);
32+
setMainAccountPlan(null);
33+
invalidateCodexWebSocketsForAccount(MAIN_CODEX_ACCOUNT_ID);
34+
return true;
35+
}
36+
37+
export function resetMainCodexAccountIdentityTrackingForTests(): void {
38+
observedMainChatgptAccountId = undefined;
39+
}
40+
1541
export function deleteCodexAccount(runtimeConfig: OcxConfig, accountId: string): void {
1642
removeCodexAccountCredential(accountId);
1743
runtimeConfig.codexAccounts = (runtimeConfig.codexAccounts ?? []).filter(account => account.id !== accountId);

‎src/codex/auth-context.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import {
66
} from "./account-store";
77
import { markAccountNeedsReauth } from "./account-runtime-state";
88
import { isCodexAccountUsable } from "./account-usability";
9+
import { reconcileMainCodexAccountRuntimeState } from "./account-lifecycle";
910
import { MAIN_CODEX_ACCOUNT_ID, getMainAccountToken } from "./main-account";
1011
import {
1112
getCodexAccountCooldownUntil,
@@ -107,6 +108,7 @@ export async function resolveCodexAuthContext(
107108
if (!hasCallerCodexBearer(headers)) throw new CodexDirectAuthenticationError();
108109
return { kind: "main", accountId: null };
109110
}
111+
reconcileMainCodexAccountRuntimeState();
110112
const threadId = headers.get("x-codex-parent-thread-id");
111113
const resolution = options.excludeAccountId
112114
? (() => {

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

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,11 +17,14 @@ import {
1717
resolveCodexAuthContext,
1818
} from "../src/codex/auth-context";
1919
import { isCodexAccountUsable } from "../src/codex/account-usability";
20+
import { resetMainCodexAccountIdentityTrackingForTests } from "../src/codex/account-lifecycle";
2021
import { MAIN_CODEX_ACCOUNT_ID, setMainAccountPlan } from "../src/codex/main-account";
2122
import { saveCodexAccountCredential } from "../src/codex/account-store";
2223
import {
2324
clearAccountNeedsReauth,
2425
clearAccountQuota,
26+
getAccountQuota,
27+
isAccountNeedsReauth,
2528
markAccountNeedsReauth,
2629
updateAccountQuota,
2730
} from "../src/codex/auth-api";
@@ -74,6 +77,7 @@ describe("main account rotation (Option A)", () => {
7477
clearThreadAccountMap();
7578
clearCodexUpstreamHealth();
7679
clearAccountQuota();
80+
resetMainCodexAccountIdentityTrackingForTests();
7781
setMainAccountPlan(null);
7882
for (const id of ["a", "b", MAIN_CODEX_ACCOUNT_ID]) clearAccountNeedsReauth(id);
7983
saveCred("a");
@@ -85,6 +89,7 @@ describe("main account rotation (Option A)", () => {
8589
clearThreadAccountMap();
8690
clearCodexUpstreamHealth();
8791
clearAccountQuota();
92+
resetMainCodexAccountIdentityTrackingForTests();
8893
setMainAccountPlan(null);
8994
for (const id of ["a", "b", MAIN_CODEX_ACCOUNT_ID]) clearAccountNeedsReauth(id);
9095
for (const d of [STORE_DIR, CODEX_DIR]) if (existsSync(d)) rmSync(d, { recursive: true });
@@ -147,6 +152,32 @@ describe("main account rotation (Option A)", () => {
147152
expect(headers.get("chatgpt-account-id")).toBe("main_acct");
148153
});
149154

155+
test("switching the main auth identity discards runtime state from the previous account", async () => {
156+
const config = makeConfig({ activeCodexAccountId: MAIN_CODEX_ACCOUNT_ID, autoSwitchThreshold: 0, codexAccounts: [] });
157+
await expect(resolveCodexAuthContext(new Headers(), config, "pool")).resolves.toMatchObject({
158+
kind: "main-pool",
159+
chatgptAccountId: "main_acct",
160+
});
161+
162+
recordCodexUpstreamOutcome(config, MAIN_CODEX_ACCOUNT_ID, 429, { retryAfter: "3600" });
163+
markAccountNeedsReauth(MAIN_CODEX_ACCOUNT_ID);
164+
updateAccountQuota(MAIN_CODEX_ACCOUNT_ID, 100, 0);
165+
writeFileSync(
166+
join(CODEX_DIR, "auth.json"),
167+
JSON.stringify({ tokens: { access_token: "replacement_access", account_id: "replacement_acct" } }),
168+
);
169+
170+
await expect(resolveCodexAuthContext(new Headers(), config, "pool")).resolves.toEqual({
171+
kind: "main-pool",
172+
accountId: MAIN_CODEX_ACCOUNT_ID,
173+
accessToken: "replacement_access",
174+
chatgptAccountId: "replacement_acct",
175+
});
176+
expect(isCodexAccountInCooldown(MAIN_CODEX_ACCOUNT_ID)).toBe(false);
177+
expect(isAccountNeedsReauth(MAIN_CODEX_ACCOUNT_ID)).toBe(false);
178+
expect(getAccountQuota(MAIN_CODEX_ACCOUNT_ID)).toBeNull();
179+
});
180+
150181
test("no active id selects from main plus added accounts and binds main affinity", async () => {
151182
const config = makeConfig({ activeCodexAccountId: undefined, autoSwitchThreshold: 0 });
152183
updateAccountQuota(MAIN_CODEX_ACCOUNT_ID, 5, 0);

0 commit comments

Comments
 (0)