Skip to content

Write HTML. Render video. Built for agents.

fix(studio-server): studio element edits keep a save that lands while they apply (#4510)

Miguel Ángel0f14691c7b57
diff --git a/packages/studio-server/src/helpers/applyFileMutations.test.ts b/packages/studio-server/src/helpers/applyFileMutations.test.ts
index 7aa1479e67..21ccb4b4d7 100644
--- a/packages/studio-server/src/helpers/applyFileMutations.test.ts
+++ b/packages/studio-server/src/helpers/applyFileMutations.test.ts
@@ -2,10 +2,10 @@ import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import { tmpdir } from "node:os";
import { describe, expect, it } from "vitest";
-import { applyFileMutations } from "./applyFileMutations.js";
+import { applyFileMutations, FileChangedError } from "./applyFileMutations.js";
import { fileContentVersion, identifyFileWrite, resetFileWriteReceipts } from "./fileVersion.js";
-function expectStaleMutation(after: string): void {
+function expectStaleMutation(after: string, pinVersion = true): void {
const projectDir = mkdtempSync(join(tmpdir(), "hf-mutation-version-"));
const path = join(projectDir, "index.html");
try {
@@ -14,9 +14,15 @@ function expectStaleMutation(after: string): void {
writeFileSync(path, "external", "utf8");
expect(() =>
applyFileMutations(projectDir, [
- { sourceFile: "index.html", absPath: path, before: "before", after, expectedVersion },
+ {
+ sourceFile: "index.html",
+ absPath: path,
+ before: "before",
+ after,
+ ...(pinVersion ? { expectedVersion } : {}),
+ },
]),
- ).toThrow("file changed since the timeline was read");
+ ).toThrow(FileChangedError);
expect(readFileSync(path, "utf8")).toBe("external");
} finally {
rmSync(projectDir, { recursive: true, force: true });
@@ -95,6 +101,10 @@ describe("applyFileMutations", () => {
}
});
+ it("refuses a file that changed since the caller read it, without an expected version", () => {
+ expectStaleMutation("after", false);
+ });
+
it("clears receipts for writes rolled back after a partial batch", () => {
resetFileWriteReceipts();
const projectDir = mkdtempSync(join(tmpdir(), "hf-mutation-rollback-"));
diff --git a/packages/studio-server/src/helpers/applyFileMutations.ts b/packages/studio-server/src/helpers/applyFileMutations.ts
index ef4ac0f3b4..7d4f1daaf6 100644
--- a/packages/studio-server/src/helpers/applyFileMutations.ts
+++ b/packages/studio-server/src/helpers/applyFileMutations.ts
@@ -43,7 +43,7 @@ export function applyFileMutations(
PreparedMutation & { version: string; writeToken: string; written: boolean }
> = [];
for (const mutation of prepared)
- assertExpectedVersion(mutation.expectedVersion, readFileSync(mutation.absPath, "utf-8"));
+ assertExpectedVersion(mutation, readFileSync(mutation.absPath, "utf-8"));
try {
for (const mutation of prepared) {
results.push(applyOneMutation(projectDir, mutation, requestToken, writeFile, attempted));
@@ -80,7 +80,7 @@ function applyOneMutation(
attempted: Array<PreparedMutation & { version: string; writeToken: string; written: boolean }>,
): AppliedFileMutation {
const current = readFileSync(mutation.absPath, "utf-8");
- assertExpectedVersion(mutation.expectedVersion, current);
+ assertExpectedVersion(mutation, current);
if (mutation.after === mutation.before) {
return {
...mutation,
@@ -93,6 +93,7 @@ function applyOneMutation(
}
const backup = snapshotBeforeWrite(projectDir, mutation.absPath);
if (backup.error) throw new Error(`backup failed: ${backup.error}`);
+ assertExpectedVersion(mutation, readFileSync(mutation.absPath, "utf-8"));
const before = current;
const version = fileContentVersion(mutation.after);
const writeToken = createWriteToken(requestToken);
@@ -115,8 +116,16 @@ function applyOneMutation(
};
}
-function assertExpectedVersion(expectedVersion: string | undefined, current: string): void {
- if (expectedVersion !== undefined && fileContentVersion(current) !== expectedVersion) {
- throw new Error("file changed since the timeline was read");
+export class FileChangedError extends Error {
+ constructor(readonly sourceFile: string) {
+ super("file changed since the timeline was read");
}
}
+
+function assertExpectedVersion(mutation: PreparedMutation, current: string): void {
+ const stale =
+ mutation.expectedVersion === undefined
+ ? current !== mutation.before
+ : fileContentVersion(current) !== mutation.expectedVersion;
+ if (stale) throw new FileChangedError(mutation.sourceFile);
+}
diff --git a/packages/studio-server/src/helpers/atomicFile.test.ts b/packages/studio-server/src/helpers/atomicFile.test.ts
index 9e8c8b084d..fe8aae462d 100644
--- a/packages/studio-server/src/helpers/atomicFile.test.ts
+++ b/packages/studio-server/src/helpers/atomicFile.test.ts
@@ -1,6 +1,6 @@
import { afterEach, describe, expect, it } from "vitest";
import * as fs from "node:fs";
-import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { lstatSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { replaceFileAtomically } from "./atomicFile.js";
@@ -13,6 +13,24 @@ describe("replaceFileAtomically", () => {
dirs.length = 0;
});
+ // Windows needs a privilege to create symlinks.
+ it.skipIf(process.platform === "win32")(
+ "replaces a link at the path, never writing its target",
+ () => {
+ const dir = mkdtempSync(join(tmpdir(), "atomic-file-test-"));
+ dirs.push(dir);
+ const target = join(dir, "target.html");
+ const link = join(dir, "link.html");
+ writeFileSync(target, "old");
+ symlinkSync(target, link);
+
+ replaceFileAtomically(link, "new", 0o644);
+
+ expect(readFileSync(target, "utf-8")).toBe("old");
+ expect(lstatSync(link).isSymbolicLink()).toBe(false);
+ },
+ );
+
it("writes the sibling completely before replacing the project file", () => {
const dir = mkdtempSync(join(tmpdir(), "atomic-file-test-"));
dirs.push(dir);
diff --git a/packages/studio-server/src/helpers/fileVersion.test.ts b/packages/studio-server/src/helpers/fileVersion.test.ts
index aa7151b230..e203ec804f 100644
--- a/packages/studio-server/src/helpers/fileVersion.test.ts
+++ b/packages/studio-server/src/helpers/fileVersion.test.ts
@@ -1,5 +1,9 @@
+import { mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
import { afterEach, describe, expect, it, vi } from "vitest";
import {
+ DELETED_VERSION,
identifyFileWrite,
fileContentVersion,
recordFileWriteReceipt,
@@ -31,6 +35,41 @@ describe("file versions and write receipts", () => {
expect(identifyFileWrite("/project/index.html", fileContentVersion("other"))).toBeNull();
});
+ // Windows needs a privilege to create symlinks.
+ it.skipIf(process.platform === "win32")(
+ "recognises a deletion and a creation in a linked folder, recorded before the file changes",
+ () => {
+ const real = mkdtempSync(join(tmpdir(), "hf-receipt-"));
+ const linked = `${real}-link`;
+ symlinkSync(real, linked, "dir");
+ try {
+ const file = join(linked, "index.html");
+ writeFileSync(file, "a");
+ recordFileWriteReceipt(file, {
+ path: "index.html",
+ version: DELETED_VERSION,
+ writeToken: "undo",
+ });
+ rmSync(file);
+ expect(identifyFileWrite(file, DELETED_VERSION)?.writeToken).toBe("undo");
+
+ const version = fileContentVersion("b");
+ recordFileWriteReceipt(file, { path: "index.html", version, writeToken: "redo" });
+ writeFileSync(file, "b");
+ expect(identifyFileWrite(file, version)?.writeToken).toBe("redo");
+
+ const nested = join(linked, "gone", "index.html");
+ recordFileWriteReceipt(nested, { path: "gone/index.html", version, writeToken: "restore" });
+ mkdirSync(join(real, "gone"));
+ writeFileSync(nested, "b");
+ expect(identifyFileWrite(nested, version)?.writeToken).toBe("restore");
+ } finally {
+ rmSync(linked, { force: true });
+ rmSync(real, { recursive: true, force: true });
+ }
+ },
+ );
+
it("stops recognising a write once the receipt TTL has passed", () => {
vi.useFakeTimers();
try {
diff --git a/packages/studio-server/src/helpers/fileVersion.ts b/packages/studio-server/src/helpers/fileVersion.ts
index 3c3a94dc66..f2249c7f83 100644
--- a/packages/studio-server/src/helpers/fileVersion.ts
+++ b/packages/studio-server/src/helpers/fileVersion.ts
@@ -1,4 +1,5 @@
import { createHash, randomUUID } from "node:crypto";
+import { realFilePath } from "./safePath.js";
export interface FileWriteReceipt {
path: string;
@@ -47,7 +48,8 @@ export function createWriteToken(requestToken?: string): string {
return token && token.length <= 200 ? token : randomUUID();
}
-export function recordFileWriteReceipt(absPath: string, receipt: FileWriteReceipt): void {
+export function recordFileWriteReceipt(filePath: string, receipt: FileWriteReceipt): void {
+ const absPath = realFilePath(filePath);
const now = Date.now();
const current = (receipts.get(absPath) ?? []).filter(
(entry) => now - entry.recordedAt < RECEIPT_TTL_MS,
@@ -56,7 +58,8 @@ export function recordFileWriteReceipt(absPath: string, receipt: FileWriteReceip
receipts.set(absPath, current);
}
-export function clearFileWriteReceipt(absPath: string, version: string, writeToken: string): void {
+export function clearFileWriteReceipt(filePath: string, version: string, writeToken: string): void {
+ const absPath = realFilePath(filePath);
const current = (receipts.get(absPath) ?? []).filter(
(entry) => entry.version !== version || entry.writeToken !== writeToken,
);
@@ -73,9 +76,10 @@ export function clearFileWriteReceipt(absPath: string, version: string, writeTok
* TTL removes a receipt.
*/
export function identifyFileWrite(
- absPath: string,
+ filePath: string,
expectedVersion: string,
): FileWriteReceipt | null {
+ const absPath = realFilePath(filePath);
const now = Date.now();
const current = (receipts.get(absPath) ?? []).filter(
(entry) => now - entry.recordedAt < RECEIPT_TTL_MS,
diff --git a/packages/studio-server/src/helpers/hfIdPersist.noFollow.test.ts b/packages/studio-server/src/helpers/hfIdPersist.noFollow.test.ts
new file mode 100644
index 0000000000..15a6062a46
--- /dev/null
+++ b/packages/studio-server/src/helpers/hfIdPersist.noFollow.test.ts
@@ -0,0 +1,44 @@
+import { lstatSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { afterEach, expect, it, vi } from "vitest";
+
+const swap = vi.hoisted(() => ({ to: "" }));
+vi.mock("./atomicFile.js", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("./atomicFile.js")>();
+ const fs = await import("node:fs");
+ return {
+ ...actual,
+ // A link to an outside file swapped in after the stamp's own no-follow checks.
+ replaceFileAtomically: (...args: Parameters<typeof actual.replaceFileAtomically>) => {
+ fs.rmSync(args[0]);
+ fs.symlinkSync(swap.to, args[0]);
+ return actual.replaceFileAtomically(...args);
+ },
+ };
+});
+
+const { stampFileHfIds } = await import("./hfIdPersist.js");
+const dirs: string[] = [];
+afterEach(() => {
+ for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true });
+});
+
+// Windows needs a privilege to create symlinks.
+it.skipIf(process.platform === "win32")(
+ "stamps over a symlink swapped in at the path without writing through it",
+ () => {
+ const dir = mkdtempSync(join(tmpdir(), "hf-stamp-nofollow-"));
+ dirs.push(dir);
+ swap.to = join(dir, "outside.html");
+ writeFileSync(swap.to, "outside");
+ const file = join(dir, "index.html");
+ writeFileSync(file, `<div class="clip"><p>Hi</p></div>`);
+
+ stampFileHfIds(file);
+
+ expect(readFileSync(swap.to, "utf-8")).toBe("outside");
+ expect(readFileSync(file, "utf-8")).toContain("data-hf-id");
+ expect(lstatSync(file).isSymbolicLink()).toBe(false);
+ },
+);
diff --git a/packages/studio-server/src/helpers/safePath.ts b/packages/studio-server/src/helpers/safePath.ts
index 1715c40ccb..3d9ccc3a3e 100644
--- a/packages/studio-server/src/helpers/safePath.ts
+++ b/packages/studio-server/src/helpers/safePath.ts
@@ -1,11 +1,34 @@
-import { join } from "node:path";
-import { readdirSync, type Dirent } from "node:fs";
+import { basename, dirname, isAbsolute, join, relative, sep } from "node:path";
+import { readdirSync, realpathSync, type Dirent } from "node:fs";
+import { resolveWithinProject } from "@hyperframes/core";
// `isSafePath` lives at the package root so non-studio-api layers (compiler,
// CLI, engine) can share it without a backwards dependency on studio-api.
// Re-exported here for back-compat with existing `../helpers/safePath.js` imports.
export { isSafePath, resolveWithinProject } from "@hyperframes/core";
+/** The real path; for a path not there (yet, or any more), the nearest existing folder's real path plus the rest. */
+export function realFilePath(filePath: string): string {
+ try {
+ return realpathSync(filePath);
+ } catch {
+ const dir = dirname(filePath);
+ return dir === filePath ? filePath : join(realFilePath(dir), basename(filePath));
+ }
+}
+
+/**
+ * `resolveWithinProject` with every link inside the project resolved now, so a write to the result lands on the
+ * file checked here even if a link on the way is retargeted before the write.
+ */
+export function pinWithinProject(base: string, relativePath: string): string | null {
+ const checked = resolveWithinProject(base, relativePath);
+ if (!checked) return null;
+ const inside = relative(realFilePath(base), realFilePath(checked));
+ const escapes = inside === ".." || inside.startsWith(`..${sep}`) || isAbsolute(inside);
+ return escapes ? null : join(base, inside);
+}
+
const IGNORE_DIRS = new Set([
".thumbnails",
".transcode-cache",
diff --git a/packages/studio-server/src/routes/files.patchRace.test.ts b/packages/studio-server/src/routes/files.patchRace.test.ts
new file mode 100644
index 0000000000..c03862028f
--- /dev/null
+++ b/packages/studio-server/src/routes/files.patchRace.test.ts
@@ -0,0 +1,308 @@
+// @vitest-environment node
+import {
+ lstatSync,
+ mkdirSync,
+ mkdtempSync,
+ readFileSync,
+ rmSync,
+ symlinkSync,
+ writeFileSync,
+} from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { Hono } from "hono";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { fileContentVersion, identifyFileWrite } from "../helpers/fileVersion";
+import { registerFileRoutes } from "./files";
+
+const hooks = vi.hoisted(() => ({
+ transforming: undefined as (() => void) | undefined,
+ backingUp: undefined as (() => void) | undefined,
+}));
+vi.mock("../helpers/backupJournal.js", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("../helpers/backupJournal.js")>();
+ return {
+ ...actual,
+ snapshotBeforeWrite: (...args: Parameters<typeof actual.snapshotBeforeWrite>) => {
+ hooks.backingUp?.();
+ return actual.snapshotBeforeWrite(...args);
+ },
+ };
+});
+vi.mock("../helpers/sourceMutation.js", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("../helpers/sourceMutation.js")>();
+ return {
+ ...actual,
+ patchElementInHtml: (...args: Parameters<typeof actual.patchElementInHtml>) => {
+ hooks.transforming?.();
+ return actual.patchElementInHtml(...args);
+ },
+ removeElementFromHtml: (...args: Parameters<typeof actual.removeElementFromHtml>) => {
+ hooks.transforming?.();
+ return actual.removeElementFromHtml(...args);
+ },
+ };
+});
+
+const dirs: string[] = [];
+afterEach(() => {
+ hooks.transforming = undefined;
+ hooks.backingUp = undefined;
+ for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true });
+});
+
+const ORIGINAL = `<h1 id="title">Title</h1><p id="note">old</p>`;
+const saved = (n: number | string) => `<h1 id="title">Title</h1><p id="note">agent ${n}</p>`;
+const zIndex = [{ type: "inline-style", property: "z-index", value: "2" }];
+const ROUTES = {
+ "patch-element": ["patch-element/index.html", { target: { id: "title" }, operations: zIndex }],
+ "patch-elements-batch": [
+ "patch-elements-batch/index.html",
+ { patches: [{ target: { id: "title" }, operations: zIndex }] },
+ ],
+ "patch-element-batches": [
+ "patch-element-batches",
+ {
+ batches: [
+ { sourceFile: "index.html", patches: [{ target: { id: "title" }, operations: zIndex }] },
+ ],
+ },
+ ],
+} as const;
+
+function project() {
+ const dir = mkdtempSync(join(tmpdir(), "hf-patch-race-"));
+ dirs.push(dir);
+ const path = join(dir, "index.html");
+ writeFileSync(path, ORIGINAL);
+ const app = new Hono();
+ registerFileRoutes(app, {
+ listProjects: () => [],
+ resolveProject: async (id: string) => ({ id, dir }),
+ bundle: async () => null,
+ lint: async () => ({ findings: [] }),
+ runtimeUrl: "/api/runtime.js",
+ rendersDir: () => "/tmp/renders",
+ startRender: () => ({ id: "job", status: "rendering", progress: 0, outputPath: "/tmp/o.mp4" }),
+ });
+ const post = (route: string, body: unknown) =>
+ app.request(`http://localhost/projects/demo/file-mutations/${route}`, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(body),
+ });
+ return { post, path, read: () => readFileSync(path, "utf-8") };
+}
+
+describe("element edits with another writer racing them", () => {
+ it.each(Object.entries(ROUTES))(
+ "%s keeps a write that lands mid-edit and applies the edit on top",
+ async (_, [route, body]) => {
+ const { post, path, read } = project();
+ hooks.transforming = () => {
+ hooks.transforming = undefined;
+ writeFileSync(path, saved(1));
+ };
+
+ expect((await post(route, body)).status).toBe(200);
+ expect(read()).toContain("agent 1");
+ expect(read()).toContain("z-index: 2");
+ },
+ );
+
+ it.each(Object.entries(ROUTES))(
+ "%s answers 409 after three raced tries and keeps the other write",
+ async (_, [route, body]) => {
+ const { post, path, read } = project();
+ let writes = 0;
+ hooks.transforming = () => {
+ writes += 1;
+ writeFileSync(path, saved(writes));
+ };
+
+ const response = await post(route, body);
+
+ expect(response.status).toBe(409);
+ expect(await response.json()).toMatchObject({ error: "file changed", conflict: true });
+ expect(writes).toBe(3);
+ expect(read()).toBe(saved(writes));
+ },
+ );
+
+ it.each(Object.entries(ROUTES))(
+ "%s refolds when a write lands while it takes its backup",
+ async (_, [route, body]) => {
+ const { post, path, read } = project();
+ hooks.backingUp = () => {
+ hooks.backingUp = undefined;
+ writeFileSync(path, saved(1));
+ };
+
+ expect((await post(route, body)).status).toBe(200);
+ expect(read()).toContain("agent 1");
+ expect(read()).toContain("z-index: 2");
+ },
+ );
+
+ it("insert-composition answers 409 instead of writing over a save that lands during its backup", async () => {
+ const { post, path, read } = project();
+ const page = `<!doctype html><html><body><div data-composition-id="main" data-width="640" data-height="360" data-duration="2"></div></body></html>`;
+ writeFileSync(path, page);
+ writeFileSync(
+ join(path, "..", "child.html"),
+ `<template><div data-composition-id="child" data-width="640" data-height="360" data-duration="3"></div></template>`,
+ );
+ hooks.backingUp = () => writeFileSync(path, saved("x"));
+
+ const response = await post("insert-composition/index.html", {
+ sourcePath: "child.html",
+ start: 0,
+ track: 0,
+ expectedVersion: fileContentVersion(page),
+ });
+
+ expect(response.status).toBe(409);
+ expect(read()).toBe(saved("x"));
+ });
+
+ // Windows needs a privilege to create symlinks.
+ it.skipIf(process.platform === "win32").each(Object.entries(ROUTES))(
+ "%s writes the linked file it checked, though the link is retargeted outside before the write",
+ async (_, [route, body]) => {
+ const { post, path, read } = project();
+ const alias = join(path, "..", "alias.html");
+ symlinkSync(path, alias);
+ const outsideDir = mkdtempSync(join(tmpdir(), "hf-patch-outside-"));
+ dirs.push(outsideDir);
+ const outside = join(outsideDir, "index.html");
+ hooks.backingUp = () => {
+ hooks.backingUp = undefined;
+ writeFileSync(outside, read());
+ rmSync(alias);
+ symlinkSync(outside, alias);
+ };
+ const aliased = JSON.parse(JSON.stringify(body).replaceAll("index.html", "alias.html"));
+
+ expect((await post(route.replace("index.html", "alias.html"), aliased)).status).toBe(200);
+ expect(readFileSync(outside, "utf-8")).toBe(ORIGINAL);
+ expect(read()).toContain("z-index: 2");
+ },
+ );
+
+ it.skipIf(process.platform === "win32").each(Object.entries(ROUTES))(
+ "%s writes the file it checked, though a folder link on its path is retargeted outside",
+ async (_, [route, body]) => {
+ const { post, path } = project();
+ const real = join(path, "..", "real");
+ mkdirSync(real);
+ writeFileSync(join(real, "index.html"), ORIGINAL);
+ const scenes = join(path, "..", "scenes");
+ symlinkSync(real, scenes, "dir");
+ const outside = mkdtempSync(join(tmpdir(), "hf-patch-outside-"));
+ dirs.push(outside);
+ hooks.backingUp = () => {
+ hooks.backingUp = undefined;
+ writeFileSync(join(outside, "index.html"), ORIGINAL);
+ rmSync(scenes);
+ symlinkSync(outside, scenes, "dir");
+ };
+ const linked = JSON.parse(JSON.stringify(body).replaceAll("index.html", "scenes/index.html"));
+
+ expect((await post(route.replace("index.html", "scenes/index.html"), linked)).status).toBe(
+ 200,
+ );
+ expect(readFileSync(join(outside, "index.html"), "utf-8")).toBe(ORIGINAL);
+ expect(readFileSync(join(real, "index.html"), "utf-8")).toContain("z-index: 2");
+ },
+ );
+
+ it.skipIf(process.platform === "win32")(
+ "split-batch writes the linked file it checked, though the link is retargeted outside",
+ async () => {
+ const { post, path, read } = project();
+ const clip = '<div id="a" data-start="0" data-duration="4">A</div>';
+ writeFileSync(path, clip);
+ const alias = join(path, "..", "alias.html");
+ symlinkSync(path, alias);
+ const outsideDir = mkdtempSync(join(tmpdir(), "hf-patch-outside-"));
+ dirs.push(outsideDir);
+ const outside = join(outsideDir, "index.html");
+ hooks.backingUp = () => {
+ hooks.backingUp = undefined;
+ writeFileSync(outside, clip);
+ rmSync(alias);
+ symlinkSync(outside, alias);
+ };
+ const target = { target: { id: "a" }, originalId: "a", splitTime: 2, elementStart: 0 };
+ const files = [
+ {
+ path: "alias.html",
+ expectedVersion: fileContentVersion(clip),
+ targets: [{ ...target, elementDuration: 4 }],
+ },
+ ];
+
+ expect((await post("split-batch", { files, transactionToken: "cut" })).status).toBe(200);
+ expect(readFileSync(outside, "utf-8")).toBe(clip);
+ expect(read()).toContain('id="a-split"');
+ },
+ );
+
+ it.skipIf(process.platform === "win32").each(Object.entries(ROUTES))(
+ "%s edits a linked file through its link and keeps the link",
+ async (_, [route, body]) => {
+ const { post, path, read } = project();
+ const alias = join(path, "..", "alias.html");
+ symlinkSync(path, alias);
+ const aliased = JSON.parse(JSON.stringify(body).replaceAll("index.html", "alias.html"));
+
+ expect((await post(route.replace("index.html", "alias.html"), aliased)).status).toBe(200);
+ expect(lstatSync(alias).isSymbolicLink()).toBe(true);
+ expect(read()).toContain("z-index: 2");
+ expect(identifyFileWrite(path, fileContentVersion(read()))).not.toBeNull();
+ },
+ );
+
+ it("patch-element answers with the version of what it wrote", async () => {
+ const { post, read } = project();
+
+ const response = await post(...ROUTES["patch-element"]);
+
+ const version = fileContentVersion(read());
+ expect(response.headers.get("ETag")).toBe(version);
+ expect(await response.json()).toMatchObject({ changed: true, version, content: read() });
+ });
+
+ it("refolds a two-file batch when its first file changes after it was read", async () => {
+ const { post, path, read } = project();
+ const scene = join(path, "..", "scene.html");
+ writeFileSync(scene, `<h2 id="sub">Sub</h2>`);
+ let folds = 0;
+ hooks.transforming = () => {
+ folds += 1;
+ if (folds === 2) writeFileSync(path, saved(1));
+ };
+
+ const response = await post("patch-element-batches", {
+ batches: [
+ { sourceFile: "index.html", patches: [{ target: { id: "title" }, operations: zIndex }] },
+ { sourceFile: "scene.html", patches: [{ target: { id: "sub" }, operations: zIndex }] },
+ ],
+ });
+
+ expect(response.status).toBe(200);
+ expect(read()).toContain("agent 1");
+ expect(read()).toContain("z-index: 2");
+ expect(readFileSync(scene, "utf-8")).toContain("z-index: 2");
+ });
+
+ it("remove-element answers 409 instead of writing over a save that lands mid-edit", async () => {
+ const { post, path, read } = project();
+ hooks.transforming = () => writeFileSync(path, saved("x"));
+
+ const response = await post("remove-element/index.html", { target: { id: "note" } });
+
+ expect(response.status).toBe(409);
+ expect(read()).toBe(saved("x"));
+ });
+});
diff --git a/packages/studio-server/src/routes/files.ts b/packages/studio-server/src/routes/files.ts
index 46830b93e9..24b7c78264 100644
--- a/packages/studio-server/src/routes/files.ts
+++ b/packages/studio-server/src/routes/files.ts
@@ -27,14 +27,14 @@ import { isAudioFile } from "../helpers/mime.js";
import { replaceFileAtomically } from "../helpers/atomicFile.js";
import { generateWaveformCache } from "../helpers/waveform.js";
import { validateUploadedMediaBuffer } from "../helpers/mediaValidation.js";
-import { isSafePath, resolveWithinProject } from "../helpers/safePath.js";
+import { isSafePath, pinWithinProject, resolveWithinProject } from "../helpers/safePath.js";
import { backupPathForResponse, snapshotBeforeWrite } from "../helpers/backupJournal.js";
import {
createWriteToken,
fileContentVersion,
recordFileWriteReceipt,
} from "../helpers/fileVersion.js";
-import { applyFileMutations } from "../helpers/applyFileMutations.js";
+import { applyFileMutations, FileChangedError } from "../helpers/applyFileMutations.js";
import {
findUnsafeDomPatchValues,
findUnsafeMutationValues,
@@ -176,7 +176,7 @@ async function resolveProjectPath(
c: RouteContext,
adapter: StudioApiAdapter,
route: string,
- opts?: { mustExist?: boolean },
+ opts?: { mustExist?: boolean; pin?: boolean },
) {
const id = c.req.param("id");
const project = await adapter.resolveProject(id);
@@ -203,7 +203,8 @@ async function resolveProjectPath(
return { error: c.json({ error: "forbidden", why: "nul" }, 403) } as const;
}
- const absPath = resolveWithinProject(project.dir, filePath);
+ // An edit pins its target; create-only writes use `wx`, and a delete or rename acts on a link itself.
+ const absPath = (opts?.pin ? pinWithinProject : resolveWithinProject)(project.dir, filePath);
if (!absPath) {
if (isDanglingSymlinkInProject(project.dir, resolve(project.dir, filePath))) {
return { error: c.json({ error: "not found", why: "dangling_symlink" }, 404) } as const;
@@ -221,13 +222,13 @@ async function resolveProjectPath(
function resolveProjectFile(
c: RouteContext,
adapter: StudioApiAdapter,
- opts?: { mustExist?: boolean },
+ opts?: { mustExist?: boolean; pin?: boolean },
) {
return resolveProjectPath(c, adapter, "files", opts);
}
function resolveFileMutationContext(c: RouteContext, adapter: StudioApiAdapter, operation: string) {
- return resolveProjectPath(c, adapter, `file-mutations/${operation}`);
+ return resolveProjectPath(c, adapter, `file-mutations/${operation}`, { pin: true });
}
type MutationTarget = {
@@ -361,13 +362,19 @@ function foldElementPatches(
return { content, matched };
}
+const PATCH_CONFLICT_ATTEMPTS = 3;
+
+type ElementPatchCommitResult =
+ | { error: "duplicate" | "forbidden" | "not-found" | "conflict"; sourceFile: string }
+ | { durable: boolean; files: ElementPatchBatchFileResult[] };
+
/**
* The single commit owner for element patch batches. All files are resolved,
* read, and folded before the first write; any unmatched target refuses the
- * whole request. Studio Server is intentionally single-process; within that
- * process the final snapshots/writes are synchronous, so another route cannot
- * interleave once the commit section begins. A multi-process deployment must
- * replace this process-local guarantee with a shared per-project file lock.
+ * whole request, and a write from elsewhere mid-fold refolds before it answers 409.
+ * Studio Server is single-process; within it the final snapshots/writes are
+ * synchronous, so another route cannot interleave once the commit begins. A
+ * multi-process deployment needs a shared per-project file lock instead.
*/
export function commitElementPatchBatches(
projectDir: string,
@@ -375,9 +382,24 @@ export function commitElementPatchBatches(
writeFile: (path: string, content: string, encoding: "utf-8") => void = (path, content) =>
replaceFileAtomically(path, content, statSync(path).mode),
requestToken?: string,
-):
- | { error: "duplicate" | "forbidden" | "not-found"; sourceFile: string }
- | { durable: boolean; files: ElementPatchBatchFileResult[] } {
+): ElementPatchCommitResult {
+ for (let attempt = 1; ; attempt += 1) {
+ try {
+ return foldAndCommitElementPatchBatches(projectDir, batches, writeFile, requestToken);
+ } catch (error) {
+ if (!(error instanceof FileChangedError)) throw error;
+ if (attempt === PATCH_CONFLICT_ATTEMPTS)
+ return { error: "conflict", sourceFile: error.sourceFile };
+ }
+ }
+}
+
+function foldAndCommitElementPatchBatches(
+ projectDir: string,
+ batches: ElementPatchBatchRequest[],
+ writeFile: (path: string, content: string, encoding: "utf-8") => void,
+ requestToken: string | undefined,
+): ElementPatchCommitResult {
const resolvedPaths = new Set<string>();
const prepared: Array<{
sourceFile: string;
@@ -388,7 +410,7 @@ export function commitElementPatchBatches(
}> = [];
for (const batch of batches) {
- const absPath = resolveWithinProject(projectDir, batch.sourceFile);
+ const absPath = pinWithinProject(projectDir, batch.sourceFile);
if (!absPath) return { error: "forbidden", sourceFile: batch.sourceFile };
if (resolvedPaths.has(absPath)) return { error: "duplicate", sourceFile: batch.sourceFile };
resolvedPaths.add(absPath);
@@ -453,7 +475,7 @@ function commitElementPatchBatchesWithReceipts(
return commitElementPatchBatches(
projectDir,
batches,
- writeFileSync,
+ undefined,
c.req.header("X-Hyperframes-Write-Token"),
);
}
@@ -497,9 +519,13 @@ function writeMutationResult(
filePath: string,
absPath: string,
html: string,
+ original: string,
): { backupPath: string | null; version: string } | Response {
const backup = snapshotBeforeWrite(projectDir, absPath);
if (backup.error) return c.json({ error: `backup failed: ${backup.error}` }, 500);
+ if (readFileSync(absPath, "utf-8") !== original) {
+ return c.json({ error: "file changed", conflict: true, path: filePath }, 409);
+ }
const { version } = writeFileWithReceipt(c, filePath, absPath, html);
return { backupPath: backupPathForResponse(projectDir, backup.backupPath), version };
}
@@ -516,7 +542,7 @@ function writeIfChanged(
if (next === original) {
return c.json({ ok: true, changed: false, content: original, path: filePath });
}
- const mutationResult = writeMutationResult(c, projectDir, filePath, absPath, next);
+ const mutationResult = writeMutationResult(c, projectDir, filePath, absPath, next, original);
if (mutationResult instanceof Response) return mutationResult;
const { backupPath } = mutationResult;
return c.json({
@@ -544,9 +570,11 @@ function rejectUnsafeMutationValues(
function elementPatchBatchCommitErrorResponse(
c: RouteContext,
- error: "duplicate" | "forbidden" | "not-found",
+ error: Extract<ElementPatchCommitResult, { error: unknown }>["error"],
sourceFile: string,
): Response {
+ if (error === "conflict")
+ return c.json({ error: "file changed", conflict: true, sourceFile }, 409);
if (error === "not-found") return c.json({ error, sourceFile }, 404);
if (error === "forbidden") return c.json({ error, sourceFile }, 403);
return c.json({ error: "duplicate source file", sourceFile }, 400);
@@ -1358,6 +1386,7 @@ async function applyGsapMutations(
res.filePath,
res.absPath,
newHtml,
+ beforeHtml,
);
if (mutationResult instanceof Response) return mutationResult;
backupPath = mutationResult.backupPath;
@@ -2374,7 +2403,7 @@ export function registerFileRoutes(api: Hono, adapter: StudioApiAdapter): void {
// ── Write (overwrite) ──
api.put("/projects/:id/files/*", async (c) => {
- const res = await resolveProjectFile(c, adapter);
+ const res = await resolveProjectFile(c, adapter, { pin: true });
if ("error" in res) return res.error;
const body = Buffer.from(await c.req.arrayBuffer());
@@ -2579,6 +2608,11 @@ export function registerFileRoutes(api: Hono, adapter: StudioApiAdapter): void {
const backup = snapshotBeforeWrite(ctx.project.dir, ctx.absPath);
if (backup.error) return c.json({ error: `backup failed: ${backup.error}` }, 500);
+ const current = readFileSync(ctx.absPath, "utf-8");
+ if (current !== before) {
+ const currentVersion = fileContentVersion(current);
+ return c.json({ error: "file conflict", currentVersion, currentContent: current }, 409);
+ }
const { version, writeToken } = writeFileWithReceipt(
c,
ctx.filePath,
@@ -2681,7 +2715,7 @@ export function registerFileRoutes(api: Hono, adapter: StudioApiAdapter): void {
const seen = new Set<string>();
const prepared: FoldedAtomicCutFile[] = [];
for (const file of files) {
- const absPath = resolveWithinProject(project.dir, file.path);
+ const absPath = pinWithinProject(project.dir, file.path);
if (!absPath) return c.json({ error: `forbidden path: ${file.path}` }, 403);
if (seen.has(absPath)) return c.json({ error: `duplicate path: ${file.path}` }, 400);
seen.add(absPath);
@@ -2853,6 +2887,7 @@ export function registerFileRoutes(api: Hono, adapter: StudioApiAdapter): void {
ctx.filePath,
ctx.absPath,
result.html,
+ originalContent,
);
if (mutationResult instanceof Response) return mutationResult;
const { version, backupPath } = mutationResult;
@@ -2885,48 +2920,54 @@ export function registerFileRoutes(api: Hono, adapter: StudioApiAdapter): void {
return rejectUnsafeMutationValues(c, unsafeFields);
}
- let originalContent: string;
- try {
- originalContent = readFileSync(ctx.absPath, "utf-8");
- } catch {
- return c.json({ error: "not found" }, 404);
- }
- const { html: patched, matched } = patchElementInHtml(
- originalContent,
- parsed.target,
- parsed.body.operations,
- );
- if (patched === originalContent) {
- const version = fileContentVersion(originalContent);
+ for (let attempt = 1; ; attempt += 1) {
+ let originalContent: string;
+ try {
+ originalContent = readFileSync(ctx.absPath, "utf-8");
+ } catch {
+ return c.json({ error: "not found" }, 404);
+ }
+ const { html: patched, matched } = patchElementInHtml(
+ originalContent,
+ parsed.target,
+ parsed.body.operations,
+ );
+ if (patched === originalContent) {
+ const version = fileContentVersion(originalContent);
+ c.header("ETag", version);
+ return c.json({
+ ok: true,
+ changed: false,
+ matched,
+ content: originalContent,
+ path: ctx.filePath,
+ version,
+ });
+ }
+ const mutationResult = writeMutationResult(
+ c,
+ ctx.project.dir,
+ ctx.filePath,
+ ctx.absPath,
+ patched,
+ originalContent,
+ );
+ if (mutationResult instanceof Response) {
+ if (mutationResult.status === 409 && attempt < PATCH_CONFLICT_ATTEMPTS) continue;
+ return mutationResult;
+ }
+ const { backupPath, version } = mutationResult;
c.header("ETag", version);
return c.json({
ok: true,
- changed: false,
+ changed: true,
matched,
- content: originalContent,
+ content: patched,
path: ctx.filePath,
version,
+ backupPath,
});
}
- const mutationResult = writeMutationResult(
- c,
- ctx.project.dir,
- ctx.filePath,
- ctx.absPath,
- patched,
- );
- if (mutationResult instanceof Response) return mutationResult;
- const { backupPath, version } = mutationResult;
- c.header("ETag", version);
- return c.json({
- ok: true,
- changed: true,
- matched,
- content: patched,
- path: ctx.filePath,
- version,
- backupPath,
- });
});
api.post("/projects/:id/file-mutations/patch-element-batches", async (c) => {
@@ -3054,6 +3095,7 @@ export function registerFileRoutes(api: Hono, adapter: StudioApiAdapter): void {
ctx.filePath,
ctx.absPath,
result.html,
+ originalContent,
);
if (mutationResult instanceof Response) return mutationResult;
const { backupPath } = mutationResult;
@@ -3185,7 +3227,14 @@ export function registerFileRoutes(api: Hono, adapter: StudioApiAdapter): void {
}
ensureDir(destAbs);
- writeFileSync(destAbs, readFileSync(srcAbs));
+ try {
+ writeFileSync(destAbs, readFileSync(srcAbs), { flag: "wx" });
+ } catch (error) {
+ if (!error || typeof error !== "object" || !("code" in error) || error.code !== "EEXIST") {
+ throw error;
+ }
+ return c.json({ error: "already exists" }, 409);
+ }
return c.json({ ok: true, path: copyPath }, 201);
});
@@ -3254,6 +3303,7 @@ export function registerFileRoutes(api: Hono, adapter: StudioApiAdapter): void {
api.post("/projects/:id/gsap-mutations/*", async (c) => {
const res = await resolveProjectPath(c, adapter, "gsap-mutations", {
mustExist: true,
+ pin: true,
});
if ("error" in res) return res.error;
@@ -3265,7 +3315,10 @@ export function registerFileRoutes(api: Hono, adapter: StudioApiAdapter): void {
});
api.post("/projects/:id/gsap-mutations-batch/*", async (c) => {
- const res = await resolveProjectPath(c, adapter, "gsap-mutations-batch", { mustExist: true });
+ const res = await resolveProjectPath(c, adapter, "gsap-mutations-batch", {
+ mustExist: true,
+ pin: true,
+ });
if ("error" in res) return res.error;
const body = (await c.req.json().catch(() => null)) as {
@@ -3285,7 +3338,10 @@ export function registerFileRoutes(api: Hono, adapter: StudioApiAdapter): void {
// mutation wrote. Keep compare + write in this synchronous server section so
// another request cannot land between a client-side check and the restore.
api.post("/projects/:id/gsap-mutation-rollback/*", async (c) => {
- const res = await resolveProjectPath(c, adapter, "gsap-mutation-rollback", { mustExist: true });
+ const res = await resolveProjectPath(c, adapter, "gsap-mutation-rollback", {
+ mustExist: true,
+ pin: true,
+ });
if ("error" in res) return res.error;
const body = (await c.req.json().catch(() => null)) as {