Skip to content

Commit 00c575d

Browse files
miga-heygenclaude
andauthored
fix(studio): prevent preview hang on burst external file rewrites (#3648)
* fix(studio): prevent preview hang on burst external file rewrites Two interacting bugs caused Studio to freeze when multiple processes (generator, check, snapshot) burst-wrote index.html within seconds: 1. SSE listener leak: the /api/events handler added a watcher listener per client connection but never removed it on disconnect. Reconnects accumulated dead listeners, each triggering readFileSync on every file change and writing to closed streams. 2. Generation starvation: processChange incremented generationRef and awaited drainPendingChanges. A second event arriving mid-drain bumped the generation, causing the first drain to bail at the generation check. With rapid writes, no drain ever completed and Studio stayed frozen on stale content. Fix 1: use stream.onAbort() to remove the watcher listener when the SSE connection closes. Fix 2: gate processChange with a draining ref. While a drain is in progress, stash the latest event. On completion, process the stashed event — the last write in a burst always completes its reload. Closes #3646 Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]> * fix(studio): align coordinator tests with drain serialization Update existing test to expect the new behavior: when two events fire in quick succession, the first drain completes and triggers a reload (previously it was silently discarded). The stashed event then starts a second drain. Also fix the burst-write test to use the drains array pattern and explicit act() flushes for stashed event processing. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]> * fix(studio): stash events with allowDuplicate and harden listener cleanup Address Rames's review findings: - Stash with allowDuplicate: true so re-dispatched events are not swallowed by the duplicate guard (the identity was already written on the way in, so the stashed event matched itself on re-entry). - Wrap SSE keepalive loop in try/finally so the listener is removed on both abort and throw, not just abort. - Restore stale-completion guard test coverage lost in the rename. - Use await act(async () => {...}) for burst dispatches so assertions depend on the stash guard rather than scheduling. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]> * fix(studio): simplify drain serialization and restore SSE cleanup Restructure processChange into intake + drain loop: - processChange is now synchronous — validates, dedupes, checks own echoes, enqueues the accepted payload, and starts the drain loop - startDrainLoop runs while the pending slot is non-null, draining one event per iteration via drainOnePending - No recursive void processChange(...) from finally, so no allowDuplicate escape hatch needed — stashed events never re-enter intake guards SSE listener: restore stream.onAbort alongside try/finally. Hono's sleep() never throws, so finally alone doesn't fire on disconnect. Both paths call removeListener (Set.delete is idempotent). Tests: remove stale-drain test that contaminated subsequent tests by emptying the shared roots array mid-test. Use sync act() for burst dispatches — the stash decision is synchronous. All 10 coordinator tests pass locally (NODE_ENV=test). Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]> --------- Co-authored-by: Claude Opus 4.6 (1M context) <[email protected]>
1 parent 64ce9fd commit 00c575d

3 files changed

Lines changed: 111 additions & 43 deletions

File tree

‎packages/cli/src/server/studioServer.ts‎

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -790,11 +790,17 @@ export function createStudioServer(options: StudioServerOptions): StudioServer {
790790
};
791791
// Re-applied here because the watcher now also emits the signature
792792
// manifest files, which must not trigger a browser reload.
793-
watcher.addListener((changedPath) => {
793+
const wrappedListener = (changedPath: string) => {
794794
if (shouldWatchProjectFile(changedPath)) listener(changedPath);
795-
});
796-
while (true) {
797-
await stream.sleep(30000);
795+
};
796+
watcher.addListener(wrappedListener);
797+
stream.onAbort(() => watcher.removeListener(wrappedListener));
798+
try {
799+
while (true) {
800+
await stream.sleep(30000);
801+
}
802+
} finally {
803+
watcher.removeListener(wrappedListener);
798804
}
799805
});
800806
});

‎packages/studio/src/hooks/useExternalFileChangeCoordinator.test.tsx‎

Lines changed: 41 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -175,7 +175,7 @@ describe("external file change coordinator", () => {
175175
expect(options.reloadSdkSession).toHaveBeenCalledOnce();
176176
});
177177

178-
it("ignores stale drain completion after a newer generation", async () => {
178+
it("serializes drains and processes stashed events", async () => {
179179
const drains: Array<(result: { status: "clean" }) => void> = [];
180180
const { options } = await mountCoordinator({
181181
drainPendingChanges: () => new Promise((resolve) => drains.push(resolve)),
@@ -184,11 +184,14 @@ describe("external file change coordinator", () => {
184184
handler?.({ path: "index.html", content: "first", version: "v2" });
185185
handler?.({ path: "index.html", content: "second", version: "v3" });
186186
});
187+
expect(drains).toHaveLength(1);
187188
await act(async () => drains[0]?.({ status: "clean" }));
188-
expect(options.reloadPreview).not.toHaveBeenCalled();
189-
await act(async () => drains[1]?.({ status: "clean" }));
190189
expect(options.reloadPreview).toHaveBeenCalledOnce();
191-
expect(options.reloadSdkSession).toHaveBeenCalledOnce();
190+
await act(async () => {});
191+
expect(drains).toHaveLength(2);
192+
await act(async () => drains[1]?.({ status: "clean" }));
193+
expect(options.reloadPreview).toHaveBeenCalledTimes(2);
194+
expect(options.reloadSdkSession).toHaveBeenCalledTimes(2);
192195
});
193196

194197
it("restores a durable unresolved conflict after remount", async () => {
@@ -285,4 +288,38 @@ describe("external file change coordinator", () => {
285288
);
286289
expect(onAcceptedPersistedFileChange).toHaveBeenCalledOnce();
287290
});
291+
292+
it("completes a reload after a burst of rapid external writes", async () => {
293+
const drains: Array<(result: { status: "clean" }) => void> = [];
294+
const reloadPreview = vi.fn();
295+
const onAcceptedPersistedFileChange = vi.fn();
296+
await mountCoordinator({
297+
drainPendingChanges: vi.fn(
298+
() => new Promise<{ status: "clean" }>((resolve) => drains.push(resolve)),
299+
),
300+
reloadPreview,
301+
onAcceptedPersistedFileChange,
302+
});
303+
304+
// Fire three events in rapid succession (simulates generator + check + snapshot)
305+
act(() => {
306+
handler?.({ path: "index.html", content: "write-1", version: "v1" });
307+
handler?.({ path: "index.html", content: "write-2", version: "v2" });
308+
handler?.({ path: "index.html", content: "write-3", version: "v3" });
309+
});
310+
311+
// Only one drain runs — events 2 and 3 are stashed (last one wins)
312+
expect(drains).toHaveLength(1);
313+
314+
// Complete the first drain — triggers reload, then stashed event starts a second drain
315+
await act(async () => drains[0]?.({ status: "clean" }));
316+
expect(reloadPreview).toHaveBeenCalledOnce();
317+
await act(async () => {});
318+
expect(drains).toHaveLength(2);
319+
320+
// Complete the second drain — processes the final write
321+
await act(async () => drains[1]?.({ status: "clean" }));
322+
expect(reloadPreview).toHaveBeenCalledTimes(2);
323+
expect(onAcceptedPersistedFileChange).toHaveBeenCalledTimes(2);
324+
});
288325
});

‎packages/studio/src/hooks/useExternalFileChangeCoordinator.ts‎

Lines changed: 60 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -135,6 +135,8 @@ export function useExternalFileChangeCoordinator({
135135
const lastEventIdentityRef = useRef<string | null>(null);
136136
const blockedRef = useRef(blocked);
137137
const snapshotWriteTailRef = useRef<Promise<void>>(Promise.resolve());
138+
const drainingRef = useRef(false);
139+
const pendingPayloadRef = useRef<{ payload: unknown } | null>(null);
138140
blockedRef.current = blocked;
139141

140142
useEffect(() => {
@@ -213,37 +215,11 @@ export function useExternalFileChangeCoordinator({
213215
await next;
214216
}, []);
215217

216-
const processChange = useCallback(
218+
const drainOnePending = useCallback(
217219
// fallow-ignore-next-line complexity
218-
async (payload: unknown, allowDuplicate = false) => {
220+
async (payload: unknown) => {
219221
const path = readStudioFileChangePath(payload);
220-
if (!path || !projectId) return;
221-
const pendingTimelinePaths = pendingTimelineEditPathRef.current;
222-
// The old path-only suppression could drop a real agent/user write that
223-
// raced ahead of the timeline write receipt. Clear the legacy marker but
224-
// decide ownership only from the exact write token/content below.
225-
pendingTimelinePaths.delete(path);
226-
227-
const content = readFileChangeContent(payload);
228-
const token = readFileChangeWriteToken(payload);
229-
logReload("file-change", { path, token: token ?? null, hasContent: content != null });
230-
const identity = eventIdentity(path, payload);
231-
if (!allowDuplicate && identity != null && identity === lastEventIdentityRef.current) {
232-
logReload("suppressed", { path, why: "duplicate event" });
233-
return;
234-
}
235-
lastEventIdentityRef.current = identity;
236-
237-
const ownWriteToken = consumeStudioWriteToken(token);
238-
const ownContentEcho = content != null && isSelfWriteEcho(path, content);
239-
if (ownWriteToken || ownContentEcho) {
240-
onAcceptedPersistedFileChange(path);
241-
logReload("suppressed", {
242-
path,
243-
why: ownWriteToken ? "own write token" : "own content echo",
244-
});
245-
return;
246-
}
222+
if (!path) return;
247223

248224
const generation = ++generationRef.current;
249225
const result = await drainPendingChanges();
@@ -253,7 +229,7 @@ export function useExternalFileChangeCoordinator({
253229
const previousBlocked = blockedRef.current;
254230
if (previousBlocked?.status === "failed" && deleteConflictSnapshot) {
255231
try {
256-
await deleteConflictSnapshot(projectId, path);
232+
await deleteConflictSnapshot(projectId!, path);
257233
} catch (error) {
258234
if (mountedRef.current && generation === generationRef.current) {
259235
setBlocked({ ...previousBlocked, generation, error });
@@ -267,6 +243,7 @@ export function useExternalFileChangeCoordinator({
267243
reloadAcceptedGeneration(path);
268244
return;
269245
}
246+
const content = readFileChangeContent(payload);
270247
if (result.status === "failed") {
271248
const candidate = getPendingCandidate?.();
272249
const studioContent = candidate?.path === path ? candidate.content : null;
@@ -275,7 +252,7 @@ export function useExternalFileChangeCoordinator({
275252
try {
276253
await persistSnapshotInOrder(() =>
277254
persistFailureSnapshot(
278-
projectId,
255+
projectId!,
279256
path,
280257
studioContent,
281258
readFileChangeVersion(payload),
@@ -305,7 +282,7 @@ export function useExternalFileChangeCoordinator({
305282
return;
306283
}
307284
try {
308-
await persistSnapshotInOrder(() => persistConflictSnapshot(projectId, result.error));
285+
await persistSnapshotInOrder(() => persistConflictSnapshot(projectId!, result.error));
309286
} catch (error) {
310287
if (!mountedRef.current || generation !== generationRef.current) return;
311288
setBlocked({
@@ -323,9 +300,8 @@ export function useExternalFileChangeCoordinator({
323300
setBlocked({ status: "conflict", generation, error: result.error, payload });
324301
},
325302
[
326-
projectId,
327-
pendingTimelineEditPathRef,
328303
drainPendingChanges,
304+
projectId,
329305
deleteConflictSnapshot,
330306
getPendingCandidate,
331307
persistConflictSnapshot,
@@ -336,6 +312,55 @@ export function useExternalFileChangeCoordinator({
336312
],
337313
);
338314

315+
const startDrainLoop = useCallback(async () => {
316+
if (drainingRef.current) return;
317+
drainingRef.current = true;
318+
try {
319+
while (mountedRef.current) {
320+
const pending = pendingPayloadRef.current;
321+
if (!pending) break;
322+
pendingPayloadRef.current = null;
323+
await drainOnePending(pending.payload);
324+
}
325+
} finally {
326+
drainingRef.current = false;
327+
}
328+
}, [drainOnePending]);
329+
330+
const processChange = useCallback(
331+
// fallow-ignore-next-line complexity
332+
(payload: unknown) => {
333+
const path = readStudioFileChangePath(payload);
334+
if (!path || !projectId) return;
335+
pendingTimelineEditPathRef.current.delete(path);
336+
337+
const content = readFileChangeContent(payload);
338+
const token = readFileChangeWriteToken(payload);
339+
logReload("file-change", { path, token: token ?? null, hasContent: content != null });
340+
const identity = eventIdentity(path, payload);
341+
if (identity != null && identity === lastEventIdentityRef.current) {
342+
logReload("suppressed", { path, why: "duplicate event" });
343+
return;
344+
}
345+
lastEventIdentityRef.current = identity;
346+
347+
const ownWriteToken = consumeStudioWriteToken(token);
348+
const ownContentEcho = content != null && isSelfWriteEcho(path, content);
349+
if (ownWriteToken || ownContentEcho) {
350+
onAcceptedPersistedFileChange(path);
351+
logReload("suppressed", {
352+
path,
353+
why: ownWriteToken ? "own write token" : "own content echo",
354+
});
355+
return;
356+
}
357+
358+
pendingPayloadRef.current = { payload };
359+
void startDrainLoop();
360+
},
361+
[projectId, pendingTimelineEditPathRef, startDrainLoop, onAcceptedPersistedFileChange],
362+
);
363+
339364
useEffect(() => {
340365
const handler = (payload?: unknown) => processChange(payload);
341366
const adapter = testHotAdapter();
@@ -357,7 +382,7 @@ export function useExternalFileChangeCoordinator({
357382
if (!current || current.status === "conflict" || current.recovered) return;
358383
resetSaveQueues?.();
359384
lastEventIdentityRef.current = null;
360-
await processChange(current.payload, true);
385+
processChange(current.payload);
361386
}, [processChange, resetSaveQueues]);
362387

363388
const useExternalFile = useCallback(

0 commit comments

Comments
 (0)