Skip to content

Commit 14c643b

Browse files
authored
Merge pull request #1855 from lidge-jun/codex/gui-auth-unwedge
fix(gui): bound the 401 session re-bootstrap and make token resolution abort-aware
2 parents f848b49 + 2511302 commit 14c643b

4 files changed

Lines changed: 431 additions & 28 deletions

File tree

‎devlog/_plan/260816_gui_loading_performance/001_repro_evidence.md‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,16 @@ following 10s+, skeleton forever. Non-polled stores have no retry path at all on
5555
their single attempt is lost inside the auth wedge (no poll tick, no visibility
5656
listener without pollMs — client-resource.ts:175 installs it only while polling).
5757

58+
CORRECTION (2026-08-16, WP2 verification): the post-heal portion of this
59+
observation was polluted by a test-harness artifact — the raw-CDP channel rejects
60+
`Fetch.disable` (silently, via my own catch), so interception never actually
61+
cleared and "heal" phases kept pausing requests. The mechanism claim stands on the
62+
code (a non-polled cold store whose single attempt dies has no refire path), and
63+
WP1's deadline converts it into a settled failed-cold with a working retry; but
64+
the specific "never recovered even after heal" live observation is withdrawn as
65+
evidence. The corrected end-to-end result (WP2 D addendum): after a real heal,
66+
ALL tabs recover automatically with no reload.
67+
5868
## E4 — hidden-tab emulation limit
5969

6070
The in-app browser keeps background tabs `visibilityState: "visible"` (verified by

‎devlog/_plan/260816_gui_loading_performance/020_phase2_auth_unwedge.md‎

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -85,6 +85,24 @@ After — signature `resolveTokenAfter401(failedToken: string | null, callerSign
8585
Note the shared async body takes NO caller signal (a dead caller must not kill the
8686
join for the others); only the re-bootstrap's own timeout bounds it.
8787

88+
### 3b. Bootstrap watchdog (added in B after live verification; scoped in A re-audit)
89+
90+
Live fault injection found a residual the 10s fetch bound misses: a bootstrap fetch
91+
that never honors the client abort leaves the shared body pending forever and
92+
re-wedges every waiter. A 15s watchdog (`resolutionWatchdogMs`) therefore races
93+
THE BOOTSTRAP CALL inside the body and resolves `{ kind: "failed" }` on a win.
94+
95+
Scope discipline (round-3 audit): the watchdog must NEVER race the admin-token
96+
prompt. The prompt is user-controlled and unbounded; while its body pends, later
97+
waves join the same `resolutionInFlight`, which is what keeps exactly one dialog
98+
on screen (promptForAdminToken has no singleton guard). A whole-body watchdog
99+
fires at 15s mid-prompt and stacks a fresh modal every cycle on non-loopback
100+
dashboards — the exact configuration the prompt exists for. Regression test:
101+
api-auth-deadline "the watchdog never bounds the prompt".
102+
103+
The conditional clear (`resolutionInFlight === tracked`) stays: a late settle of
104+
an abandoned body must not wipe a newer in-flight resolution.
105+
88106
### 4. Thread the caller signal through installApiAuthFetch (~line 191-226)
89107

90108
- Extract `const callerSignal = init?.signal ?? (input instanceof Request ? input.signal : undefined)`
@@ -145,3 +163,25 @@ the abort-race branch; browser check repeats 001/E2 end-to-end.
145163
## Out of scope (WP2)
146164

147165
Server-side session TTL changes; token UX redesign; /v1/* proxy-path auth.
166+
167+
## D addendum — landed (2026-08-16)
168+
169+
Implementation: commits 4f489ddf9 (bounded tri-state bootstrap + abort-aware
170+
resolution), 6ced61d45 (bootstrap watchdog + 001/E3 harness-artifact correction),
171+
edc51e6b2 (watchdog scoped off the prompt — round-3 audit fix).
172+
173+
Verification evidence:
174+
- `cd gui && bun test tests/api-auth-deadline.test.ts tests/api-auth-memory.test.ts tests/admin-token-dialog.test.ts tests/bounded-fetch.test.ts`
175+
→ 23 pass / 0 fail (6 new deadline cases: hung-bootstrap re-arm, no-prompt on
176+
timeout/5xx, per-caller abort unwind with listener-balance spy, signal carry on
177+
retry, signal-dropping zombie bounded by the watchdog, prompt never watchdog-
178+
bounded with single-dialog join).
179+
- `cd gui && bun run build` → green.
180+
- Live E2 (in-app browser, CDP Fetch injection on a sandboxed instance): 401 storm
181+
+ bootstrap stalled past every bound → poll waves settle and re-arm (~15s
182+
cycle); after the injection clears, EVERY tab recovers automatically with no
183+
reload (full 5s poll wave of 200s, dashboard exits the cannot-connect state).
184+
Harness note: the raw CDP channel rejects Fetch.disable — interception is
185+
cleared with Fetch.enable + empty patterns; earlier "post-heal silence"
186+
observations were that artifact, recorded as a correction in 001/E3.
187+
- Audit: binding rounds r3 (FAIL → fixed) and r4 (PASS, fresh).

‎gui/src/api.ts‎

Lines changed: 115 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import { promptForAdminToken, type AdminTokenVerifier } from "./admin-token-dialog";
2+
import { createBoundedFetch } from "./bounded-fetch";
23

34
let installed = false;
45
/** Shared 401 refresh gate — concurrent waiters join one prompt / token resolution. */
@@ -25,6 +26,29 @@ const SESSION_REBOOTSTRAP_PATH = "/opencodex-session";
2526
/** Safe authenticated read used to validate a raw admin token before closing the sign-in form. */
2627
const ADMIN_TOKEN_VALIDATION_PATH = "/api/settings";
2728

29+
/**
30+
* The silent re-bootstrap must fail fast: every /api/* request queues behind the
31+
* shared resolution, so an unbounded bootstrap hangs the whole dashboard (H2).
32+
*/
33+
const SESSION_REBOOTSTRAP_TIMEOUT_MS = 10_000;
34+
let rebootstrapTimeoutMs = SESSION_REBOOTSTRAP_TIMEOUT_MS;
35+
36+
/**
37+
* Whole-resolution watchdog. The bootstrap bound covers a well-behaved fetch; this
38+
* covers everything else — a fetch that never honors the abort, a prompt path that
39+
* pends without settling, any surprise inside the shared body. Without it one stuck
40+
* resolution pins every /api/* waiter for the page lifetime, which is the exact
41+
* failure this module exists to kill.
42+
*
43+
* Scope note: the watchdog races the BOOTSTRAP CALL ONLY, never the admin-token
44+
* prompt. The prompt is user-controlled and unbounded by design; while its body
45+
* pends, later waves join the same resolution, which is what keeps a single dialog
46+
* on screen (promptForAdminToken has no singleton guard — a watchdog that fired
47+
* during the prompt would stack a fresh modal every cycle).
48+
*/
49+
const RESOLUTION_WATCHDOG_MS = 15_000;
50+
let resolutionWatchdogMs = RESOLUTION_WATCHDOG_MS;
51+
2852
function needsApiAuth(input: RequestInfo | URL): boolean {
2953
try {
3054
const raw = input instanceof Request ? input.url : String(input);
@@ -102,23 +126,42 @@ function metaContentFromHtml(html: string, name: string): string | null {
102126
* Silently renew the GUI session from a freshly served document. Loopback servers mint
103127
* short-lived sessions into the HTML on every page load, so an expired session (5-minute
104128
* TTL) or one invalidated by a proxy restart is replaced without ever asking the user for
105-
* a token. Returns null when the server refuses to mint sessions (non-loopback operator
106-
* dashboards), where the manual admin-token prompt remains the fallback.
129+
* a token.
130+
*
131+
* Tri-state by design: only a definitive refusal ("unavailable": 4xx, or an OK
132+
* document without valid session meta — the non-loopback shape) may fall through to
133+
* the admin-token prompt. Anything transient — timeout, abort, network error, 5xx
134+
* from an intermediate proxy — is "failed", which settles this wave as an ordinary
135+
* request failure and lets the next poll retry. Mapping a transient failure to the
136+
* prompt would pop a credential modal on a loopback dashboard that needs no token.
107137
*/
108-
async function reBootstrapSessionToken(): Promise<string | null> {
109-
if (!rawFetch) return null;
138+
type RebootstrapResult =
139+
| { kind: "minted"; token: string }
140+
| { kind: "unavailable" }
141+
| { kind: "failed" };
142+
143+
async function reBootstrapSessionToken(): Promise<RebootstrapResult> {
144+
if (!rawFetch) return { kind: "failed" };
145+
const bounded = createBoundedFetch(rebootstrapTimeoutMs);
110146
try {
111-
const response = await rawFetch(SESSION_REBOOTSTRAP_PATH, { cache: "no-store" });
112-
if (!response.ok) return null;
147+
const response = await rawFetch(SESSION_REBOOTSTRAP_PATH, { cache: "no-store", signal: bounded.signal });
148+
if (!response.ok) {
149+
// Only a definitive refusal is "unavailable"; 5xx and everything else is transient.
150+
return response.status >= 400 && response.status < 500 ? { kind: "unavailable" } : { kind: "failed" };
151+
}
113152
const html = await response.text();
114153
const stored = storeSession(
115154
metaContentFromHtml(html, "opencodex-session-token"),
116155
metaContentFromHtml(html, "opencodex-session-csrf"),
117156
metaContentFromHtml(html, "opencodex-session-origin"),
118157
);
119-
return stored ? readToken() : null;
158+
const token = readToken();
159+
if (stored && token) return { kind: "minted", token };
160+
return { kind: "unavailable" };
120161
} catch {
121-
return null;
162+
return { kind: "failed" };
163+
} finally {
164+
bounded.clear();
122165
}
123166
}
124167

@@ -162,30 +205,61 @@ function withToken(input: RequestInfo | URL, init: RequestInit | undefined, toke
162205
* memoryToken before prompting so waiters that wake after another request already stored a token
163206
* do not re-prompt.
164207
*/
165-
async function resolveTokenAfter401(failedToken: string | null): Promise<string | null> {
208+
async function resolveTokenAfter401(failedToken: string | null, callerSignal?: AbortSignal): Promise<string | null> {
166209
if (promptCancelled) return null;
167-
if (resolutionInFlight) return resolutionInFlight;
210+
if (callerSignal?.aborted) return null;
211+
if (!resolutionInFlight) {
212+
const body = (async () => {
213+
if (promptCancelled) return null;
214+
const current = readToken();
215+
if (current && current !== failedToken) return current;
168216

169-
resolutionInFlight = (async () => {
170-
if (promptCancelled) return null;
171-
const current = readToken();
172-
if (current && current !== failedToken) return current;
217+
// The watchdog races the bootstrap call only — never the prompt below. When
218+
// it wins, the wave fails and the conditional clear lets the NEXT 401 start
219+
// a fresh resolution instead of joining the zombie.
220+
let watchdog: ReturnType<typeof setTimeout> | undefined;
221+
const renewed = await Promise.race([
222+
reBootstrapSessionToken(),
223+
new Promise<RebootstrapResult>((resolve) => {
224+
watchdog = setTimeout(() => resolve({ kind: "failed" }), resolutionWatchdogMs);
225+
}),
226+
]).finally(() => clearTimeout(watchdog));
227+
if (renewed.kind === "minted") return renewed.token;
228+
// Transient bootstrap failure: this wave fails and the next 401 re-arms a
229+
// fresh resolution (the finally clears resolutionInFlight). No prompt.
230+
if (renewed.kind === "failed") return null;
173231

174-
const renewed = await reBootstrapSessionToken();
175-
if (renewed) return renewed;
232+
// User-controlled and unbounded: later waves join this pending body, which
233+
// is what keeps exactly one prompt dialog on screen.
234+
const prompted = await requestAdminToken(verifyAdminToken);
235+
if (prompted) {
236+
storeToken(prompted);
237+
return prompted;
238+
}
239+
promptCancelled = true;
240+
return null;
241+
})();
242+
const tracked = body.finally(() => {
243+
// Only clear if nobody replaced us — a late settle must not wipe a newer
244+
// in-flight resolution. (Async callback: tracked is assigned long before
245+
// this can run.)
246+
if (resolutionInFlight === tracked) resolutionInFlight = null;
247+
});
248+
resolutionInFlight = tracked;
249+
}
176250

177-
const prompted = await requestAdminToken(verifyAdminToken);
178-
if (prompted) {
179-
storeToken(prompted);
180-
return prompted;
181-
}
182-
promptCancelled = true;
183-
return null;
184-
})().finally(() => {
185-
resolutionInFlight = null;
251+
if (!callerSignal) return resolutionInFlight;
252+
// Per-caller race: an abort unwinds THIS caller only — a dead caller must not
253+
// cancel the shared resolution other waiters still need. The listener is removed
254+
// whether the race resolves by token or by abort, so waiters never accumulate.
255+
let onAbort: (() => void) | undefined;
256+
const aborted = new Promise<null>((resolve) => {
257+
onAbort = () => resolve(null);
258+
callerSignal.addEventListener("abort", onAbort, { once: true });
259+
});
260+
return Promise.race([resolutionInFlight, aborted]).finally(() => {
261+
if (onAbort) callerSignal.removeEventListener("abort", onAbort);
186262
});
187-
188-
return resolutionInFlight;
189263
}
190264

191265
export function installApiAuthFetch(): void {
@@ -199,6 +273,7 @@ export function installApiAuthFetch(): void {
199273
window.fetch = async (input: RequestInfo | URL, init?: RequestInit) => {
200274
if (!needsApiAuth(input)) return originalFetch(input, init);
201275

276+
const callerSignal = init?.signal ?? (input instanceof Request ? input.signal : undefined);
202277
const token = readToken();
203278
const [firstInput, firstInit] = token ? withToken(input, init, token) : [input, init];
204279
const response = await originalFetch(firstInput, firstInit);
@@ -215,7 +290,7 @@ export function installApiAuthFetch(): void {
215290
clearTokenIfCurrent(token);
216291
}
217292

218-
const nextToken = await resolveTokenAfter401(token);
293+
const nextToken = await resolveTokenAfter401(token, callerSignal ?? undefined);
219294
if (!nextToken) return response;
220295

221296
const [retryInput, retryInit] = withToken(input, init, nextToken);
@@ -235,4 +310,16 @@ export function resetApiAuthFetchForTests(adminTokenPrompt: AdminTokenPrompt = p
235310
rawFetch = null;
236311
promptCancelled = false;
237312
requestAdminToken = adminTokenPrompt;
313+
rebootstrapTimeoutMs = SESSION_REBOOTSTRAP_TIMEOUT_MS;
314+
resolutionWatchdogMs = RESOLUTION_WATCHDOG_MS;
315+
}
316+
317+
/** Test-only: shrink the re-bootstrap deadline so timeout paths run in milliseconds. */
318+
export function setRebootstrapTimeoutForTests(ms: number): void {
319+
rebootstrapTimeoutMs = ms;
320+
}
321+
322+
/** Test-only: shrink the whole-resolution watchdog so zombie paths run in milliseconds. */
323+
export function setResolutionWatchdogForTests(ms: number): void {
324+
resolutionWatchdogMs = ms;
238325
}

0 commit comments

Comments
 (0)