Skip to content

Commit dc6d557

Browse files
committed
fix(gui): dedupe dashboard API token prompts on concurrent 401s
Re-read the in-memory token after a 401 and share one refresh gate so a management fan-out prompts once instead of once per in-flight /api request when OPENCODEX_API_AUTH_TOKEN is required. Fixes #647.
1 parent ca7b104 commit dc6d557

2 files changed

Lines changed: 94 additions & 6 deletions

File tree

‎gui/src/api.ts‎

Lines changed: 30 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
let installed = false;
2+
/** Shared 401 refresh gate — concurrent waiters join one prompt / token resolution. */
23
let promptInFlight: Promise<string | null> | null = null;
34

45
function needsApiAuth(input: RequestInfo | URL): boolean {
@@ -46,11 +47,25 @@ function withToken(input: RequestInfo | URL, init: RequestInit | undefined, toke
4647
return [input, { ...init, headers }];
4748
}
4849

49-
async function promptForToken(): Promise<string | null> {
50+
/**
51+
* Resolve a token after a 401. Concurrent callers share one in-flight resolution so a dashboard
52+
* fan-out does not open one window.prompt per /api request (#647). Re-reads memoryToken before
53+
* prompting so waiters that wake after another request already stored a token do not re-prompt.
54+
*/
55+
async function resolveTokenAfter401(failedToken: string | null): Promise<string | null> {
5056
if (promptInFlight) return promptInFlight;
51-
promptInFlight = Promise.resolve()
52-
.then(() => window.prompt("OpenCodex API token")?.trim() || null)
53-
.finally(() => { promptInFlight = null; });
57+
58+
promptInFlight = (async () => {
59+
const current = readToken();
60+
if (current && current !== failedToken) return current;
61+
62+
const prompted = window.prompt("OpenCodex API token")?.trim() || null;
63+
if (prompted) storeToken(prompted);
64+
return prompted;
65+
})().finally(() => {
66+
promptInFlight = null;
67+
});
68+
5469
return promptInFlight;
5570
}
5671

@@ -69,10 +84,19 @@ export function installApiAuthFetch(): void {
6984
if (response.status !== 401) return response;
7085

7186
if (token) clearToken();
72-
const nextToken = await promptForToken();
87+
88+
// Another request may have stored a token while this one was in flight (or while prompt blocked).
89+
const refreshed = readToken();
90+
if (refreshed && refreshed !== token) {
91+
const [retryInput, retryInit] = withToken(input, init, refreshed);
92+
const retry = await originalFetch(retryInput, retryInit);
93+
if (retry.status !== 401) return retry;
94+
clearToken();
95+
}
96+
97+
const nextToken = await resolveTokenAfter401(token);
7398
if (!nextToken) return response;
7499

75-
storeToken(nextToken);
76100
const [retryInput, retryInit] = withToken(input, init, nextToken);
77101
const retry = await originalFetch(retryInput, retryInit);
78102
if (retry.status === 401) clearToken();

‎gui/tests/api-auth-memory.test.ts‎

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -113,6 +113,70 @@ test("cross-origin /api/* requests do not receive the API key or token prompt",
113113
expect(promptCalls).toBe(beforeCrossPrompts);
114114
});
115115

116+
test("concurrent 401s share one token prompt and all retry with the stored token", async () => {
117+
// Repro for #647: many /api/* requests start without a token (dashboard fan-out).
118+
// Delivering 401s one-by-one after each auth cycle finishes matches the browser case where
119+
// window.prompt blocks the main thread: each continuation still holds a captured null token
120+
// and must reuse the in-memory token from an earlier request instead of prompting again.
121+
let promptCalls = 0;
122+
const release401: Array<() => void> = [];
123+
const mockFetch = (async (_input: RequestInfo | URL, init?: RequestInit) => {
124+
const headers = new Headers(init?.headers);
125+
if (headers.get("X-OpenCodex-API-Key") === "shared-token") {
126+
return new Response("{}", { status: 200 });
127+
}
128+
await new Promise<void>((resolve) => {
129+
release401.push(resolve);
130+
});
131+
return new Response("unauthorized", { status: 401 });
132+
}) as typeof fetch;
133+
window.prompt = () => {
134+
promptCalls += 1;
135+
return "shared-token";
136+
};
137+
await installMockAuthFetch(mockFetch);
138+
139+
const endpoints = [
140+
"/api/config",
141+
"/api/providers",
142+
"/api/models",
143+
"/api/selected-models",
144+
"/api/disabled-models",
145+
"/api/effort-caps",
146+
"/api/sidecar-settings",
147+
"/api/injection-model",
148+
"/api/v2",
149+
"/api/keys",
150+
"/api/provider-presets",
151+
"/api/key-providers",
152+
"/api/oauth/providers",
153+
"/api/codex-auth/accounts",
154+
];
155+
const pending = endpoints.map((path) => fetch(path).then((r) => r.status));
156+
// Let every request reach the 401 gate before any response is delivered.
157+
for (let i = 0; i < 20 && release401.length < endpoints.length; i += 1) {
158+
await Promise.resolve();
159+
}
160+
expect(release401.length).toBe(endpoints.length);
161+
162+
for (let i = 0; i < endpoints.length; i += 1) {
163+
const done = pending[i]!;
164+
let settled = false;
165+
void done.then(() => {
166+
settled = true;
167+
});
168+
release401.shift()!();
169+
for (let spin = 0; spin < 50 && !settled; spin += 1) {
170+
await Promise.resolve();
171+
}
172+
expect(settled).toBe(true);
173+
}
174+
175+
const statuses = await Promise.all(pending);
176+
expect(promptCalls).toBe(1);
177+
expect([...new Set(statuses)]).toEqual([200]);
178+
});
179+
116180
test("cross-origin /v1/* requests do not receive the API key or token prompt", async () => {
117181
let promptCalls = 0;
118182
let phase: "seed" | "cross" = "seed";

0 commit comments

Comments
 (0)