Write HTML. Render video. Built for agents.
JavaScript aiai-agentsanimationclaude-codeffmpegframeworkgsaphtmlhtml-to-videomcpmotion-graphicspuppeteerrenderingtypescriptvideo-editor
fix(studio): quick saves no longer refuse each other as outside changes (#4612)
Miguel Ángeld4801086c4b8
diff --git a/packages/studio/src/components/editor/BlockParamsPanel.tsx b/packages/studio/src/components/editor/BlockParamsPanel.tsxindex 0d5327891a..f2456b9524 100644--- a/packages/studio/src/components/editor/BlockParamsPanel.tsx+++ b/packages/studio/src/components/editor/BlockParamsPanel.tsx@@ -3,6 +3,7 @@ import type { BlockParam } from "@hyperframes/core/registry";import { useFileManagerContextOptional } from "../../contexts/FileManagerContext";import { useStudioPlaybackContext } from "../../contexts/StudioContext";import { trackBlockParamCommit } from "../../telemetry/events";+import { serializeStudioFileMutation } from "../../utils/studioFileMutationCoordinator";interface BlockParamsPanelProps {blockName: string;@@ -77,7 +78,11 @@ export const BlockParamsPanel = memo(function BlockParamsPanel({trackBlockParamCommit({ tone: "error", blockName, key });return;}- await fileManager.writeProjectFile(compositionPath, content.replace(matcher, nextValue));+ await fileManager.writeProjectFile(+ compositionPath,+ content.replace(matcher, nextValue),+ content,+ );appliedRef.current[key] = nextValue;setCommitState({ tone: "saved" });trackBlockParamCommit({ tone: "saved", blockName, key });@@ -90,16 +95,15 @@ export const BlockParamsPanel = memo(function BlockParamsPanel({[fileManager, compositionPath, setRefreshKey, blockName],);- // Commits are serialized: two params committing concurrently would each- // read-modify-write the same file and the second write would drop the first.- const commitChainRef = useRef<Promise<void>>(Promise.resolve());+ // Commits join the file's queue: two read-modify-writes of one file must not interleave.const commitParam = useCallback(- (key: string, nextValue: string) => {- const run = commitChainRef.current.then(() => commitParamNow(key, nextValue));- commitChainRef.current = run.catch(() => undefined);- return run;- },- [commitParamNow],+ (key: string, nextValue: string) =>+ fileManager+ ? serializeStudioFileMutation(fileManager.writeProjectFile, compositionPath, () =>+ commitParamNow(key, nextValue),+ )+ : Promise.resolve(),+ [commitParamNow, compositionPath, fileManager],);const handleChange = useCallback(diff --git a/packages/studio/src/components/studioColorGradingScope.ts b/packages/studio/src/components/studioColorGradingScope.tsindex 267543c2b5..50d1b6ddcd 100644--- a/packages/studio/src/components/studioColorGradingScope.ts+++ b/packages/studio/src/components/studioColorGradingScope.ts@@ -40,31 +40,6 @@ function colorGradingScopePaths(return scope === "source-file" ? [selectedSourceFile] : compositionPaths;}-async function patchColorGradingScopeFiles(- paths: string[],- value: string | null,- readProjectFile: ProjectFileReader,-): Promise<{ files: Record<string, string>; changedElements: number }> {- const snapshots = await Promise.all(- Array.from(new Set(paths)).map(async (path) => ({- path,- before: await readProjectFile(path),- })),- );- const files: Record<string, string> = {};- let changedElements = 0;-- for (const { path, before } of snapshots) {- const result = patchMediaColorGradingInHtml(before, value);- if (result.html !== before) {- files[path] = result.html;- changedElements += result.count;- }- }-- return { files, changedElements };-}-// fallow-ignore-next-line complexityexport async function applyColorGradingScopeUpdate({scope,@@ -88,24 +63,25 @@ export async function applyColorGradingScopeUpdate({return EMPTY_COLOR_GRADING_SCOPE_RESULT;}- const { files, changedElements } = await patchColorGradingScopeFiles(- colorGradingScopePaths(scope, selectedSourceFile, compositionPaths),- value,- readProjectFile,- );- if (Object.keys(files).length === 0) {- showToast("No color grading changed", "info");- return EMPTY_COLOR_GRADING_SCOPE_RESULT;- }-+ let changedElements = 0;+ const patchGrading = (before: string) => {+ const result = patchMediaColorGradingInHtml(before, value);+ changedElements += result.count;+ return result.html;+ };+ const paths = colorGradingScopePaths(scope, selectedSourceFile, compositionPaths);const changedPaths = await saveProjectFilesWithHistory({projectId,label: value ? "Apply color grading" : "Clear color grading",- files,+ files: Object.fromEntries(paths.map((path) => [path, patchGrading])),readFile: readProjectFile,writeFile: writeProjectFile,recordEdit,});+ if (changedPaths.length === 0) {+ showToast("No color grading changed", "info");+ return EMPTY_COLOR_GRADING_SCOPE_RESULT;+ }reloadPreview();showToast(`${value ? "Applied" : "Cleared"} color grading on ${changedElements} media item${changedElements === 1 ? "" : "s"}`,diff --git a/packages/studio/src/hooks/canvasQuickSaves.test.tsx b/packages/studio/src/hooks/canvasQuickSaves.test.tsxnew file mode 100644index 0000000000..d4b7781b5e--- /dev/null+++ b/packages/studio/src/hooks/canvasQuickSaves.test.tsx@@ -0,0 +1,195 @@+// @vitest-environment happy-dom+import { act, createElement } from "react";+import { createRoot } from "react-dom/client";+import { afterEach, describe, expect, it, vi } from "vitest";+import type { DomEditSelection, DomEditTextField } from "../components/editor/domEditing";+import type { TimelineElement } from "../player/store/playerStore";+import { buildTimelineMoveTimingPatch, persistTimelineEdit } from "./timelineEditingHelpers";+import { useDomEditCommits } from "./useDomEditCommits";++Reflect.set(globalThis, "IS_REACT_ACT_ENVIRONMENT", true);+vi.mock("../utils/studioTelemetry", () => ({ trackStudioEvent: vi.fn() }));++const SOURCE =+ '<!doctype html><html><head></head><body><div data-hf-id="hf-card" style="color: red">Card</div>' ++ '<div id="clip" class="clip" data-start="1" data-duration="5" data-track-index="0"></div></body></html>';++// The server patches whatever is on disk; the writer refuses a stale base like If-Match does.+// The first write can be held mid-flight.+function fakeProject() {+ let disk = SOURCE;+ const refused: string[] = [];+ let writes = 0;+ let release = () => {};+ const firstWrite = new Promise<void>((resolve) => (release = resolve));+ vi.stubGlobal(+ "fetch",+ vi.fn(async (input: string, init?: RequestInit) => {+ if (input.includes("/file-mutations/patch-element/")) {+ const { operations } = JSON.parse(String(init?.body)) as {+ operations: Array<{ property?: string; value?: string }>;+ };+ for (const op of operations) {+ if (op.property === "color") disk = disk.replace(/color: \w+/, `color: ${op.value}`);+ }+ return Response.json({ ok: true, changed: true, matched: true, content: disk });+ }+ return Response.json({ content: disk });+ }),+ );+ const writeProjectFile = async (path: string, content: string, expected?: string) => {+ if (++writes === 1) await firstWrite;+ if (expected !== undefined && expected !== disk && content !== disk) {+ refused.push(path);+ throw new Error(`409 conflict on ${path}`);+ }+ disk = content;+ };+ return { writeProjectFile, refused, release: () => release(), read: () => disk };+}++type Project = ReturnType<typeof fakeProject>;++function mountCanvasCommits(project: Project) {+ const iframe = document.createElement("iframe");+ document.body.append(iframe);+ iframe.contentDocument!.body.innerHTML =+ '<div data-hf-id="hf-card" style="color: red">Card</div>';+ const element = iframe.contentDocument!.querySelector<HTMLElement>('[data-hf-id="hf-card"]')!;+ const selection = {+ element,+ label: "Card",+ tagName: "div",+ sourceFile: "index.html",+ compositionPath: "index.html",+ isCompositionHost: false,+ isInsideLockedComposition: false,+ boundingBox: { x: 0, y: 0, width: 120, height: 40 },+ textContent: "Card",+ dataAttributes: {},+ inlineStyles: { color: "red" },+ computedStyles: {},+ textFields: [],+ capabilities: { canSelect: true, canEditStyles: true, canMove: true, canResize: true },+ hfId: "hf-card",+ selector: '[data-hf-id="hf-card"]',+ selectorIndex: 0,+ } as unknown as DomEditSelection;+ const captured: { current: ReturnType<typeof useDomEditCommits> | null } = { current: null };+ const toasts: string[] = [];+ function Probe() {+ captured.current = useDomEditCommits({+ activeCompPath: "index.html",+ previewIframeRef: { current: iframe },+ showToast: (message) => toasts.push(message),+ queueDomEditSave: (save) => save(),+ writeProjectFile: project.writeProjectFile,+ editHistory: { recordEdit: async () => {} },+ fileTree: [],+ importedFontAssetsRef: { current: [] },+ projectId: "p1",+ projectIdRef: { current: "p1" },+ reloadPreview: () => {},+ domEditSelection: selection,+ applyDomSelection: () => {},+ clearDomSelection: () => {},+ refreshDomEditSelectionFromPreview: () => {},+ buildDomSelectionFromTarget: async () => null,+ readOnlyPreview: false,+ });+ return null;+ }+ const root = createRoot(document.createElement("div"));+ act(() => root.render(createElement(Probe)));+ return { hook: captured.current!, selection, toasts };+}++const selfText: DomEditTextField = {+ key: "self",+ label: "self",+ value: "Card",+ tagName: "div",+ attributes: [],+ inlineStyles: {},+ computedStyles: {},+ source: "self",+};++const moveClip = (project: Project) =>+ persistTimelineEdit({+ projectId: "p1",+ activeCompPath: "index.html",+ element: {+ id: "clip",+ key: "clip",+ domId: "clip",+ tag: "div",+ start: 1,+ duration: 5,+ track: 0,+ } as TimelineElement,+ label: "Move clip",+ buildPatches: (original, target) => buildTimelineMoveTimingPatch(original, target, 3, 5),+ writeProjectFile: project.writeProjectFile,+ recordEdit: async () => {},+ pendingTimelineEditPathRef: { current: new Set<string>() },+ });++// Starts the second save while the first one's write is in flight; both must land unrefused.+async function expectBothLand(+ project: Project,+ first: () => Promise<unknown>,+ second: () => Promise<unknown>,+) {+ await act(async () => {+ const saves = [first()];+ await new Promise((resolve) => setTimeout(resolve, 0));+ saves.push(second());+ await new Promise((resolve) => setTimeout(resolve, 0));+ project.release();+ await Promise.allSettled(saves);+ });+ expect(project.refused).toEqual([]);+}++afterEach(() => {+ vi.unstubAllGlobals();+ document.body.innerHTML = "";+});++describe("canvas edit commits share the file queue", () => {+ it("lands a second canvas commit started while the first one's font write is held", async () => {+ const project = fakeProject();+ const { hook, selection, toasts } = mountCanvasCommits(project);+ const font = {+ family: "Imported",+ path: "fonts/Imported.woff2",+ url: "/api/projects/p1/preview/fonts/Imported.woff2",+ };++ await expectBothLand(+ project,+ () => hook.commitDomTextFields(selection, [selfText], { importedFont: font }),+ () => hook.handleDomStyleCommit("color", "green"),+ );++ expect(toasts).toEqual([]);+ expect(project.read()).toContain("@font-face");+ expect(project.read()).toContain("color: green");+ });++ it("lands a canvas commit started while a timeline save is writing", async () => {+ const project = fakeProject();+ const { hook, toasts } = mountCanvasCommits(project);++ await expectBothLand(+ project,+ () => moveClip(project),+ () => hook.handleDomStyleCommit("color", "green"),+ );++ expect(toasts).toEqual([]);+ expect(project.read()).toContain('id="clip" class="clip" data-start="3"');+ expect(project.read()).toContain("color: green");+ });+});diff --git a/packages/studio/src/hooks/gsapMutationClient.ts b/packages/studio/src/hooks/gsapMutationClient.tsnew file mode 100644index 0000000000..fb9c0871f0--- /dev/null+++ b/packages/studio/src/hooks/gsapMutationClient.ts@@ -0,0 +1,116 @@+import { studioWriteHeaders } from "../utils/studioFileVersion";++export class GsapPreviewConvergenceError extends Error {}+export class GsapOwnershipProtocolError extends GsapPreviewConvergenceError {}++/** Verify rollback ownership support before any GSAP mutation can land. */+export async function requireGsapOwnershipProtocol(projectId: string): Promise<void> {+ const response = await fetch(+ `/api/projects/${encodeURIComponent(projectId)}/gsap-mutation-capabilities`,+ );+ if (!response.ok) {+ throw new GsapOwnershipProtocolError("Server does not support owned GSAP mutations");+ }+ const body = await response.json().catch(() => null);+ if (!isRecord(body) || body.atomicOwnershipPairs !== true) {+ throw new GsapOwnershipProtocolError("Invalid GSAP mutation capability response");+ }+}++/** Atomically restore one GSAP mutation only while its exact output still owns+ * the file. The server performs compare + write synchronously, eliminating the+ * client GET→PUT window that could overwrite a successor edit. */+export async function rollbackOwnedMutation(+ projectId: string,+ targetPath: string,+ expected: string,+ restore: string,+): Promise<"restored" | "conflict"> {+ if (targetPath.includes("\0") || targetPath.includes("..")) {+ throw new Error(`Unsafe path: ${targetPath}`);+ }+ const response = await fetch(+ `/api/projects/${encodeURIComponent(projectId)}/gsap-mutation-rollback/${encodeURIComponent(targetPath)}`,+ {+ method: "POST",+ // Deliberately unclaimed: a rollback runs because a mutation did not+ // converge, so let the restored file reload the preview.+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ expected, restore }),+ },+ );+ if (!response.ok) {+ throw new Error(`Failed to restore ${targetPath}`);+ }+ const result = (await response.json()) as { restored?: unknown; conflict?: unknown };+ if (result.restored === true && result.conflict === false) return "restored";+ if (result.restored === false && result.conflict === true) return "conflict";+ throw new Error(`Invalid restore response for ${targetPath}`);+}++/** The server's GSAP-mutation response. `scriptText` is the rewritten root script for a soft+ * reload, null when none came back: the caller then full-reloads when `mutated`, or rebinds+ * the runtime timing in place when nothing was rewritten (see syncTimingEditPreview). */+export type GsapMutationStatus = {+ mutated: boolean;+ scriptText: string | null;+ /** Atomic whole-file ownership pair returned by the mutation endpoint. */+ before?: string;+ after?: string;+};++function isRecord(value: unknown): value is Record<string, unknown> {+ return typeof value === "object" && value !== null;+}++function readMutationStatus(value: unknown): GsapMutationStatus {+ if (+ !isRecord(value) ||+ typeof value.mutated !== "boolean" ||+ typeof value.before !== "string" ||+ typeof value.after !== "string" ||+ value.mutated !== (value.before !== value.after) ||+ ("changed" in value && value.changed !== value.mutated)+ ) {+ throw new GsapOwnershipProtocolError("Invalid owned GSAP mutation response");+ }+ return {+ mutated: value.mutated,+ scriptText: typeof value.scriptText === "string" ? value.scriptText : null,+ before: value.before,+ after: value.after,+ };+}++function readMutationError(value: unknown, fallback: string): string {+ if (isRecord(value) && typeof value.error === "string") return value.error;+ return fallback;+}++export async function postGsapMutation(+ projectId: string,+ filePath: string,+ mutation: Record<string, unknown>,+ fallback: string,+): Promise<GsapMutationStatus> {+ let response: Response;+ try {+ response = await fetch(+ `/api/projects/${encodeURIComponent(projectId)}/gsap-mutations/${encodeURIComponent(filePath)}`,+ {+ method: "POST",+ headers: { "Content-Type": "application/json", ...studioWriteHeaders() },+ body: JSON.stringify(mutation),+ },+ );+ } catch (error) {+ throw new GsapPreviewConvergenceError(`${fallback}: mutation outcome unknown`, {+ cause: error,+ });+ }+ const body: unknown = await response.json().catch(() => null);+ if (!response.ok) {+ throw new GsapPreviewConvergenceError(readMutationError(body, fallback));+ }+ return readMutationStatus(body);+}diff --git a/packages/studio/src/hooks/timelineAudioGroupCreate.ts b/packages/studio/src/hooks/timelineAudioGroupCreate.tsindex c027039f69..9405b6abba 100644--- a/packages/studio/src/hooks/timelineAudioGroupCreate.ts+++ b/packages/studio/src/hooks/timelineAudioGroupCreate.ts@@ -14,9 +14,9 @@ import { runtimeAudioId } from "../player/lib/timelineElementHelpers";import { invalidateGroupInfoCache } from "../player/lib/timelineGroupInfo";import { readTagSnippetByTarget, type PatchOperation } from "../utils/sourcePatcher";import {- applyPatchByTarget,- buildPatchTarget,findTimelineElementInIframe,+ operationChanges,+ patchTimelineChangesInSource,readFileContent,type RecordEditInput,} from "./timelineEditingHelpers";@@ -197,52 +197,30 @@ export async function createAudioGroupAndAssignMembers({property: HF_AUDIO_GROUP_ATTR,value: groupId,};- const originalByPath = new Map<string, string>();- const files: Record<string, string> = {};+ const groupPath = activeCompPath || "index.html";+ const byPath = groupElementsByTargetPath(elements, activeCompPath);+ const files: Record<string, (current: string) => string> = {};+ for (const targetPath of new Set([...byPath.keys(), groupPath])) {+ files[targetPath] = (current) => {+ let patched = patchTimelineChangesInSource(+ current,+ targetPath,+ operationChanges(byPath.get(targetPath) ?? [], groupOperation),+ );+ if (targetPath === groupPath) patched = insertGroupElement(patched, groupId, groupLabel);+ if (patched !== current) pendingTimelineEditPathRef.current.add(targetPath);+ return patched;+ };+ }try {- for (const [targetPath, fileElements] of groupElementsByTargetPath(elements, activeCompPath)) {- let patchedContent = await readFileContent(projectId, targetPath);- originalByPath.set(targetPath, patchedContent);-- for (const element of fileElements) {- const patchTarget = buildPatchTarget(element);- if (!patchTarget) {- throw new Error(`Timeline element ${element.id} is missing a patchable target`);- }- if (readTagSnippetByTarget(patchedContent, patchTarget) === undefined) {- throw new Error(`Unable to patch timeline element ${element.id} in ${targetPath}`);- }- patchedContent = applyPatchByTarget(patchedContent, patchTarget, groupOperation);- }-- files[targetPath] = patchedContent;- pendingTimelineEditPathRef.current.add(targetPath);- }-- const groupPath = activeCompPath || "index.html";- let groupContent = files[groupPath];- if (groupContent === undefined) {- groupContent = await readFileContent(projectId, groupPath);- originalByPath.set(groupPath, groupContent);- }- const withGroupElement = insertGroupElement(groupContent, groupId, groupLabel);- if (withGroupElement !== groupContent) {- files[groupPath] = withGroupElement;- pendingTimelineEditPathRef.current.add(groupPath);- }-const changedPaths = await saveProjectFilesWithHistory({projectId,label: groupLabel? `Group ${elements.length} clips as ${groupLabel}`: `Group ${elements.length} voice clips`,files,- readFile: async (path) => {- const original = originalByPath.get(path);- if (original !== undefined) return original;- return readFileContent(projectId, path);- },+ readFile: (path) => readFileContent(projectId, path),writeFile: writeProjectFile,recordEdit,});diff --git a/packages/studio/src/hooks/timelineEditingHelpers.ts b/packages/studio/src/hooks/timelineEditingHelpers.tsindex 69e2d9294a..09d5fbab1f 100644--- a/packages/studio/src/hooks/timelineEditingHelpers.ts+++ b/packages/studio/src/hooks/timelineEditingHelpers.ts@@ -308,25 +308,26 @@ export interface PersistTimelineEditInput {export async function persistTimelineEdit(input: PersistTimelineEditInput): Promise<void> {const targetPath = input.element.sourceFile || input.activeCompPath || "index.html";- const originalContent = await readFileContent(input.projectId, targetPath);-const patchTarget = buildPatchTarget(input.element);if (!patchTarget) {throw new Error(`Timeline element ${input.element.id} is missing a patchable target`);}- const patchedContent = input.buildPatches(originalContent, patchTarget);- if (patchedContent === originalContent) {- throw new Error(`Unable to patch timeline element ${input.element.id} in ${targetPath}`);- }-input.pendingTimelineEditPathRef.current.add(targetPath);await saveProjectFilesWithHistory({projectId: input.projectId,label: input.label,coalesceKey: input.coalesceKey,- files: { [targetPath]: patchedContent },- readFile: async () => originalContent,+ files: {+ [targetPath]: (current) => {+ const patched = input.buildPatches(current, patchTarget);+ if (patched === current) {+ throw new Error(`Unable to patch timeline element ${input.element.id} in ${targetPath}`);+ }+ return patched;+ },+ },+ readFile: (path) => readFileContent(input.projectId, path),writeFile: input.writeProjectFile,recordEdit: input.recordEdit,});@@ -337,6 +338,36 @@ export interface PersistTimelineBatchChange {buildPatches: (original: string, target: PatchTarget) => string;}+/** One batch change per element, each applying the same patch operation. */+export function operationChanges(+ elements: readonly TimelineElement[],+ operation: PatchOperation,+): PersistTimelineBatchChange[] {+ return elements.map((element) => ({+ element,+ buildPatches: (html, target) => applyPatchByTarget(html, target, operation),+ }));+}++/** Patches each change into `source`, failing loudly on a target the file does not hold. */+export function patchTimelineChangesInSource(+ source: string,+ targetPath: string,+ changes: readonly PersistTimelineBatchChange[],+): string {+ let current = source;+ for (const { element, buildPatches } of changes) {+ const target = buildPatchTarget(element);+ if (!target) throw new Error(`Timeline element ${element.id} is missing a patchable target`);+ // Resolve first: a member already at its target values patches to the same string, a missing one must throw.+ if (!findTagByTarget(current, target)) {+ throw new Error(`Unable to patch timeline element ${element.id} in ${targetPath}`);+ }+ current = buildPatches(current, target);+ }+ return current;+}+export interface PersistTimelineBatchEditInput {projectId: string;activeCompPath: string | null;@@ -353,50 +384,24 @@ export interface PersistTimelineBatchEditInput {export async function persistTimelineBatchEdit(input: PersistTimelineBatchEditInput,): Promise<void> {- const originals = new Map<string, string>();- const patchedByPath = new Map<string, string>();-+ const changesByPath = new Map<string, PersistTimelineBatchChange[]>();for (const change of input.changes) {const targetPath = change.element.sourceFile || input.activeCompPath || "index.html";- const original =- originals.get(targetPath) ?? (await readFileContent(input.projectId, targetPath));- originals.set(targetPath, original);-- const patchTarget = buildPatchTarget(change.element);- if (!patchTarget) {- throw new Error(`Timeline element ${change.element.id} is missing a patchable target`);- }-- const current = patchedByPath.get(targetPath) ?? original;- // Resolve the target FIRST: byte-identical output below is only a legit- // no-op when the member actually resolved in the source. A mistargeted- // member (stale id/selector) must fail loudly like the single-edit path,- // not be silently dropped as "already at target".- if (!findTagByTarget(current, patchTarget)) {- throw new Error(`Unable to patch timeline element ${change.element.id} in ${targetPath}`);- }- const patched = change.buildPatches(current, patchTarget);- // The target resolved, so a member whose attributes already hold the target- // values patches to the identical string — e.g. a track-insert renumber- // where one clip's lane is already correct. That is a legitimate no-op:- // skip it instead of aborting (and rolling back) the whole batch.- if (patched === current) continue;- patchedByPath.set(targetPath, patched);+ changesByPath.set(targetPath, [...(changesByPath.get(targetPath) ?? []), change]);}+ const buildFile = (targetPath: string) => (original: string) => {+ const next = patchTimelineChangesInSource(original, targetPath, changesByPath.get(targetPath)!);+ if (next !== original) input.pendingTimelineEditPathRef.current.add(targetPath);+ return next;+ };- if (patchedByPath.size === 0) return;-- const files = Object.fromEntries(patchedByPath);- for (const targetPath of Object.keys(files)) {- input.pendingTimelineEditPathRef.current.add(targetPath);- }await saveProjectFilesWithHistory({projectId: input.projectId,label: input.label,coalesceKey: input.coalesceKey,coalesceMs: input.coalesceMs,- files,- readFile: async (path) => originals.get(path) ?? readFileContent(input.projectId, path),+ files: Object.fromEntries([...changesByPath.keys()].map((path) => [path, buildFile(path)])),+ readFile: (path) => readFileContent(input.projectId, path),writeFile: input.writeProjectFile,recordEdit: input.recordEdit,});@@ -427,7 +432,7 @@ export function readTargetAttribute(return readAttributeByTarget(html, patchTarget, attr) ?? null;}-export { applyPatchByTarget, formatTimelineAttributeNumber, formatTimelineMediaOffset };+export { formatTimelineAttributeNumber, formatTimelineMediaOffset };export { patchDocumentRootDuration } from "./timelineEditingGsap";@@ -490,8 +495,8 @@ export async function persistElementAttribute({return await writeProjectFilesWithHistoryInQueue({projectId,label,- files: { [targetPath]: patched },- readFile: async (path) => (path === targetPath ? before : readFileContent(projectId, path)),+ files: { [targetPath]: () => patched },+ readFile: async () => before,writeFile: writeProjectFile,recordEdit,});diff --git a/packages/studio/src/hooks/timelineQuickSaves.test.ts b/packages/studio/src/hooks/timelineQuickSaves.test.tsnew file mode 100644index 0000000000..ec7a17b300--- /dev/null+++ b/packages/studio/src/hooks/timelineQuickSaves.test.ts@@ -0,0 +1,195 @@+// @vitest-environment jsdom+import { afterEach, describe, expect, it, vi } from "vitest";+import {+ buildTimelineMoveTimingPatch,+ buildTimelineResizeTimingPatch,+ persistElementAttribute,+ persistTimelineBatchEdit,+ persistTimelineEdit,+} from "./timelineEditingHelpers";+import type { TimelineElement } from "../player/store/playerStore";+import { finishClipTimingFallback } from "./timelineTimingSync";+import { applyColorGradingScopeUpdate } from "../components/studioColorGradingScope";++const SOURCE =+ '<div id="root"><video id="a" class="clip" data-start="1" data-duration="5" data-track-index="0"></video>' ++ '<video id="b" class="clip" data-start="2" data-duration="5" data-track-index="1"></video>' ++ '<script>gsap.to("#a", { x: 1 }, 1)</script></div>';++// Refuses a write whose base is stale, like the server's If-Match; one write can be held mid-flight.+// A GSAP shift lands 10 ms after it is posted and releases the held write.+function fakeProject() {+ let file = SOURCE;+ const refused: string[] = [];+ let writes = 0;+ let release = () => {};+ const firstWrite = new Promise<void>((resolve) => (release = resolve));+ vi.stubGlobal(+ "fetch",+ vi.fn(async (input: string) => {+ if (input.includes("/gsap-mutation-capabilities")) {+ return Response.json({ atomicOwnershipPairs: true });+ }+ if (input.includes("/gsap-mutations/")) {+ await new Promise((resolve) => setTimeout(resolve, 10));+ const before = file;+ file = file.replace("{ x: 1 }, 1)", "{ x: 1 }, 3)");+ release();+ return Response.json({ mutated: true, before, after: file, scriptText: null });+ }+ return Response.json({ content: file });+ }),+ );+ const writeProjectFile = async (path: string, content: string, expected?: string) => {+ if (++writes === 1) await firstWrite;+ if (expected !== undefined && expected !== file && content !== file) {+ refused.push(path);+ throw new Error(`409 conflict on ${path}`);+ }+ file = content;+ };+ return { writeProjectFile, refused, release: () => release(), read: () => file };+}++type Project = ReturnType<typeof fakeProject>;++function clip(id: string): TimelineElement {+ return { id, key: id, domId: id, tag: "video", label: id, start: 0, duration: 5, track: 0 };+}++const shared = (project: Project) => ({+ projectId: "p1",+ activeCompPath: "index.html",+ writeProjectFile: project.writeProjectFile,+ recordEdit: async () => {},+ pendingTimelineEditPathRef: { current: new Set<string>() },+});++const move = (project: Project, id: string, start: number) =>+ persistTimelineEdit({+ ...shared(project),+ element: clip(id),+ label: "Move clip",+ buildPatches: (original, target) => buildTimelineMoveTimingPatch(original, target, start, 5),+ });++const trim = (project: Project, id: string, duration: number) =>+ persistTimelineBatchEdit({+ ...shared(project),+ label: "Trim clip",+ changes: [+ {+ element: clip(id),+ buildPatches: (original, target) =>+ buildTimelineResizeTimingPatch(original, target, clip(id), { start: 0, duration }),+ },+ ],+ });++// Starts the second save while the first one's write is in flight; both must land unrefused.+async function expectBothLand(+ project: Project,+ first: () => Promise<unknown>,+ second: () => Promise<unknown>,+) {+ const saves = [first()];+ await new Promise((resolve) => setTimeout(resolve, 0));+ saves.push(second());+ await new Promise((resolve) => setTimeout(resolve, 0));+ project.release();+ const results = await Promise.allSettled(saves);+ expect(project.refused).toEqual([]);+ expect(results.map((r) => r.status)).toEqual(["fulfilled", "fulfilled"]);+}++afterEach(() => {+ vi.unstubAllGlobals();+});++describe("two quick timeline saves on one file", () => {+ it("lands both moves", async () => {+ const project = fakeProject();+ await expectBothLand(+ project,+ () => move(project, "a", 3),+ () => move(project, "b", 4),+ );++ expect(project.read()).toContain('id="a" class="clip" data-start="3"');+ expect(project.read()).toContain('id="b" class="clip" data-start="4"');+ });++ it("lands both trims", async () => {+ const project = fakeProject();+ await expectBothLand(+ project,+ () => trim(project, "a", 3),+ () => trim(project, "b", 2),+ );++ expect(project.read()).toMatch(/id="a"[^>]*data-duration="3"/);+ expect(project.read()).toMatch(/id="b"[^>]*data-duration="2"/);+ });++ it("lands a move started while a volume save is writing", async () => {+ const project = fakeProject();+ const volume = () =>+ persistElementAttribute({+ ...shared(project),+ targetPath: "index.html",+ patchTarget: { id: "a" },+ attr: "data-volume",+ value: "0.5",+ label: "Set volume",+ patchLive: () => {},+ onFileRead: () => {},+ });+ await expectBothLand(project, volume, () => move(project, "b", 4));++ expect(project.read()).toContain('data-volume="0.5"');+ expect(project.read()).toContain('id="b" class="clip" data-start="4"');+ });++ it("keeps a move when a color grade starts while it is writing", async () => {+ const project = fakeProject();+ const grade = () =>+ applyColorGradingScopeUpdate({+ scope: "source-file",+ value: "warm",+ selectedSourceFile: "index.html",+ fileTree: ["index.html"],+ projectId: "p1",+ waitForPendingDomEditSaves: async () => {},+ readProjectFile: async () => project.read(),+ writeProjectFile: project.writeProjectFile,+ recordEdit: async () => {},+ reloadPreview: () => {},+ showToast: () => {},+ });+ await expectBothLand(project, () => move(project, "a", 3), grade);++ expect(project.read()).toContain('id="a" class="clip" data-start="3"');+ expect(project.read()).toContain('data-color-grading="warm"');+ });++ it("lands a move started while the previous move's GSAP rewrite is in flight", async () => {+ const project = fakeProject();+ const shiftA = finishClipTimingFallback({+ iframe: null,+ reloadPreview: () => {},+ projectId: "p1",+ targetPath: "index.html",+ domId: "a",+ label: "Move clip",+ recordEdit: async () => {},+ writeProjectFile: project.writeProjectFile,+ edit: { kind: "shift", delta: 2 },+ });+ const results = await Promise.allSettled([shiftA, move(project, "b", 4)]);++ expect(project.refused).toEqual([]);+ expect(results.map((r) => r.status)).toEqual(["fulfilled", "fulfilled"]);+ expect(project.read()).toContain('gsap.to("#a", { x: 1 }, 3)');+ expect(project.read()).toContain('id="b" class="clip" data-start="4"');+ });+});diff --git a/packages/studio/src/hooks/timelineTimingSync.test.ts b/packages/studio/src/hooks/timelineTimingSync.test.tsindex 8ff9dffcf4..956d843bfa 100644--- a/packages/studio/src/hooks/timelineTimingSync.test.ts+++ b/packages/studio/src/hooks/timelineTimingSync.test.ts@@ -11,6 +11,8 @@ import {shiftGsapPositions,} from "./timelineTimingSync";+const writeProjectFile = async () => {};+afterEach(() => {usePlayerStore.getState().reset();vi.restoreAllMocks();@@ -68,6 +70,7 @@ function clipFallbackInput(overrides: {domId: "clip",label: "Move timeline clip",recordEdit: overrides.recordEdit as never,+ writeProjectFile,edit: { kind: "shift", delta: 1 } as const,};}@@ -495,6 +498,7 @@ describe("nothing-to-rewrite timing edits rebind in place (no script re-executioconst element = { sourceFile: "index.html" } as TimelineElement;await finishGroupTimingGsapFallback({+ writeProjectFile,projectId: "p1",iframe,reloadPreview,@@ -522,6 +526,7 @@ describe("nothing-to-rewrite timing edits rebind in place (no script re-executioconst reloadPreview = vi.fn();await finishGroupTimingGsapFallback({+ writeProjectFile,projectId: "p1",iframe,reloadPreview,@@ -602,6 +607,7 @@ describe("foldGsapMutationIntoHistory — owned GSAP transaction", () => {let clipIndex = 0;await finishGroupTimingGsapFallback({+ writeProjectFile,projectId: "p1",iframe: buildLivePreviewIframe().iframe,reloadPreview: vi.fn(),@@ -632,6 +638,7 @@ describe("foldGsapMutationIntoHistory — owned GSAP transaction", () => {let clipIndex = 0;await finishGroupTimingGsapFallback({+ writeProjectFile,projectId: "p1",iframe: buildLivePreviewIframe().iframe,reloadPreview: vi.fn(),@@ -669,6 +676,7 @@ describe("foldGsapMutationIntoHistory — owned GSAP transaction", () => {const reloadPreview = vi.fn();await finishGroupTimingGsapFallback({+ writeProjectFile,projectId: "p1",iframe: buildLivePreviewIframe().iframe,reloadPreview,@@ -698,6 +706,7 @@ describe("foldGsapMutationIntoHistory — owned GSAP transaction", () => {let clipIndex = 0;await finishGroupTimingGsapFallback({+ writeProjectFile,projectId: "p1",iframe: buildLivePreviewIframe().iframe,reloadPreview,@@ -728,6 +737,7 @@ describe("foldGsapMutationIntoHistory — owned GSAP transaction", () => {const recordEdit = vi.fn(async () => {});await finishGroupTimingGsapFallback({+ writeProjectFile,projectId: "p1",iframe: buildLivePreviewIframe().iframe,reloadPreview: vi.fn(),@@ -762,6 +772,7 @@ describe("foldGsapMutationIntoHistory — owned GSAP transaction", () => {const reloadPreview = vi.fn();await finishGroupTimingGsapFallback({+ writeProjectFile,projectId: "p1",iframe: buildLivePreviewIframe().iframe,reloadPreview,@@ -797,6 +808,7 @@ describe("foldGsapMutationIntoHistory — owned GSAP transaction", () => {const server = installOwnedFileServer(contents, { failReadAt: 1 });await finishGroupTimingGsapFallback({+ writeProjectFile,projectId: "p1",iframe: buildLivePreviewIframe().iframe,reloadPreview: vi.fn(),diff --git a/packages/studio/src/hooks/timelineTimingSync.ts b/packages/studio/src/hooks/timelineTimingSync.tsindex c2514c4caa..e66ff3bc84 100644--- a/packages/studio/src/hooks/timelineTimingSync.ts+++ b/packages/studio/src/hooks/timelineTimingSync.ts@@ -7,10 +7,18 @@ import { applySoftReload, applySoftReloadFinalization } from "../utils/gsapSoftRimport { furthestClipEndFromDocument } from "../player/lib/timelineElementHelpers";import type { RecordEditInput } from "../utils/studioFileHistory";import { patchDocumentRootDuration } from "./timelineEditingGsap";-import { studioWriteHeaders } from "../utils/studioFileVersion";--class GsapPreviewConvergenceError extends Error {}-class GsapOwnershipProtocolError extends GsapPreviewConvergenceError {}+import {+ GsapOwnershipProtocolError,+ GsapPreviewConvergenceError,+ postGsapMutation,+ requireGsapOwnershipProtocol,+ rollbackOwnedMutation,+ type GsapMutationStatus,+} from "./gsapMutationClient";+import {+ serializeStudioFileMutations,+ type StudioProjectFileWriter,+} from "../utils/studioFileMutationCoordinator";export async function readFileContent(projectId: string, targetPath: string): Promise<string> {if (targetPath.includes("\0") || targetPath.includes("..")) {@@ -29,51 +37,6 @@ export async function readFileContent(projectId: string, targetPath: string): Prreturn data.content;}-/** Verify rollback ownership support before any GSAP mutation can land. */-async function requireGsapOwnershipProtocol(projectId: string): Promise<void> {- const response = await fetch(- `/api/projects/${encodeURIComponent(projectId)}/gsap-mutation-capabilities`,- );- if (!response.ok) {- throw new GsapOwnershipProtocolError("Server does not support owned GSAP mutations");- }- const body = await response.json().catch(() => null);- if (!isRecord(body) || body.atomicOwnershipPairs !== true) {- throw new GsapOwnershipProtocolError("Invalid GSAP mutation capability response");- }-}--/** Atomically restore one GSAP mutation only while its exact output still owns- * the file. The server performs compare + write synchronously, eliminating the- * client GET→PUT window that could overwrite a successor edit. */-async function rollbackOwnedMutation(- projectId: string,- targetPath: string,- expected: string,- restore: string,-): Promise<"restored" | "conflict"> {- if (targetPath.includes("\0") || targetPath.includes("..")) {- throw new Error(`Unsafe path: ${targetPath}`);- }- const response = await fetch(- `/api/projects/${encodeURIComponent(projectId)}/gsap-mutation-rollback/${encodeURIComponent(targetPath)}`,- {- method: "POST",- // Deliberately unclaimed: a rollback runs because a mutation did not- // converge, so let the restored file reload the preview.- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ expected, restore }),- },- );- if (!response.ok) {- throw new Error(`Failed to restore ${targetPath}`);- }- const result = (await response.json()) as { restored?: unknown; conflict?: unknown };- if (result.restored === true && result.conflict === false) return "restored";- if (result.restored === false && result.conflict === true) return "conflict";- throw new Error(`Invalid restore response for ${targetPath}`);-}-/** Best-effort live-iframe wrapper for patchDocumentRootDuration (see timelineEditingGsap). */function patchIframeRootDuration(iframe: HTMLIFrameElement | null, contentEnd: number): void {try {@@ -102,79 +65,6 @@ export function captureDurationRollback(iframe: HTMLIFrameElement | null): () =>};}-/**- * The bits of the server GSAP-mutation response the timeline edit path needs.- * `scriptText` is the rewritten root GSAP script — feeding it to `applySoftReload`- * swaps the runtime timeline in place (no iframe reload = no all-clips flash). Null- * when the endpoint didn't return one (older server, or a multi-script comp the- * soft path can't scope) — the caller then full-reloads when `mutated`, or- * rebinds the runtime timing in place when nothing was rewritten (see- * syncTimingEditPreview).- */-export type GsapMutationStatus = {- mutated: boolean;- scriptText: string | null;- /** Atomic whole-file ownership pair returned by the mutation endpoint. */- before?: string;- after?: string;-};--function isRecord(value: unknown): value is Record<string, unknown> {- return typeof value === "object" && value !== null;-}--function readMutationStatus(value: unknown): GsapMutationStatus {- if (- !isRecord(value) ||- typeof value.mutated !== "boolean" ||- typeof value.before !== "string" ||- typeof value.after !== "string" ||- value.mutated !== (value.before !== value.after) ||- ("changed" in value && value.changed !== value.mutated)- ) {- throw new GsapOwnershipProtocolError("Invalid owned GSAP mutation response");- }- return {- mutated: value.mutated,- scriptText: typeof value.scriptText === "string" ? value.scriptText : null,- before: value.before,- after: value.after,- };-}--function readMutationError(value: unknown, fallback: string): string {- if (isRecord(value) && typeof value.error === "string") return value.error;- return fallback;-}--async function postGsapMutation(- projectId: string,- filePath: string,- mutation: Record<string, unknown>,- fallback: string,-): Promise<GsapMutationStatus> {- let response: Response;- try {- response = await fetch(- `/api/projects/${encodeURIComponent(projectId)}/gsap-mutations/${encodeURIComponent(filePath)}`,- {- method: "POST",- headers: { "Content-Type": "application/json", ...studioWriteHeaders() },- body: JSON.stringify(mutation),- },- );- } catch (error) {- throw new GsapPreviewConvergenceError(`${fallback}: mutation outcome unknown`, {- cause: error,- });- }- const body: unknown = await response.json().catch(() => null);- if (!response.ok) {- throw new GsapPreviewConvergenceError(readMutationError(body, fallback));- }- return readMutationStatus(body);-}-/** Re-derive live timing windows without re-executing composition scripts.* Works for zero-GSAP compositions; false asks the caller to full-reload. */function rebindPreviewTiming(iframe: HTMLIFrameElement | null, currentTime: number): boolean {@@ -341,7 +231,7 @@ async function rollbackAfterFailure(// The ledger, reverse rollback, final ownership check, and history fold are one// transaction; extracting phases would obscure which function owns convergence.// fallow-ignore-next-line complexity-async function foldGsapMutationIntoHistory(input: {+async function foldGsapMutationInQueue(input: {projectId: string;label: string;coalesceKey?: string;@@ -411,6 +301,18 @@ async function foldGsapMutationIntoHistory(input: {return status;}+// The mutations, the ownership read and any rollback hold every touched file's queue.+function foldGsapMutationIntoHistory(+ input: Parameters<typeof foldGsapMutationInQueue>[0] & {+ writeFile: StudioProjectFileWriter;+ paths: readonly string[];+ },+): Promise<GsapMutationStatus> {+ return serializeStudioFileMutations(input.writeFile, input.paths, () =>+ foldGsapMutationInQueue(input),+ );+}+/*** Shift all GSAP animation positions targeting a given element by a time delta.* Calls the server-side GSAP mutation endpoint which uses the AST-based parser.@@ -491,6 +393,7 @@ export function finishClipTimingFallback(input: {label: string;coalesceKey?: string;recordEdit: (edit: RecordEditInput) => Promise<void>;+ writeProjectFile: StudioProjectFileWriter;edit: SingleClipGsapEdit;}): Promise<void> {const { projectId, targetPath, domId, edit } = input;@@ -519,6 +422,8 @@ export function finishClipTimingFallback(input: {timingChanged && domId && projectId? () =>foldGsapMutationIntoHistory({+ writeFile: input.writeProjectFile,+ paths: [targetPath],projectId,label: input.label,coalesceKey: input.coalesceKey,@@ -552,6 +457,7 @@ export async function finishGroupTimingGsapFallback<C extends { element: TimelinerrorLabel: string;coalesceKey?: string;recordEdit: (edit: RecordEditInput) => Promise<void>;+ writeProjectFile: StudioProjectFileWriter;activeCompPath: string | null;changes: readonly C[];resolveChangePath: (element: TimelineElement) => string;@@ -568,6 +474,8 @@ export async function finishGroupTimingGsapFallback<C extends { element: TimelinreloadPreview: input.reloadPreview,gsapMutation: () =>foldGsapMutationIntoHistory({+ writeFile: input.writeProjectFile,+ paths: input.changes.map((change) => input.resolveChangePath(change.element)),projectId: input.projectId,label: input.label,coalesceKey: input.coalesceKey,diff --git a/packages/studio/src/hooks/timelineTrackVisibility.ts b/packages/studio/src/hooks/timelineTrackVisibility.tsindex 0876dd9a91..19bbb88c8f 100644--- a/packages/studio/src/hooks/timelineTrackVisibility.ts+++ b/packages/studio/src/hooks/timelineTrackVisibility.ts@@ -9,11 +9,11 @@ import {} from "../player/components/timelineTrackDisplay";import { saveProjectFilesWithHistory } from "../utils/studioFileHistory";import { isAudioTimelineElement } from "../utils/timelineInspector";-import { readTagSnippetByTarget, type PatchOperation } from "../utils/sourcePatcher";+import type { PatchOperation } from "../utils/sourcePatcher";import {- applyPatchByTarget,- buildPatchTarget,findTimelineElementInIframe,+ operationChanges,+ patchTimelineChangesInSource,readFileContent,type RecordEditInput,} from "./timelineEditingHelpers";@@ -149,38 +149,24 @@ async function setElementsHidden({property: "hidden",value: hidden ? "" : null,};- const originalByPath = new Map<string, string>();- const files: Record<string, string> = {};-- try {- for (const [targetPath, fileElements] of groupElementsByTargetPath(elements, activeCompPath)) {- let patchedContent = await readFileContent(projectId, targetPath);- originalByPath.set(targetPath, patchedContent);-- for (const element of fileElements) {- const patchTarget = buildPatchTarget(element);- if (!patchTarget) {- throw new Error(`Timeline element ${element.id} is missing a patchable target`);- }- if (readTagSnippetByTarget(patchedContent, patchTarget) === undefined) {- throw new Error(`Unable to patch timeline element ${element.id} in ${targetPath}`);- }- patchedContent = applyPatchByTarget(patchedContent, patchTarget, hiddenOperation);- }-- files[targetPath] = patchedContent;+ const files: Record<string, (current: string) => string> = {};+ for (const [targetPath, fileElements] of groupElementsByTargetPath(elements, activeCompPath)) {+ files[targetPath] = (current) => {pendingTimelineEditPathRef.current.add(targetPath);- }+ return patchTimelineChangesInSource(+ current,+ targetPath,+ operationChanges(fileElements, hiddenOperation),+ );+ };+ }+ try {const changedPaths = await saveProjectFilesWithHistory({projectId,label,files,- readFile: async (path) => {- const original = originalByPath.get(path);- if (original !== undefined) return original;- return readFileContent(projectId, path);- },+ readFile: (path) => readFileContent(projectId, path),writeFile: writeProjectFile,recordEdit,});diff --git a/packages/studio/src/hooks/useClipboard.ts b/packages/studio/src/hooks/useClipboard.tsindex 2bdeef8d5e..1075b09dfc 100644--- a/packages/studio/src/hooks/useClipboard.ts+++ b/packages/studio/src/hooks/useClipboard.ts@@ -356,21 +356,17 @@ export function useClipboard({const targetPath = activeCompPath || "index.html";try {- const originalContent = await readFileContent(pid, targetPath);- let patchedContent: string;let pastedIds: string[] = [];-- if (payload.kind === "timeline-clip") {+ const paste = (originalContent: string) => {+ if (payload.kind !== "timeline-clip") return pasteElementHtml(originalContent, payload);const { currentTime, elements } = usePlayerStore.getState();const pasted = pasteTimelineClips(originalContent, payload.clips, currentTime, elements);+ pastedIds = pasted.ids;// A clip pasted past the current composition end would exist in the// file but never appear on the timeline or in playback/export (the// root's data-duration is what actually bounds the render).- patchedContent = extendRootDurationInSource(pasted.content, pasted.requiredEnd);- pastedIds = pasted.ids;- } else {- patchedContent = pasteElementHtml(originalContent, payload);- }+ return extendRootDurationInSource(pasted.content, pasted.requiredEnd);+ };const label =payload.kind === "timeline-clip"@@ -380,8 +376,8 @@ export function useClipboard({await saveProjectFilesWithHistory({projectId: pid,label,- files: { [targetPath]: patchedContent },- readFile: async () => originalContent,+ files: { [targetPath]: paste },+ readFile: (path) => readFileContent(pid, path),writeFile: writeProjectFile,recordEdit,});@@ -422,17 +418,19 @@ export function useClipboard({try {const clips = await readClips(targets);- const originalContent = await readFileContent(pid, targetPath);- const liveElements = usePlayerStore.getState().elements;- const pasted = pasteTimelineClips(originalContent, clips, anchorTime, liveElements);- const patchedContent = extendRootDurationInSource(pasted.content, pasted.requiredEnd);- const ids = pasted.ids;+ let ids: string[] = [];+ const duplicate = (originalContent: string) => {+ const liveElements = usePlayerStore.getState().elements;+ const pasted = pasteTimelineClips(originalContent, clips, anchorTime, liveElements);+ ids = pasted.ids;+ return extendRootDurationInSource(pasted.content, pasted.requiredEnd);+ };await saveProjectFilesWithHistory({projectId: pid,label: clipLabel("Duplicate", clips.length),- files: { [targetPath]: patchedContent },- readFile: async () => originalContent,+ files: { [targetPath]: duplicate },+ readFile: (path) => readFileContent(pid, path),writeFile: writeProjectFile,recordEdit,});diff --git a/packages/studio/src/hooks/useDomEditCommits.test.tsx b/packages/studio/src/hooks/useDomEditCommits.test.tsxindex f931d34645..60b5b554b0 100644--- a/packages/studio/src/hooks/useDomEditCommits.test.tsx+++ b/packages/studio/src/hooks/useDomEditCommits.test.tsx@@ -1252,8 +1252,15 @@ describe("useDomEditCommits style persist handling", () => {const secondCommit = rendered.hook.handleDomStyleCommit("color", "green");await flushAsyncWork();- expect(patchCount).toBe(2);+ // The newer commit waits for the older one in the file's queue.+ expect(patchCount).toBe(1);+ firstPatch.reject(new Error("server rejected blue"));+ await firstCommit;+ expect(element.style.getPropertyValue("color")).toBe("green");++ await flushAsyncWork();+ expect(patchCount).toBe(2);secondPatch.resolve(jsonResponse({ok: true,@@ -1263,10 +1270,6 @@ describe("useDomEditCommits style persist handling", () => {}),);await secondCommit;- expect(element.style.getPropertyValue("color")).toBe("green");-- firstPatch.reject(new Error("server rejected blue"));- await firstCommit;expect(element.style.getPropertyValue("color")).toBe("green");} finally {@@ -1698,15 +1701,16 @@ describe("useDomEditCommits attribute persist handling", () => {try {// Older commit's persist stays pending (captures previousValue=null); the// newer commit captures previousValue="first-value" (the older commit's- // optimistic apply) and succeeds before the older one rejects. Without the+ // optimistic apply) and is still queued when the older one rejects. Without the// per-key version guard, the stale rejection would revert to the older// commit's own previousValue (null) and stomp the newer commit's value.const firstCommit = rendered.hook.handleDomHtmlAttributeCommit("muted", "first-value");await act(async () => {- await rendered.hook.handleDomHtmlAttributeCommit("muted", "second-value");+ const secondCommit = rendered.hook.handleDomHtmlAttributeCommit("muted", "second-value");+ first.reject(new Error("stale request failed"));+ await firstCommit;+ await secondCommit;});- first.reject(new Error("stale request failed"));- await firstCommit;expect(element.getAttribute("muted")).toBe("second-value");} finally {diff --git a/packages/studio/src/hooks/useDomEditCommits.ts b/packages/studio/src/hooks/useDomEditCommits.tsindex 5c5d089d61..4a13a3a76f 100644--- a/packages/studio/src/hooks/useDomEditCommits.ts+++ b/packages/studio/src/hooks/useDomEditCommits.ts@@ -5,11 +5,7 @@ import { FONT_EXT } from "../utils/mediaTypes";import { trackStudioEvent } from "../utils/studioTelemetry";import { primaryFontFamilyValue } from "../utils/studioFontHelpers";-import {- createStudioSaveHttpError,- StudioSaveHttpError,- trackStudioSaveFailure,-} from "../utils/studioSaveDiagnostics";+import { StudioSaveHttpError, trackStudioSaveFailure } from "../utils/studioSaveDiagnostics";import { buildDomEditPatchTarget, type DomEditSelection } from "../components/editor/domEditing";import { fontFamilyFromAssetPath, type ImportedFontAsset } from "../components/editor/fontAssets";import type { CommitDomEditPatchBatches, PersistDomEditOperations } from "./domEditCommitTypes";@@ -26,15 +22,15 @@ import { useElementLifecycleOps } from "./useElementLifecycleOps";import {AtomicElementPatchConvergenceError,batchesAreInlineStyleOnly,- formatPatchRejectionMessage,formatUnsafeFieldList,- getErrorDetail,patchElementBatches,- readErrorResponseBody,+ postPatchElement,+ writePreparedContent,} from "./useDomEditCommitsHelpers";import type { CutoverResult } from "../utils/sdkCutover";-import { studioWriteHeaders } from "../utils/studioFileVersion";import { reseekPreviewRuntime } from "./timelineTrackVisibility";+import { serializeStudioFileMutations } from "../utils/studioFileMutationCoordinator";+import { readProjectFileContent } from "../utils/studioFileHistory";interface RecordEditInput {label: string;coalesceKey?: string;@@ -159,23 +155,13 @@ export function useDomEditCommits({return result;};- const readResponse = await fetch(- buildProjectApiPath(pid, `/files/${encodeURIComponent(targetPath)}`),- );- if (!readResponse.ok) {- throw await createStudioSaveHttpError(readResponse, `Failed to read ${targetPath}`);- }- const readData = (await readResponse.json()) as { content?: string };- const originalContent = readData.content;- if (typeof originalContent !== "string") {- throw new Error(`Missing file contents for ${targetPath}`);- }-- if (projectIdRef.current !== expectedProjectId) {- throw new Error("Active project changed before the edit could be saved");- }-- if (options?.shouldSave && !options.shouldSave()) return;+ const readTarget = async (): Promise<string | null> => {+ const content = await readProjectFileContent(pid, targetPath);+ if (projectIdRef.current !== expectedProjectId) {+ throw new Error("Active project changed before the edit could be saved");+ }+ return options?.shouldSave && !options.shouldSave() ? null : content;+ };// Validate layout values BEFORE any persist path runs. The SDK cutover// path (onTrySdkPersist) returns early on success, so leaving this check@@ -195,7 +181,10 @@ export function useDomEditCommits({// Skip the SDK path when prepareContent is set (e.g. @font-face injection// for a custom font): sdkCutoverPersist serializes only the patched DOM// and would drop the injected content. Let the server path run prepareContent.+ // The SDK joins the file queue itself and re-reads there; this read is only its fallback.if (onTrySdkPersist && !options?.prepareContent) {+ const originalContent = await readTarget();+ if (originalContent === null) return;const cutover = await onTrySdkPersist(selection, operations, originalContent, targetPath, {label: options?.label,coalesceKey: options?.coalesceKey,@@ -212,31 +201,41 @@ export function useDomEditCommits({}}- const patchResponse = await fetch(- buildProjectApiPath(pid, `/file-mutations/patch-element/${encodeURIComponent(targetPath)}`),- {- method: "POST",- headers: { "Content-Type": "application/json", ...studioWriteHeaders() },- body: JSON.stringify(patchBody),- },- );- if (!patchResponse.ok) {- showToast(formatPatchRejectionMessage(await readErrorResponseBody(patchResponse)), "error");- throw await createStudioSaveHttpError(patchResponse, `Failed to patch ${targetPath}`, {- alreadyToasted: true,- });- }-- const patchData = (await patchResponse.json()) as {- ok?: boolean;- changed?: boolean;- matched?: boolean;- content?: string;- path?: string;- version?: string;+ const history = {+ label: options?.label ?? "Edit layer",+ coalesceKey: options?.coalesceKey,+ coalesceMs: options?.coalesceMs,};+ const prepare = options?.prepareContent;+ // Read, server patch, follow-up write and history hold the file's queue, so no save lands between them.+ const saved = await serializeStudioFileMutations(writeProjectFile, [targetPath], async () => {+ const originalContent = await readTarget();+ if (originalContent === null) return null;+ const patchData = await postPatchElement(pid, targetPath, patchBody, showToast);+ if (!patchData.changed) return { patchData, patchedContent: null, finalContent: null };++ const patchedContent =+ typeof patchData.content === "string" ? patchData.content : originalContent;+ const finalContent = prepare+ ? await writePreparedContent(+ targetPath,+ patchedContent,+ prepare,+ writeProjectFile,+ showToast,+ )+ : patchedContent;++ await editHistory.recordEdit({+ ...history,+ files: { [targetPath]: { before: originalContent, after: finalContent } },+ });+ return { patchData, patchedContent, finalContent };+ });+ if (saved === null) return;+ const { patchData, patchedContent, finalContent } = saved;- if (!patchData.changed) {+ if (finalContent === null) {if (patchData.matched === false) {const targetKey = selection.selector ?? selection.id ?? "selection";if (!reportedUnresolvableRef.current.has(targetKey)) {@@ -258,36 +257,6 @@ export function useDomEditCommits({false,);}-- const patchedContent =- typeof patchData.content === "string" ? patchData.content : originalContent;-- let finalContent = patchedContent;- if (options?.prepareContent) {- const preparedContent = options.prepareContent(patchedContent, targetPath);- if (preparedContent !== patchedContent) {- try {- await writeProjectFile(targetPath, preparedContent, patchedContent);- finalContent = preparedContent;- } catch (error) {- // The patch above already landed on disk — only the prepareContent- // embellishment (e.g. an injected @font-face) failed to write. Keep- // the already-persisted patchedContent instead of throwing, which- // would otherwise revert a change the server already committed.- showToast(- `Saved, but couldn't finish updating ${targetPath}: ${getErrorDetail(error)}`,- "error",- );- }- }- }-- await editHistory.recordEdit({- label: options?.label ?? "Edit layer",- coalesceKey: options?.coalesceKey,- coalesceMs: options?.coalesceMs,- files: { [targetPath]: { before: originalContent, after: finalContent } },- });forceReloadSdkSession?.();if (!options?.skipRefresh) {@@ -350,24 +319,38 @@ export function useDomEditCommits({);}- const atomicResult = await patchElementBatches(pid, batches);- const allMatched =- atomicResult.durable && atomicResult.files.every((result) => result.allMatched);- const files = Object.fromEntries(- atomicResult.files- .filter((result) => result.changed)- .map((result) => [result.sourceFile, { before: result.before, after: result.after }]),+ const sourceFiles = batches.map((batch) => batch.sourceFile);+ // The server patch and its history entry hold every touched file's queue.+ const { allMatched, changed } = await serializeStudioFileMutations(+ writeProjectFile,+ sourceFiles,+ async () => {+ const atomicResult = await patchElementBatches(pid, batches);+ const files = Object.fromEntries(+ atomicResult.files+ .filter((result) => result.changed)+ .map((result) => [+ result.sourceFile,+ { before: result.before, after: result.after },+ ]),+ );+ const anyChanged = Object.keys(files).length > 0;+ if (anyChanged) {+ await editHistory.recordEdit({+ label: options.label,+ coalesceKey: options.coalesceKey,+ coalesceMs: options.coalesceMs,+ files,+ });+ }+ return {+ allMatched:+ atomicResult.durable && atomicResult.files.every((result) => result.allMatched),+ changed: anyChanged,+ };+ },);- const changed = Object.keys(files).length > 0;- if (changed) {- await editHistory.recordEdit({- label: options.label,- coalesceKey: options.coalesceKey,- coalesceMs: options.coalesceMs,- files,- });- forceReloadSdkSession?.();- }+ if (changed) forceReloadSdkSession?.();const durable = allMatched;// A z-only reorder already applied its inline styles to the live iframe// DOM (and the store) synchronously, so remounting the iframe here only@@ -399,7 +382,15 @@ export function useDomEditCommits({throw error;});},- [editHistory, forceReloadSdkSession, projectIdRef, queueDomEditSave, reloadPreview, showToast],+ [+ editHistory,+ forceReloadSdkSession,+ projectIdRef,+ queueDomEditSave,+ reloadPreview,+ showToast,+ writeProjectFile,+ ],);// ── Text & style commits (delegated to useDomEditTextCommits) ──diff --git a/packages/studio/src/hooks/useDomEditCommitsHelpers.ts b/packages/studio/src/hooks/useDomEditCommitsHelpers.tsindex a440c6e4ef..e9db2c69ef 100644--- a/packages/studio/src/hooks/useDomEditCommitsHelpers.ts+++ b/packages/studio/src/hooks/useDomEditCommitsHelpers.ts@@ -1,4 +1,9 @@-import { StudioSaveHttpError, trackStudioSaveFailure } from "../utils/studioSaveDiagnostics";+import {+ createStudioSaveHttpError,+ StudioSaveHttpError,+ trackStudioSaveFailure,+} from "../utils/studioSaveDiagnostics";+import { buildProjectApiPath } from "../utils/projectRouting";import type { DomEditPatchBatch } from "./domEditCommitTypes";import { formatFieldsSuffix } from "./gsapScriptCommitHelpers";import { studioWriteHeaders } from "../utils/studioFileVersion";@@ -7,11 +12,11 @@ export function formatUnsafeFieldList(fields: Array<{ path: string }>): string {return fields.map((field) => field.path).join(", ");}-export function getErrorDetail(error: unknown): string {+function getErrorDetail(error: unknown): string {return error instanceof Error ? error.message : String(error);}-export async function readErrorResponseBody(+async function readErrorResponseBody(response: Response,): Promise<{ error?: string; fields?: string[] } | null> {const contentType = response.headers.get("content-type") ?? "";@@ -19,9 +24,7 @@ export async function readErrorResponseBody(return (await response.json().catch(() => null)) as { error?: string; fields?: string[] } | null;}-export function formatPatchRejectionMessage(- body: { error?: string; fields?: string[] } | null,-): string {+function formatPatchRejectionMessage(body: { error?: string; fields?: string[] } | null): string {if (!body?.error) return "Couldn't save edit";return `Couldn't save edit: ${body.error}${formatFieldsSuffix(body.fields)}`;}@@ -157,3 +160,63 @@ export function batchesAreInlineStyleOnly(batches: DomEditPatchBatch[]): booleanbatch.patches.every((patch) => patch.operations.every((op) => op.type === "inline-style")),);}++export interface PatchElementResponse {+ ok?: boolean;+ changed?: boolean;+ matched?: boolean;+ content?: string;+ path?: string;+ version?: string;+}++type ShowToast = (message: string, tone?: "error" | "info") => void;++export async function postPatchElement(+ projectId: string,+ targetPath: string,+ body: unknown,+ showToast: ShowToast,+): Promise<PatchElementResponse> {+ const response = await fetch(+ buildProjectApiPath(+ projectId,+ `/file-mutations/patch-element/${encodeURIComponent(targetPath)}`,+ ),+ {+ method: "POST",+ headers: { "Content-Type": "application/json", ...studioWriteHeaders() },+ body: JSON.stringify(body),+ },+ );+ if (!response.ok) {+ showToast(formatPatchRejectionMessage(await readErrorResponseBody(response)), "error");+ throw await createStudioSaveHttpError(response, `Failed to patch ${targetPath}`, {+ alreadyToasted: true,+ });+ }+ return (await response.json()) as PatchElementResponse;+}++/** Writes `prepare`'s embellishment over the server's patch; returns what the file ends up holding. */+export async function writePreparedContent(+ targetPath: string,+ patchedContent: string,+ prepare: (html: string, sourceFile: string) => string,+ writeProjectFile: (path: string, content: string, expectedContent?: string) => Promise<void>,+ showToast: ShowToast,+): Promise<string> {+ const preparedContent = prepare(patchedContent, targetPath);+ if (preparedContent === patchedContent) return patchedContent;+ try {+ await writeProjectFile(targetPath, preparedContent, patchedContent);+ return preparedContent;+ } catch (error) {+ // The patch already landed on disk; keep it rather than revert a committed change.+ showToast(+ `Saved, but couldn't finish updating ${targetPath}: ${getErrorDetail(error)}`,+ "error",+ );+ return patchedContent;+ }+}diff --git a/packages/studio/src/hooks/useEditorSave.ts b/packages/studio/src/hooks/useEditorSave.tsindex 38a8e00685..f0ccba7a15 100644--- a/packages/studio/src/hooks/useEditorSave.ts+++ b/packages/studio/src/hooks/useEditorSave.ts@@ -107,7 +107,7 @@ export function useEditorSave({projectId: candidate.projectId,label: "Edit source",coalesceKey: `source:${candidate.path}`,- files: { [candidate.path]: candidate.content },+ files: { [candidate.path]: () => candidate.content },readFile: readProjectFile,writeFile: writeProjectFile,recordEdit,diff --git a/packages/studio/src/hooks/useElementLifecycleOps.ts b/packages/studio/src/hooks/useElementLifecycleOps.tsindex 9b5ee2feef..3352457c81 100644--- a/packages/studio/src/hooks/useElementLifecycleOps.ts+++ b/packages/studio/src/hooks/useElementLifecycleOps.ts@@ -3,7 +3,7 @@ import { useCallback } from "react";import { usePlayerStore } from "../player";import {readProjectFileContent,- saveProjectFilesWithHistory,+ saveServerRewriteWithHistory,type DomEditCommitBaseParams,} from "../utils/studioFileHistory";import { createStudioSaveHttpError } from "../utils/studioSaveDiagnostics";@@ -111,8 +111,6 @@ export function useElementLifecycleOps({(candidate) => (candidate.sourceFile || activeCompPath || "index.html") === targetPath,);try {- const originalContent = await readProjectFileContent(pid, targetPath);-const patchTargets = sameFile.map((member) => buildDomEditPatchTarget(member));if (patchTargets.some((t) => !t.id && !t.selector && !t.hfId)) {throw new Error("Selected element has no patchable target");@@ -125,6 +123,7 @@ export function useElementLifecycleOps({.map((member) => member.hfId).filter((hfId): hfId is string => Boolean(hfId));if (onTrySdkDelete && hfIds.length === sameFile.length) {+ const originalContent = await readProjectFileContent(pid, targetPath);let allHandled = true;for (const hfId of hfIds) {// The SDK owns the document it edits, so every member is removed@@ -150,28 +149,41 @@ export function useElementLifecycleOps({// cost a round trip and a rewrite of the file EACH, and a canvas// selection runs to hundreds of members — the file ended up correct, but// only after long enough that Delete looked like it had done nothing.- const removeResponse = await fetch(- buildProjectApiPath(- pid,- `/file-mutations/remove-elements/${encodeURIComponent(targetPath)}`,- ),- {- method: "POST",- headers: { "Content-Type": "application/json", ...studioWriteHeaders() },- body: JSON.stringify({ targets: patchTargets }),+ const deleted = await saveServerRewriteWithHistory({+ projectId: pid,+ path: targetPath,+ label: "Delete element",+ writeFile: writeProjectFile,+ recordEdit: editHistory.recordEdit,+ rewrite: async (originalContent) => {+ const removeResponse = await fetch(+ buildProjectApiPath(+ pid,+ `/file-mutations/remove-elements/${encodeURIComponent(targetPath)}`,+ ),+ {+ method: "POST",+ headers: { "Content-Type": "application/json", ...studioWriteHeaders() },+ body: JSON.stringify({ targets: patchTargets }),+ },+ );+ if (!removeResponse.ok) {+ throw await createStudioSaveHttpError(+ removeResponse,+ `Failed to delete element from ${targetPath}`,+ );+ }+ const removeData = (await removeResponse.json()) as {+ changed?: boolean;+ content?: string;+ };+ if (!removeData.changed) return null;+ return {+ disk: typeof removeData.content === "string" ? removeData.content : originalContent,+ };},- );- if (!removeResponse.ok) {- throw await createStudioSaveHttpError(- removeResponse,- `Failed to delete element from ${targetPath}`,- );- }- const removeData = (await removeResponse.json()) as {- changed?: boolean;- content?: string;- };- if (!removeData.changed) {+ });+ if (!deleted) {// A member the file no longer holds simply does not match, which is// normal for one nested inside another member already removed. Nothing// matching at all means the preview is describing a document the file@@ -180,19 +192,6 @@ export function useElementLifecycleOps({showToast("Nothing to delete, the preview was out of date. Try again.");return domEditCommitDeclined("preview-stale");}- const patchedContent =- typeof removeData.content === "string" ? removeData.content : originalContent;- await saveProjectFilesWithHistory({- projectId: pid,- label: "Delete element",- files: { [targetPath]: patchedContent },- readFile: async () => originalContent,- // remove-element already wrote the removal, so disk holds THAT — not- // the content read at the top. Undo still goes back to the original.- diskContent: { [targetPath]: patchedContent },- writeFile: writeProjectFile,- recordEdit: editHistory.recordEdit,- });clearDomSelection();usePlayerStore.getState().setSelectedElementId(null);diff --git a/packages/studio/src/hooks/useFileManager.ts b/packages/studio/src/hooks/useFileManager.tsindex 0023375a20..9010ffb175 100644--- a/packages/studio/src/hooks/useFileManager.ts+++ b/packages/studio/src/hooks/useFileManager.ts@@ -4,6 +4,7 @@ import { FONT_EXT, isMediaFile } from "../utils/mediaTypes";import { fontFamilyFromAssetPath, type ImportedFontAsset } from "../components/editor/fontAssets";import { findTagByTarget, type PatchTarget } from "../utils/sourcePatcher";import { StudioFileConflictError } from "../utils/studioSaveDiagnostics";+import { serializeStudioFileMutation } from "../utils/studioFileMutationCoordinator";import { useFileTree } from "./useFileTree";import { useEditorSave } from "./useEditorSave";import { useProjectFileWriter } from "./useProjectFileWriter";@@ -98,16 +99,18 @@ export function useFileManager({const overwriteExternalConflict = useCallback(async (conflict: StudioFileConflictError) => {- if (conflict.currentContent != null) {- await writeProjectFile(- conflict.filePath,- conflict.attemptedContent,- conflict.currentContent,- );- } else {- fileVersions.set(conflict.filePath, conflict.currentVersion);- await writeProjectFile(conflict.filePath, conflict.attemptedContent);- }+ await serializeStudioFileMutation(writeProjectFile, conflict.filePath, async () => {+ if (conflict.currentContent != null) {+ await writeProjectFile(+ conflict.filePath,+ conflict.attemptedContent,+ conflict.currentContent,+ );+ } else {+ fileVersions.set(conflict.filePath, conflict.currentVersion);+ await writeProjectFile(conflict.filePath, conflict.attemptedContent);+ }+ });updateEditingFileContent(conflict.filePath, conflict.attemptedContent);},[fileVersions, updateEditingFileContent, writeProjectFile],diff --git a/packages/studio/src/hooks/useGroupCommits.ts b/packages/studio/src/hooks/useGroupCommits.tsindex 4e230a04aa..29628dcb82 100644--- a/packages/studio/src/hooks/useGroupCommits.ts+++ b/packages/studio/src/hooks/useGroupCommits.ts@@ -1,8 +1,7 @@import { buildProjectApiPath } from "../utils/projectRouting";import { useCallback } from "react";import {- readProjectFileContent,- saveProjectFilesWithHistory,+ saveServerRewriteWithHistory,type DomEditCommitBaseParams,} from "../utils/studioFileHistory";import {@@ -125,36 +124,36 @@ async function commitStructuralMutation(| "reloadPreview">,): Promise<{ content?: string; groupId?: string }> {- const originalContent = await readProjectFileContent(pid, targetPath);-- const mutateResponse = await fetch(- buildProjectApiPath(pid, `/file-mutations/${route}/${encodeURIComponent(targetPath)}`),- {- method: "POST",- headers: { "Content-Type": "application/json", ...studioWriteHeaders() },- body: JSON.stringify(body),- },- );- if (!mutateResponse.ok) {- const errBody = (await mutateResponse.json().catch(() => null)) as { error?: string } | null;- throw new Error(errBody?.error ?? `Failed to ${label.toLowerCase()} in ${targetPath}`);- }- const mutateData = (await mutateResponse.json()) as { content?: string; groupId?: string };- const patchedContent =- typeof mutateData.content === "string" ? mutateData.content : originalContent;-- await saveProjectFilesWithHistory({+ let result: { content?: string; groupId?: string } = {};+ await saveServerRewriteWithHistory({projectId: pid,+ path: targetPath,label,- files: { [targetPath]: patchedContent },- readFile: async () => originalContent,writeFile: deps.writeProjectFile,recordEdit: deps.editHistory.recordEdit,+ rewrite: async (originalContent) => {+ const mutateResponse = await fetch(+ buildProjectApiPath(pid, `/file-mutations/${route}/${encodeURIComponent(targetPath)}`),+ {+ method: "POST",+ headers: { "Content-Type": "application/json", ...studioWriteHeaders() },+ body: JSON.stringify(body),+ },+ );+ if (!mutateResponse.ok) {+ const errBody = (await mutateResponse.json().catch(() => null)) as {+ error?: string;+ } | null;+ throw new Error(errBody?.error ?? `Failed to ${label.toLowerCase()} in ${targetPath}`);+ }+ result = (await mutateResponse.json()) as { content?: string; groupId?: string };+ return { disk: typeof result.content === "string" ? result.content : originalContent };+ },});deps.clearDomSelection();deps.forceReloadSdkSession?.();deps.reloadPreview();- return mutateData;+ return result;}export function useGroupCommits(params: UseGroupCommitsParams) {diff --git a/packages/studio/src/hooks/useGsapAnimationOps.ts b/packages/studio/src/hooks/useGsapAnimationOps.tsindex 95f9ea97ec..fafaa9fb79 100644--- a/packages/studio/src/hooks/useGsapAnimationOps.ts+++ b/packages/studio/src/hooks/useGsapAnimationOps.ts@@ -1,4 +1,8 @@import { useCallback } from "react";+import {+ serializeStudioFileMutation,+ type StudioProjectFileWriter,+} from "../utils/studioFileMutationCoordinator";import type { Composition } from "@hyperframes/sdk";import type { DomEditSelection } from "../components/editor/domEditingTypes";import { roundTo3 } from "../utils/rounding";@@ -27,6 +31,7 @@ interface GsapAnimationOpsParams extends SdkAnimationDeps {commitMutation: CommitMutation;commitMutationSafely: SafeGsapCommitMutation;showToast: (message: string, tone?: "error" | "info") => void;+ writeProjectFile?: StudioProjectFileWriter;}export function useGsapAnimationOps({@@ -37,6 +42,7 @@ export function useGsapAnimationOps({showToast,sdkSession,sdkDeps,+ writeProjectFile,}: GsapAnimationOpsParams) {const updateGsapMeta = useCallback(async (@@ -122,13 +128,17 @@ export function useGsapAnimationOps({const pid = projectIdRef.current;const targetPath = selection.sourceFile || activeCompPath || "index.html";if (!pid) return;- const assigned = await assignGsapTargetAutoIdIfNeeded({- projectId: pid,- targetPath,- selection,- autoId,- showToast,- });+ const assign = () =>+ assignGsapTargetAutoIdIfNeeded({+ projectId: pid,+ targetPath,+ selection,+ autoId,+ showToast,+ });+ const assigned = await (writeProjectFile+ ? serializeStudioFileMutation(writeProjectFile, targetPath, assign)+ : assign());if (!assigned) return;}@@ -181,7 +191,15 @@ export function useGsapAnimationOps({{ label: `Add GSAP ${method} animation`, softReload: true },);},- [activeCompPath, commitMutation, projectIdRef, showToast, sdkSession, sdkDeps],+ [+ activeCompPath,+ commitMutation,+ projectIdRef,+ showToast,+ sdkSession,+ sdkDeps,+ writeProjectFile,+ ],);type KeyframeEntry = {diff --git a/packages/studio/src/hooks/useGsapScriptCommits.ts b/packages/studio/src/hooks/useGsapScriptCommits.tsindex 9c4689f7f2..efdad24d3a 100644--- a/packages/studio/src/hooks/useGsapScriptCommits.ts+++ b/packages/studio/src/hooks/useGsapScriptCommits.ts@@ -523,6 +523,7 @@ export function useGsapScriptCommits({ projectIdRef, activeCompPath, previewIfrashowToast,sdkSession,sdkDeps,+ writeProjectFile,});const keyframeOps = useGsapKeyframeOps({activeCompPath,diff --git a/packages/studio/src/hooks/useTimelineAssetDropOps.ts b/packages/studio/src/hooks/useTimelineAssetDropOps.tsindex e30d86ca48..47e1397284 100644--- a/packages/studio/src/hooks/useTimelineAssetDropOps.ts+++ b/packages/studio/src/hooks/useTimelineAssetDropOps.ts@@ -109,8 +109,6 @@ export function useTimelineAssetDropOps({}try {- const originalContent = await readFileContent(pid, targetPath);-const normalizedStart = Number(formatTimelineAttributeNumber(placement.start));const duration =Number.isFinite(durationOverride) && durationOverride != null && durationOverride > 0@@ -120,7 +118,6 @@ export function useTimelineAssetDropOps({// A video with an audio stream lands audible; the mixer only hears a// <video> marked data-has-audio, and a muted drop was losing the sound.const hasAudio = await resolveDroppedAssetHasAudio(pid, assetPath, kind);- const newId = buildTimelineAssetId(assetPath, collectHtmlIds(originalContent));const resolvedAssetSrc = resolveTimelineAssetSrc(targetPath, assetPath);const resolvedTargetPath = targetPath || "index.html";@@ -129,45 +126,51 @@ export function useTimelineAssetDropOps({);const newElementZIndex = Math.max(1, relevantElements.length + 1);- const { source: sourceWithRoom, track } = resolveDropTrack({- source: originalContent,- // insertRow counts the rows the timeline shows, so plan against those.- elements: relevantElements,- placement,- dropped: {- id: newId,- tag: kind === "image" ? "img" : kind,- start: normalizedStart,- duration: normalizedDuration,- },- });- const patchedContent = extendRootDurationInSource(- insertTimelineAssetIntoSource(- sourceWithRoom,- buildTimelineAssetInsertHtml({+ let newId = "";+ let track = 0;+ const insertAsset = (originalContent: string) => {+ newId = buildTimelineAssetId(assetPath, collectHtmlIds(originalContent));+ const resolved = resolveDropTrack({+ source: originalContent,+ // insertRow counts the rows the timeline shows, so plan against those.+ elements: relevantElements,+ placement,+ dropped: {id: newId,- hfId: `hf-${generateId()}`,- assetPath: resolvedAssetSrc,- kind,+ tag: kind === "image" ? "img" : kind,start: normalizedStart,duration: normalizedDuration,- track,- zIndex: newElementZIndex,- hasAudio,- geometry: fitTimelineAssetGeometry(- null,- resolveTimelineAssetCompositionSize(originalContent),- ),- }),- ),- normalizedStart + normalizedDuration,- );+ },+ });+ track = resolved.track;+ return extendRootDurationInSource(+ insertTimelineAssetIntoSource(+ resolved.source,+ buildTimelineAssetInsertHtml({+ id: newId,+ hfId: `hf-${generateId()}`,+ assetPath: resolvedAssetSrc,+ kind,+ start: normalizedStart,+ duration: normalizedDuration,+ track,+ zIndex: newElementZIndex,+ hasAudio,+ geometry: fitTimelineAssetGeometry(+ null,+ resolveTimelineAssetCompositionSize(originalContent),+ ),+ }),+ ),+ normalizedStart + normalizedDuration,+ );+ };await saveProjectFilesWithHistory({projectId: pid,label: "Add timeline asset",- files: { [targetPath]: patchedContent },- readFile: async () => originalContent,+ files: { [targetPath]: insertAsset },+ readFile: (path) => readFileContent(pid, path),writeFile: writeProjectFile,recordEdit,});diff --git a/packages/studio/src/hooks/useTimelineDeleteOps.ts b/packages/studio/src/hooks/useTimelineDeleteOps.tsindex ec0c1c014c..0503d9705f 100644--- a/packages/studio/src/hooks/useTimelineDeleteOps.ts+++ b/packages/studio/src/hooks/useTimelineDeleteOps.ts@@ -5,11 +5,11 @@ import { buildProjectApiPath } from "../utils/projectRouting";import { useCallback, useRef, type MutableRefObject, type RefObject } from "react";import type { TimelineElement } from "../player";import { usePlayerStore } from "../player";-import { saveProjectFilesWithHistory, type RecordEditInput } from "../utils/studioFileHistory";+import { saveServerRewriteWithHistory, type RecordEditInput } from "../utils/studioFileHistory";import { studioWriteHeaders } from "../utils/studioFileVersion";import { getTimelineElementLabel } from "../utils/studioHelpers";import { buildPatchTarget, removeIframeTimelineElements } from "./timelineEditingHelpers";-import { captureDurationRollback, readFileContent } from "./timelineTimingSync";+import { captureDurationRollback } from "./timelineTimingSync";import { setCompositionDurationToContent } from "../utils/timelineAssetDrop";import { furthestClipEndFromSource } from "../player/lib/timelineElementHelpers";import {@@ -100,71 +100,68 @@ export function useTimelineDeleteOps({(candidate) => (candidate.sourceFile || activeCompPath || "index.html") === targetPath,);try {- const originalContent = await readFileContent(pid, targetPath);-- // Remove every selected element before saving once. The server rewrites- // the file per call, so `removedContent` after the last one holds them- // all — which is what makes this a single history entry, and a single- // undo, rather than one per clip.- let removedContent = originalContent;- for (const target of sameFile) {- const patchTarget = buildPatchTarget(target);- if (!patchTarget) {- throw new Error(`Timeline element ${target.id} is missing a patchable target`);- }-- const removeResponse = await fetch(- buildProjectApiPath(- pid,- `/file-mutations/remove-element/${encodeURIComponent(targetPath)}`,- ),- {- method: "POST",- headers: { "Content-Type": "application/json", ...studioWriteHeaders() },- body: JSON.stringify({ target: patchTarget }),- },- );- if (!removeResponse.ok) {- throw new Error(`Failed to delete ${target.id} from ${targetPath}`);- }-- const removeData = (await removeResponse.json()) as {- changed?: boolean;- content?: string;- };- if (typeof removeData.content === "string") removedContent = removeData.content;- }- // Content-driven duration: shrink the composition to the furthest- // remaining clip end, read from the post-removal SOURCE (raw- // data-duration), so deleting the last/longest clip removes trailing- // empty space. Measured from the source, not the store, whose- // durations are runtime-truncated.- const deleteContentEnd = furthestClipEndFromSource(removedContent);- const patchedContent = setCompositionDurationToContent(removedContent, deleteContentEnd);- // Optimistically reflect the shrunk length in the readout/seek bar,- // rolling it back if the persist below fails (see captureDurationRollback).- const rollbackDuration = captureDurationRollback(previewIframeRef.current);- if (deleteContentEnd > 0 && targetPath === (activeCompPath || "index.html")) {- usePlayerStore.getState().setDuration(deleteContentEnd);- }-// Shared with the ripple move below so a folded ripple is one undo// step with the delete, not two (editHistory.ts coalesces by key +// window across separate recordEdit calls, not by label).const coalesceKey = `main-track-ripple-delete:${deleteGestureSeq++}`;const deleteHistoryLabel = "Delete timeline clip";+ let rollbackDuration = () => {};try {- await saveProjectFilesWithHistory({+ await saveServerRewriteWithHistory({projectId: pid,+ path: targetPath,label: deleteHistoryLabel,coalesceKey,- files: { [targetPath]: patchedContent },- readFile: async () => originalContent,- // remove-element already wrote the removal, so disk holds THAT — not the- // content read at the top. Undo still goes back to the original.- diskContent: { [targetPath]: removedContent },writeFile: writeProjectFile,recordEdit,+ rewrite: async (originalContent) => {+ // Remove every selected element before saving once. The server rewrites+ // the file per call, so `removedContent` after the last one holds them+ // all — which is what makes this a single history entry, and a single+ // undo, rather than one per clip.+ let removedContent = originalContent;+ for (const target of sameFile) {+ const patchTarget = buildPatchTarget(target);+ if (!patchTarget) {+ throw new Error(`Timeline element ${target.id} is missing a patchable target`);+ }++ const removeResponse = await fetch(+ buildProjectApiPath(+ pid,+ `/file-mutations/remove-element/${encodeURIComponent(targetPath)}`,+ ),+ {+ method: "POST",+ headers: { "Content-Type": "application/json", ...studioWriteHeaders() },+ body: JSON.stringify({ target: patchTarget }),+ },+ );+ if (!removeResponse.ok) {+ throw new Error(`Failed to delete ${target.id} from ${targetPath}`);+ }++ const removeData = (await removeResponse.json()) as {+ changed?: boolean;+ content?: string;+ };+ if (typeof removeData.content === "string") removedContent = removeData.content;+ }+ // Shrink to the furthest remaining clip end, read from the post-removal source:+ // store durations are runtime-truncated.+ const deleteContentEnd = furthestClipEndFromSource(removedContent);+ const patchedContent = setCompositionDurationToContent(+ removedContent,+ deleteContentEnd,+ );+ // Optimistically reflect the shrunk length in the readout/seek bar,+ // rolling it back if the persist below fails (see captureDurationRollback).+ rollbackDuration = captureDurationRollback(previewIframeRef.current);+ if (deleteContentEnd > 0 && targetPath === (activeCompPath || "index.html")) {+ usePlayerStore.getState().setDuration(deleteContentEnd);+ }+ return { disk: removedContent, after: patchedContent };+ },});} catch (error) {rollbackDuration();diff --git a/packages/studio/src/hooks/useTimelineEditing.ts b/packages/studio/src/hooks/useTimelineEditing.tsindex 245ea62534..e3bad2ef74 100644--- a/packages/studio/src/hooks/useTimelineEditing.ts+++ b/packages/studio/src/hooks/useTimelineEditing.ts@@ -243,6 +243,7 @@ export function useTimelineEditing({label: "Move timeline clip",coalesceKey,recordEdit,+ writeProjectFile,edit: { kind: "shift", delta: updates.start - element.start },}).finally(() => invalidateGsapCache?.());const moveFallback = () =>@@ -346,6 +347,7 @@ export function useTimelineEditing({label: "Resize timeline clip",coalesceKey,recordEdit,+ writeProjectFile,edit: {kind: "scale",from: { start: element.start, duration: element.duration },diff --git a/packages/studio/src/hooks/useTimelineGroupEditing.ts b/packages/studio/src/hooks/useTimelineGroupEditing.tsindex 5b1a051277..70923e934e 100644--- a/packages/studio/src/hooks/useTimelineGroupEditing.ts+++ b/packages/studio/src/hooks/useTimelineGroupEditing.ts@@ -330,6 +330,7 @@ export function useTimelineGroupEditing({errorLabel: "Failed to shift GSAP positions",coalesceKey,recordEdit,+ writeProjectFile,activeCompPath,changes,resolveChangePath: (element) => targetPathFor(element, activeCompPath),@@ -365,6 +366,7 @@ export function useTimelineGroupEditing({trySdkBatchPersist,showToast,invalidateGsapCache,+ writeProjectFile,],);@@ -437,6 +439,7 @@ export function useTimelineGroupEditing({errorLabel: "Failed to scale GSAP positions",coalesceKey,recordEdit,+ writeProjectFile,activeCompPath,changes,resolveChangePath: (element) => targetPathFor(element, activeCompPath),@@ -478,6 +481,7 @@ export function useTimelineGroupEditing({trySdkBatchPersist,showToast,invalidateGsapCache,+ writeProjectFile,],);diff --git a/packages/studio/src/utils/blockInstaller.ts b/packages/studio/src/utils/blockInstaller.tsindex 6784710615..f4cf59a924 100644--- a/packages/studio/src/utils/blockInstaller.ts+++ b/packages/studio/src/utils/blockInstaller.ts@@ -9,6 +9,7 @@ import { collectHtmlIds } from "./studioHelpers";import { generateId } from "./generateId";import { formatTimelineAttributeNumber } from "../player/components/timelineEditing";import { saveProjectFilesWithHistory } from "./studioFileHistory";+import { serializeStudioFileMutation } from "./studioFileMutationCoordinator";import { extendRootDurationInSource } from "./rootDuration";import { deriveTimelineStoreKeyForDomId } from "../player/lib/timelineElementHelpers";@@ -93,12 +94,14 @@ async function makeComponentBackgroundTransparent(writeProjectFile: AddBlockOptions["writeProjectFile"],): Promise<void> {if (block.type !== "hyperframes:component") return;- const content = await readProjectFile(compositionFile);- const transparentContent = content.replace(- /background:\s*(?:#(?:0a0a0a|000000|000|0a0805)|rgba?\([^)]*\))\s*;/g,- "background: transparent;",- );- if (transparentContent !== content) await writeProjectFile(compositionFile, transparentContent);+ await serializeStudioFileMutation(writeProjectFile, compositionFile, async () => {+ const content = await readProjectFile(compositionFile);+ const transparentContent = content.replace(+ /background:\s*(?:#(?:0a0a0a|000000|000|0a0805)|rgba?\([^)]*\))\s*;/g,+ "background: transparent;",+ );+ if (transparentContent !== content) await writeProjectFile(compositionFile, transparentContent);+ });}function resolveBlockPlacement({@@ -201,7 +204,6 @@ export async function addBlockToProject();const targetPath = activeCompPath || "index.html";- const originalContent = await readProjectFile(targetPath);const relevantElements = timelineElements.filter((element) => (element.sourceFile || targetPath) === targetPath,);@@ -211,29 +213,32 @@ export async function addBlockToProject(timelineElements: relevantElements,currentTime: opts.currentTime ?? 0,});- const { width, height } = resolveTimelineAssetCompositionSize(originalContent);- const hostId = buildUniqueCompositionId(block.name, collectHtmlIds(originalContent));- const subComposition = buildSubCompositionHtml({- id: hostId,- compositionFile,- start,- duration,- track,- width,- height,- left: visualPosition ? Math.round(visualPosition.left) : 0,- top: visualPosition ? Math.round(visualPosition.top) : 0,- zIndex: getMaxZIndexFromIframe(opts.previewIframe ?? null) + 1,- });- const patchedContent = extendRootDurationInSource(- insertTimelineAssetIntoSource(originalContent, subComposition),- start + duration,- );+ let hostId = "";+ const insertHost = (originalContent: string) => {+ const { width, height } = resolveTimelineAssetCompositionSize(originalContent);+ hostId = buildUniqueCompositionId(block.name, collectHtmlIds(originalContent));+ const subComposition = buildSubCompositionHtml({+ id: hostId,+ compositionFile,+ start,+ duration,+ track,+ width,+ height,+ left: visualPosition ? Math.round(visualPosition.left) : 0,+ top: visualPosition ? Math.round(visualPosition.top) : 0,+ zIndex: getMaxZIndexFromIframe(opts.previewIframe ?? null) + 1,+ });+ return extendRootDurationInSource(+ insertTimelineAssetIntoSource(originalContent, subComposition),+ start + duration,+ );+ };await saveProjectFilesWithHistory({projectId,label: `Add ${isBlock ? "block" : "component"}: ${block.title}`,- files: { [targetPath]: patchedContent },- readFile: async () => originalContent,+ files: { [targetPath]: insertHost },+ readFile: readProjectFile,writeFile: writeProjectFile,recordEdit,});diff --git a/packages/studio/src/utils/studioFileHistory.test.ts b/packages/studio/src/utils/studioFileHistory.test.tsindex f0bfdad517..31392e2b7d 100644--- a/packages/studio/src/utils/studioFileHistory.test.ts+++ b/packages/studio/src/utils/studioFileHistory.test.ts@@ -11,7 +11,7 @@ describe("saveProjectFilesWithHistory", () => {await saveProjectFilesWithHistory({projectId: "project-1",label: "Move layer",- files: { "index.html": "after" },+ files: { "index.html": () => "after" },readFile: async (path) => reads[path],writeFile: async (path, content) => {writes[path] = content;@@ -40,7 +40,7 @@ describe("saveProjectFilesWithHistory", () => {await saveProjectFilesWithHistory({projectId: "project-1",label: "Delete timeline clip",- files: { "index.html": "removed+shrunk" },+ files: { "index.html": () => "removed+shrunk" },readFile: async () => "original",diskContent: { "index.html": "removed" },writeFile: async (path, _content, expectedContent) => {@@ -64,7 +64,7 @@ describe("saveProjectFilesWithHistory", () => {await saveProjectFilesWithHistory({projectId: "project-1",label: "Move layer",- files: { "index.html": "after" },+ files: { "index.html": () => "after" },readFile: async () => "before",writeFile: async (path, _content, expectedContent) => {expectations[path] = expectedContent;@@ -81,7 +81,7 @@ describe("saveProjectFilesWithHistory", () => {const changedPaths = await saveProjectFilesWithHistory({projectId: "project-1",label: "Edit layer",- files: { "index.html": "same" },+ files: { "index.html": () => "same" },readFile: async () => "same",writeFile,recordEdit,@@ -105,8 +105,8 @@ describe("saveProjectFilesWithHistory", () => {projectId: "project-1",label: "Move layer",files: {- "index.html": "index-after",- "scene.html": "scene-after",+ "index.html": () => "index-after",+ "scene.html": () => "scene-after",},readFile: async (path) => reads[path],writeFile: async (path, content) => {@@ -139,8 +139,8 @@ describe("saveProjectFilesWithHistory", () => {projectId: "project-1",label: "Move layer",files: {- "index.html": "index-after",- "scene.html": "scene-after",+ "index.html": () => "index-after",+ "scene.html": () => "scene-after",},readFile: async (path) => reads[path],writeFile: async (path, content) => {@@ -172,8 +172,8 @@ describe("saveProjectFilesWithHistory", () => {projectId: "project-1",label: "Move layer",files: {- "index.html": "index-after",- "scene.html": "scene-after",+ "index.html": () => "index-after",+ "scene.html": () => "scene-after",},readFile: async (path) => reads[path],writeFile: async (path, content) => {@@ -196,7 +196,7 @@ describe("saveProjectFilesWithHistory", () => {]);});- it("reads and writes after an earlier same-file mutation completes", async () => {+ it("builds from what the file holds after an earlier same-file mutation completes", async () => {let disk = "before";let release!: () => void;const blocked = new Promise<void>((resolve) => {@@ -215,7 +215,7 @@ describe("saveProjectFilesWithHistory", () => {const save = saveProjectFilesWithHistory({projectId: "project-1",label: "Edit source",- files: { "index.html": "editor-after" },+ files: { "index.html": (current) => `${current}+editor` },readFile,writeFile,recordEdit,@@ -227,10 +227,10 @@ describe("saveProjectFilesWithHistory", () => {await priorMutation;await save;- expect(disk).toBe("editor-after");+ expect(disk).toBe("sdk-after+editor");expect(recordEdit).toHaveBeenCalledWith(expect.objectContaining({- files: { "index.html": { before: "sdk-after", after: "editor-after" } },+ files: { "index.html": { before: "sdk-after", after: "sdk-after+editor" } },}),);});diff --git a/packages/studio/src/utils/studioFileHistory.ts b/packages/studio/src/utils/studioFileHistory.tsindex 288cd7d563..bdbb58d23a 100644--- a/packages/studio/src/utils/studioFileHistory.ts+++ b/packages/studio/src/utils/studioFileHistory.ts@@ -27,7 +27,7 @@ interface SaveProjectFilesWithHistoryInput {label: string;coalesceKey?: string;coalesceMs?: number;- files: Record<string, string>;+ files: Record<string, (contentInsideFileQueue: string) => string>;readFile: (path: string) => Promise<string>;writeFile: ProjectFileWriter;recordEdit: (entry: RecordEditInput) => Promise<void>;@@ -68,6 +68,34 @@ export async function saveProjectFilesWithHistory();}+/**+ * A server-side rewrite and its undo entry, holding the file's queue from the read to the history write.+ * `rewrite` returns what the server left on disk (and the edit's final content if it goes further), or null.+ */+export async function saveServerRewriteWithHistory(input: {+ projectId: string;+ path: string;+ label: string;+ coalesceKey?: string;+ writeFile: ProjectFileWriter;+ recordEdit: (entry: RecordEditInput) => Promise<void>;+ rewrite: (original: string) => Promise<{ disk: string; after?: string } | null>;+}): Promise<boolean> {+ const { projectId, path, writeFile } = input;+ return serializeStudioFileMutations(writeFile, [path], async () => {+ const original = await readProjectFileContent(projectId, path);+ const result = await input.rewrite(original);+ if (!result) return false;+ await writeProjectFilesWithHistoryInQueue({+ ...input,+ files: { [path]: () => result.after ?? result.disk },+ readFile: async () => original,+ diskContent: { [path]: result.disk },+ });+ return true;+ });+}+export async function writeProjectFilesWithHistoryInQueue({label,coalesceKey,@@ -79,8 +107,9 @@ export async function writeProjectFilesWithHistoryInQueue({diskContent,}: SaveProjectFilesWithHistoryInput): Promise<string[]> {const snapshots: Record<string, { before: string; after: string }> = {};- for (const [path, after] of Object.entries(files)) {+ for (const [path, build] of Object.entries(files)) {const before = await readFile(path);+ const after = build(before);if (before !== after) {snapshots[path] = { before, after };}