Skip to content

Commit bea32b8

Browse files
fix(studio): stop a Studio edit from reloading the preview (#3137)
* fix(studio): stop a Studio edit from reloading the preview as if it were external Every mutation route wrote the file without leaving a write receipt, so the watcher's broadcast of Studio's own edit arrived with no identity on it. The external-change coordinator could not tell that echo from an agent or an editor writing the file behind Studio's back, so it took the safe branch and did a full iframe reload. That reload hides the stage for the length of the reload, which is what the flash after a text edit was. Every mutation write now goes through one helper that records the receipt, and the client claims the write before the request goes out rather than after it: the server writes and the watcher fires while the request is still in flight, so a token marked from the response can arrive after the echo it was meant to match. Reproduced in the browser before and after, with the reload path traced end to end. Before, a patch-element write logged `token: null` then a reload from the coordinator; after, the same write logs the token and `suppressed: own write token`, with no reload. Adds `hf-reload-debug` (localStorage, off by default) alongside the existing `hf-resize-debug`: it records each file-change decision and its reason, plus the stack of whoever asked for a full reload. * fix(studio): claim the timeline and caption writes too, not just the DOM ones The receipt only helps when the client marked the token it sent, and the GSAP mutation writers never sent one. A drag commits through gsap-mutations, so the server minted a token the client had never seen, the change came back looking like someone else's, and the preview did the full reload the receipt was meant to prevent. Same one-line claim on both GSAP mutation writers, the timing sync's mutation call, and the caption auto-save PUT. The rollback call stays deliberately unclaimed and says why: it runs because a mutation did not converge, so the preview is on bytes nobody can vouch for and the reload is the point. Verified live: a drag-shaped update-properties on the timeline now logs `suppressed: own write token` with no reload, where it logged a coordinator reload before. * refactor(studio): keep timelineTimingSync under the size cap Claiming the timeline writes pushed this file one line past the 600-line gate. Same change as the branch made later, landed with the commit that caused it. * fix(studio): cover remaining write receipt paths * fix(studio): preserve batch write receipts * fix(cli): emit every file in a watcher burst
1 parent adb13ce commit bea32b8

24 files changed

Lines changed: 419 additions & 81 deletions

‎packages/cli/src/server/fileWatcher.test.ts‎

Lines changed: 34 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,21 @@
11
import { EventEmitter } from "node:events";
2-
import { describe, expect, it, vi } from "vitest";
2+
import { beforeEach, describe, expect, it, vi } from "vitest";
3+
4+
type WatchCallback = (eventType: string, filename: string | Buffer | null) => void;
35

46
const mockWatcher = new EventEmitter() as EventEmitter & { close: () => void };
57
mockWatcher.close = vi.fn();
68

7-
vi.mock("node:fs", () => ({
8-
watch: vi.fn(() => mockWatcher),
9-
}));
9+
vi.mock("node:fs", async (importOriginal) => {
10+
const original = await importOriginal<typeof import("node:fs")>();
11+
return {
12+
...original,
13+
watch: vi.fn((_path: string, _options: unknown, onChange: WatchCallback) => {
14+
mockWatcher.on("change", onChange);
15+
return mockWatcher;
16+
}),
17+
};
18+
});
1019

1120
const { shouldWatchProjectFile, createProjectWatcher } = await import("./fileWatcher.js");
1221

@@ -30,6 +39,27 @@ describe("shouldWatchProjectFile", () => {
3039
});
3140

3241
describe("createProjectWatcher", () => {
42+
beforeEach(() => {
43+
mockWatcher.removeAllListeners();
44+
vi.clearAllMocks();
45+
vi.useRealTimers();
46+
});
47+
48+
it("notifies once for every file changed in one debounce burst", () => {
49+
vi.useFakeTimers();
50+
const projectWatcher = createProjectWatcher("/fake/project/dir");
51+
const listener = vi.fn();
52+
projectWatcher.addListener(listener);
53+
54+
mockWatcher.emit("change", "change", "scene-a.html");
55+
mockWatcher.emit("change", "change", "scene-b.html");
56+
mockWatcher.emit("change", "change", "scene-a.html");
57+
vi.advanceTimersByTime(300);
58+
59+
expect(listener.mock.calls).toEqual([["scene-a.html"], ["scene-b.html"]]);
60+
projectWatcher.close();
61+
});
62+
3363
// Regression: fs.watch can fail asynchronously (e.g. EMFILE from exhausted
3464
// OS watch handles) via an 'error' event, not a thrown exception. An
3565
// EventEmitter 'error' with no listener crashes the whole process — this

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

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@ export function shouldWatchProjectFile(filename: string): boolean {
3434

3535
export function createProjectWatcher(projectDir: string): ProjectWatcher {
3636
const listeners = new Set<FileChangeListener>();
37+
const pendingPaths = new Set<string>();
3738
let debounceTimer: ReturnType<typeof setTimeout> | null = null;
3839
let watcher: FSWatcher | null = null;
3940

@@ -43,10 +44,16 @@ export function createProjectWatcher(projectDir: string): ProjectWatcher {
4344
const relativePath = filename.toString();
4445
if (!shouldWatchProjectFile(relativePath)) return;
4546

47+
pendingPaths.add(relativePath);
4648
if (debounceTimer) clearTimeout(debounceTimer);
4749
debounceTimer = setTimeout(() => {
48-
for (const fn of listeners) {
49-
fn(relativePath);
50+
const changedPaths = [...pendingPaths];
51+
pendingPaths.clear();
52+
debounceTimer = null;
53+
for (const changedPath of changedPaths) {
54+
for (const fn of listeners) {
55+
fn(changedPath);
56+
}
5057
}
5158
}, DEBOUNCE_MS);
5259
});
@@ -72,6 +79,7 @@ export function createProjectWatcher(projectDir: string): ProjectWatcher {
7279
},
7380
close() {
7481
if (debounceTimer) clearTimeout(debounceTimer);
82+
pendingPaths.clear();
7583
watcher?.close();
7684
listeners.clear();
7785
},

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

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@ import {
3030
createProjectSignature,
3131
createBackgroundRemovalJob,
3232
consumeFileWriteReceipt,
33+
fileContentVersion,
3334
getMimeType,
3435
type PreviewApiAdapter,
3536
thumbnailDeviceScaleFactor,
@@ -752,7 +753,14 @@ export function createStudioServer(options: StudioServerOptions): StudioServer {
752753
app.get("/api/events", (c) => {
753754
return streamSSE(c, async (stream) => {
754755
const listener = (path: string) => {
755-
const receipt = consumeFileWriteReceipt(resolve(projectDir, path));
756+
const absPath = resolve(projectDir, path);
757+
let version: string | null = null;
758+
try {
759+
version = fileContentVersion(readFileSync(absPath, "utf-8"));
760+
} catch {
761+
// A deletion has no current bytes to match against an API write receipt.
762+
}
763+
const receipt = version ? consumeFileWriteReceipt(absPath, version) : null;
756764
stream
757765
.writeSSE({ event: "file-change", data: JSON.stringify(receipt ?? { path }) })
758766
.catch(() => {});

‎packages/studio-server/src/helpers/fileVersion.test.ts‎

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,25 @@ describe("file versions and write receipts", () => {
2323
};
2424
recordFileWriteReceipt("/project/index.html", receipt);
2525

26-
expect(consumeFileWriteReceipt("/project/index.html")).toEqual(receipt);
27-
expect(consumeFileWriteReceipt("/project/index.html")).toBeNull();
26+
expect(consumeFileWriteReceipt("/project/index.html", receipt.version)).toEqual(receipt);
27+
expect(consumeFileWriteReceipt("/project/index.html", receipt.version)).toBeNull();
28+
});
29+
30+
it("matches the final debounced watcher version instead of receipt insertion order", () => {
31+
const first = {
32+
path: "index.html",
33+
version: fileContentVersion("first"),
34+
writeToken: "write-1",
35+
};
36+
const last = {
37+
path: "index.html",
38+
version: fileContentVersion("last"),
39+
writeToken: "write-2",
40+
};
41+
recordFileWriteReceipt("/project/index.html", first);
42+
recordFileWriteReceipt("/project/index.html", last);
43+
44+
expect(consumeFileWriteReceipt("/project/index.html", last.version)).toEqual(last);
45+
expect(consumeFileWriteReceipt("/project/index.html", first.version)).toEqual(first);
2846
});
2947
});

‎packages/studio-server/src/helpers/fileVersion.ts‎

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -32,13 +32,17 @@ export function recordFileWriteReceipt(absPath: string, receipt: FileWriteReceip
3232
receipts.set(absPath, current);
3333
}
3434

35-
/** Attach one API write's identity to the corresponding filesystem-watch echo. */
36-
export function consumeFileWriteReceipt(absPath: string): FileWriteReceipt | null {
35+
/** Attach one API write's identity to the watcher echo for its exact bytes. */
36+
export function consumeFileWriteReceipt(
37+
absPath: string,
38+
expectedVersion: string,
39+
): FileWriteReceipt | null {
3740
const now = Date.now();
3841
const current = (receipts.get(absPath) ?? []).filter(
3942
(entry) => now - entry.recordedAt < RECEIPT_TTL_MS,
4043
);
41-
const receipt = current.shift() ?? null;
44+
const receiptIndex = current.findIndex((entry) => entry.version === expectedVersion);
45+
const receipt = receiptIndex === -1 ? null : (current.splice(receiptIndex, 1)[0] ?? null);
4246
if (current.length > 0) receipts.set(absPath, current);
4347
else receipts.delete(absPath);
4448
if (!receipt) return null;

‎packages/studio-server/src/routes/files.test.ts‎

Lines changed: 128 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -65,21 +65,33 @@ function createAdapter(projectDir: string): StudioApiAdapter {
6565
};
6666
}
6767

68-
function postElementPatchBatch(app: Hono, file: string, patches: unknown[]): Promise<Response> {
68+
function postElementPatchBatch(
69+
app: Hono,
70+
file: string,
71+
patches: unknown[],
72+
writeToken?: string,
73+
): Promise<Response> {
6974
return app.request(`http://localhost/projects/demo/file-mutations/patch-elements-batch/${file}`, {
7075
method: "POST",
71-
headers: { "Content-Type": "application/json" },
76+
headers: {
77+
"Content-Type": "application/json",
78+
...(writeToken ? { "X-Hyperframes-Write-Token": writeToken } : {}),
79+
},
7280
body: JSON.stringify({ patches }),
7381
});
7482
}
7583

7684
function postElementPatchBatches(
7785
app: Hono,
7886
batches: Array<{ sourceFile: string; patches: unknown[] }>,
87+
writeToken?: string,
7988
): Promise<Response> {
8089
return app.request("http://localhost/projects/demo/file-mutations/patch-element-batches", {
8190
method: "POST",
82-
headers: { "Content-Type": "application/json" },
91+
headers: {
92+
"Content-Type": "application/json",
93+
...(writeToken ? { "X-Hyperframes-Write-Token": writeToken } : {}),
94+
},
8395
body: JSON.stringify({ batches }),
8496
});
8597
}
@@ -119,7 +131,10 @@ describe("registerFileRoutes", () => {
119131
const insert = (expectedVersion: string) =>
120132
app.request("http://localhost/projects/demo/file-mutations/insert-composition/index.html", {
121133
method: "POST",
122-
headers: { "Content-Type": "application/json" },
134+
headers: {
135+
"Content-Type": "application/json",
136+
"X-Hyperframes-Write-Token": "studio-insert-1",
137+
},
123138
body: JSON.stringify({ sourcePath: "child.html", start: 4, track: 0, expectedVersion }),
124139
});
125140

@@ -131,6 +146,11 @@ describe("registerFileRoutes", () => {
131146
expect(result.after).toContain('data-duration="7"');
132147
expect(result.after).toContain(`id="${result.hostId}"`);
133148
expect(result.version).toBe(fileContentVersion(result.after));
149+
expect(consumeFileWriteReceipt(join(projectDir, "index.html"), result.version)).toEqual({
150+
path: "index.html",
151+
version: result.version,
152+
writeToken: "studio-insert-1",
153+
});
134154

135155
const committed = result.after;
136156
const stale = await insert(fileContentVersion(before));
@@ -366,7 +386,7 @@ describe("registerFileRoutes", () => {
366386
expect(payload.version).toBe(fileContentVersion("after"));
367387
expect(payload.writeToken).toBe("studio-write-1");
368388
expect(response.headers.get("etag")).toBe(payload.version);
369-
expect(consumeFileWriteReceipt(join(projectDir, "index.html"))).toEqual({
389+
expect(consumeFileWriteReceipt(join(projectDir, "index.html"), payload.version!)).toEqual({
370390
path: "index.html",
371391
version: payload.version,
372392
writeToken: "studio-write-1",
@@ -425,6 +445,39 @@ describe("registerFileRoutes", () => {
425445
expect(readFileSync(join(projectDir, "index.html"), "utf-8")).toContain("After");
426446
});
427447

448+
// Without the receipt the client cannot recognise its own edit in the watcher
449+
// broadcast, so it treats it as someone else's write and does a full preview
450+
// reload — a visible blank on the stage right after the user typed.
451+
it("leaves a write receipt so the patch's own file-change echo is identifiable", async () => {
452+
const projectDir = createProjectDir();
453+
writeFileSync(projectDir + "/index.html", '<div id="title">Before</div>');
454+
const app = new Hono();
455+
registerFileRoutes(app, createAdapter(projectDir));
456+
457+
const response = await app.request(
458+
"http://localhost/projects/demo/file-mutations/patch-element/index.html",
459+
{
460+
method: "POST",
461+
headers: {
462+
"Content-Type": "application/json",
463+
"X-Hyperframes-Write-Token": "studio-patch-1",
464+
},
465+
body: JSON.stringify({
466+
target: { id: "title" },
467+
operations: [{ type: "text-content", property: "textContent", value: "After" }],
468+
}),
469+
},
470+
);
471+
472+
expect(response.status).toBe(200);
473+
const version = fileContentVersion(readFileSync(join(projectDir, "index.html"), "utf-8"));
474+
expect(consumeFileWriteReceipt(join(projectDir, "index.html"), version)).toEqual({
475+
path: "index.html",
476+
version,
477+
writeToken: "studio-patch-1",
478+
});
479+
});
480+
428481
it("applies an ordered element patch batch with one file write", async () => {
429482
const projectDir = createProjectDir();
430483
const original =
@@ -433,16 +486,21 @@ describe("registerFileRoutes", () => {
433486
const app = new Hono();
434487
registerFileRoutes(app, createAdapter(projectDir));
435488

436-
const response = await postElementPatchBatch(app, "index.html", [
437-
{
438-
target: { id: "back" },
439-
operations: [{ type: "inline-style", property: "z-index", value: "2" }],
440-
},
441-
{
442-
target: { id: "front" },
443-
operations: [{ type: "inline-style", property: "z-index", value: "1" }],
444-
},
445-
]);
489+
const response = await postElementPatchBatch(
490+
app,
491+
"index.html",
492+
[
493+
{
494+
target: { id: "back" },
495+
operations: [{ type: "inline-style", property: "z-index", value: "2" }],
496+
},
497+
{
498+
target: { id: "front" },
499+
operations: [{ type: "inline-style", property: "z-index", value: "1" }],
500+
},
501+
],
502+
"studio-layer-order-1",
503+
);
446504
expect(response.status).toBe(200);
447505
const payload = (await response.json()) as {
448506
changed?: boolean;
@@ -458,6 +516,12 @@ describe("registerFileRoutes", () => {
458516
expect(payload.content).toContain('id="back" style="z-index: 2"');
459517
expect(payload.content).toContain('id="front" style="z-index: 1"');
460518
expect(readFileSync(join(projectDir, payload.backupPath!), "utf-8")).toBe(original);
519+
const version = fileContentVersion(payload.content!);
520+
expect(consumeFileWriteReceipt(join(projectDir, "index.html"), version)).toEqual({
521+
path: "index.html",
522+
version,
523+
writeToken: "studio-layer-order-1",
524+
});
461525
expect(readdirSync(join(projectDir, ".hyperframes", "backup"))).toHaveLength(1);
462526
});
463527

@@ -519,6 +583,52 @@ describe("registerFileRoutes", () => {
519583
expect(existsSync(join(projectDir, ".hyperframes", "backup"))).toBe(false);
520584
});
521585

586+
it("leaves one exact write receipt for every file in a durable element patch batch", async () => {
587+
const projectDir = createProjectDir();
588+
writeFileSync(join(projectDir, "index.html"), '<div id="index">Before</div>');
589+
writeFileSync(join(projectDir, "scene.html"), '<div id="scene">Before</div>');
590+
const app = new Hono();
591+
registerFileRoutes(app, createAdapter(projectDir));
592+
593+
const response = await postElementPatchBatches(
594+
app,
595+
[
596+
{
597+
sourceFile: "index.html",
598+
patches: [
599+
{
600+
target: { id: "index" },
601+
operations: [{ type: "text-content", property: "textContent", value: "After" }],
602+
},
603+
],
604+
},
605+
{
606+
sourceFile: "scene.html",
607+
patches: [
608+
{
609+
target: { id: "scene" },
610+
operations: [{ type: "text-content", property: "textContent", value: "After" }],
611+
},
612+
],
613+
},
614+
],
615+
"studio-group-drag-1",
616+
);
617+
const payload = (await response.json()) as {
618+
files: Array<{ sourceFile: string; after: string }>;
619+
};
620+
621+
expect(response.status).toBe(200);
622+
for (const file of payload.files) {
623+
const version = fileContentVersion(file.after);
624+
expect(consumeFileWriteReceipt(join(projectDir, file.sourceFile), version)).toEqual({
625+
path: file.sourceFile,
626+
version,
627+
writeToken: "studio-group-drag-1",
628+
});
629+
}
630+
});
631+
522632
it("refuses every file when one batch contains an unmatched target", async () => {
523633
const projectDir = createProjectDir();
524634
const indexOriginal = '<div id="present" style="z-index: 1">Present</div>';
@@ -732,7 +842,9 @@ describe("registerFileRoutes", () => {
732842
expect(payload.files[0].after).toContain('id="a-split"');
733843
expect(payload.files[0].after).toContain('id="b-split"');
734844
expect(readFileSync(join(projectDir, "index.html"), "utf-8")).toBe(payload.files[0].after);
735-
expect(consumeFileWriteReceipt(join(projectDir, "index.html"))).toEqual({
845+
expect(
846+
consumeFileWriteReceipt(join(projectDir, "index.html"), payload.files[0].version),
847+
).toEqual({
736848
path: "index.html",
737849
version: payload.files[0].version,
738850
writeToken: "cut-test",

0 commit comments

Comments
 (0)