Skip to content

Commit fd5ad59

Browse files
committed
fix(gui): close Startup/Storage/Usage abort and Debug PUT races
Invalidate load generations on effect cleanup before abort, and serialize Debug PUTs so server writes follow user action order.
1 parent 46bef6c commit fd5ad59

6 files changed

Lines changed: 242 additions & 19 deletions

File tree

‎gui/src/pages/Debug.tsx‎

Lines changed: 21 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ export default function Debug({ apiBase, embedded }: { apiBase: string; embedded
2525
const [refreshing, setRefreshing] = useState(false);
2626
const afterRef = useRef(0);
2727
const mutationGenerationRef = useRef(0);
28+
const mutationQueueRef = useRef<Promise<void> | null>(null);
2829
const scrollContainerRef = useRef<HTMLDivElement>(null);
2930

3031
const debugPoll = useKeyedClientResource(
@@ -131,17 +132,27 @@ export default function Debug({ apiBase, embedded }: { apiBase: string; embedded
131132
const runDebugMutation = async (body: Record<string, unknown>) => {
132133
const generation = ++mutationGenerationRef.current;
133134
setDebugBusy(true);
135+
// Serialize PUTs so server writes follow user-action order. Latest-wins
136+
// response filtering alone cannot prevent out-of-order server state.
137+
const run = async () => {
138+
try {
139+
const res = await fetch(`${apiBase}/api/debug`, {
140+
method: "PUT",
141+
headers: { "content-type": "application/json" },
142+
body: JSON.stringify(body),
143+
});
144+
if (!res.ok) return;
145+
const next = await res.json() as DebugSettings;
146+
if (generation !== mutationGenerationRef.current) return;
147+
setClientResourceData(debugSettingsKey(apiBase), next);
148+
} catch { /* ignore */ }
149+
};
150+
const previous = mutationQueueRef.current ?? Promise.resolve();
151+
const queued = previous.then(run, run);
152+
mutationQueueRef.current = queued.then(() => undefined, () => undefined);
134153
try {
135-
const res = await fetch(`${apiBase}/api/debug`, {
136-
method: "PUT",
137-
headers: { "content-type": "application/json" },
138-
body: JSON.stringify(body),
139-
});
140-
if (!res.ok) return;
141-
const next = await res.json() as DebugSettings;
142-
if (generation !== mutationGenerationRef.current) return;
143-
setClientResourceData(debugSettingsKey(apiBase), next);
144-
} catch { /* ignore */ } finally {
154+
await queued;
155+
} finally {
145156
if (generation === mutationGenerationRef.current) setDebugBusy(false);
146157
}
147158
};

‎gui/src/pages/Startup.tsx‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -125,6 +125,9 @@ export default function Startup({ apiBase }: { apiBase: string }) {
125125
const timer = window.setTimeout(() => { void refresh(controller.signal); }, 0);
126126
return () => {
127127
window.clearTimeout(timer);
128+
// Invalidate before abort so a superseded request's finally cannot clear
129+
// loading in the gap before the deferred replacement increments generation.
130+
loadGenerationRef.current += 1;
128131
controller.abort();
129132
};
130133
}, [refresh]);

‎gui/src/pages/Storage.tsx‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -144,6 +144,9 @@ export default function Storage({ apiBase }: { apiBase: string }) {
144144
}, 0);
145145
return () => {
146146
window.clearTimeout(timeout);
147+
// Invalidate before abort so a superseded request's finally cannot clear
148+
// loading in the gap before the deferred replacement increments generation.
149+
loadGenerationRef.current += 1;
147150
controller.abort();
148151
};
149152
}, [fetchStorage]);

‎gui/src/pages/Usage.tsx‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -616,6 +616,9 @@ export default function Usage({ apiBase }: { apiBase: string }) {
616616
}, 0);
617617
return () => {
618618
window.clearTimeout(timeout);
619+
// Invalidate before abort so a superseded request's finally cannot clear
620+
// loading in the gap before the deferred replacement increments generation.
621+
loadGenerationRef.current += 1;
619622
controller.abort();
620623
};
621624
}, [fetchUsage, range, surface]);

‎gui/tests/debug-mutation-busy.test.tsx‎

Lines changed: 130 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -160,36 +160,157 @@ test("rapid Debug flag/reset keeps controls busy and applies only the latest mut
160160
(btn.textContent ?? "").includes("Clear runtime overrides"),
161161
);
162162

163-
// Fire flag + reset before the first busy paint can serialize them.
163+
// Fire flag + reset before the first busy paint can serialize them via disabled controls.
164164
await act(async () => {
165165
usageSwitch()?.click();
166166
resetBtn()?.click();
167167
});
168-
await waitFor(() => putGates.length >= 2);
169-
168+
// Serialized: only the first PUT is in flight until it settles.
169+
await waitFor(() => putGates.length === 1);
170+
expect(putBodies).toEqual([{ usage: true }]);
170171
expect(usageSwitch()?.disabled).toBe(true);
171172
expect(resetBtn()?.disabled).toBe(true);
172-
expect(putBodies[0]).toEqual({ usage: true });
173-
expect(putBodies[1]).toEqual({ reset: true });
174173

175-
// Older usage response lands first — must not stick after reset settles.
176174
await act(async () => {
177175
putGates[0]!.resolve();
178176
await Promise.resolve();
179177
});
178+
await waitFor(() => putGates.length === 2);
179+
expect(putBodies[1]).toEqual({ reset: true });
180+
expect(usageSwitch()?.disabled).toBe(true);
181+
180182
await act(async () => {
181-
await new Promise<void>(resolve => testWindow.setTimeout(resolve, 0));
183+
putGates[1]!.resolve();
184+
await Promise.resolve();
182185
});
186+
await waitFor(() => usageSwitch()?.disabled === false);
183187
expect(usageSwitch()?.getAttribute("aria-pressed")).toBe("false");
184-
expect(usageSwitch()?.disabled).toBe(true);
188+
expect(resetBtn()?.disabled).toBe(false);
189+
190+
await act(async () => {
191+
root.unmount();
192+
});
193+
container.remove();
194+
});
195+
196+
test("Debug PUTs are serialized so reverse-order response settlement cannot leave server ahead of UI", async () => {
197+
const { createRoot } = await import("react-dom/client");
198+
const container = document.createElement("div");
199+
document.body.append(container);
200+
201+
type Gate = { resolve: () => void };
202+
const putGates: Gate[] = [];
203+
const putStartOrder: string[] = [];
204+
let inFlight = 0;
205+
let maxInFlight = 0;
206+
let serverSettings: DebugSettings = { ...BASE_SETTINGS, runtimeOverride: {}, env: { ...BASE_SETTINGS.env } };
207+
const serverSnapshots: DebugSettings[] = [];
208+
209+
globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
210+
const url = String(input);
211+
const method = (init?.method ?? "GET").toUpperCase();
212+
if (url.includes("/api/debug/logs") || url.includes("/api/debug/usage-logs") || url.includes("/api/debug/injection-logs")) {
213+
return Response.json([]);
214+
}
215+
if (url.endsWith("/api/debug") && method === "GET") {
216+
return Response.json(serverSettings);
217+
}
218+
if (url.endsWith("/api/debug") && method === "PUT") {
219+
const body = JSON.parse(String(init?.body ?? "{}")) as Record<string, unknown>;
220+
putStartOrder.push(body.reset === true ? "reset" : Object.keys(body).sort().join(","));
221+
inFlight += 1;
222+
maxInFlight = Math.max(maxInFlight, inFlight);
223+
try {
224+
await new Promise<void>(resolve => {
225+
putGates.push({ resolve });
226+
});
227+
// Apply when the response settles. Concurrent PUTs + reverse resolve
228+
// order (reset, then usage) would leave usage=true on the server while
229+
// browser generation checks show the reset UI — serialization prevents that.
230+
if (body.reset === true) {
231+
serverSettings = {
232+
...BASE_SETTINGS,
233+
enabled: false,
234+
usage: false,
235+
injection: false,
236+
claude: false,
237+
runtimeOverride: {},
238+
env: { ...BASE_SETTINGS.env },
239+
};
240+
} else {
241+
serverSettings = {
242+
...serverSettings,
243+
enabled: body.debug === undefined ? serverSettings.enabled : body.debug === true,
244+
usage: body.usage === undefined ? serverSettings.usage : body.usage === true,
245+
injection: body.injection === undefined ? serverSettings.injection : body.injection === true,
246+
claude: body.claude === undefined ? serverSettings.claude : body.claude === true,
247+
runtimeOverride: {
248+
...serverSettings.runtimeOverride,
249+
...(body.debug === undefined ? {} : { debug: body.debug === true }),
250+
...(body.usage === undefined ? {} : { usage: body.usage === true }),
251+
...(body.injection === undefined ? {} : { injection: body.injection === true }),
252+
...(body.claude === undefined ? {} : { claude: body.claude === true }),
253+
},
254+
};
255+
}
256+
serverSnapshots.push({
257+
...serverSettings,
258+
runtimeOverride: { ...serverSettings.runtimeOverride },
259+
env: { ...serverSettings.env },
260+
});
261+
return Response.json(serverSettings);
262+
} finally {
263+
inFlight -= 1;
264+
}
265+
}
266+
return new Response(null, { status: 404 });
267+
}) as typeof fetch;
268+
269+
let root!: Root;
270+
await act(async () => {
271+
root = createRoot(container);
272+
root.render(
273+
<LanguageProvider>
274+
<Debug apiBase="http://localhost" />
275+
</LanguageProvider>,
276+
);
277+
});
278+
await waitFor(() => container.querySelector('button.switch[aria-label="Usage extraction"]') != null);
279+
280+
const usageSwitch = () => container.querySelector<HTMLButtonElement>('button.switch[aria-label="Usage extraction"]');
281+
const resetBtn = () => Array.from(container.querySelectorAll<HTMLButtonElement>("button")).find(btn =>
282+
(btn.textContent ?? "").includes("Clear runtime overrides"),
283+
);
284+
285+
await act(async () => {
286+
usageSwitch()?.click();
287+
resetBtn()?.click();
288+
});
289+
290+
await waitFor(() => putGates.length === 1);
291+
expect(putStartOrder).toEqual(["usage"]);
292+
// Attempt reverse-order settlement: only the in-flight PUT can resolve.
293+
// A concurrent implementation would have putGates[1] available here.
294+
expect(putGates[1]).toBeUndefined();
295+
await act(async () => {
296+
putGates[0]!.resolve();
297+
await Promise.resolve();
298+
});
299+
await waitFor(() => putGates.length === 2);
300+
expect(putStartOrder).toEqual(["usage", "reset"]);
301+
expect(serverSnapshots[0]?.usage).toBe(true);
185302

186303
await act(async () => {
187304
putGates[1]!.resolve();
188305
await Promise.resolve();
189306
});
190307
await waitFor(() => usageSwitch()?.disabled === false);
308+
309+
expect(maxInFlight).toBe(1);
310+
expect(serverSettings.usage).toBe(false);
311+
expect(serverSettings.runtimeOverride).toEqual({});
191312
expect(usageSwitch()?.getAttribute("aria-pressed")).toBe("false");
192-
expect(resetBtn()?.disabled).toBe(false);
313+
expect(serverSnapshots.at(-1)?.usage).toBe(false);
193314

194315
await act(async () => {
195316
root.unmount();

‎gui/tests/storage-loading-race.test.tsx‎

Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -126,3 +126,85 @@ test("an aborted Storage fetch must not clear loading while its replacement is i
126126
});
127127
container.remove();
128128
});
129+
130+
test("effect cleanup invalidates generation before abort so loading stays owned across the deferred replacement gap", async () => {
131+
const { createRoot } = await import("react-dom/client");
132+
const container = document.createElement("div");
133+
document.body.append(container);
134+
135+
type Gate = {
136+
resolve: (body: unknown) => void;
137+
reject: (reason?: unknown) => void;
138+
};
139+
const gates: Gate[] = [];
140+
globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
141+
const url = String(input);
142+
if (!url.includes("/api/storage")) return new Response(null, { status: 404 });
143+
const signal = init?.signal;
144+
const body = await new Promise<unknown>((resolve, reject) => {
145+
const gate: Gate = { resolve, reject };
146+
gates.push(gate);
147+
if (signal?.aborted) {
148+
reject(new DOMException("The operation was aborted.", "AbortError"));
149+
return;
150+
}
151+
signal?.addEventListener("abort", () => {
152+
reject(new DOMException("The operation was aborted.", "AbortError"));
153+
}, { once: true });
154+
});
155+
return Response.json(body);
156+
}) as typeof fetch;
157+
158+
function Harness() {
159+
const [apiBase, setApiBase] = useState("http://old");
160+
(window as unknown as { __bumpApiBase?: () => void }).__bumpApiBase = () => setApiBase("http://new");
161+
return (
162+
<LanguageProvider>
163+
<Storage apiBase={apiBase} />
164+
</LanguageProvider>
165+
);
166+
}
167+
168+
let root!: Root;
169+
await act(async () => {
170+
root = createRoot(container);
171+
root.render(<Harness />);
172+
});
173+
await act(async () => {
174+
await new Promise<void>(resolve => testWindow.setTimeout(resolve, 0));
175+
});
176+
await waitFor(() => gates.length === 1);
177+
178+
// Cleanup aborts + invalidates generation; replacement is still deferred (setTimeout 0).
179+
await act(async () => {
180+
(window as unknown as { __bumpApiBase: () => void }).__bumpApiBase();
181+
});
182+
183+
// Flush abort rejection / finally microtasks without running the deferred fetch.
184+
await act(async () => {
185+
await Promise.resolve();
186+
await Promise.resolve();
187+
});
188+
189+
const refresh = container.querySelector<HTMLButtonElement>("button.btn");
190+
expect(gates.length).toBe(1);
191+
expect(container.textContent).toContain("Scanning storage");
192+
expect(refresh?.disabled).toBe(true);
193+
194+
await act(async () => {
195+
await new Promise<void>(resolve => testWindow.setTimeout(resolve, 0));
196+
});
197+
await waitFor(() => gates.length === 2);
198+
199+
await act(async () => {
200+
gates[1]!.resolve(REPORT_B);
201+
await Promise.resolve();
202+
});
203+
await waitFor(() => (container.textContent ?? "").includes("/tmp/b"));
204+
expect(refresh?.disabled).toBe(false);
205+
206+
await act(async () => {
207+
root.unmount();
208+
});
209+
container.remove();
210+
});

0 commit comments

Comments
 (0)