Skip to content

Write HTML. Render video. Built for agents.

fix(cli): timeline ids never writes over a save that lands while it stamps (#4494)

Miguel Ángel3746c9821af6
diff --git a/packages/cli/src/timeline/a2Commands.ids.test.ts b/packages/cli/src/timeline/a2Commands.ids.test.ts
new file mode 100644
index 0000000000..91387f6870
--- /dev/null
+++ b/packages/cli/src/timeline/a2Commands.ids.test.ts
@@ -0,0 +1,52 @@
+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { consumeCommandResult } from "../utils/commandResult.js";
+import { runIds } from "./a2Commands.js";
+
+const hooks = vi.hoisted(() => ({ minting: undefined as (() => void) | undefined }));
+vi.mock("@hyperframes/parsers/hf-ids", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("@hyperframes/parsers/hf-ids")>();
+ return {
+ ...actual,
+ ensureHfIds: (html: string) => {
+ hooks.minting?.();
+ return actual.ensureHfIds(html);
+ },
+ };
+});
+
+const dirs: string[] = [];
+afterEach(() => {
+ vi.restoreAllMocks();
+ for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true });
+});
+
+describe("timeline ids", () => {
+ it("keeps a save that lands while ids are minted instead of writing over it", async () => {
+ const dir = mkdtempSync(join(tmpdir(), "hf-timeline-ids-"));
+ dirs.push(dir);
+ const indexPath = join(dir, "index.html");
+ writeFileSync(
+ indexPath,
+ `<div data-composition-id="main" data-duration="4"><div id="clip" data-start="0" data-duration="2" data-track-index="0"></div></div>`,
+ );
+ const save = `<div data-composition-id="main" data-duration="4"><div id="clip" data-start="1" data-duration="2" data-track-index="0"></div></div>`;
+ hooks.minting = () => {
+ hooks.minting = undefined;
+ writeFileSync(indexPath, save);
+ };
+ vi.spyOn(console, "log").mockImplementation(() => {});
+ const stderr = vi.spyOn(console, "error").mockImplementation(() => {});
+
+ await runIds({ dir, json: true });
+
+ expect(readFileSync(indexPath, "utf-8")).toBe(save);
+ expect(consumeCommandResult().exitCode).toBe(2);
+ expect(JSON.parse(String(stderr.mock.calls[0]?.[0]))).toMatchObject({
+ ok: false,
+ reason: "file changed since the timeline was read",
+ });
+ });
+});
diff --git a/packages/cli/src/timeline/a2Commands.ts b/packages/cli/src/timeline/a2Commands.ts
index 324dbe45e6..80e506ecf0 100644
--- a/packages/cli/src/timeline/a2Commands.ts
+++ b/packages/cli/src/timeline/a2Commands.ts
@@ -1,4 +1,8 @@
-import { applyFileMutations, fileContentVersion } from "@hyperframes/studio-server";
+import {
+ applyFileMutations,
+ fileContentVersion,
+ type AppliedFileMutation,
+} from "@hyperframes/studio-server";
import { ensureHfIds } from "@hyperframes/parsers/hf-ids";
import { readFileSync } from "node:fs";
import { join } from "node:path";
@@ -21,6 +25,8 @@ import {
rowAt,
type MutationContext,
type MutationVerb,
+ isFileChanged,
+ refusal,
} from "./a2Shared.js";
export async function runIds(args: Record<string, unknown>): Promise<void> {
@@ -34,9 +40,24 @@ export async function runIds(args: Record<string, unknown>): Promise<void> {
const after = ensureHfIds(before);
return after === before
? []
- : [{ sourceFile: file, absPath: join(project.dir, file), before, after }];
+ : [
+ {
+ sourceFile: file,
+ absPath: join(project.dir, file),
+ before,
+ after,
+ expectedVersion: fileContentVersion(before),
+ },
+ ];
});
- const receipts = inputs.length > 0 ? applyFileMutations(project.dir, inputs) : [];
+ let receipts: AppliedFileMutation[] = [];
+ try {
+ if (inputs.length > 0) receipts = applyFileMutations(project.dir, inputs);
+ } catch (error) {
+ if (isFileChanged(error))
+ return refusal(error.message, "re-run hyperframes timeline ids", json);
+ throw error;
+ }
const afterTimeline = await describeProject(project.indexPath);
const result = {
ok: true,
diff --git a/packages/cli/src/timeline/a2MutationCommand.ts b/packages/cli/src/timeline/a2MutationCommand.ts
index 25b945c219..c95f5e5b46 100644
--- a/packages/cli/src/timeline/a2MutationCommand.ts
+++ b/packages/cli/src/timeline/a2MutationCommand.ts
@@ -22,6 +22,7 @@ import {
type MutationContext,
type MutationDecision,
type MutationVerb,
+ isFileChanged,
} from "./a2Shared.js";
export async function runMutation(
@@ -249,9 +250,7 @@ function applyMutation(
},
])[0];
} catch (error) {
- if (error instanceof Error && error.message === "file changed since the timeline was read") {
- return { error: error.message };
- }
+ if (isFileChanged(error)) return { error: error.message };
throw error;
}
}
diff --git a/packages/cli/src/timeline/a2Shared.ts b/packages/cli/src/timeline/a2Shared.ts
index a8779726bc..3ef5e4a66f 100644
--- a/packages/cli/src/timeline/a2Shared.ts
+++ b/packages/cli/src/timeline/a2Shared.ts
@@ -42,6 +42,9 @@ export function refusal(reason: string, fix: string, json: boolean): void {
console.error(json ? JSON.stringify(payload, null, 2) : `${reason}; ${fix}.`);
}
+export const isFileChanged = (error: unknown): error is Error =>
+ error instanceof Error && error.message === "file changed since the timeline was read";
+
export function refuse(kind: string, detail: { reason: string; fix: string }, json: boolean): void {
refusal(`${kind}: ${detail.reason}`, detail.fix, json);
}
diff --git a/packages/studio-server/src/helpers/applyFileMutations.test.ts b/packages/studio-server/src/helpers/applyFileMutations.test.ts
index 07ac259f77..7aa1479e67 100644
--- a/packages/studio-server/src/helpers/applyFileMutations.test.ts
+++ b/packages/studio-server/src/helpers/applyFileMutations.test.ts
@@ -32,6 +32,69 @@ describe("applyFileMutations", () => {
expectStaleMutation("before");
});
+ it("keeps a save to an earlier file when a later file's conflict rolls the batch back", () => {
+ const projectDir = mkdtempSync(join(tmpdir(), "hf-mutation-version-"));
+ const first = join(projectDir, "first.html");
+ const second = join(projectDir, "second.html");
+ try {
+ writeFileSync(first, "first-before", "utf8");
+ writeFileSync(second, "second-before", "utf8");
+ const writeFile = (path: string, content: string, encoding: "utf-8") => {
+ writeFileSync(path, content, encoding);
+ if (path !== first || content !== "first-after") return;
+ writeFileSync(first, "first-saved", "utf8");
+ writeFileSync(second, "second-saved", "utf8");
+ };
+ expect(() =>
+ applyFileMutations(
+ projectDir,
+ ["first", "second"].map((name) => ({
+ sourceFile: `${name}.html`,
+ absPath: join(projectDir, `${name}.html`),
+ before: `${name}-before`,
+ after: `${name}-after`,
+ expectedVersion: fileContentVersion(`${name}-before`),
+ })),
+ undefined,
+ writeFile,
+ ),
+ ).toThrow("file changed since the timeline was read");
+ expect(readFileSync(first, "utf8")).toBe("first-saved");
+ expect(readFileSync(second, "utf8")).toBe("second-saved");
+ } finally {
+ rmSync(projectDir, { recursive: true, force: true });
+ }
+ });
+
+ it("writes nothing when a later file is already stale", () => {
+ const projectDir = mkdtempSync(join(tmpdir(), "hf-mutation-version-"));
+ try {
+ for (const name of ["first", "second"])
+ writeFileSync(join(projectDir, `${name}.html`), `${name}-before`, "utf8");
+ writeFileSync(join(projectDir, "second.html"), "second-saved", "utf8");
+ let writes = 0;
+ expect(() =>
+ applyFileMutations(
+ projectDir,
+ ["first", "second"].map((name) => ({
+ sourceFile: `${name}.html`,
+ absPath: join(projectDir, `${name}.html`),
+ before: `${name}-before`,
+ after: `${name}-after`,
+ expectedVersion: fileContentVersion(`${name}-before`),
+ })),
+ undefined,
+ () => {
+ writes += 1;
+ },
+ ),
+ ).toThrow("file changed since the timeline was read");
+ expect(writes).toBe(0);
+ } finally {
+ rmSync(projectDir, { recursive: true, force: true });
+ }
+ });
+
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 5e912228b2..ef4ac0f3b4 100644
--- a/packages/studio-server/src/helpers/applyFileMutations.ts
+++ b/packages/studio-server/src/helpers/applyFileMutations.ts
@@ -39,7 +39,11 @@ export function applyFileMutations(
before: mutation.before ?? readFileSync(mutation.absPath, "utf-8"),
}));
const results: AppliedFileMutation[] = [];
- const attempted: Array<PreparedMutation & { version: string; writeToken: string }> = [];
+ const attempted: Array<
+ PreparedMutation & { version: string; writeToken: string; written: boolean }
+ > = [];
+ for (const mutation of prepared)
+ assertExpectedVersion(mutation.expectedVersion, readFileSync(mutation.absPath, "utf-8"));
try {
for (const mutation of prepared) {
results.push(applyOneMutation(projectDir, mutation, requestToken, writeFile, attempted));
@@ -49,7 +53,8 @@ export function applyFileMutations(
const rollbackErrors: unknown[] = [];
for (const mutation of attempted.reverse()) {
try {
- writeFile(mutation.absPath, mutation.before, "utf-8");
+ if (!mutation.written || readFileSync(mutation.absPath, "utf-8") === mutation.after)
+ writeFile(mutation.absPath, mutation.before, "utf-8");
clearFileWriteReceipt(mutation.absPath, mutation.version, mutation.writeToken);
} catch (rollbackError) {
rollbackErrors.push(rollbackError);
@@ -72,7 +77,7 @@ function applyOneMutation(
mutation: PreparedMutation,
requestToken: string | undefined,
writeFile: (path: string, content: string, encoding: "utf-8") => void,
- attempted: Array<PreparedMutation & { version: string; writeToken: string }>,
+ attempted: Array<PreparedMutation & { version: string; writeToken: string; written: boolean }>,
): AppliedFileMutation {
const current = readFileSync(mutation.absPath, "utf-8");
assertExpectedVersion(mutation.expectedVersion, current);
@@ -91,8 +96,10 @@ function applyOneMutation(
const before = current;
const version = fileContentVersion(mutation.after);
const writeToken = createWriteToken(requestToken);
- attempted.push({ ...mutation, before, version, writeToken });
+ const attempt = { ...mutation, before, version, writeToken, written: false };
+ attempted.push(attempt);
writeFile(mutation.absPath, mutation.after, "utf-8");
+ attempt.written = true;
recordFileWriteReceipt(mutation.absPath, {
path: mutation.sourceFile,
version,