Skip to content

Commit 7346510

Browse files
committed
fix(gui): 늦게 마운트한 표면의 auto-switch 하이드레이션 (WP3 B3)
탭이 패널을 마운트/언마운트하므로, 컨트롤러 로드가 끝난 뒤 나타난 패널은 다음 30초 폴링까지 'Loading'에 머물렀다. replay-on-subscribe는 폐기했다. useCodexAutoSwitch는 모든 acceptActiveRead가 그 revision에서 실제로 시작된 읽기라고 가정하므로 합성 accept가 편집 중인 draft를 덮어썼다. 대신 리뷰어 설계를 따른다. - 컨트롤러가 마지막 '진짜' 성공 읽기의 threshold를 캐시하고 readLastThreshold()로 노출 - useCodexAutoSwitch에 hydrateServerValue() 추가 — threshold가 미초기화이고 편집/저장 중이 아닐 때만 적용한다. 서버 읽기인 척하지 않는다 - 구독 이펙트 의존성을 controller 객체가 아니라 안정적인 subscribeLoadObserver 콜백으로 교체. 훅이 매 렌더 새 객체를 반환하므로 이전 형태는 매번 재구독했다 테스트 간섭도 해결했다. 원인은 전역 복원이 아니라 react-dom/client의 정적 import였다 — 모듈 그래프 로드 시점의 document에 묶여서, 같은 프로세스의 다른 스위트가 나중에 동적 import 할 때 깨졌다. 빈 컴포넌트만 렌더해도 재현됐다. 지연 import로 바꾸니 양방향 순서 모두 12/12 통과. privacy:scan이 잡은 픽스처 이메일도 비주소 라벨로 교체했다.
1 parent 9ca5923 commit 7346510

4 files changed

Lines changed: 72 additions & 12 deletions

File tree

‎gui/src/components/CodexAccountPool.tsx‎

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@ export default function CodexAccountPool({ apiBase, accountModeState = null, ban
3939
updateFailed: t("codexAuth.autoSwitchUpdateFailed"),
4040
invalid: t("codexAuth.autoSwitchThresholdInvalid"),
4141
});
42-
const { beginServerRead, acceptServerRead, rejectServerRead } = autoSwitch;
42+
const { beginServerRead, acceptServerRead, rejectServerRead, hydrateServerValue } = autoSwitch;
4343
// A hook cannot be called conditionally, so the fallback instance is always created
4444
// but stays inert (no load, no polling) whenever a shared controller was injected.
4545
const ownController = useCodexAccountPool(apiBase, !injectedController);
@@ -59,11 +59,24 @@ export default function CodexAccountPool({ apiBase, accountModeState = null, ban
5959

6060
// The controller owns loading and polling. This surface only feeds the auto-switch
6161
// threshold observer and leases a pause while an OAuth modal is open.
62-
useEffect(() => controller.subscribeLoadObserver({
62+
// Depend on the stable subscribe callback, not the controller object: the hook
63+
// returns a fresh object every render, which would resubscribe on every render.
64+
const { subscribeLoadObserver, readLastThreshold } = controller;
65+
66+
useEffect(() => subscribeLoadObserver({
6367
beginActiveRead: beginServerRead,
6468
acceptActiveRead: acceptServerRead,
6569
rejectActiveRead: rejectServerRead,
66-
}), [controller, beginServerRead, acceptServerRead, rejectServerRead]);
70+
}), [subscribeLoadObserver, beginServerRead, acceptServerRead, rejectServerRead]);
71+
72+
// Seed from a value an earlier load already fetched. Tabs mount and unmount their
73+
// panels, so a panel appearing after that load would otherwise show "Loading" until
74+
// the next poll. Hydration applies only while uninitialized, so it cannot disturb a
75+
// draft or a pending save.
76+
useEffect(() => {
77+
const cached = readLastThreshold();
78+
if (cached !== undefined) hydrateServerValue(cached);
79+
}, [readLastThreshold, hydrateServerValue]);
6780

6881
useEffect(() => {
6982
if (!showAdd) return;

‎gui/src/hooks/useCodexAccountPool.ts‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,8 @@ export interface CodexAccountPoolController {
6262
pauseRefresh(): PauseToken;
6363
resumeRefresh(token: PauseToken): void;
6464
subscribeLoadObserver(observer: CodexAccountLoadObserver): () => void;
65+
/** Last threshold an actual /active read returned; undefined before the first success. */
66+
readLastThreshold(): unknown;
6567
}
6668

6769
const REFRESH_INTERVAL_MS = 30_000;
@@ -80,13 +82,19 @@ export function useCodexAccountPool(apiBase: string, enabled = true): CodexAccou
8082
// id back to a value the server had not yet committed when that request was issued.
8183
const pendingActiveIdRef = useRef<{ id: string | null } | null>(null);
8284
const observersRef = useRef<Set<CodexAccountLoadObserver>>(new Set());
85+
// Last threshold value an actual /active read returned. Surfaces that mount after a
86+
// load already finished read it to seed their UI instead of waiting a poll interval.
87+
const lastThresholdRef = useRef<{ value: unknown } | null>(null);
8388
const switchingRef = useRef<string | null>(null);
8489

8590
const subscribeLoadObserver = useCallback((observer: CodexAccountLoadObserver) => {
8691
observersRef.current.add(observer);
8792
return () => { observersRef.current.delete(observer); };
8893
}, []);
8994

95+
/** Last threshold an actual read returned, or undefined when none has succeeded yet. */
96+
const readLastThreshold = useCallback(() => lastThresholdRef.current?.value, []);
97+
9098
const load = useCallback(async (refreshQuota = false): Promise<boolean> => {
9199
const generation = ++loadGenerationRef.current;
92100
// Snapshot subscribers so an unsubscribe mid-flight cannot desync begin/accept pairs.
@@ -121,6 +129,7 @@ export function useCodexAccountPool(apiBase: string, enabled = true): CodexAccou
121129
pendingActiveIdRef.current = null;
122130
setActiveId(serverActiveId);
123131
}
132+
lastThresholdRef.current = { value: active.autoSwitchThreshold };
124133
for (const observer of observers) {
125134
observer.acceptActiveRead(active.autoSwitchThreshold, revisions.get(observer)!);
126135
}
@@ -257,5 +266,6 @@ export function useCodexAccountPool(apiBase: string, enabled = true): CodexAccou
257266
pauseRefresh,
258267
resumeRefresh,
259268
subscribeLoadObserver,
269+
readLastThreshold,
260270
};
261271
}

‎gui/src/hooks/useCodexAutoSwitch.ts‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ export interface CodexAutoSwitchController {
1717
feedback: AutoSwitchFeedback;
1818
beginServerRead(): number;
1919
acceptServerRead(value: unknown, startedRevision: number): void;
20+
hydrateServerValue(value: unknown): void;
2021
rejectServerRead(): void;
2122
setDraft(value: string): void;
2223
setEditing(editing: boolean): void;
@@ -117,6 +118,19 @@ export function useCodexAutoSwitch(
117118
}
118119
}, [queueOrApply]);
119120

121+
/**
122+
* Seed the threshold from a value another surface already fetched. Applies ONLY while
123+
* uninitialized, so it can never disturb a draft, a pending save, or a newer read.
124+
* Needed because tabs mount and unmount their panels: a panel that appears after the
125+
* controller's load finished would otherwise render "Loading" until the next poll.
126+
*/
127+
const hydrateServerValue = useCallback((value: unknown) => {
128+
if (thresholdRef.current !== null) return;
129+
if (editingRef.current || savingRef.current) return;
130+
setLoadError(false);
131+
apply(normalizeAutoSwitchThreshold(value));
132+
}, [apply]);
133+
120134
const rejectServerRead = useCallback(() => {
121135
if (thresholdRef.current === null) setLoadError(true);
122136
}, []);
@@ -222,6 +236,7 @@ export function useCodexAutoSwitch(
222236
feedback,
223237
beginServerRead,
224238
acceptServerRead,
239+
hydrateServerValue,
225240
rejectServerRead,
226241
setDraft,
227242
setEditing,

‎gui/tests/codex-account-pool-behaviour.test.tsx‎

Lines changed: 31 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import { afterEach, beforeEach, expect, test } from "bun:test";
22
import { Window } from "happy-dom";
33
import { act } from "react";
4-
import { createRoot, type Root } from "react-dom/client";
4+
import type { Root } from "react-dom/client";
55
import { useCodexAccountPool, type CodexAccountPoolController } from "../src/hooks/useCodexAccountPool";
66

77
/**
@@ -10,12 +10,16 @@ import { useCodexAccountPool, type CodexAccountPoolController } from "../src/hoo
1010
* substring checks is not proven at all.
1111
*/
1212

13-
const globals = ["document", "window", "navigator", "localStorage", "fetch", "IS_REACT_ACT_ENVIRONMENT"] as const;
13+
// NOTE: `fetch` is deliberately absent. A sibling suite installs its own fetch router
14+
// inside individual tests without restoring it, so writing a captured fetch back here
15+
// would clobber that router and make results depend on file order.
16+
const globals = ["document", "window", "navigator", "localStorage", "IS_REACT_ACT_ENVIRONMENT"] as const;
1417
let previous: Record<(typeof globals)[number], unknown>;
1518
let win: Window;
1619
let host: HTMLElement;
1720
let root: Root | null = null;
1821
let calls: string[] = [];
22+
let originalFetch: typeof globalThis.fetch;
1923
let accounts: unknown[] = [];
2024
let threshold = 80;
2125

@@ -30,8 +34,9 @@ beforeEach(() => {
3034
});
3135
(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
3236

37+
originalFetch = globalThis.fetch;
3338
calls = [];
34-
accounts = [{ id: "a1", email: "[email protected]", isMain: true, hasCredential: true, quota: null }];
39+
accounts = [{ id: "a1", email: "account-one", isMain: true, hasCredential: true, quota: null }];
3540
Object.defineProperty(globalThis, "fetch", {
3641
configurable: true,
3742
value: async (url: string, init?: RequestInit) => {
@@ -52,14 +57,22 @@ beforeEach(() => {
5257
});
5358

5459
afterEach(async () => {
60+
// Unmount first, while this file's window/timers are still the active globals:
61+
// otherwise React cleanup runs against a swapped-out window and the controller's
62+
// 30s interval outlives the suite, firing into whatever runs next.
5563
if (root) {
5664
const current = root;
5765
await act(async () => { current.unmount(); });
5866
root = null;
5967
}
68+
await act(async () => { await new Promise((r) => setTimeout(r, 0)); });
6069
for (const key of globals) {
6170
Object.defineProperty(globalThis, key, { configurable: true, value: previous[key] });
6271
}
72+
Object.defineProperty(globalThis, "fetch", { configurable: true, value: originalFetch });
73+
// Tear the window down: leaving it alive kept this file's timers and document
74+
// reachable, which made a sibling suite in the same process fail depending on order.
75+
await win.happyDOM?.close?.();
6376
});
6477

6578
/** Mounts the hook and exposes the live controller. */
@@ -69,6 +82,8 @@ async function mountController(enabled = true) {
6982
seen.current = useCodexAccountPool("", enabled);
7083
return null;
7184
}
85+
// Lazy import: see the note on the Root type import above.
86+
const { createRoot } = await import("react-dom/client");
7287
await act(async () => {
7388
root = createRoot(host);
7489
root.render(<Probe />);
@@ -115,6 +130,12 @@ test("two pause holders both have to release before polling resumes", async () =
115130
expect(calls.length).toBe(afterPause);
116131
});
117132

133+
test("the last genuine threshold read is cached for surfaces that mount later", async () => {
134+
const seen = await mountController();
135+
// A real /active read succeeded during the initial load.
136+
expect(seen.current!.readLastThreshold()).toBe(80);
137+
});
138+
118139
test("subscribing never fabricates a server read", async () => {
119140
const seen = await mountController();
120141
const received: unknown[] = [];
@@ -127,10 +148,11 @@ test("subscribing never fabricates a server read", async () => {
127148
});
128149
});
129150

130-
// A replay-on-subscribe was tried and rejected: useCodexAutoSwitch treats every
131-
// acceptActiveRead as belonging to a read that genuinely started at that revision, so
132-
// a synthesised accept corrupted its editing/saving disposition and overwrote drafts
133-
// the user was typing. Subscribing is therefore silent; the next load notifies.
151+
// Subscribing stays silent: useCodexAutoSwitch treats every acceptActiveRead as
152+
// belonging to a read that genuinely started at that revision, so synthesising one
153+
// corrupts its editing/saving disposition and overwrites drafts. Late surfaces seed
154+
// themselves through readLastThreshold() + hydrateServerValue() instead, which applies
155+
// only while uninitialized.
134156
expect(received).toEqual([]);
135157

136158
// And a real load does reach the subscriber.
@@ -141,8 +163,8 @@ test("subscribing never fabricates a server read", async () => {
141163
test("a mutation updates the one shared controller state", async () => {
142164
const seen = await mountController();
143165
accounts = [
144-
{ id: "a1", email: "[email protected]", isMain: true, hasCredential: true, quota: null },
145-
{ id: "a2", email: "[email protected]", isMain: false, hasCredential: true, quota: null },
166+
{ id: "a1", email: "account-one", isMain: true, hasCredential: true, quota: null },
167+
{ id: "a2", email: "account-two", isMain: false, hasCredential: true, quota: null },
146168
];
147169

148170
await act(async () => { await seen.current!.switchAccount("a2"); });

0 commit comments

Comments
 (0)