Skip to content

Commit 4d2a48a

Browse files
committed
fix(studio): preserve batch write receipts
1 parent 0ef4413 commit 4d2a48a

5 files changed

Lines changed: 159 additions & 31 deletions

File tree

‎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: 90 additions & 18 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
}
@@ -134,7 +146,7 @@ describe("registerFileRoutes", () => {
134146
expect(result.after).toContain('data-duration="7"');
135147
expect(result.after).toContain(`id="${result.hostId}"`);
136148
expect(result.version).toBe(fileContentVersion(result.after));
137-
expect(consumeFileWriteReceipt(join(projectDir, "index.html"))).toEqual({
149+
expect(consumeFileWriteReceipt(join(projectDir, "index.html"), result.version)).toEqual({
138150
path: "index.html",
139151
version: result.version,
140152
writeToken: "studio-insert-1",
@@ -374,7 +386,7 @@ describe("registerFileRoutes", () => {
374386
expect(payload.version).toBe(fileContentVersion("after"));
375387
expect(payload.writeToken).toBe("studio-write-1");
376388
expect(response.headers.get("etag")).toBe(payload.version);
377-
expect(consumeFileWriteReceipt(join(projectDir, "index.html"))).toEqual({
389+
expect(consumeFileWriteReceipt(join(projectDir, "index.html"), payload.version!)).toEqual({
378390
path: "index.html",
379391
version: payload.version,
380392
writeToken: "studio-write-1",
@@ -458,9 +470,10 @@ describe("registerFileRoutes", () => {
458470
);
459471

460472
expect(response.status).toBe(200);
461-
expect(consumeFileWriteReceipt(join(projectDir, "index.html"))).toEqual({
473+
const version = fileContentVersion(readFileSync(join(projectDir, "index.html"), "utf-8"));
474+
expect(consumeFileWriteReceipt(join(projectDir, "index.html"), version)).toEqual({
462475
path: "index.html",
463-
version: fileContentVersion(readFileSync(join(projectDir, "index.html"), "utf-8")),
476+
version,
464477
writeToken: "studio-patch-1",
465478
});
466479
});
@@ -473,16 +486,21 @@ describe("registerFileRoutes", () => {
473486
const app = new Hono();
474487
registerFileRoutes(app, createAdapter(projectDir));
475488

476-
const response = await postElementPatchBatch(app, "index.html", [
477-
{
478-
target: { id: "back" },
479-
operations: [{ type: "inline-style", property: "z-index", value: "2" }],
480-
},
481-
{
482-
target: { id: "front" },
483-
operations: [{ type: "inline-style", property: "z-index", value: "1" }],
484-
},
485-
]);
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+
);
486504
expect(response.status).toBe(200);
487505
const payload = (await response.json()) as {
488506
changed?: boolean;
@@ -498,6 +516,12 @@ describe("registerFileRoutes", () => {
498516
expect(payload.content).toContain('id="back" style="z-index: 2"');
499517
expect(payload.content).toContain('id="front" style="z-index: 1"');
500518
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+
});
501525
expect(readdirSync(join(projectDir, ".hyperframes", "backup"))).toHaveLength(1);
502526
});
503527

@@ -559,6 +583,52 @@ describe("registerFileRoutes", () => {
559583
expect(existsSync(join(projectDir, ".hyperframes", "backup"))).toBe(false);
560584
});
561585

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+
562632
it("refuses every file when one batch contains an unmatched target", async () => {
563633
const projectDir = createProjectDir();
564634
const indexOriginal = '<div id="present" style="z-index: 1">Present</div>';
@@ -772,7 +842,9 @@ describe("registerFileRoutes", () => {
772842
expect(payload.files[0].after).toContain('id="a-split"');
773843
expect(payload.files[0].after).toContain('id="b-split"');
774844
expect(readFileSync(join(projectDir, "index.html"), "utf-8")).toBe(payload.files[0].after);
775-
expect(consumeFileWriteReceipt(join(projectDir, "index.html"))).toEqual({
845+
expect(
846+
consumeFileWriteReceipt(join(projectDir, "index.html"), payload.files[0].version),
847+
).toEqual({
776848
path: "index.html",
777849
version: payload.files[0].version,
778850
writeToken: "cut-test",

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

Lines changed: 33 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -400,30 +400,56 @@ export function commitElementPatchBatches(
400400
return { durable: true, files };
401401
}
402402

403+
function commitElementPatchBatchesWithReceipts(
404+
c: RouteContext,
405+
projectDir: string,
406+
batches: ElementPatchBatchRequest[],
407+
): ReturnType<typeof commitElementPatchBatches> {
408+
const result = commitElementPatchBatches(projectDir, batches);
409+
if ("error" in result || !result.durable) return result;
410+
411+
for (const file of result.files) {
412+
if (!file.changed) continue;
413+
const absPath = resolveWithinProject(projectDir, file.sourceFile);
414+
if (!absPath) throw new Error(`Committed element patch escaped project: ${file.sourceFile}`);
415+
recordMutationReceipt(c, file.sourceFile, absPath, file.after);
416+
}
417+
return result;
418+
}
419+
403420
/**
404-
* Write a mutation result, and leave behind the receipt that claims it.
421+
* Record the receipt that claims a mutation result.
405422
*
406423
* The file watcher broadcasts every write, including the ones Studio itself just
407424
* asked for. The receipt is what lets the client tell its own echo from an agent
408425
* or an editor writing the file behind its back: without one, the client treats
409426
* its own edit as an external change and does a full preview reload, which blanks
410427
* the stage for a few hundred milliseconds right after the user typed. Every
411-
* mutation route writes through here so no route can forget.
428+
* mutation route records through here so no route can forget.
412429
*/
413-
function writeFileWithReceipt(
430+
function recordMutationReceipt(
414431
c: RouteContext,
415432
filePath: string,
416433
absPath: string,
417434
html: string,
418435
): { version: string; writeToken: string } {
419-
writeFileSync(absPath, html, "utf-8");
420-
// The synchronous write cannot yield before its receipt is recorded; keep this block await-free.
421436
const version = fileContentVersion(html);
422437
const writeToken = createWriteToken(c.req.header("X-Hyperframes-Write-Token"));
423438
recordFileWriteReceipt(absPath, { path: filePath, version, writeToken });
424439
return { version, writeToken };
425440
}
426441

442+
function writeFileWithReceipt(
443+
c: RouteContext,
444+
filePath: string,
445+
absPath: string,
446+
html: string,
447+
): { version: string; writeToken: string } {
448+
writeFileSync(absPath, html, "utf-8");
449+
// The synchronous write cannot yield before its receipt is recorded; keep this block await-free.
450+
return recordMutationReceipt(c, filePath, absPath, html);
451+
}
452+
427453
function writeMutationResult(
428454
c: RouteContext,
429455
projectDir: string,
@@ -2755,7 +2781,7 @@ export function registerFileRoutes(api: Hono, adapter: StudioApiAdapter): void {
27552781
const unsafeFields = findUnsafeElementPatchBatchValues(body.batches);
27562782
if (unsafeFields.length > 0) return rejectUnsafeMutationValues(c, unsafeFields);
27572783

2758-
const result = commitElementPatchBatches(project.dir, body.batches);
2784+
const result = commitElementPatchBatchesWithReceipts(c, project.dir, body.batches);
27592785
if ("error" in result) {
27602786
return elementPatchBatchCommitErrorResponse(c, result.error, result.sourceFile);
27612787
}
@@ -2783,7 +2809,7 @@ export function registerFileRoutes(api: Hono, adapter: StudioApiAdapter): void {
27832809
return rejectUnsafeMutationValues(c, unsafeFields);
27842810
}
27852811

2786-
const result = commitElementPatchBatches(ctx.project.dir, [batch]);
2812+
const result = commitElementPatchBatchesWithReceipts(c, ctx.project.dir, [batch]);
27872813
if ("error" in result) {
27882814
return elementPatchBatchCommitErrorResponse(c, result.error, result.sourceFile);
27892815
}

0 commit comments

Comments
 (0)