Write HTML. Render video. Built for agents.
JavaScript aiai-agentsanimationclaude-codeffmpegframeworkgsaphtmlhtml-to-videomcpmotion-graphicspuppeteerrenderingtypescriptvideo-editor
perf(studio): drag and resize any number of selected clips, saved in one write per file (#4937)
Miguel Ángelcd82ce044d9f
diff --git a/packages/parsers/src/clipTweens.ts b/packages/parsers/src/clipTweens.tsindex 525a8810b5..088f42dd4e 100644--- a/packages/parsers/src/clipTweens.ts+++ b/packages/parsers/src/clipTweens.ts@@ -8,14 +8,27 @@ type TweenTime = Pick<GsapAnimation, "position" | "implicitPosition">;export function clipTweenMatcher(clipSelectors: string | readonly string[],root?: ParentNode,+ queries: Map<string, Element[]> = new Map(),): (tween: TweenTarget) => boolean {const own = typeof clipSelectors === "string" ? [clipSelectors] : clipSelectors;- const clips = root ? own.flatMap((selector) => queryAll(root, selector)) : [];+ if (!root)+ return ({ targetSelector, hasPartialSelector }) =>+ !hasPartialSelector && own.includes(targetSelector);+ const queryAll = (selector: string): Element[] => {+ if (ID_SELECTOR.test(selector)) {+ if (!queries.has(ALL_IDS)) indexIds(root, queries);+ return queries.get(selector) ?? [];+ }+ let found = queries.get(selector);+ if (!found) queries.set(selector, (found = queryRoot(root, selector)));+ return found;+ };+ const clips = own.flatMap((selector) => queryAll(selector));return ({ targetSelector, hasPartialSelector }) => {if (hasPartialSelector) return false;if (own.includes(targetSelector)) return true;- if (!root || clips.length === 0) return false;- const targets = queryAll(root, targetSelector);+ if (clips.length === 0) return false;+ const targets = queryAll(targetSelector);return (targets.length > 0 &&targets.every((target) => {@@ -38,7 +51,23 @@ export function hasExplicitTime<T extends TweenTime>(return typeof animation.position === "number" && !animation.implicitPosition;}-function queryAll(root: ParentNode, selector: string): Element[] {+const ID_SELECTOR = /^#-?[A-Za-z_][\w-]*$/;+const ALL_IDS = "[id]";++// One DOM walk answers every `#id` lookup; a query per clip cost ~3 ms each on a 100-clip file.+function indexIds(root: ParentNode, queries: Map<string, Element[]>): void {+ const all = queryRoot(root, ALL_IDS);+ queries.set(ALL_IDS, all);+ for (const el of all) {+ const key = `#${el.id}`;+ if (!ID_SELECTOR.test(key)) continue;+ const list = queries.get(key);+ if (list) list.push(el);+ else queries.set(key, [el]);+ }+}++function queryRoot(root: ParentNode, selector: string): Element[] {try {return Array.from(root.querySelectorAll(selector));} catch {diff --git a/packages/parsers/src/gsapWriter.parity.test.ts b/packages/parsers/src/gsapWriter.parity.test.tsindex 13a7f9e204..84401d55be 100644--- a/packages/parsers/src/gsapWriter.parity.test.ts+++ b/packages/parsers/src/gsapWriter.parity.test.ts@@ -57,6 +57,8 @@ import {removeAnimationFromScript as removeAnimAcorn,shiftPositionsInScript as shiftAcorn,scalePositionsInScript as scaleAcorn,+ retimeClipTweensInScript,+ type ClipTweenRetime,dedupePositionWritesInScript as dedupePosAcorn,} from "./gsapWriterAcorn.js";@@ -1985,6 +1987,131 @@ tl.to("#el", { y: 50, duration: 1 }, "+=0.5");`;});});+describe("retimeClipTweensInScript: one parse, the bytes of one call per retime", () => {+ const { document } = parseHTML(`<html><body>+<div id="scene" data-start="1" data-duration="4"><h1>Hi</h1><p id="child">Kid</p></div>+<div id="side" data-start="0" data-duration="8"></div>+</body></html>`);+ const script = `const tl = gsap.timeline({ paused: true });+tl.from("#scene", { opacity: 0, duration: 1 }, 1);+tl.from("#scene h1", { y: 20, duration: 1.25 }, 1.5);+tl.to("#child", { rotation: 90 });+tl.to(["#child", "#side"], { x: 1, duration: 1 }, 0.2);+tl.to("#side", { x: 5, duration: 1 }, 2);+tl.to("#side", { y: 5, duration: 1 }, "+=0.5");+tl.to("#hero", { opacity: 0, duration: 0.5 }, 0.0004);`;+ const oneByOne = (source: string, retimes: ClipTweenRetime[]) =>+ retimes.reduce(+ (current, r) =>+ r.kind === "shift"+ ? shiftAcorn(current, r.targetSelector, r.delta, document)+ : scaleAcorn(+ current,+ r.targetSelector,+ r.oldStart,+ r.oldDuration,+ r.newStart,+ r.newDuration,+ document,+ ),+ source,+ );+ const cases: Array<[string, ClipTweenRetime[]]> = [+ [+ "shifts of several clips, one clamped at zero",+ [+ { kind: "shift", targetSelector: "#scene", delta: 2 },+ { kind: "shift", targetSelector: "#side", delta: -0.5 },+ { kind: "shift", targetSelector: "#hero", delta: 0.3333 },+ ],+ ],+ [+ "two retimes landing on the same tween, in order",+ [+ { kind: "shift", targetSelector: "#child", delta: -0.3 },+ {+ kind: "scale",+ targetSelector: "#side",+ oldStart: 0,+ oldDuration: 8,+ newStart: 1,+ newDuration: 3,+ },+ { kind: "shift", targetSelector: "#side", delta: 0.75 },+ ],+ ],+ [+ "scales then a shift of the parent clip",+ [+ {+ kind: "scale",+ targetSelector: "#scene",+ oldStart: 1,+ oldDuration: 4,+ newStart: 1,+ newDuration: 7,+ },+ {+ kind: "scale",+ targetSelector: "#scene",+ oldStart: 1,+ oldDuration: 7,+ newStart: 2,+ newDuration: 7,+ },+ { kind: "shift", targetSelector: "#scene", delta: -1.5 },+ ],+ ],+ ];+ for (const [name, retimes] of cases) {+ it(name, () => {+ const folded = retimeClipTweensInScript(script, retimes, document);+ expect(folded.script).toBe(oneByOne(script, retimes));+ expect(folded.script).not.toBe(script);+ });+ }++ it("answers every #id lookup from one DOM walk, duplicate ids included", () => {+ const { document: dup } = parseHTML(`<html><body>+<div id="a" data-start="0" data-duration="2"></div><div id="b" data-start="0" data-duration="2"></div>+<div id="a" data-start="3" data-duration="2"></div></body></html>`);+ const retimes: ClipTweenRetime[] = ["#a", "#b", "#c"].map((targetSelector) => ({+ kind: "shift",+ targetSelector,+ delta: 1,+ }));+ const source = `const tl = gsap.timeline();\ntl.to("#b", { x: 1 }, 1);\ntl.to("#a", { y: 1 }, 2);`;+ const expected = retimes.reduce(+ (current, r) =>+ r.kind === "shift" ? shiftAcorn(current, r.targetSelector, r.delta, dup) : current,+ source,+ );+ const queried: string[] = [];+ const real = dup.querySelectorAll.bind(dup);+ dup.querySelectorAll = ((selector: string) => (+ queried.push(selector), real(selector)+ )) as typeof real;+ expect(retimeClipTweensInScript(source, retimes, dup).script).toBe(expected);+ expect(queried).toEqual(["[id]"]);+ });++ it("reports which retimes moved something and leaves a script nothing matches alone", () => {+ const folded = retimeClipTweensInScript(+ script,+ [+ { kind: "shift", targetSelector: "#nobody", delta: 1 },+ { kind: "shift", targetSelector: "#side", delta: 1 },+ ],+ document,+ );+ expect(folded.changed).toEqual([false, true]);+ const none = retimeClipTweensInScript(script, [+ { kind: "shift", targetSelector: "#nobody", delta: 1 },+ ]);+ expect(none.script).toBe(script);+ });+});+describe("shift/scalePositionsInScript carry the clip's inner tweens", () => {const { document } = parseHTML(`<html><body><div id="scene" data-start="1" data-duration="4">diff --git a/packages/parsers/src/gsapWriterAcorn.ts b/packages/parsers/src/gsapWriterAcorn.tsindex 33370b9f4f..19c3019042 100644--- a/packages/parsers/src/gsapWriterAcorn.ts+++ b/packages/parsers/src/gsapWriterAcorn.ts@@ -435,17 +435,82 @@ export function shiftPositionsInScript(delta: number,root?: ParentNode,): string {- const parsed = parseGsapScriptAcornForWrite(script);- if (!parsed) return script;- const carries = clipTweenMatcher(targetSelector, root);+ return retimeClipTweensInScript(script, [{ kind: "shift", targetSelector, delta }], root).script;+}++export type ClipTweenRetime =+ | { kind: "shift"; targetSelector: string; delta: number }+ | {+ kind: "scale";+ targetSelector: string;+ oldStart: number;+ oldDuration: number;+ newStart: number;+ newDuration: number;+ };++const isLiveRetime = (r: ClipTweenRetime) =>+ r.kind === "shift" || (r.oldDuration > 0 && r.newDuration > 0);++/** Moves `animation`'s written position and duration for one retime; says which of the two it wrote. */+function applyRetime(+ animation: GsapAnimation,+ retime: ClipTweenRetime,+): { position: boolean; duration: boolean } {+ if (retime.kind === "shift") {+ if (!hasExplicitTime(animation)) return { position: false, duration: false };+ animation.position = shiftedPosition(animation.position, retime.delta);+ return { position: true, duration: false };+ }+ const touched = { position: false, duration: false };+ if (!isLiveRetime(retime) || typeof animation.position !== "number") return touched;+ const ratio = retime.newDuration / retime.oldDuration;+ if (hasExplicitTime(animation)) {+ const scaled = retime.newStart + (animation.position - retime.oldStart) * ratio;+ animation.position = Math.max(0, Math.round(scaled * 1000) / 1000);+ touched.position = true;+ }+ if (typeof animation.duration === "number" && animation.duration > 0) {+ animation.duration = Math.max(0.001, Math.round(animation.duration * ratio * 1000) / 1000);+ touched.duration = true;+ }+ return touched;+}++/**+ * Applies `retimes` in order with one parse: the bytes equal running shift/scalePositionsInScript once+ * per retime. `changed[i]` says whether retime i moved a value.+ */+export function retimeClipTweensInScript(+ script: string,+ retimes: readonly ClipTweenRetime[],+ root?: ParentNode,+): { script: string; changed: boolean[] } {+ const changed = retimes.map(() => false);+ const parsed = retimes.some(isLiveRetime) ? parseGsapScriptAcornForWrite(script) : null;+ if (!parsed) return { script, changed };+ // Matchers share one query cache: each selector is looked up in the DOM once, not once per clip.+ const queries = new Map<string, Element[]>();+ const matchers = retimes.map((r) => clipTweenMatcher(r.targetSelector, root, queries));const ms = new MagicString(script);- let changed = false;+ let wrote = false;for (const entry of parsed.located) {- if (!carries(entry.animation) || !hasExplicitTime(entry.animation)) continue;- overwritePosition(ms, entry.call, shiftedPosition(entry.animation.position, delta));- changed = true;+ const animation = { ...entry.animation };+ let position = false;+ let duration = false;+ retimes.forEach((retime, i) => {+ if (!matchers[i]!(animation)) return;+ const before = [animation.position, animation.duration];+ const touched = applyRetime(animation, retime);+ position ||= touched.position;+ duration ||= touched.duration;+ if (before[0] !== animation.position || before[1] !== animation.duration) changed[i] = true;+ });+ if (position) overwritePosition(ms, entry.call, animation.position as number);+ if (duration) upsertProp(ms, entry.call.varsArg, "duration", animation.duration);+ wrote ||= position || duration;}- return changed ? ms.toString() : script;+ return { script: wrote ? ms.toString() : script, changed };}/** Copies each tween on `fromSelector` for `toSelector`, `delta` seconds later, in its own argument text. Exact or@@ -559,29 +624,11 @@ export function scalePositionsInScript(newDuration: number,root?: ParentNode,): string {- if (oldDuration <= 0 || newDuration <= 0) return script;- const ratio = newDuration / oldDuration;- const parsed = parseGsapScriptAcornForWrite(script);- if (!parsed) return script;- const carries = clipTweenMatcher(targetSelector, root);- const ms = new MagicString(script);- let changed = false;- for (const entry of parsed.located) {- if (!carries(entry.animation) || typeof entry.animation.position !== "number") continue;- if (hasExplicitTime(entry.animation)) {- const newPos = Math.max(- 0,- Math.round((newStart + (entry.animation.position - oldStart) * ratio) * 1000) / 1000,- );- overwritePosition(ms, entry.call, newPos);- }- if (typeof entry.animation.duration === "number" && entry.animation.duration > 0) {- const newDur = Math.max(0.001, Math.round(entry.animation.duration * ratio * 1000) / 1000);- upsertProp(ms, entry.call.varsArg, "duration", newDur);- }- changed = true;- }- return changed ? ms.toString() : script;+ return retimeClipTweensInScript(+ script,+ [{ kind: "scale", targetSelector, oldStart, oldDuration, newStart, newDuration }],+ root,+ ).script;}export function addAnimationToScript(diff --git a/packages/studio-server/src/history/projectHistory.test.ts b/packages/studio-server/src/history/projectHistory.test.tsindex fa846ec88a..ca5a839ed5 100644--- a/packages/studio-server/src/history/projectHistory.test.ts+++ b/packages/studio-server/src/history/projectHistory.test.ts@@ -1625,6 +1625,19 @@ describe("claim: a writer that records after writing", () => {expect(history.list()[0]).toMatchObject({ id: first!.id, files: [{ path: "index.html" }] });});+ it("dates a held claim by its last write, not by the later edit that commits it", async () => {+ let clock = 1_000;+ const { history, write } = await project({ "index.html": "A" }, { now: () => clock });+ const held = { idleMs: Number.POSITIVE_INFINITY };+ write("index.html", "B");+ await history.claim(you, "Moved clip", ["index.html"], { ...held, coalesceKey: "move:1" });+ clock = 600_000;+ write("index.html", "C");+ await history.claim(you, "Moved clip", ["index.html"], { ...held, coalesceKey: "move:2" });++ expect(history.list().map((entry) => entry.endedAt)).toEqual([1_000]);+ });+it("a coalescing claim whose writes net to nothing returns null and records nothing", async () => {const { history, write } = await project({ "index.html": "A" });write("index.html", "B");diff --git a/packages/studio-server/src/history/projectHistory.ts b/packages/studio-server/src/history/projectHistory.tsindex 787ba3ba20..0ba9409a6b 100644--- a/packages/studio-server/src/history/projectHistory.ts+++ b/packages/studio-server/src/history/projectHistory.ts@@ -734,6 +734,7 @@ class Engine {? setTimeout(() => this.background(() => this.commitClaim()), idleMs): undefined;timer?.unref?.();+ group.lastWriteAt = this.now();this.claimed = { group, key, timer };return group.changes.size ? { id: group.id } : null;}diff --git a/packages/studio-server/src/routes/files.test.ts b/packages/studio-server/src/routes/files.test.tsindex 50315bea52..caec102039 100644--- a/packages/studio-server/src/routes/files.test.ts+++ b/packages/studio-server/src/routes/files.test.ts@@ -2759,6 +2759,60 @@ tl.to("#b", { duration: 1, x: 200 }, 2);expect(batch.after).toBe(seqAfter);});+ it("a gsap-mutations-batch of clip retimes writes what single requests in turn write", async () => {+ // #k is keyframed after t=0, so every write re-syncs its position hold.+ const SCENE = `<!DOCTYPE html><html><body>+<div id="a" data-start="1" data-duration="2"></div><div id="b" data-start="2" data-duration="2"></div>+<div id="k" data-start="0" data-duration="6"></div>+<script data-hyperframes-gsap>+const tl = gsap.timeline({ paused: true });+tl.to("#a", { duration: 1, x: 100 }, 1);+tl.to("#b", { duration: 1.5, x: 200 }, 2);+tl.to("#k", { keyframes: [{ x: 10 }, { x: 40 }], duration: 2 }, 1.5);+</script></body></html>`;+ const mutations = [+ { type: "shift-positions", targetSelector: "#a", delta: 1 },+ { type: "shift-positions", targetSelector: "#nobody", delta: 0 },+ {+ type: "scale-positions",+ targetSelector: "#b",+ oldStart: 2,+ oldDuration: 2,+ newStart: 2.5,+ newDuration: 3,+ },+ { type: "shift-positions", targetSelector: "#k", delta: 0.75 },+ ];+ const post = (app: Hono, path: string, body: unknown) =>+ app.request(`http://localhost/projects/demo/${path}`, {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify(body),+ });++ const seqDir = createProjectDir();+ writeHtml(seqDir, "scene.html", SCENE);+ const seqApp = new Hono();+ registerFileRoutes(seqApp, createAdapter(seqDir));+ let seqAfter = "";+ for (const mutation of mutations) {+ const res = await post(seqApp, "gsap-mutations/scene.html", mutation);+ seqAfter = ((await res.json()) as { after: string }).after;+ }++ const batchDir = createProjectDir();+ writeHtml(batchDir, "scene.html", SCENE);+ const batchApp = new Hono();+ registerFileRoutes(batchApp, createAdapter(batchDir));+ const res = await post(batchApp, "gsap-mutations-batch/scene.html", { mutations });+ const batch = (await res.json()) as { after: string; mutationChanges: boolean[] };++ expect(res.status).toBe(200);+ expect(batch.after).toBe(seqAfter);+ expect(batch.after).not.toBe(SCENE);+ expect(batch.mutationChanges).toEqual([true, false, true, true]);+ });+it("reports no GSAP mutation for shift-positions-batch in a file with no GSAP script", async () => {// Same contract as its shift-positions / scale-positions siblings: a file with// no GSAP block is a no-op {ok, changed:false}, not a 400.diff --git a/packages/studio-server/src/routes/files.ts b/packages/studio-server/src/routes/files.tsindex 03476dc847..4ec9f359b3 100644--- a/packages/studio-server/src/routes/files.ts+++ b/packages/studio-server/src/routes/files.ts@@ -76,8 +76,8 @@ import {replaceTweenWithKeyframesInScript,splitAnimationsInScript,splitIntoPropertyGroupsFromScript,- shiftPositionsInScript,- scalePositionsInScript,+ retimeClipTweensInScript,+ type ClipTweenRetime,dedupePositionWritesInScript,syncPositionHoldsBeforeKeyframes,clipQueryRoot,@@ -1491,6 +1491,46 @@ async function prepareGsapMutationScript(return { html, beforeHtml, block };}+type RetimeSlot = ClipTweenRetime | "no-op";++function retimeRuns(mutations: readonly GsapMutationRequest[]): Map<number, RetimeSlot[]> {+ const runs = new Map<number, RetimeSlot[]>();+ let start = -1;+ mutations.forEach((mutation, index) => {+ const retime = clipRetimeOf(mutation);+ if (!retime) return void (start = -1);+ if (start < 0) runs.set((start = index), []);+ runs.get(start)!.push(retime);+ });+ return runs;+}++// The one owner of the clip-retime no-op rules; a no-op keeps its slot so flags line up.+function clipRetimeOf(mutation: GsapMutationRequest): RetimeSlot | null {+ if (mutation.type === "shift-positions") {+ const { targetSelector, delta } = mutation;+ return targetSelector && Number.isFinite(delta) && delta !== 0+ ? { kind: "shift", targetSelector, delta }+ : "no-op";+ }+ if (mutation.type !== "scale-positions") return null;+ const { targetSelector, oldStart, oldDuration, newStart, newDuration } = mutation;+ const finite = [oldStart, oldDuration, newStart, newDuration].every(Number.isFinite);+ if (!targetSelector || !finite || oldDuration <= 0 || newDuration <= 0) return "no-op";+ if (oldStart === newStart && oldDuration === newDuration) return "no-op";+ return { kind: "scale", targetSelector, oldStart, oldDuration, newStart, newDuration };+}++function retimeRun(script: string, run: readonly RetimeSlot[], root: ParentNode | undefined) {+ const live = run.filter((slot): slot is ClipTweenRetime => slot !== "no-op");+ const retimed = retimeClipTweensInScript(script, live, root);+ const synced = syncPositionHoldsBeforeKeyframes(retimed.script);+ let next = 0;+ const changed = run.map((slot) => slot !== "no-op" && retimed.changed[next++]!);+ if (synced !== retimed.script) changed[changed.length - 1] = true;+ return { script: synced, changed: synced === script ? changed.map(() => false) : changed };+}+async function applyGsapMutations(c: RouteContext,res: ResolvedGsapFile,@@ -1516,7 +1556,17 @@ async function applyGsapMutations(}const mutationChanges: boolean[] = [];- for (const mutation of mutations) {+ const retimes = writer === "acorn" ? retimeRuns(mutations) : new Map<number, RetimeSlot[]>();+ for (let index = 0; index < mutations.length; index++) {+ const run = retimes.get(index);+ if (run) {+ const retimed = retimeRun(block.scriptText, run, block.root);+ mutationChanges.push(...retimed.changed);+ block.scriptText = retimed.script;+ index += run.length - 1;+ continue;+ }+ const mutation = mutations[index]!;const previousScript = block.scriptText;const result = await executeGsapMutation(mutation, block, respond, writer);if (result instanceof Response) return result;@@ -1864,41 +1914,18 @@ function executeGsapMutationAcorn(case "unroll-timeline": {return unrollComputedTimeline(block.scriptText);}- case "shift-positions": {- const { targetSelector, delta } = body;- if (!targetSelector || !Number.isFinite(delta) || delta === 0) return block.scriptText;- return shiftPositionsInScript(block.scriptText, targetSelector, delta, block.root);- }case "shift-positions-batch": {- let script = block.scriptText;- for (const s of body.shifts) {- if (!s.targetSelector || !Number.isFinite(s.delta) || s.delta === 0) continue;- script = shiftPositionsInScript(script, s.targetSelector, s.delta, block.root);- }- return script;+ const shifts = body.shifts+ .filter((s) => s.targetSelector && Number.isFinite(s.delta) && s.delta !== 0)+ .map((s) => ({ kind: "shift" as const, targetSelector: s.targetSelector, delta: s.delta }));+ return retimeClipTweensInScript(block.scriptText, shifts, block.root).script;}+ case "shift-positions":case "scale-positions": {- const { targetSelector, oldStart, oldDuration, newStart, newDuration } = body;- if (- !targetSelector ||- !Number.isFinite(oldStart) ||- !Number.isFinite(oldDuration) ||- !Number.isFinite(newStart) ||- !Number.isFinite(newDuration) ||- oldDuration <= 0 ||- newDuration <= 0- )- return block.scriptText;- if (oldStart === newStart && oldDuration === newDuration) return block.scriptText;- return scalePositionsInScript(- block.scriptText,- targetSelector,- oldStart,- oldDuration,- newStart,- newDuration,- block.root,- );+ const retime = clipRetimeOf(body);+ return retime && retime !== "no-op"+ ? retimeClipTweensInScript(block.scriptText, [retime], block.root).script+ : block.scriptText;}default:return respond({ error: `unknown mutation type: ${(body as { type: string }).type}` }, 400);diff --git a/packages/studio/src/components/editor/commitPreflightHandles.test.tsx b/packages/studio/src/components/editor/commitPreflightHandles.test.tsxindex c772626c9a..1d98005fa4 100644--- a/packages/studio/src/components/editor/commitPreflightHandles.test.tsx+++ b/packages/studio/src/components/editor/commitPreflightHandles.test.tsx@@ -207,6 +207,13 @@ async function select(animations: GsapAnimation[] | null, props: Partial<EditorPreturn view;}+async function selectLoopedPair() {+ const a = resolved(element("a"));+ const b = resolved(element("b"));+ const view = await select([loop({ x: 120 }, "#a")], { selection: a, groups: [a, b] });+ return { a, b, ...view };+}+describe("handles follow what Studio would commit", () => {beforeEach(() => {HTMLElement.prototype.setPointerCapture = () => undefined;@@ -442,6 +449,31 @@ describe("handles follow what Studio would commit", () => {expect(spies.onManualDragStart).not.toHaveBeenCalled();});+ it("re-checks only the members that changed when the group is handed back anew", async () => {+ const { a, b, seen, render } = await selectLoopedPair();+ const [narrowedA, narrowedB] = seen.groups;++ render({ selection: a, groups: [a, b] });+ expect(seen.groups[0]).toBe(narrowedA);+ expect(seen.groups[1]).toBe(narrowedB);+ const movedA = resolved(a.element);+ render({ selection: movedA, groups: [movedA, b] });+ expect(seen.groups[0]).not.toBe(narrowedA);+ expect(flags(seen.groups[0]!)[0]).toBe(false);+ expect(seen.groups[1]).toBe(narrowedB);+ });++ it("checks again on a new cache version even when that re-read fails", async () => {+ const { a, b, seen, render } = await selectLoopedPair();+ const [narrowedA] = seen.groups;++ parses.fetch.mockResolvedValueOnce(null);+ render({ selection: a, groups: [a, b], version: 1 });+ await settle();+ expect(seen.groups[0]).not.toBe(narrowedA);+ expect(flags(seen.groups[0]!)[0]).toBe(false);+ });+it.each([["rotation", loop({ rotation: 90 }), [true, true, false], { dots: 4, rotate: false }],["resize", loop({ width: 320, height: 90 }), [true, false, true], { dots: 0, rotate: true }],diff --git a/packages/studio/src/components/editor/domEditingLayers.test.ts b/packages/studio/src/components/editor/domEditingLayers.test.tsindex 629275a827..17ba52d670 100644--- a/packages/studio/src/components/editor/domEditingLayers.test.ts+++ b/packages/studio/src/components/editor/domEditingLayers.test.ts@@ -1,5 +1,5 @@// @vitest-environment jsdom-import { describe, expect, it } from "vitest";+import { afterEach, describe, expect, it, vi } from "vitest";import {collectDomEditLayerItems,resolveDomEditSelection,@@ -100,6 +100,37 @@ describe("resolveDomEditSelection — hfId from data-hf-id", () => {});});+describe("resolveDomEditSelection — source probe on re-resolve", () => {+ afterEach(() => vi.unstubAllGlobals());+ const probing = { activeCompositionPath: "index.html", isMasterView: true, projectId: "p" };++ it("asks the server once per node and target; re-resolving the same pair keeps the answer", async () => {+ const fetchMock = vi.fn(() =>+ Promise.resolve({ ok: true, json: () => Promise.resolve({ exists: [false] }) }),+ );+ vi.stubGlobal("fetch", fetchMock);+ const el = document.createElement("div");+ el.id = "generated";+ document.body.appendChild(el);++ const first = await resolveDomEditSelection(el, probing);+ const again = await resolveDomEditSelection(el, { ...probing, previous: first });+ el.id = "renamed";+ await resolveDomEditSelection(el, { ...probing, previous: again });+ el.id = "generated";+ const replaced = document.createElement("div");+ replaced.id = "generated";+ el.replaceWith(replaced);+ await resolveDomEditSelection(replaced, { ...probing, previous: again });+ replaced.remove();++ expect(first?.existsInSource).toBe(false);+ expect(again?.existsInSource).toBe(false);+ expect(again?.capabilities.canMove).toBe(false);+ expect(fetchMock).toHaveBeenCalledTimes(3);+ });+});+describe("resolveDomEditSelection — data-hf-group capture", () => {// <div id="parent"><div data-hf-group="Group 1"><div data-hf-group="Group 2">// <span id="child"/></div></div></div>@@ -236,17 +267,19 @@ describe("buildTextFieldChildLocator", () => {});});-describe("collectDomEditLayerItems item budget", () => {- function documentWith(count: number): HTMLElement {- const root = document.createElement("div");- root.setAttribute("data-composition-id", "index.html");- for (let i = 0; i < count; i++) {- const child = document.createElement("div");- child.id = `el-${i}`;- root.append(child);- }- return root;+function compositionWith(count: number, child: (el: HTMLElement, i: number) => void): HTMLElement {+ const root = document.createElement("div");+ root.setAttribute("data-composition-id", "index.html");+ for (let i = 0; i < count; i++) {+ const el = document.createElement("div");+ child(el, i);+ root.append(el);}+ return root;+}++describe("collectDomEditLayerItems item budget", () => {+ const documentWith = (count: number) => compositionWith(count, (el, i) => (el.id = `el-${i}`));it("returns the whole document by default", () => {// A default cap here silently truncated the marquee's candidate list: a drag@@ -264,13 +297,7 @@ describe("collectDomEditLayerItems selector-index cost", () => {// Attached, unlike the fixture above: a detached subtree is invisible to// document.querySelectorAll, so the occurrence lookup would find nothing.function attachedRootWithSharedClass(count: number): HTMLElement {- const root = document.createElement("div");- root.setAttribute("data-composition-id", "index.html");- for (let i = 0; i < count; i++) {- const child = document.createElement("div");- child.className = "box";- root.append(child);- }+ const root = compositionWith(count, (el) => (el.className = "box"));document.body.append(root);return root;}diff --git a/packages/studio/src/components/editor/domEditingLayers.ts b/packages/studio/src/components/editor/domEditingLayers.tsindex 9bca9d611d..287c0a1e68 100644--- a/packages/studio/src/components/editor/domEditingLayers.ts+++ b/packages/studio/src/components/editor/domEditingLayers.ts@@ -1,4 +1,4 @@-import { probeSourceElement } from "./probeSourceElement";+import { knownSourceAnswer, probeSourceElement, type ProbeTarget } from "./probeSourceElement";import { isAudibleVideoNode } from "../../player/lib/timelineElementHelpers";import type { PatchOperation } from "../../utils/sourcePatcher";import {@@ -288,6 +288,7 @@ export async function resolveDomEditSelection(projectId?: string | null;skipSourceProbe?: boolean;exactTarget?: boolean;+ previous?: DomEditSelection | null;},): Promise<DomEditSelection | null> {if (!startEl) return null;@@ -330,14 +331,14 @@ export async function resolveDomEditSelection(isCompositionRootLayer(current, doc, computedStyles);const textFields = collectDomEditTextFields(current);const isInsideLocked = Boolean(findClosestByAttribute(current, ["data-timeline-locked"]));- let existsInSource: boolean | undefined;- if (!options.skipSourceProbe && options.projectId && (current.id || selector || hfId)) {- const probeTarget: { id?: string; hfId?: string; selector?: string; selectorIndex?: number } =- {};- if (current.id) probeTarget.id = current.id;- if (hfId) probeTarget.hfId = hfId;- if (selector) probeTarget.selector = selector;- if (selectorIndex != null) probeTarget.selectorIndex = selectorIndex;+ const probeTarget: ProbeTarget = {};+ if (current.id) probeTarget.id = current.id;+ if (hfId) probeTarget.hfId = hfId;+ if (selector) probeTarget.selector = selector;+ if (selectorIndex != null) probeTarget.selectorIndex = selectorIndex;+ let existsInSource = knownSourceAnswer(options.previous, current, sourceFile, probeTarget);+ const probe = existsInSource === undefined && !options.skipSourceProbe;+ if (probe && options.projectId && (current.id || selector || hfId)) {existsInSource = await probeSourceElement(options.projectId, sourceFile, probeTarget);}const capabilities = resolveEditingAffordances(@@ -380,6 +381,7 @@ export async function resolveDomEditSelection(computedStyles,textFields,capabilities,+ existsInSource,};}diff --git a/packages/studio/src/components/editor/domEditingTypes.ts b/packages/studio/src/components/editor/domEditingTypes.tsindex adfe2fe5d3..1839b56e04 100644--- a/packages/studio/src/components/editor/domEditingTypes.ts+++ b/packages/studio/src/components/editor/domEditingTypes.ts@@ -92,6 +92,7 @@ export interface DomEditSelection extends PatchTarget {computedStyles: Record<string, string>;textFields: DomEditTextField[];capabilities: DomEditCapabilities;+ existsInSource?: boolean;gsapAnimations?: GsapAnimation[];}diff --git a/packages/studio/src/components/editor/probeSourceElement.ts b/packages/studio/src/components/editor/probeSourceElement.tsindex 4599a320fd..a1e6c551ad 100644--- a/packages/studio/src/components/editor/probeSourceElement.ts+++ b/packages/studio/src/components/editor/probeSourceElement.ts@@ -1,7 +1,23 @@import { buildProjectApiPath } from "../../utils/projectRouting";import { studioApiFetch } from "../../utils/studioApiFetch";+import type { DomEditSelection } from "./domEditingTypes";-type ProbeTarget = { id?: string; hfId?: string; selector?: string; selectorIndex?: number };+export type ProbeTarget = { id?: string; hfId?: string; selector?: string; selectorIndex?: number };++export function knownSourceAnswer(+ previous: DomEditSelection | null | undefined,+ element: HTMLElement,+ sourceFile: string,+ target: ProbeTarget,+): boolean | undefined {+ if (!previous || previous.element !== element || previous.sourceFile !== sourceFile) return;+ const same =+ previous.id === target.id &&+ previous.hfId === target.hfId &&+ previous.selector === target.selector &&+ previous.selectorIndex === target.selectorIndex;+ return same ? previous.existsInSource : undefined;+}interface PendingProbe {target: ProbeTarget;diff --git a/packages/studio/src/components/nle/useCanvasZOrderTimelineMirror.test.tsx b/packages/studio/src/components/nle/useCanvasZOrderTimelineMirror.test.tsxindex e4c94d4eef..40eca087a3 100644--- a/packages/studio/src/components/nle/useCanvasZOrderTimelineMirror.test.tsx+++ b/packages/studio/src/components/nle/useCanvasZOrderTimelineMirror.test.tsx@@ -79,24 +79,14 @@ function mountMirrorHarness(history: {moveCoalesceKeys: string[];records: RecordedWrite[];}) {- const record = (- label: string,- coalesceKey: string,- _coalesceMs: number | undefined,- after: string,- ) => {+ const record = (label: string, coalesceKey: string, after: string) => {history.records.push({ label, coalesceKey, after });history.fileContent.current = after;};- const onMoveElements: TimelineEditCallbacks["onMoveElements"] = (- _edits,- coalesceKey,- _operation,- coalesceMs,- ) => {+ const onMoveElements: TimelineEditCallbacks["onMoveElements"] = (_edits, coalesceKey) => {history.moveCoalesceKeys.push(coalesceKey ?? "<none>");- record("Move timeline clips", coalesceKey ?? "<none>", coalesceMs, "C-move");+ record("Move timeline clips", coalesceKey ?? "<none>", "C-move");};const api: Partial<HarnessApi> = {};@@ -104,7 +94,7 @@ function mountMirrorHarness(history: {const { handleDomZIndexReorderCommit } = useElementLifecycleOps(makeLifecycleOpsParams({commitDomEditPatchBatches: async (_batches, options) => {- record(options.label, options.coalesceKey, options.coalesceMs, "B-z");+ record(options.label, options.coalesceKey, "B-z");return { durable: true, allMatched: true, changed: true };},}),diff --git a/packages/studio/src/components/nle/useCanvasZOrderTimelineMirror.ts b/packages/studio/src/components/nle/useCanvasZOrderTimelineMirror.tsindex 7d104ba9e3..9f1528a452 100644--- a/packages/studio/src/components/nle/useCanvasZOrderTimelineMirror.ts+++ b/packages/studio/src/components/nle/useCanvasZOrderTimelineMirror.ts@@ -163,13 +163,6 @@ function useMirrorLaneMoveCommit(): (// stacking sync must not re-trigger and fight the just-set z values.},coalesceKey,- // Unbounded fold window: this record lands only AFTER the z persist's- // server round-trip resolved, so the gap between the gesture's two- // records exceeds editHistory's 300ms default under real latency and- // the fold would silently split into two undo entries. The shared key- // is unique per gesture (zReorderCoalesceKey's gesture seq), so the- // unbounded window can never merge two distinct user actions.- Number.POSITIVE_INFINITY,);},[onMoveElements],diff --git a/packages/studio/src/components/nle/useTimelineEditCallbacks.ts b/packages/studio/src/components/nle/useTimelineEditCallbacks.tsindex a1adfe2b2d..76792031c6 100644--- a/packages/studio/src/components/nle/useTimelineEditCallbacks.ts+++ b/packages/studio/src/components/nle/useTimelineEditCallbacks.ts@@ -32,7 +32,6 @@ export interface TimelineEditCallbackDeps {edits: Array<{ element: TimelineElement; updates: Pick<TimelineElement, "start" | "track"> }>,coalesceKey?: string,operation?: TimelineMoveOperation,- coalesceMs?: number,) => Promise<void> | void;handleTimelineElementResize: (element: TimelineElement,diff --git a/packages/studio/src/hooks/gsapKeyframeCacheHelpers.test.ts b/packages/studio/src/hooks/gsapKeyframeCacheHelpers.test.tsindex 2c2ff4fc47..985d09634b 100644--- a/packages/studio/src/hooks/gsapKeyframeCacheHelpers.test.ts+++ b/packages/studio/src/hooks/gsapKeyframeCacheHelpers.test.ts@@ -78,6 +78,56 @@ describe("non-string cache keys", () => {});});+describe("replaceKeyframeCacheForFile re-reads", () => {+ it("publishes nothing when a file re-reads to the same entries, and the change when one differs", () => {+ const write = (x: number) =>+ replaceKeyframeCacheForFile(+ "comp.html",+ new Map([+ ["box", { format: "percentage", keyframes: [{ percentage: 0, properties: { x } }] }],+ ]),+ new Map([["box", [animWithKeyframes("box")]]]),+ );+ write(0);+ let notified = 0;+ const stop = usePlayerStore.subscribe(() => notified++);+ write(0);+ expect(notified).toBe(0);+ write(5);+ stop();+ expect(notified).toBe(1);+ expect(cache().get("comp.html#box")?.keyframes[0]?.properties).toEqual({ x: 5 });+ });++ it("leaves a sub-composition's entries alone when index.html re-reads", () => {+ const one = (id: string) => new Map([[id, entry()]]);+ const anims = (id: string) => new Map([[id, [animWithKeyframes(id)]]]);+ replaceKeyframeCacheForFile("comp.html", one("box"), anims("box"));+ replaceKeyframeCacheForFile("index.html", one("hero"), anims("hero"));+ let notified = 0;+ const stop = usePlayerStore.subscribe(() => notified++);+ replaceKeyframeCacheForFile("index.html", one("hero"), anims("hero"));+ stop();++ expect(notified).toBe(0);+ for (const key of ["comp.html#box", "index.html#box", "box", "index.html#hero", "hero"]) {+ expect(cache().has(key)).toBe(true);+ }+ });++ it("still drops index.html's own element that shares an id with a sub-composition", () => {+ const one = (id: string) => new Map([[id, entry()]]);+ const anims = (id: string) => new Map([[id, [animWithKeyframes(id)]]]);+ const own = { format: "percentage", keyframes: [{ percentage: 0, properties: { x: 9 } }] };+ replaceKeyframeCacheForFile("comp.html", one("title"), anims("title"));+ replaceKeyframeCacheForFile("index.html", new Map([["title", own]]), anims("title"));+ replaceKeyframeCacheForFile("index.html", new Map(), new Map());++ expect(cache().has("index.html#title")).toBe(false);+ expect(cache().has("comp.html#title")).toBe(true);+ });+});+describe("clearKeyframeCacheForElement", () => {it("drops the prefixed, index.html fallback, and bare key for a non-index source", () => {seed("comp.html#box");diff --git a/packages/studio/src/hooks/gsapKeyframeCacheHelpers.ts b/packages/studio/src/hooks/gsapKeyframeCacheHelpers.tsindex 63a7c85065..b0920bc5b2 100644--- a/packages/studio/src/hooks/gsapKeyframeCacheHelpers.ts+++ b/packages/studio/src/hooks/gsapKeyframeCacheHelpers.ts@@ -5,6 +5,7 @@import type { GsapAnimation } from "@hyperframes/core/gsap-parser";import { usePlayerStore, type KeyframeCacheEntry } from "../player/store/playerStore";import { trackStudioEvent } from "../utils/studioTelemetry";+import { sameData } from "../utils/sameData";import { resolveClipTimingBasis, resolveSelectorElementIds, toClipKeyframes } from "./gsapShared";import {deduplicateKeyframes,@@ -18,6 +19,14 @@ export interface KeyframeCacheDraft {gsapAnimations: Map<string, GsapAnimation[]>;}+// A rebuilt entry equal to the one shown keeps its object, so re-reading an unchanged file publishes nothing.+function keepEqualEntries<V>(before: ReadonlyMap<string, V>, draft: Map<string, V>): void {+ for (const [key, value] of draft) {+ const shown = before.get(key);+ if (shown !== undefined && shown !== value && sameData(shown, value)) draft.set(key, shown);+ }+}+function sameEntries<V>(before: ReadonlyMap<string, V>, after: ReadonlyMap<string, V>): boolean {if (before.size !== after.size) return false;for (const [key, value] of before) {@@ -42,6 +51,8 @@ export function publishKeyframeCache(edit: (draft: KeyframeCacheDraft) => void):gsapAnimations: new Map(gsapAnimations),};edit(draft);+ keepEqualEntries(keyframeCache, draft.keyframeCache);+ keepEqualEntries(gsapAnimations, draft.gsapAnimations);if (sameEntries(keyframeCache, draft.keyframeCache) &&sameEntries(gsapAnimations, draft.gsapAnimations)@@ -175,8 +186,16 @@ function cachedElementIdsForFile(const sfPrefix = `${sourceFile}#`;const ids = new Set<string>();for (const key of [...keyframeCache.keys(), ...gsapAnimations.keys()]) {- if (!key.startsWith(sfPrefix)) continue;- ids.add(key.slice(sfPrefix.length));+ if (key.startsWith(sfPrefix)) ids.add(key.slice(sfPrefix.length));+ }+ if (sourceFile !== "index.html") return ids;+ // Another file's element also writes the `index.html#id` fallback, as the very same entry object.+ for (const [key, entry] of keyframeCache) {+ const hash = key.indexOf("#");+ const id = key.slice(hash + 1);+ if (hash > 0 && !key.startsWith(sfPrefix) && keyframeCache.get(sfPrefix + id) === entry) {+ ids.delete(id);+ }}return ids;}diff --git a/packages/studio/src/hooks/gsapMutationClient.ts b/packages/studio/src/hooks/gsapMutationClient.tsindex 393c9aa995..cbe53c3cd5 100644--- a/packages/studio/src/hooks/gsapMutationClient.ts+++ b/packages/studio/src/hooks/gsapMutationClient.ts@@ -88,9 +88,11 @@ function readMutationError(value: unknown, fallback: string): string {return fallback;}+type GsapMutationRoute = "gsap-mutations" | "gsap-mutations-batch";+export function requestGsapMutation(projectId: string,- route: "gsap-mutations" | "gsap-mutations-batch",+ route: GsapMutationRoute,filePath: string,body: unknown,): Promise<Response> {@@ -104,23 +106,49 @@ export function requestGsapMutation();}-export async function postGsapMutation(+async function postOwnedGsapMutation(+ route: GsapMutationRoute,projectId: string,filePath: string,- mutation: Record<string, unknown>,+ body: Record<string, unknown>,fallback: string,): Promise<GsapMutationStatus> {let response: Response;try {- response = await requestGsapMutation(projectId, "gsap-mutations", filePath, mutation);+ response = await requestGsapMutation(projectId, route, filePath, body);} catch (error) {throw new GsapPreviewConvergenceError(`${fallback}: mutation outcome unknown`, {cause: error,});}- const body: unknown = await response.json().catch(() => null);+ const payload: unknown = await response.json().catch(() => null);if (!response.ok) {- throw new GsapPreviewConvergenceError(readMutationError(body, fallback));+ throw new GsapPreviewConvergenceError(readMutationError(payload, fallback));}- return readMutationStatus(body);+ return readMutationStatus(payload);+}++export function postGsapMutation(+ projectId: string,+ filePath: string,+ mutation: Record<string, unknown>,+ fallback: string,+): Promise<GsapMutationStatus> {+ return postOwnedGsapMutation("gsap-mutations", projectId, filePath, mutation, fallback);+}++/** Every mutation in one request: the file is parsed and written once, with one ownership pair. */+export function postGsapMutations(+ projectId: string,+ filePath: string,+ mutations: readonly Record<string, unknown>[],+ fallback: string,+): Promise<GsapMutationStatus> {+ return postOwnedGsapMutation(+ "gsap-mutations-batch",+ projectId,+ filePath,+ { mutations },+ fallback,+ );}diff --git a/packages/studio/src/hooks/gsapRuntimeKeyframes.test.ts b/packages/studio/src/hooks/gsapRuntimeKeyframes.test.tsindex b09a326148..32c6a432a4 100644--- a/packages/studio/src/hooks/gsapRuntimeKeyframes.test.ts+++ b/packages/studio/src/hooks/gsapRuntimeKeyframes.test.ts@@ -1,9 +1,10 @@-import { describe, expect, it } from "vitest";+import { describe, expect, it, vi } from "vitest";import {arcPathFromMotionPathValue,hasNonHoldTweenForElement,readRuntimeKeyframes,} from "./gsapRuntimeKeyframes";+import { tweensTargeting, withTweenIndex } from "./gsapRuntimeTweenIndex";// Build a fake preview iframe whose runtime timeline holds the given child tweens// and resolves `selector` to `el`.@@ -261,3 +262,53 @@ describe("arcPathFromMotionPathValue", () => {expect(arcPathFromMotionPathValue(null)).toBeUndefined();});});++describe("withTweenIndex — many elements, one scan of the tweens", () => {+ const ids = Array.from({ length: 20 }, (_, i) => `clip-${i}`);+ const tweens = ids.map((id) => ({+ targets: vi.fn(() => [{ id }]),+ vars: { x: 10, duration: 1 },+ duration: () => 1,+ startTime: () => 0,+ }));+ const timeline = { getChildren: () => tweens };+ const preview = {+ contentWindow: { __timelines: { "index.html": timeline } },+ contentDocument: { querySelector: (sel: string) => ({ id: sel.slice(1) }) },+ } as unknown as HTMLIFrameElement;+ const askAll = () => ids.map((id) => hasNonHoldTweenForElement(preview, `#${id}`));++ it("answers the same as the plain scan", () => {+ const plain = askAll();+ expect(withTweenIndex(askAll)).toEqual(plain);+ expect(plain.every(Boolean)).toBe(true);+ });++ it("reads each tween's targets once per pass instead of once per element", () => {+ for (const tween of tweens) tween.targets.mockClear();+ withTweenIndex(askAll);+ expect(tweens.every((tween) => tween.targets.mock.calls.length === 1)).toBe(true);+ });++ it("skips a timelines entry that is not an object", () => {+ const odd = {+ contentWindow: {+ __timelines: { stray: null, label: "x", main: { getChildren: () => tweens } },+ },+ contentDocument: { querySelector: (sel: string) => ({ id: sel.slice(1) }) },+ } as unknown as HTMLIFrameElement;+ expect(withTweenIndex(() => hasNonHoldTweenForElement(odd, "#clip-3"))).toBe(true);+ expect(withTweenIndex(() => hasNonHoldTweenForElement(odd, "#nobody"))).toBe(false);+ });++ it("returns the plain scan's tweens, once each and in timeline order", () => {+ const el = { id: "clip-2" } as unknown as Element;+ const byElement = { targets: () => [el], vars: {}, duration: () => 1 };+ const byId = { targets: () => [{ id: "clip-2" }], vars: {}, duration: () => 1 };+ const both = { targets: () => [el, { id: "clip-2" }], vars: {}, duration: () => 1 };+ const tl = { getChildren: () => [byId, byElement, both] };+ const plain = tweensTargeting(tl, el);+ expect(withTweenIndex(() => tweensTargeting(tl, el))).toEqual(plain);+ expect(plain).toEqual([byId, byElement, both]);+ });+});diff --git a/packages/studio/src/hooks/gsapRuntimeKeyframes.ts b/packages/studio/src/hooks/gsapRuntimeKeyframes.tsindex a52bed69a0..765fbb7d29 100644--- a/packages/studio/src/hooks/gsapRuntimeKeyframes.ts+++ b/packages/studio/src/hooks/gsapRuntimeKeyframes.ts@@ -11,6 +11,7 @@import { buildArcPath, type ArcPathConfig } from "@hyperframes/core/gsap-parser-acorn";import { parsePercentageKeyframes, toAbsoluteTime } from "./gsapShared";import { roundTo3 } from "../utils/rounding";+import { matchesElement, tweensTargeting } from "./gsapRuntimeTweenIndex";import { withParsedStart } from "./gsapParsedTween";import { BOX_SIZE_STYLE_PROPS } from "../components/editor/manualEditsDomPatches";import { gsapRendersTransform } from "../components/editor/gsapAnimatesProperty";@@ -168,14 +169,6 @@ function readTween(vars: Record<string, unknown>): ReadTween | null {return flat ? { keyframes: flat } : null;}-function matchesElement(tween: RuntimeTween, el: Element): boolean {- if (!tween.targets) return false;- for (const t of tween.targets()) {- if (t === el || (el.id && (t as Element).id === el.id)) return true;- }- return false;-}-function tweenTiming(tween: RuntimeTween): { start: number; duration: number } {const rawStart = typeof tween.startTime === "function" ? tween.startTime() : 0;const rawDur = typeof tween.duration === "function" ? tween.duration() : 0;@@ -438,10 +431,9 @@ export const GSAP_TRANSFORM_KEYS = new Set(export function gsapWritesChannels(el: Element, channels: string[]): boolean {const win = el.ownerDocument.defaultView as { __timelines?: Record<string, RuntimeTimeline> };return Object.values(win?.__timelines ?? {}).some((tl) =>- (tl?.getChildren?.(true) ?? []).some(+ tweensTargeting(tl, el).some((tween) =>!!tween.vars &&- matchesElement(tween, el) &&(channels.some((ch) => ch in tween.vars!) ||keyframeVarsCarryChannel(tween.vars, channels)),),@@ -515,9 +507,8 @@ function hasNonHoldTween(): boolean {if (!timelines) return false;for (const tlId of compositionId ? [compositionId] : Object.keys(timelines)) {- // fallow-ignore-next-line code-duplication- for (const tween of timelines[tlId]?.getChildren?.(true) ?? []) {- if (!tween.vars || !matchesElement(tween, targetEl)) continue;+ for (const tween of tweensTargeting(timelines[tlId], targetEl)) {+ if (!tween.vars) continue;const dur = typeof tween.duration === "function" ? tween.duration() : 0;if (isZeroDurationSet(dur)) continue; // skip hold/set tweens (see isZeroDurationSet)if (channels && keyframeVarsCarryChannel(tween.vars, channels)) return true;diff --git a/packages/studio/src/hooks/gsapRuntimeTweenIndex.ts b/packages/studio/src/hooks/gsapRuntimeTweenIndex.tsnew file mode 100644index 0000000000..12aeae2e71--- /dev/null+++ b/packages/studio/src/hooks/gsapRuntimeTweenIndex.ts@@ -0,0 +1,53 @@+import type { RuntimeTimeline, RuntimeTween } from "./gsapRuntimeKeyframes";++export function matchesElement(tween: RuntimeTween, el: Element): boolean {+ if (!tween.targets) return false;+ for (const t of tween.targets()) {+ if (t === el || (el.id && (t as Element).id === el.id)) return true;+ }+ return false;+}++type TweenIndex = { byElement: Map<unknown, RuntimeTween[]>; byId: Map<string, RuntimeTween[]> };+let tweenIndexes: WeakMap<RuntimeTimeline, TweenIndex> | null = null;++/** Within `run`, finding the tweens on an element reads one index per timeline, not every tween. */+export function withTweenIndex<T>(run: () => T): T {+ const outer = tweenIndexes;+ tweenIndexes ??= new WeakMap();+ try {+ return run();+ } finally {+ tweenIndexes = outer;+ }+}++function indexTweens(children: RuntimeTween[]): TweenIndex {+ const index: TweenIndex = { byElement: new Map(), byId: new Map() };+ const add = <K>(map: Map<K, RuntimeTween[]>, key: K, tween: RuntimeTween) => {+ const list = map.get(key);+ // A tween's targets are added together, so a repeat of its key is always the last entry.+ if (!list) map.set(key, [tween]);+ else if (list.at(-1) !== tween) list.push(tween);+ };+ for (const tween of children) {+ for (const target of tween.targets?.() ?? []) {+ add(index.byElement, target, tween);+ const id = (target as Element).id;+ if (id) add(index.byId, id, tween);+ }+ }+ return index;+}++export function tweensTargeting(+ timeline: RuntimeTimeline | undefined,+ el: Element,+): RuntimeTween[] {+ if (!timeline || typeof timeline !== "object" || !tweenIndexes)+ return (timeline?.getChildren?.(true) ?? []).filter((tween) => matchesElement(tween, el));+ let index = tweenIndexes.get(timeline);+ if (!index) tweenIndexes.set(timeline, (index = indexTweens(timeline.getChildren?.(true) ?? [])));+ // The same rule as matchesElement: an element with an id matches every tween on that id.+ return (el.id ? index.byId.get(el.id) : index.byElement.get(el)) ?? [];+}diff --git a/packages/studio/src/hooks/timelineEditingHelpers.test.ts b/packages/studio/src/hooks/timelineEditingHelpers.test.tsindex e2bff20622..8d629f2542 100644--- a/packages/studio/src/hooks/timelineEditingHelpers.test.ts+++ b/packages/studio/src/hooks/timelineEditingHelpers.test.ts@@ -1,6 +1,7 @@// @vitest-environment jsdomimport { afterEach, describe, expect, it, vi } from "vitest";import {+ applyTimelineMoveAttributes,applyTimelineStackingReorder,buildTimelineMoveTimingPatch,buildTimelineResizeTimingPatch,@@ -316,6 +317,26 @@ describe("persistTimelineBatchEdit", () => {vi.unstubAllGlobals();});+ it("syncs each file's root duration once, landing where per-member sync would", async () => {+ const source = `<div id="root" data-composition-id="main" data-duration="4"><video id="a" class="clip" data-start="1" data-duration="1"></video><video id="b" class="clip" data-start="2" data-duration="1"></video><video id="c" class="clip" data-start="3" data-duration="1"></video></div>`;+ const members = ["a", "b", "c"].map((id, i) => ({+ element: el({ id, tag: "video", domId: id, start: i + 1, duration: 1 }),+ buildPatches: (original: string, target: Parameters<typeof applyTimelineMoveAttributes>[1]) =>+ applyTimelineMoveAttributes(original, target, i + 6, 1),+ }));+ stubReadFileContent(source);+ const writes: Array<[string, string]> = [];+ await persistTimelineBatchEdit(batchInput(members, writes));++ const perMember = members.reduce(+ (current, { element }, i) =>+ buildTimelineMoveTimingPatch(current, { id: element.id }, i + 6, 1),+ source,+ );+ expect(writes).toEqual([["index.html", perMember]]);+ expect(perMember).toContain('data-duration="9"');+ });+it("skips no-op members instead of aborting the batch (track-insert renumber)", async () => {// A track-insert renumber can include a member whose attributes already// hold the target values — its patch is string-identical. The batch mustdiff --git a/packages/studio/src/hooks/timelineEditingHelpers.ts b/packages/studio/src/hooks/timelineEditingHelpers.tsindex a315ea316a..93078796bd 100644--- a/packages/studio/src/hooks/timelineEditingHelpers.ts+++ b/packages/studio/src/hooks/timelineEditingHelpers.ts@@ -225,7 +225,7 @@ function resolveResizePlaybackStart(};}-export function buildTimelineMoveTimingPatch(+export function applyTimelineMoveAttributes(original: string,target: PatchTarget,start: number,@@ -235,7 +235,7 @@ export function buildTimelineMoveTimingPatch(): string {if (!Number.isFinite(start) || !Number.isFinite(duration)) {console.warn(- `[Timeline] buildTimelineMoveTimingPatch: non-finite timing (start=${start}, duration=${duration}) — patch skipped`,+ `[Timeline] applyTimelineMoveAttributes: non-finite timing (start=${start}, duration=${duration}) — patch skipped`,);return original;}@@ -257,15 +257,31 @@ export function buildTimelineMoveTimingPatch(property: "data-audio-group",value: null,});- // Content-driven duration: sync data-duration to the furthest clip end read- // from the PATCHED SOURCE (raw data-duration), so it grows if a clip moved- // past the end and shrinks if the furthest clip moved left. Measured from the- // source, NOT the store — store durations are runtime-truncated to the current- // comp length, which would ratchet the duration down every move.- return setCompositionDurationToContent(patched, furthestClipEndFromSource(patched));+ return patched;}-export function buildTimelineResizeTimingPatch(+// Root data-duration follows the furthest clip end in the source; the store's durations are+// truncated to the current length, so reading them would ratchet the duration down every edit.+export function syncCompositionDurationToContent(source: string): string {+ return setCompositionDurationToContent(source, furthestClipEndFromSource(source));+}++export function buildTimelineMoveTimingPatch(+ original: string,+ target: PatchTarget,+ start: number,+ duration: number,+ track?: number,+ audioGroup?: null,+): string {+ const patched = applyTimelineMoveAttributes(original, target, start, duration, track, audioGroup);+ // A non-finite timing skips the patch above; skip the duration sync with it.+ return !(Number.isFinite(start) && Number.isFinite(duration))+ ? patched+ : syncCompositionDurationToContent(patched);+}++export function applyTimelineResizeAttributes(original: string,target: PatchTarget,element: TimelineElement,@@ -289,10 +305,13 @@ export function buildTimelineResizeTimingPatch(value: formatTimelineMediaOffset(pbs.value),});}- // Content-driven duration from the PATCHED SOURCE (raw data-duration) —- // grows/shrinks to the furthest clip end. Not from the store, whose- // durations are runtime-truncated.- return setCompositionDurationToContent(patched, furthestClipEndFromSource(patched));+ return patched;+}++export function buildTimelineResizeTimingPatch(+ ...args: Parameters<typeof applyTimelineResizeAttributes>+): string {+ return syncCompositionDurationToContent(applyTimelineResizeAttributes(...args));}export interface PersistTimelineEditInput {@@ -305,6 +324,7 @@ export interface PersistTimelineEditInput {recordEdit: (input: RecordEditInput) => Promise<void>;pendingTimelineEditPathRef: React.MutableRefObject<Set<string>>;coalesceKey?: string;+ coalesceMs?: number;}export async function persistTimelineEdit(input: PersistTimelineEditInput): Promise<void> {@@ -319,6 +339,7 @@ export async function persistTimelineEdit(input: PersistTimelineEditInput): PromprojectId: input.projectId,label: input.label,coalesceKey: input.coalesceKey,+ coalesceMs: input.coalesceMs,files: {[targetPath]: (current) => {const patched = input.buildPatches(current, patchTarget);@@ -391,7 +412,12 @@ export async function persistTimelineBatchEdit(changesByPath.set(targetPath, [...(changesByPath.get(targetPath) ?? []), change]);}const buildFile = (targetPath: string) => (original: string) => {- const next = patchTimelineChangesInSource(original, targetPath, changesByPath.get(targetPath)!);+ const patched = patchTimelineChangesInSource(+ original,+ targetPath,+ changesByPath.get(targetPath)!,+ );+ const next = syncCompositionDurationToContent(patched);if (next !== original) input.pendingTimelineEditPathRef.current.add(targetPath);return next;};diff --git a/packages/studio/src/hooks/timelineLinkEditPlan.ts b/packages/studio/src/hooks/timelineLinkEditPlan.tsindex 56f293c816..932c11ef85 100644--- a/packages/studio/src/hooks/timelineLinkEditPlan.ts+++ b/packages/studio/src/hooks/timelineLinkEditPlan.ts@@ -1,12 +1,14 @@import type { TimelineElement } from "../player";import type { TimelineLinkEdit } from "../player/components/timelineCallbacks";-import { buildPatchTarget, type PatchTarget } from "./timelineEditingHelpers";+import {+ buildPatchTarget,+ syncCompositionDurationToContent,+ type PatchTarget,+} from "./timelineEditingHelpers";import { sharesLinkGroup } from "../player/components/audioClipLink";import { toAuthoredStart } from "../player/store/timelineElement";import { formatTimelineMediaOffset } from "../player/components/timelineEditing";import { applyPatchByTarget } from "../utils/sourcePatcher";-import { setCompositionDurationToContent } from "../utils/timelineAssetDrop";-import { furthestClipEndFromSource } from "../player/lib/timelineElementHelpers";import {detachAudioInSource,linkInSource,@@ -64,7 +66,7 @@ function planSyncEdit(edit: SyncEdit): LinkEditPlan | null {property: "start",value,});- return setCompositionDurationToContent(moved, furthestClipEndFromSource(moved));+ return syncCompositionDurationToContent(moved);},};}diff --git a/packages/studio/src/hooks/timelineMoveAdapter.ts b/packages/studio/src/hooks/timelineMoveAdapter.tsindex 0738b73322..30e1ec860d 100644--- a/packages/studio/src/hooks/timelineMoveAdapter.ts+++ b/packages/studio/src/hooks/timelineMoveAdapter.ts@@ -27,7 +27,6 @@ export type TimelineMoveEditsHandler = (edits: TimelineAtomicMoveEdit[],coalesceKey?: string,operation?: TimelineMoveOperation,- coalesceMs?: number,) => Promise<void>;export function persistTimelineMoveEditsAtomically(@@ -35,7 +34,6 @@ export function persistTimelineMoveEditsAtomically(coalesceKey: string | undefined,operation: TimelineMoveOperation,deps: AtomicMoveDeps,- coalesceMs?: number,): Promise<void> {return deps.handleTimelineGroupMove(edits.map(({ element, updates }) => ({@@ -48,7 +46,7 @@ export function persistTimelineMoveEditsAtomically(// ("timing") omit it so they stay eligible for the SDK fast path.track: operation === "timing" ? undefined : updates.track,})),- { coalesceKey, coalesceMs },+ { coalesceKey },);}@@ -56,9 +54,9 @@ export function useTimelineMoveEditsHandler(handleTimelineGroupMove: AtomicMoveDeps["handleTimelineGroupMove"],): TimelineMoveEditsHandler {return useCallback(- async (edits, coalesceKey, operation: TimelineMoveOperation = "timing", coalesceMs) => {+ async (edits, coalesceKey, operation: TimelineMoveOperation = "timing") => {const deps = { handleTimelineGroupMove };- await persistTimelineMoveEditsAtomically(edits, coalesceKey, operation, deps, coalesceMs);+ await persistTimelineMoveEditsAtomically(edits, coalesceKey, operation, deps);},[handleTimelineGroupMove],);diff --git a/packages/studio/src/hooks/timelineTimingSync.test.ts b/packages/studio/src/hooks/timelineTimingSync.test.tsindex da4b09b04f..7cb94add67 100644--- a/packages/studio/src/hooks/timelineTimingSync.test.ts+++ b/packages/studio/src/hooks/timelineTimingSync.test.ts@@ -7,6 +7,8 @@ import {captureDurationRollback,finishClipTimingFallback,finishGroupTimingGsapFallback,+ finishTimelineTimingFallback,+ foldGsapMutationIntoHistory,readFileContent,shiftGsapPositions,} from "./timelineTimingSync";@@ -509,7 +511,7 @@ describe("nothing-to-rewrite timing edits rebind in place (no script re-executiochanges: [{ element }, { element }],resolveChangePath: () => "index.html",// No domId → nothing to rewrite for ANY change (the gap-close blink path).- mutateChange: () => null,+ mutationFor: () => null,});expect(reloadPreview).not.toHaveBeenCalled();@@ -539,7 +541,7 @@ describe("nothing-to-rewrite timing edits rebind in place (no script re-executio{ element: { sourceFile: "scenes/intro.html" } as TimelineElement },],resolveChangePath: (el) => el.sourceFile ?? "index.html",- mutateChange: () => null,+ mutationFor: () => null,});expect(reloadPreview).toHaveBeenCalledTimes(1);@@ -658,32 +660,53 @@ function ownedMutation(contents: Map<string, string>, path: string, before: strireturn { mutated: true, scriptText: null, before, after };}-describe("foldGsapMutationIntoHistory — owned GSAP transaction", () => {- const element = { sourceFile: "index.html" } as TimelineElement;+type OwnedStep = () => Promise<ReturnType<typeof ownedMutation>>;+/** Runs `steps` as one owned same-file transaction, wired the way a group edit wires it. */+function runOwnedChain(+ steps: readonly OwnedStep[],+ options: {+ reloadPreview?: () => void;+ recordEdit?: (edit: never) => Promise<void>;+ } = {},+) {+ const onGsapError = (err: unknown) =>+ console.error("[Timeline] Failed to shift GSAP positions", err);+ return finishTimelineTimingFallback({+ iframe: buildLivePreviewIframe().iframe,+ projectId: "p1",+ reloadPreview: options.reloadPreview ?? vi.fn(),+ gsapMutation: () =>+ foldGsapMutationIntoHistory({+ writeFile: writeProjectFile,+ paths: ["index.html"],+ projectId: "p1",+ label: "Move timeline clips",+ recordEdit: (options.recordEdit ?? vi.fn(async () => {})) as never,+ gsapMutation: async (runOwnedMutation) => {+ let status = { mutated: false, scriptText: null } as Awaited<ReturnType<OwnedStep>>;+ for (const step of steps) status = await runOwnedMutation("index.html", step);+ return status;+ },+ onRollbackError: onGsapError,+ }),+ onGsapError,+ rebindWhenUnmutated: true,+ });+}++describe("foldGsapMutationIntoHistory — owned GSAP transaction", () => {it("reverse-rolls back every successful same-file step after a late failure", async () => {const contents = new Map<string, string>([["index.html", "ORIGINAL"]]);const server = installOwnedFileServer(contents);- let clipIndex = 0;- await finishGroupTimingGsapFallback({- writeProjectFile,- projectId: "p1",- iframe: buildLivePreviewIframe().iframe,- reloadPreview: vi.fn(),- label: "Move timeline clips",- errorLabel: "Failed to shift GSAP positions",- recordEdit: vi.fn(async () => {}) as never,- activeCompPath: "index.html",- changes: [{ element }, { element }, { element }],- resolveChangePath: () => "index.html",- mutateChange: async () => {- clipIndex += 1;- if (clipIndex === 1) return ownedMutation(contents, "index.html", "ORIGINAL", "STEP-1");- if (clipIndex === 2) return ownedMutation(contents, "index.html", "STEP-1", "STEP-2");+ await runOwnedChain([+ async () => ownedMutation(contents, "index.html", "ORIGINAL", "STEP-1"),+ async () => ownedMutation(contents, "index.html", "STEP-1", "STEP-2"),+ async () => {throw new Error("late failure");},- });+ ]);expect(server.rollbacks).toEqual([{ path: "index.html", expected: "STEP-2", restore: "STEP-1", conflict: false },@@ -695,27 +718,13 @@ describe("foldGsapMutationIntoHistory — owned GSAP transaction", () => {it("uses the endpoint's atomic before when a foreign write precedes mutation", async () => {const contents = new Map<string, string>([["index.html", "FOREIGN"]]);const server = installOwnedFileServer(contents);- let clipIndex = 0;- await finishGroupTimingGsapFallback({- writeProjectFile,- projectId: "p1",- iframe: buildLivePreviewIframe().iframe,- reloadPreview: vi.fn(),- label: "Move timeline clips",- errorLabel: "Failed to shift GSAP positions",- recordEdit: vi.fn(async () => {}) as never,- activeCompPath: "index.html",- changes: [{ element }, { element }],- resolveChangePath: () => "index.html",- mutateChange: async () => {- clipIndex += 1;- if (clipIndex === 1) {- return ownedMutation(contents, "index.html", "FOREIGN", "FOREIGN+OWNED");- }+ await runOwnedChain([+ async () => ownedMutation(contents, "index.html", "FOREIGN", "FOREIGN+OWNED"),+ async () => {throw new Error("late failure");},- });+ ]);expect(server.readCount()).toBe(0);expect(server.rollbacks[0]).toEqual({@@ -732,26 +741,17 @@ describe("foldGsapMutationIntoHistory — owned GSAP transaction", () => {const server = installOwnedFileServer(contents, {beforeRollback: () => contents.set("index.html", "SUCCESSOR"),});- let clipIndex = 0;-const reloadPreview = vi.fn();- await finishGroupTimingGsapFallback({- writeProjectFile,- projectId: "p1",- iframe: buildLivePreviewIframe().iframe,- reloadPreview,- label: "Move timeline clips",- errorLabel: "Failed to shift GSAP positions",- recordEdit: vi.fn(async () => {}) as never,- activeCompPath: "index.html",- changes: [{ element }, { element }],- resolveChangePath: () => "index.html",- mutateChange: async () => {- clipIndex += 1;- if (clipIndex === 1) return ownedMutation(contents, "index.html", "ORIGINAL", "OWNED");- throw new Error("late failure");- },- });++ await runOwnedChain(+ [+ async () => ownedMutation(contents, "index.html", "ORIGINAL", "OWNED"),+ async () => {+ throw new Error("late failure");+ },+ ],+ { reloadPreview },+ );expect(server.rollbacks[0]?.conflict).toBe(true);expect(contents.get("index.html")).toBe("SUCCESSOR");@@ -763,25 +763,16 @@ describe("foldGsapMutationIntoHistory — owned GSAP transaction", () => {installOwnedFileServer(contents, { failRollback: true });const reloadPreview = vi.fn();const consoleError = vi.spyOn(console, "error").mockImplementation(() => {});- let clipIndex = 0;- await finishGroupTimingGsapFallback({- writeProjectFile,- projectId: "p1",- iframe: buildLivePreviewIframe().iframe,- reloadPreview,- label: "Move timeline clips",- errorLabel: "Failed to shift GSAP positions",- recordEdit: vi.fn(async () => {}) as never,- activeCompPath: "index.html",- changes: [{ element }, { element }],- resolveChangePath: () => "index.html",- mutateChange: async () => {- clipIndex += 1;- if (clipIndex === 1) return ownedMutation(contents, "index.html", "ORIGINAL", "OWNED");- throw new Error("late failure");- },- });+ await runOwnedChain(+ [+ async () => ownedMutation(contents, "index.html", "ORIGINAL", "OWNED"),+ async () => {+ throw new Error("late failure");+ },+ ],+ { reloadPreview },+ );expect(contents.get("index.html")).toBe("OWNED");expect(reloadPreview).toHaveBeenCalledTimes(1);@@ -796,23 +787,13 @@ describe("foldGsapMutationIntoHistory — owned GSAP transaction", () => {const server = installOwnedFileServer(contents);const recordEdit = vi.fn(async () => {});- await finishGroupTimingGsapFallback({- writeProjectFile,- projectId: "p1",- iframe: buildLivePreviewIframe().iframe,- reloadPreview: vi.fn(),- label: "Move timeline clips",- errorLabel: "Failed to shift GSAP positions",- recordEdit: recordEdit as never,- activeCompPath: "index.html",- changes: [{ element }, { element }],- resolveChangePath: () => "index.html",- mutateChange: async (_change, _path) => {- const before = contents.get("index.html")!;- const after = before === "FOREIGN" ? "FOREIGN+ONE" : "FOREIGN+ONE+TWO";- return ownedMutation(contents, "index.html", before, after);- },- });+ await runOwnedChain(+ [+ async () => ownedMutation(contents, "index.html", "FOREIGN", "FOREIGN+ONE"),+ async () => ownedMutation(contents, "index.html", "FOREIGN+ONE", "FOREIGN+ONE+TWO"),+ ],+ { recordEdit },+ );expect(server.readCount()).toBe(1); // final ownership verification onlyexpect(recordEdit).toHaveBeenCalledWith(@@ -828,26 +809,15 @@ describe("foldGsapMutationIntoHistory — owned GSAP transaction", () => {const contents = new Map<string, string>([["index.html", "ORIGINAL"]]);const server = installOwnedFileServer(contents);const recordEdit = vi.fn(async () => {});- let clipIndex = 0;-const reloadPreview = vi.fn();- await finishGroupTimingGsapFallback({- writeProjectFile,- projectId: "p1",- iframe: buildLivePreviewIframe().iframe,- reloadPreview,- label: "Move timeline clips",- errorLabel: "Failed to shift GSAP positions",- recordEdit: recordEdit as never,- activeCompPath: "index.html",- changes: [{ element }, { element }],- resolveChangePath: () => "index.html",- mutateChange: async () => {- clipIndex += 1;- if (clipIndex === 1) return ownedMutation(contents, "index.html", "ORIGINAL", "STEP-1");- return ownedMutation(contents, "index.html", "FOREIGN", "FOREIGN+STEP-2");- },- });++ await runOwnedChain(+ [+ async () => ownedMutation(contents, "index.html", "ORIGINAL", "STEP-1"),+ async () => ownedMutation(contents, "index.html", "FOREIGN", "FOREIGN+STEP-2"),+ ],+ { recordEdit, reloadPreview },+ );expect(recordEdit).not.toHaveBeenCalled();expect(server.rollbacks).toEqual([@@ -867,19 +837,7 @@ describe("foldGsapMutationIntoHistory — owned GSAP transaction", () => {const contents = new Map<string, string>([["index.html", "ORIGINAL"]]);const server = installOwnedFileServer(contents, { failReadAt: 1 });- await finishGroupTimingGsapFallback({- writeProjectFile,- projectId: "p1",- iframe: buildLivePreviewIframe().iframe,- reloadPreview: vi.fn(),- label: "Move timeline clips",- errorLabel: "Failed to shift GSAP positions",- recordEdit: vi.fn(async () => {}) as never,- activeCompPath: "index.html",- changes: [{ element }],- resolveChangePath: () => "index.html",- mutateChange: async () => ownedMutation(contents, "index.html", "ORIGINAL", "OWNED"),- });+ await runOwnedChain([async () => ownedMutation(contents, "index.html", "ORIGINAL", "OWNED")]);expect(server.rollbacks[0]).toEqual({path: "index.html",diff --git a/packages/studio/src/hooks/timelineTimingSync.ts b/packages/studio/src/hooks/timelineTimingSync.tsindex 2b6b941f73..05419d7c31 100644--- a/packages/studio/src/hooks/timelineTimingSync.ts+++ b/packages/studio/src/hooks/timelineTimingSync.ts@@ -17,6 +17,7 @@ import {GsapOwnershipProtocolError,GsapPreviewConvergenceError,postGsapMutation,+ postGsapMutations,requireGsapOwnershipProtocol,rollbackOwnedMutation,type GsapMutationStatus,@@ -140,7 +141,9 @@ function syncTimingEditPreview(if (result === "cannot-soft-reload") reloadPreview();}-async function finishTimelineTimingFallback(input: {+const UNMUTATED: GsapMutationStatus = { mutated: false, scriptText: null };++export async function finishTimelineTimingFallback(input: {iframe: HTMLIFrameElement | null;projectId: string | null;reloadPreview: () => void;@@ -155,7 +158,7 @@ async function finishTimelineTimingFallback(input: {*/rebindWhenUnmutated: boolean;}): Promise<void> {- let outcome: GsapMutationStatus = { mutated: false, scriptText: null };+ let outcome = UNMUTATED;if (input.gsapMutation) {try {outcome = await input.gsapMutation();@@ -185,9 +188,20 @@ async function finishTimelineTimingFallback(input: {);}-// Coalesce window for folding a GSAP mutation into the preceding timing edit; only has to-// outlast one GSAP server round-trip, never a real second edit.-const GSAP_HISTORY_COALESCE_MS = 10_000;+// Held until the next edit: the key is the gesture's own, so only its GSAP fold can join it.+const UNTIL_NEXT_EDIT = Number.POSITIVE_INFINITY;+let timingGestures = 0;++/** One timing gesture's undo step, shared by its timing write and its GSAP fold however long the fold takes. */+export function timingGestureStep(+ kind: string,+ given?: { coalesceKey?: string },+): { coalesceKey: string; coalesceMs: number } {+ return {+ coalesceKey: given?.coalesceKey ?? `${kind}:${++timingGestures}`,+ coalesceMs: UNTIL_NEXT_EDIT,+ };+}type OwnedMutationStep = {path: string;@@ -265,7 +279,7 @@ async function foldGsapMutationInQueue(input: {const ownedSteps: OwnedMutationStep[] = [];const runOwnedMutation: OwnedMutationRunner = async (path, mutation) => {const pending = mutation();- if (!pending) return { mutated: false, scriptText: null };+ if (!pending) return UNMUTATED;const status = await pending;if (!status.mutated) return status;if (status.before === undefined || status.after === undefined) {@@ -313,7 +327,7 @@ async function foldGsapMutationInQueue(input: {await input.recordEdit({label: input.label,coalesceKey: input.coalesceKey,- coalesceMs: GSAP_HISTORY_COALESCE_MS,+ coalesceMs: UNTIL_NEXT_EDIT,files,});}@@ -325,7 +339,7 @@ async function foldGsapMutationInQueue(input: {}// The mutations, the ownership read and any rollback hold every touched file's queue.-function foldGsapMutationIntoHistory(+export function foldGsapMutationIntoHistory(input: Parameters<typeof foldGsapMutationInQueue>[0] & {writeFile: StudioProjectFileWriter;paths: readonly string[];@@ -336,6 +350,30 @@ function foldGsapMutationIntoHistory();}+export function shiftGsapMutation(elementId: string | undefined, delta: number) {+ if (delta === 0 || !elementId) return null;+ return { type: "shift-positions", targetSelector: `#${elementId}`, delta };+}++export function scaleGsapMutation(+ elementId: string | undefined,+ oldStart: number,+ oldDuration: number,+ newStart: number,+ newDuration: number,+) {+ if (!elementId || oldDuration <= 0 || newDuration <= 0) return null;+ if (oldStart === newStart && oldDuration === newDuration) return null;+ return {+ type: "scale-positions",+ targetSelector: `#${elementId}`,+ oldStart,+ oldDuration,+ newStart,+ newDuration,+ };+}+/*** 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.@@ -347,20 +385,12 @@ export async function shiftGsapPositions(elementId: string,delta: number,): Promise<GsapMutationStatus> {- if (delta === 0 || !elementId) return { mutated: false, scriptText: null };- return postGsapMutation(- projectId,- filePath,- {- type: "shift-positions",- targetSelector: `#${elementId}`,- delta,- },- "shift-positions failed",- );+ const mutation = shiftGsapMutation(elementId, delta);+ if (!mutation) return UNMUTATED;+ return postGsapMutation(projectId, filePath, mutation, "shift-positions failed");}-export async function scaleGsapPositions(+async function scaleGsapPositions(projectId: string,filePath: string,elementId: string,@@ -369,23 +399,9 @@ export async function scaleGsapPositions(newStart: number,newDuration: number,): Promise<GsapMutationStatus> {- if (!elementId || oldDuration <= 0 || newDuration <= 0)- return { mutated: false, scriptText: null };- if (oldStart === newStart && oldDuration === newDuration)- return { mutated: false, scriptText: null };- return postGsapMutation(- projectId,- filePath,- {- type: "scale-positions",- targetSelector: `#${elementId}`,- oldStart,- oldDuration,- newStart,- newDuration,- },- "scale-positions failed",- );+ const mutation = scaleGsapMutation(elementId, oldStart, oldDuration, newStart, newDuration);+ if (!mutation) return UNMUTATED;+ return postGsapMutation(projectId, filePath, mutation, "scale-positions failed");}/** The GSAP sync a committed SDK timing write made, or null when its timeline script is unchanged. */@@ -502,8 +518,8 @@ export async function finishGroupTimingGsapFallback<C extends { element: TimelinactiveCompPath: string | null;changes: readonly C[];resolveChangePath: (element: TimelineElement) => string;- /** Per-change GSAP mutation; return null to skip a change with no timing delta. */- mutateChange: (change: C, changePath: string) => Promise<GsapMutationStatus> | null;+ /** The change's GSAP mutation; null skips a change with no timing delta. */+ mutationFor: (change: C) => Record<string, unknown> | null;sdkGsap?: GsapMutationStatus | null;}): Promise<void> {const activePath = input.activeCompPath || "index.html";@@ -539,14 +555,18 @@ export async function finishGroupTimingGsapFallback<C extends { element: Timelinlet mutated = false;let scriptText: GsapMutationStatus["scriptText"] = null;let after: string | undefined;+ const byPath = new Map<string, Record<string, unknown>[]>();for (const change of input.changes) {+ const mutation = input.mutationFor(change);+ if (!mutation) continue;const changePath = input.resolveChangePath(change.element);+ byPath.set(changePath, [...(byPath.get(changePath) ?? []), mutation]);+ }+ for (const [changePath, mutations] of byPath) {const status = await runOwnedMutation(changePath, () =>- input.mutateChange(change, changePath),+ postGsapMutations(input.projectId, changePath, mutations, input.errorLabel),);mutated = mutated || status.mutated;- // The LAST mutation against the active comp carries the cumulative- // rewritten script for that file.if (changePath === activePath) ({ scriptText, after } = status);}return { mutated, scriptText: otherFileChanged ? null : scriptText, after };diff --git a/packages/studio/src/hooks/useBlockedTimelineEditToast.ts b/packages/studio/src/hooks/useBlockedTimelineEditToast.tsindex 5bbd4d4f06..0ad69388da 100644--- a/packages/studio/src/hooks/useBlockedTimelineEditToast.ts+++ b/packages/studio/src/hooks/useBlockedTimelineEditToast.ts@@ -8,28 +8,19 @@import { useCallback, useRef } from "react";import type { TimelineElement } from "../player";-import {- MAX_HAND_EDIT_CLIPS,- type BlockedTimelineEditIntent,-} from "../player/components/timelineEditing";const BLOCKED_TOAST_INTERVAL_MS = 1500;export function useBlockedTimelineEditToast(showToast: (message: string, tone?: "info" | "error") => void,-): (element: TimelineElement, intent: BlockedTimelineEditIntent) => void {+): (element: TimelineElement) => void {const lastAtRef = useRef(0);return useCallback(- (_element: TimelineElement, intent: BlockedTimelineEditIntent) => {+ (_element: TimelineElement) => {const now = Date.now();if (now - lastAtRef.current < BLOCKED_TOAST_INTERVAL_MS) return;lastAtRef.current = now;- showToast(- intent === "edit-many"- ? `Select ${MAX_HAND_EDIT_CLIPS} or fewer clips to move or resize by hand, or describe the change.`- : "This clip can't be moved or resized from the timeline yet.",- "info",- );+ showToast("This clip can't be moved or resized from the timeline yet.", "info");},[showToast],);diff --git a/packages/studio/src/hooks/useCommitPreflightCapabilities.ts b/packages/studio/src/hooks/useCommitPreflightCapabilities.tsindex 44459341c1..373bac0ff8 100644--- a/packages/studio/src/hooks/useCommitPreflightCapabilities.ts+++ b/packages/studio/src/hooks/useCommitPreflightCapabilities.ts@@ -3,6 +3,7 @@ import type { GsapAnimation } from "@hyperframes/core/gsap-parser";import type { DomEditSelection } from "../components/editor/domEditingTypes";import { dragEditOutcome, preflightGsapRotationIntercept } from "./gsapRuntimeBridge";import { preflightGsapResizeIntercept } from "./gsapResizePreflight";+import { withTweenIndex } from "./gsapRuntimeTweenIndex";import { gsapEditBlockMessage, type GsapEditOutcome } from "./gsapEditOutcome";import { fetchParsedAnimations, parseCacheKey } from "./keyframeCacheAstLoad";import { getAnimationsForElement } from "./gsapElementMatch";@@ -32,6 +33,38 @@ function runCommitPreflights(// Studio can hand a narrowed copy back as a new selection; narrowing starts from the resolved one.const resolvedSelections = new WeakMap<DomEditSelection, DomEditSelection>();+interface CheckInputs {+ animations: GsapAnimation[];+ iframe: HTMLIFrameElement | null;+ group: boolean;+ version: number;+}++interface Checked extends CheckInputs {+ preflight: CommitPreflight;+ narrowed?: DomEditSelection;+}++// A member whose selection, parse, preview and cache version are unchanged keeps its answer.+const checkedSelections = new WeakMap<DomEditSelection, Checked>();++function checkedPreflight(resolved: DomEditSelection, inputs: CheckInputs): Checked {+ const known = checkedSelections.get(resolved);+ const same =+ known?.animations === inputs.animations &&+ known.iframe === inputs.iframe &&+ known.group === inputs.group &&+ known.version === inputs.version;+ if (same) return known;+ const { animations, iframe, group } = inputs;+ const checked = {+ ...inputs,+ preflight: runCommitPreflights(resolved, animations, iframe, group),+ };+ checkedSelections.set(resolved, checked);+ return checked;+}+const resolvedOf = (selection: DomEditSelection) => resolvedSelections.get(selection) ?? selection;const MANUAL_FLAGS = [@@ -123,17 +156,19 @@ export function useCommitPreflightCapabilities({void parseTick;if (!enabled || !projectId) return { selection, groupSelections };const group = groupSelections.length > 1;+ const iframe = previewIframeRef.current;const narrow = (target: DomEditSelection) => {const file = gsapSourceFileForSelection(target);const animations = parsesRef.current.get(parseCacheKey(projectId, file))?.animations;- const preflight = animations- ? runCommitPreflights(resolvedOf(target), animations, previewIframeRef.current, group)- : null;- return narrowCapabilities(target, preflight);+ if (!animations) return narrowCapabilities(target, null);+ const inputs = { animations, iframe, group, version };+ const checked = checkedPreflight(resolvedOf(target), inputs);+ checked.narrowed ??= narrowCapabilities(target, checked.preflight);+ return checked.narrowed;};- return {+ return withTweenIndex(() => ({selection: selection && narrow(selection),groupSelections: groupSelections.map(narrow),- };- }, [enabled, projectId, selection, groupSelections, parseTick, previewIframeRef]);+ }));+ }, [enabled, projectId, selection, groupSelections, parseTick, previewIframeRef, version]);}diff --git a/packages/studio/src/hooks/useDomEditPreviewSync.ts b/packages/studio/src/hooks/useDomEditPreviewSync.tsindex b0b6b8eda1..1a2b5cb265 100644--- a/packages/studio/src/hooks/useDomEditPreviewSync.ts+++ b/packages/studio/src/hooks/useDomEditPreviewSync.ts@@ -10,6 +10,7 @@ import { useDockLayoutStore } from "../components/dock/dockLayoutStore";import type { PatchTarget } from "../utils/sourcePatcher";import { logSelect } from "../utils/selectDebug";import { onPreviewContentReplaced } from "../player/sceneSwap";+import type { ResolveDomSelectionOptions } from "./useDomSelectionTypes";interface UseDomEditPreviewSyncParams {previewIframe: HTMLIFrameElement | null;@@ -24,7 +25,10 @@ interface UseDomEditPreviewSyncParams {selection: DomEditSelection | null,options?: { revealPanel?: boolean; preserveGroup?: boolean },) => void;- buildDomSelectionFromTarget: (element: HTMLElement) => Promise<DomEditSelection | null>;+ buildDomSelectionFromTarget: (+ element: HTMLElement,+ options?: Pick<ResolveDomSelectionOptions, "previous">,+ ) => Promise<DomEditSelection | null>;refreshPreviewDocumentVersion: () => void;syncPreviewHotkeys: (iframe: HTMLIFrameElement | null) => void;applyStudioManualEditsToPreviewRef: React.MutableRefObject<@@ -96,7 +100,9 @@ export function useDomEditPreviewSync({return;}- const nextSelection = await buildDomSelectionFromTarget(nextElement);+ const nextSelection = await buildDomSelectionFromTarget(nextElement, {+ previous: currentSelection,+ });if (nextSelection) {applyDomSelection(nextSelection, { revealPanel: false, preserveGroup: true });}diff --git a/packages/studio/src/hooks/useDomSelection.test.ts b/packages/studio/src/hooks/useDomSelection.test.tsindex fe24abb79e..27c0b0c4b0 100644--- a/packages/studio/src/hooks/useDomSelection.test.ts+++ b/packages/studio/src/hooks/useDomSelection.test.ts@@ -280,6 +280,33 @@ describe("useDomSelection", () => {harness.cleanup();});+ it("keeps the shown selection when a group-preserving refresh reads nothing new", () => {+ const element = document.createElement("div");+ element.id = "headline";+ const first = { ...makeSelection("Headline", element), dataAttributes: { start: "1" } };+ const harness = renderHarness({+ activeCompPath: "intro.html",+ projectId: "project-1",+ refreshKey: 0,+ });+ const refresh = (selection: typeof first) =>+ act(() =>+ harness.current().applyDomSelection(selection, { preserveGroup: true, revealPanel: false }),+ );++ act(() => harness.current().applyDomSelection(first));+ harness.timeline.setTimelineSelectionSet.mockClear();+ refresh({ ...first, dataAttributes: { start: "1" } });+ expect(harness.current().domEditSelection).toBe(first);+ expect(harness.timeline.setTimelineSelectionSet).not.toHaveBeenCalled();++ const moved = { ...first, dataAttributes: { start: "2" } };+ refresh(moved);+ expect(harness.current().domEditSelection).toBe(moved);+ expect(harness.current().domEditGroupSelections).toEqual([moved]);+ harness.cleanup();+ });+it("clears a committed selection when the active composition path changes", () => {const { selection, harness } = setupSelectedHarness();expect(harness.current().domEditSelection).toBe(selection);diff --git a/packages/studio/src/hooks/useDomSelection.ts b/packages/studio/src/hooks/useDomSelection.tsindex f64c04e044..f830c017e9 100644--- a/packages/studio/src/hooks/useDomSelection.ts+++ b/packages/studio/src/hooks/useDomSelection.ts@@ -5,6 +5,7 @@ import {getPreviewTargetFromPointer,} from "../utils/studioPreviewHelpers";import {+ domEditSelectionsEqual,domEditSelectionsTargetSame,domEditSelectionInGroup,toggleDomEditGroupSelection,@@ -23,6 +24,7 @@ import { logSelect } from "../utils/selectDebug";import { announceTimelineSelection as announceSelectionToTimeline } from "./domSelectionTimelineMirror";import type {ApplyDomSelectionOptions,+ ResolveDomSelectionOptions,UseDomSelectionParams,UseDomSelectionReturn,} from "./useDomSelectionTypes";@@ -125,6 +127,12 @@ export function useDomSelection({previousGroup.length === 1 &&domEditSelectionsTargetSame(currentSelection, selection) &&domEditSelectionsTargetSame(previousGroup[0], selection);+ const isUnchangedRefresh =+ options?.preserveGroup &&+ currentSelection !== null &&+ (previousGroup.length === 0 || previousGroup.includes(currentSelection)) &&+ domEditSelectionsEqual(currentSelection, selection);+ if (isUnchangedRefresh) return;if (isRepeatedSingleSelection) {if (options?.revealPanel !== false) {setRightCollapsed(false);@@ -206,23 +214,14 @@ export function useDomSelection({);const buildDomSelectionFromTarget = useCallback(- (- target: HTMLElement,- options?: {- preferClipAncestor?: boolean;- skipSourceProbe?: boolean;- exactTarget?: boolean;- // Override the drill-in scope (used by canvas double-click to resolve the- // child inside a group before the activeGroupElement state has re-rendered).- activeGroupElement?: HTMLElement | null;- },- ) => {+ (target: HTMLElement, options?: ResolveDomSelectionOptions) => {return resolveDomEditSelection(target, {activeCompositionPath: activeCompPath,isMasterView,preferClipAncestor: options?.preferClipAncestor,skipSourceProbe: options?.skipSourceProbe,exactTarget: options?.exactTarget,+ previous: options?.previous,activeGroupElement:options && "activeGroupElement" in options? options.activeGroupElement@@ -384,7 +383,7 @@ export function useDomSelection({return;}- const nextSelection = await buildDomSelectionFromTarget(element);+ const nextSelection = await buildDomSelectionFromTarget(element, { previous: selection });if (nextSelection) {applyDomSelection(nextSelection, {revealPanel: false,@@ -411,7 +410,7 @@ export function useDomSelection({for (const selection of selections) {const element = findElementForSelection(doc, selection, activeCompPath);if (!element) continue;- const nextSelection = await buildDomSelectionFromTarget(element);+ const nextSelection = await buildDomSelectionFromTarget(element, { previous: selection });if (nextSelection) nextGroup.push(nextSelection);}if (nextGroup.length === 0) return;diff --git a/packages/studio/src/hooks/useDomSelectionTypes.ts b/packages/studio/src/hooks/useDomSelectionTypes.tsindex b118cd4ae1..6d994d2f86 100644--- a/packages/studio/src/hooks/useDomSelectionTypes.ts+++ b/packages/studio/src/hooks/useDomSelectionTypes.ts@@ -23,6 +23,7 @@ export interface ResolveDomSelectionOptions {activeGroupElement?: HTMLElement | null;/** Resolve this node itself instead of applying human group-capture behavior. */exactTarget?: boolean;+ previous?: DomEditSelection | null;}// Shared by every hook that needs the project/timeline/panel context a DOMdiff --git a/packages/studio/src/hooks/useEditHistoryActions.test.tsx b/packages/studio/src/hooks/useEditHistoryActions.test.tsxindex 2a5c3f7cd4..09c943c5c3 100644--- a/packages/studio/src/hooks/useEditHistoryActions.test.tsx+++ b/packages/studio/src/hooks/useEditHistoryActions.test.tsx@@ -5,12 +5,19 @@ import { createRoot, type Root } from "react-dom/client";import { afterEach, describe, expect, it, vi } from "vitest";import { STUDIO_MOTION_PATH } from "../components/editor/studioMotion";import { useEditHistoryActions, type EditHistoryHandle } from "./useEditHistoryActions";-import { trackStudioPendingEdit } from "../utils/studioPendingEdits";+import {+ beginStudioPendingEdit,+ setStudioPendingEditClaimClock,+ trackStudioPendingEdit,+} from "../utils/studioPendingEdits";(globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;let root: Root | null = null;-afterEach(() => act(() => root?.unmount()));+afterEach(() => {+ act(() => root?.unmount());+ setStudioPendingEditClaimClock(null);+});type RestoreFiles = Record<string, { previous: string; restored: string }>;type Prediction = { id: string; files: RestoreFiles };@@ -26,12 +33,13 @@ function mount(files?: RestoreFiles;},predicted?: Prediction,+ claims: () => number = () => 7,) {const editHistory = {undo: vi.fn<EditHistoryHandle["undo"]>(async () => result),redo: vi.fn<EditHistoryHandle["redo"]>(async () => result),predict: () => predicted ?? null,- claims: () => 7,+ claims,};const putBack = vi.fn();const deps = {@@ -108,6 +116,49 @@ describe("useEditHistoryActions", () => {});});+ it("reverts an edit still saving before painting an older predicted step", async () => {+ const reapply = vi.fn();+ const revert = vi.fn(() => reapply);+ const saving = beginStudioPendingEdit(revert);+ const { deps, actions } = mount(+ { ok: true, label: "Undid: Move", paths: ["index.html"], undoes: "e2" },+ PREDICTED,+ );+ const undone = actions.undo();+ expect(revert).toHaveBeenCalledTimes(1);+ expect(deps.showHistoryRestoreNow).not.toHaveBeenCalled();+ saving.settle();+ await act(() => undone);+ expect(deps.editHistory.undo).not.toHaveBeenCalled();+ expect(reapply).not.toHaveBeenCalled();+ });++ // Claim counts: when the edit began, at the key, and once its save landed.+ it.each([+ ["its claim counted while undo waited, the server undo is the shown revert", 7, 7, 8, 0],+ ["its claim counted before the key, the server undo is the shown revert", 7, 8, 8, 0],+ ["its claim never counted, the move is shown again", 7, 7, 7, 1],+ ])("an edit that lands while undo waits: %s", async (_, atBegin, atKey, atLand, reapplied) => {+ let claimCount = atBegin;+ setStudioPendingEditClaimClock(() => claimCount);+ const reapply = vi.fn();+ const saving = beginStudioPendingEdit(() => reapply);+ claimCount = atKey;+ const { deps, actions } = mount(+ { ok: true, label: "Undid: Move", paths: ["index.html"], undoes: "e8" },+ PREDICTED,+ () => claimCount,+ );+ const undone = actions.undo();+ saving.settle(saving.adopt(() => Promise.resolve()));+ claimCount = atLand;+ await act(() => undone);+ expect(deps.editHistory.undo).toHaveBeenCalledTimes(1);+ expect(deps.editHistory.undo.mock.calls[0]![0].claimedAfter).toBe(atBegin);+ expect(deps.showHistoryRestoreNow).not.toHaveBeenCalled();+ expect(reapply).toHaveBeenCalledTimes(reapplied);+ });+it("puts a shown step back when the server refuses it", async () => {const { deps, actions } = mount({ ok: false, reason: "failed", message: "disk full" },diff --git a/packages/studio/src/hooks/useEditHistoryActions.ts b/packages/studio/src/hooks/useEditHistoryActions.tsindex 14292658df..ab48857a44 100644--- a/packages/studio/src/hooks/useEditHistoryActions.ts+++ b/packages/studio/src/hooks/useEditHistoryActions.ts@@ -78,14 +78,14 @@ export function useEditHistoryActions({const apply = useCallback(async (direction: "undo" | "redo") => {const noun = direction === "undo" ? "Undo" : "Redo";- // Paint the step in the key's own task when this tab knows it; the server's answer then confirms or corrects.- const predicted = editHistory.predict?.(direction) ?? null;+ // An edit still saving is newer than any step this tab predicts, so it paints back first.+ const pendingEditShown = direction === "undo" ? paintBackNewestStudioPendingEdit() : null;+ const predicted = pendingEditShown ? null : (editHistory.predict?.(direction) ?? null);const predictedShown = predicted ? (showHistoryRestoreNow?.(predicted.files) ?? null) : null;- const pendingEditShown =- !predictedShown && direction === "undo" ? paintBackNewestStudioPendingEdit() : null;const putBack = predictedShown ?? pendingEditShown?.showAgain;const claimedAfter =- direction === "undo" && hasStudioPendingEdits() ? editHistory.claims?.() : undefined;+ pendingEditShown?.claimsAtBegin ??+ (direction === "undo" && hasStudioPendingEdits() ? editHistory.claims?.() : undefined);let result: HistoryResult = { ok: false, reason: "failed" };let serverSteppedShown = false;let revertIsTheUndo = false;@@ -99,9 +99,12 @@ export function useEditHistoryActions({claimedAfter,});const stepped = Boolean(result.ok && result.label);+ const editClaimed =+ pendingEditShown !== null &&+ (editHistory.claims?.() ?? 0) > pendingEditShown.claimsAtBegin;serverSteppedShown = predictedShown? stepped && result.undoes === predicted?.id- : stepped && Boolean(pendingEditShown);+ : stepped && editClaimed;} finally {if (putBack && !serverSteppedShown && !revertIsTheUndo) putBack();}diff --git a/packages/studio/src/hooks/usePersistentEditHistory.test.ts b/packages/studio/src/hooks/usePersistentEditHistory.test.tsindex 36d75166c7..06c69b5668 100644--- a/packages/studio/src/hooks/usePersistentEditHistory.test.ts+++ b/packages/studio/src/hooks/usePersistentEditHistory.test.ts@@ -14,6 +14,10 @@ import {type StudioApiAdapter,} from "@hyperframes/studio-server";import { consumeStudioWriteToken } from "../utils/studioFileVersion";+import {+ beginStudioPendingEdit,+ paintBackNewestStudioPendingEdit,+} from "../utils/studioPendingEdits";import { usePersistentEditHistory } from "./usePersistentEditHistory";const cleanup: Array<() => unknown> = [];@@ -88,6 +92,22 @@ it("an edit Studio saved is undone and redone by the project's history, with theexpect(file()).toBe("B");});+it("gives an edit that begins the history's claim count, so undo can tell its claims from older ones", async () => {+ const { hook, save } = await studio();+ save("B");+ await act(() =>+ hook().recordEdit({+ label: "Moved Title",+ files: { "index.html": { before: "A", after: "B" } },+ }),+ );+ const saving = beginStudioPendingEdit(() => () => {});++ expect(paintBackNewestStudioPendingEdit()?.claimsAtBegin).toBe(hook().claims());+ expect(hook().claims()).toBe(1);+ saving.settle();+});+it("undoes the edit claimed since the key, not a later edit the server took in first", async () => {const { dir, hook, file, save, readFile } = await studio();const atKey = hook().claims();@@ -366,6 +386,31 @@ it("a drag's edits under one key undo as one step, even before the drag goes idlexpect(file()).toBe("A");});+it("a key one page holds does not join another page's edit under the same key", async () => {+ const { hook, file, save, readFile } = await studio();+ let reloaded!: ReturnType<typeof usePersistentEditHistory>;+ function Reloaded() {+ reloaded = usePersistentEditHistory({ projectId: "demo" });+ return null;+ }+ const root = createRoot(document.createElement("div"));+ await act(async () => root.render(createElement(Reloaded)));+ cleanup.push(() => act(() => root.unmount()));+ const held = { label: "Moved Title", coalesceKey: "timeline-move:1", coalesceMs: Infinity };+ save("B");+ await act(() =>+ hook().recordEdit({ ...held, files: { "index.html": { before: "A", after: "B" } } }),+ );+ save("C");+ await act(() =>+ reloaded.recordEdit({ ...held, files: { "index.html": { before: "B", after: "C" } } }),+ );++ await act(() => reloaded.undo({ readFile }));++ expect(file()).toBe("B");+});+it("an undo before the history view shows a drag's held claim still waits on the files it wrote", async () => {const { hook, save, readFile } = await studio();const server = globalThis.fetch;diff --git a/packages/studio/src/hooks/usePersistentEditHistory.ts b/packages/studio/src/hooks/usePersistentEditHistory.tsindex 4e27217ab6..28b6035e86 100644--- a/packages/studio/src/hooks/usePersistentEditHistory.ts+++ b/packages/studio/src/hooks/usePersistentEditHistory.ts@@ -3,7 +3,9 @@ import type { HistoryListItem, HistoryResult } from "@hyperframes/studio-server"import { studioFileContentVersion, studioWriteHeaders } from "../utils/studioFileVersion";import type { RestoreFiles } from "../utils/gsapUndoRestore";import { studioApiFetch } from "../utils/studioApiFetch";+import { setStudioPendingEditClaimClock } from "../utils/studioPendingEdits";import type { RecordEditInput } from "../utils/studioFileHistory";+import { generateId } from "../utils/generateId";interface ApplyCallbacks {readFile: (path: string) => Promise<string>;@@ -206,6 +208,7 @@ export function usePersistentEditHistory({ projectId }: UsePersistentEditHistoryconst projectIdRef = useRef(projectId);projectIdRef.current = projectId;const [own] = useState(createOwnHistory);+ const [pageKeyScope] = useState(generateId);const refresh = useCallback(async () => {if (!projectId) return;@@ -228,6 +231,11 @@ export function usePersistentEditHistory({ projectId }: UsePersistentEditHistoryvoid refresh().finally(() => setLoaded(true));}, [refresh, own]);+ useEffect(() => {+ setStudioPendingEditClaimClock(own.claimCount);+ return () => setStudioPendingEditClaimClock(null);+ }, [own]);+const recordEdit = useCallback(async ({ label, coalesceKey, coalesceMs, files, created = [] }: RecordEditInput) => {if (!projectId) return;@@ -237,7 +245,10 @@ export function usePersistentEditHistory({ projectId }: UsePersistentEditHistorylabel,paths,overwrote: await overwroteVersions(files),- ...(coalesceKey && { coalesceKey, idleMs: coalesceMs ?? DEFAULT_COALESCE_MS }),+ ...(coalesceKey && {+ coalesceKey: `${pageKeyScope}:${coalesceKey}`,+ idleMs: coalesceMs ?? DEFAULT_COALESCE_MS,+ }),});const claimed = claimHeld(reply, label);if (claimed) {@@ -247,7 +258,7 @@ export function usePersistentEditHistory({ projectId }: UsePersistentEditHistoryheldClaimRef.current = claimed && coalesceKey ? { paths, at: Date.now() } : null;await refresh();},- [projectId, refresh, own],+ [projectId, refresh, own, pageKeyScope],);const step = useCallback(diff --git a/packages/studio/src/hooks/useTimelineClipTimingEditing.ts b/packages/studio/src/hooks/useTimelineClipTimingEditing.tsnew file mode 100644index 0000000000..ca550ccf00--- /dev/null+++ b/packages/studio/src/hooks/useTimelineClipTimingEditing.ts@@ -0,0 +1,343 @@+import { useCallback, type MutableRefObject } from "react";+import type { TimelineElement } from "../player";+import { toAuthoredStart, toCompositionTime } from "../player/store/timelineElement";+import {+ applyTimelineStackingReorder,+ patchIframeDomTiming,+ persistTimelineEdit,+ formatTimelineAttributeNumber,+ formatTimelineMediaOffset,+ extendRootDurationIfNeeded,+ buildTimelineMoveTimingPatch,+ buildTimelineResizeTimingPatch,+ type PersistTimelineEditInput,+} from "./timelineEditingHelpers";+import { playbackStartAttributeForElement } from "../player/lib/timelineElementHelpers";+import {+ captureDurationRollback,+ finishClipTimingFallback,+ sdkTimingGsapSync,+ readFileContent,+ syncPreviewContentDuration,+ timingGestureStep,+} from "./timelineTimingSync";+import { serializeZLaneGesture } from "../components/nle/zLaneGesture";+import { cutoverCommittedOrThrow, sdkTimingPersist } from "../utils/sdkCutover";+import type { TimelineMoveUpdates, UseTimelineEditingOptions } from "./useTimelineEditingTypes";+import { getStudioSaveErrorMessage } from "../utils/studioSaveDiagnostics";++type UseTimelineClipTimingEditingOptions = Pick<+ UseTimelineEditingOptions,+ | "activeCompPath"+ | "timelineElements"+ | "showToast"+ | "writeProjectFile"+ | "recordEdit"+ | "reloadPreview"+ | "previewIframeRef"+ | "pendingTimelineEditPathRef"+ | "isRecordingRef"+ | "sdkSession"+ | "publishSdkSession"+ | "forceReloadSdkSession"+ | "invalidateGsapCache"+ | "handleDomZIndexReorderCommitRef"+> & {+ editQueueRef: MutableRefObject<Promise<unknown>>;+ projectIdRef: MutableRefObject<string | null>;+};++/** One clip's move and resize: the timing write, then its tween rewrite, as one undo step. */+export function useTimelineClipTimingEditing({+ activeCompPath,+ timelineElements,+ showToast,+ writeProjectFile,+ recordEdit,+ reloadPreview,+ previewIframeRef,+ pendingTimelineEditPathRef,+ isRecordingRef,+ sdkSession,+ publishSdkSession,+ forceReloadSdkSession,+ invalidateGsapCache,+ handleDomZIndexReorderCommitRef,+ editQueueRef,+ projectIdRef,+}: UseTimelineClipTimingEditingOptions) {+ const enqueueEdit = useCallback(+ (+ element: TimelineElement,+ label: string,+ buildPatches: PersistTimelineEditInput["buildPatches"],+ step: ReturnType<typeof timingGestureStep>,+ ): Promise<void> => {+ if (isRecordingRef?.current) {+ showToast("Cannot edit timeline while recording", "error");+ return Promise.resolve();+ }+ const pid = projectIdRef.current;+ if (!pid) return Promise.resolve();+ const queued = editQueueRef.current+ .then(() =>+ persistTimelineEdit({+ projectId: pid,+ element,+ activeCompPath,+ label,+ buildPatches,+ writeProjectFile,+ recordEdit,+ pendingTimelineEditPathRef,+ ...step,+ }),+ )+ .then(() => {+ forceReloadSdkSession?.();+ });+ editQueueRef.current = queued.catch((error) => {+ console.error(`[Timeline] Failed to persist: ${label}`, error);+ });+ return queued;+ },+ [+ activeCompPath,+ recordEdit,+ writeProjectFile,+ pendingTimelineEditPathRef,+ showToast,+ isRecordingRef,+ forceReloadSdkSession,+ editQueueRef,+ projectIdRef,+ ],+ );+ const handleTimelineElementMove = useCallback(+ // fallow-ignore-next-line complexity+ (element: TimelineElement, updates: TimelineMoveUpdates) => {+ // fallow-ignore-next-line complexity+ const commitMove = () => {+ const targetPath = element.sourceFile || activeCompPath || "index.html";+ const startChanged = updates.start !== element.start;+ // A vertical-only lane move (start unchanged, authored track already in updates.track) must+ // persist like any other move, or the lane snaps back on reload.+ const trackChanged = updates.track !== element.track;+ const authoredStart = toAuthoredStart(element, updates.start);+ if (startChanged || trackChanged) {+ const liveAttrs: Array<[string, string]> = [];+ if (startChanged)+ liveAttrs.push(["data-start", formatTimelineAttributeNumber(authoredStart)]);+ if (trackChanged) {+ liveAttrs.push(["data-track-index", formatTimelineAttributeNumber(updates.track)]);+ }+ patchIframeDomTiming(previewIframeRef.current, element, liveAttrs, activeCompPath);+ }++ const reorderDone = applyTimelineStackingReorder({+ element,+ stackingReorder: updates.stackingReorder,+ timelineElements,+ iframe: previewIframeRef.current,+ activeCompPath,+ commit: handleDomZIndexReorderCommitRef?.current,+ });++ if (!startChanged && !trackChanged) return reorderDone;++ // Snapshot the duration BEFORE the optimistic updates below so a failed+ // persist can roll the readout + live root back (see captureDurationRollback).+ const rollbackDuration = captureDurationRollback(previewIframeRef.current);+ // Read before the readout sync below: the SDK path (setTiming) can't grow the root duration.+ const needsExtension = extendRootDurationIfNeeded(updates.start + element.duration);+ // Optimistic duration readout from the just-patched live DOM (grows and shrinks).+ syncPreviewContentDuration(previewIframeRef.current);++ const buildMovePatches: PersistTimelineEditInput["buildPatches"] = (original, target) => {+ // Persist lane changes too — data-start-only writes let reload snap the lane back.+ const track = trackChanged ? updates.track : undefined;+ return buildTimelineMoveTimingPatch(+ original,+ target,+ authoredStart,+ element.duration,+ track,+ );+ };+ const step = timingGestureStep("timeline-move");+ const finishMoveGsapSync = (sdkGsap?: ReturnType<typeof sdkTimingGsapSync>) =>+ // One GSAP sync per edit: the SDK commit's own (sdkGsap), else the server rewrite here.+ finishClipTimingFallback({+ iframe: previewIframeRef.current,+ reloadPreview,+ projectId: projectIdRef.current,+ targetPath,+ domId: element.domId,+ label: "Move timeline clip",+ coalesceKey: step.coalesceKey,+ recordEdit,+ writeProjectFile,+ edit: { kind: "shift", delta: updates.start - element.start },+ sdkGsap,+ }).finally(() => invalidateGsapCache?.());+ const moveFallback = () =>+ enqueueEdit(element, "Move timeline clip", buildMovePatches, step).then(() =>+ finishMoveGsapSync(),+ );+ return reorderDone+ .then(() => {+ // SDK setTiming writes start only; a lane change needs the fallback's track patch.+ if (sdkSession && element.hfId && !element.link && !needsExtension && !trackChanged) {+ return sdkTimingPersist(+ element.hfId,+ targetPath,+ { start: authoredStart },+ sdkSession,+ {+ editHistory: { recordEdit },+ writeProjectFile,+ reloadPreview,+ compositionPath: activeCompPath,+ // Capture on-disk bytes as the undo `before` so undoing a timing move+ // restores the file verbatim, not a normalized full-DOM re-emit.+ readProjectFile: (path) => readFileContent(projectIdRef.current ?? "", path),+ publishSession: publishSdkSession,+ },+ { label: "Move timeline clip", ...step, skipRefresh: true },+ ).then((result) => {+ if (!cutoverCommittedOrThrow(result)) return moveFallback();+ return finishMoveGsapSync(sdkTimingGsapSync(result));+ });+ }+ return moveFallback();+ })+ .catch((error) => {+ // Failed persist: revert the optimistic duration readout + live root.+ rollbackDuration();+ showToast(getStudioSaveErrorMessage(error), "error");+ throw error;+ });+ };+ return updates.stackingReorder ? serializeZLaneGesture(commitMove) : commitMove();+ },+ [+ previewIframeRef,+ enqueueEdit,+ activeCompPath,+ sdkSession,+ publishSdkSession,+ recordEdit,+ writeProjectFile,+ reloadPreview,+ timelineElements,+ handleDomZIndexReorderCommitRef,+ showToast,+ invalidateGsapCache,+ projectIdRef,+ ],+ );++ const handleTimelineElementResize = useCallback(+ // fallow-ignore-next-line complexity+ (+ element: TimelineElement,+ updates: Pick<TimelineElement, "start" | "duration" | "playbackStart">,+ ) => {+ const authoredStart = toAuthoredStart(element, updates.start);+ const liveAttrs: Array<[string, string]> = [+ ["data-start", formatTimelineAttributeNumber(authoredStart)],+ ["data-duration", formatTimelineAttributeNumber(updates.duration)],+ ];+ if (updates.playbackStart != null) {+ const liveAttr = playbackStartAttributeForElement(element);+ liveAttrs.push([liveAttr, formatTimelineMediaOffset(updates.playbackStart)]);+ }+ patchIframeDomTiming(previewIframeRef.current, element, liveAttrs, activeCompPath);+ // Snapshot the duration BEFORE the optimistic updates below so a failed+ // persist can roll the readout + live root back (see captureDurationRollback).+ const rollbackDuration = captureDurationRollback(previewIframeRef.current);+ // Read before the readout sync below: the SDK path (setTiming) can't grow the root duration.+ const needsExtension = extendRootDurationIfNeeded(updates.start + updates.duration);+ // Optimistic duration readout from the just-patched live DOM (grows and shrinks).+ syncPreviewContentDuration(previewIframeRef.current);+ const targetPath = element.sourceFile || activeCompPath || "index.html";+ const buildResizePatches: PersistTimelineEditInput["buildPatches"] = (original, target) => {+ return buildTimelineResizeTimingPatch(original, target, element, updates);+ };+ const hasPbsAdjustment =+ updates.playbackStart != null ||+ (updates.start !== element.start && element.playbackStart != null);+ // Server-path fallback: after persisting the attr patch, scale GSAP tween+ // positions/durations on the server, then soft-reload with the rewritten+ // script (timing-only resize) — same no-flash path as move; full reload is+ // the fallback.+ const step = timingGestureStep("timeline-resize");+ const finishResizeGsapSync = (sdkGsap?: ReturnType<typeof sdkTimingGsapSync>) =>+ finishClipTimingFallback({+ iframe: previewIframeRef.current,+ reloadPreview,+ projectId: projectIdRef.current,+ targetPath,+ domId: element.domId,+ label: "Resize timeline clip",+ coalesceKey: step.coalesceKey,+ recordEdit,+ writeProjectFile,+ edit: {+ kind: "scale",+ from: { start: toCompositionTime(element, element.start), duration: element.duration },+ to: { start: toCompositionTime(element, updates.start), duration: updates.duration },+ },+ sdkGsap,+ }).finally(() => invalidateGsapCache?.());+ const resizeFallback = () =>+ enqueueEdit(element, "Resize timeline clip", buildResizePatches, step).then(() =>+ finishResizeGsapSync(),+ );+ const persistDone =+ sdkSession && element.hfId && !element.link && !hasPbsAdjustment && !needsExtension+ ? sdkTimingPersist(+ element.hfId,+ targetPath,+ { start: authoredStart, duration: updates.duration },+ sdkSession,+ {+ editHistory: { recordEdit },+ writeProjectFile,+ reloadPreview,+ compositionPath: activeCompPath,+ // Capture on-disk bytes as the undo `before` so undoing a timing+ // resize restores the file verbatim, not a normalized full-DOM re-emit.+ readProjectFile: (path) => readFileContent(projectIdRef.current ?? "", path),+ publishSession: publishSdkSession,+ },+ { label: "Resize timeline clip", ...step, skipRefresh: true },+ ).then((result) => {+ if (!cutoverCommittedOrThrow(result)) return resizeFallback();+ return finishResizeGsapSync(sdkTimingGsapSync(result));+ })+ : resizeFallback();+ return persistDone.catch((error) => {+ // Failed persist: revert the optimistic duration readout + live root.+ rollbackDuration();+ showToast(getStudioSaveErrorMessage(error), "error");+ throw error;+ });+ },+ [+ previewIframeRef,+ enqueueEdit,+ activeCompPath,+ sdkSession,+ publishSdkSession,+ recordEdit,+ writeProjectFile,+ reloadPreview,+ showToast,+ invalidateGsapCache,+ projectIdRef,+ ],+ );++ return { handleTimelineElementMove, handleTimelineElementResize };+}diff --git a/packages/studio/src/hooks/useTimelineDeleteOps.test.tsx b/packages/studio/src/hooks/useTimelineDeleteOps.test.tsxindex df155ebfab..1c1bc63c37 100644--- a/packages/studio/src/hooks/useTimelineDeleteOps.test.tsx+++ b/packages/studio/src/hooks/useTimelineDeleteOps.test.tsx@@ -62,6 +62,7 @@ describe("useTimelineDeleteOps: ripple undo label", () => {function mountDeleteHarness(overrides: {handleTimelineGroupMove: DeleteOpsOptions["handleTimelineGroupMove"];showToast?: DeleteOpsOptions["showToast"];+ recordEdit?: DeleteOpsOptions["recordEdit"];}) {const elements = [el("hf-a", 0, 2), el("hf-b", 2, 2), el("hf-c", 4, 2)];let hook: ReturnType<typeof useTimelineDeleteOps> | null = null;@@ -72,7 +73,7 @@ describe("useTimelineDeleteOps: ripple undo label", () => {timelineElements: elements,showToast: overrides.showToast ?? vi.fn(),writeProjectFile: vi.fn().mockResolvedValue(undefined),- recordEdit: vi.fn().mockResolvedValue(undefined),+ recordEdit: overrides.recordEdit ?? vi.fn().mockResolvedValue(undefined),reloadPreview: vi.fn(),previewIframeRef: { current: null },handleTimelineGroupMove: overrides.handleTimelineGroupMove,@@ -120,6 +121,24 @@ describe("useTimelineDeleteOps: ripple undo label", () => {);});+ it("holds the delete's undo step open under the key its ripple joins, however late the ripple lands", async () => {+ stubRemoveElementsFetch(html, html.replace(/<div data-hf-id="hf-b"[^\n]*\n/, ""));+ const handleTimelineGroupMove = vi.fn().mockResolvedValue(undefined);+ const recordEdit = vi.fn().mockResolvedValue(undefined);+ const { b, getHook } = mountDeleteHarness({ handleTimelineGroupMove, recordEdit });++ await act(async () => {+ await getHook().handleTimelineElementDelete(b);+ });++ const [[deleted]] = recordEdit.mock.calls;+ expect(deleted).toMatchObject({ coalesceMs: Infinity });+ expect(handleTimelineGroupMove).toHaveBeenCalledWith(+ expect.anything(),+ expect.objectContaining({ coalesceKey: deleted.coalesceKey }),+ );+ });+it("removes a multi-clip selection with one request, however many clips it holds", async () => {const handleTimelineGroupMove = vi.fn().mockResolvedValue(undefined);const { elements, getHook } = mountDeleteHarness({ handleTimelineGroupMove });diff --git a/packages/studio/src/hooks/useTimelineDeleteOps.ts b/packages/studio/src/hooks/useTimelineDeleteOps.tsindex 12c480cec4..a7d0155fe7 100644--- a/packages/studio/src/hooks/useTimelineDeleteOps.ts+++ b/packages/studio/src/hooks/useTimelineDeleteOps.ts@@ -9,7 +9,7 @@ import { saveServerRewriteWithHistory, type RecordEditInput } from "../utils/stuimport { studioWriteHeaders } from "../utils/studioFileVersion";import { getTimelineElementLabel } from "../utils/studioHelpers";import { buildPatchTarget, removeIframeTimelineElements } from "./timelineEditingHelpers";-import { captureDurationRollback } from "./timelineTimingSync";+import { captureDurationRollback, timingGestureStep } from "./timelineTimingSync";import { setLinkInSource } from "../components/editor/mediaLinkEdits";import { setCompositionDurationToContent } from "../utils/timelineAssetDrop";import { furthestClipEndFromSource } from "../player/lib/timelineElementHelpers";@@ -57,11 +57,6 @@ interface UseTimelineDeleteOpsOptions {) => Promise<void>;}-// Per-gesture-unique coalesce key — a monotonic counter, not Date.now() /-// Math.random() (determinism rules), mirroring gapCloseGestureSeq in-// timelineGapCommit.ts.-let deleteGestureSeq = 0;-function unlinkInSource(source: string, survivors: readonly TimelineElement[]): string {const targets = survivors.map(buildPatchTarget).filter((target) => target !== null);return targets.length > 0 ? setLinkInSource(source, targets, null) : source;@@ -107,10 +102,8 @@ export function useTimelineDeleteOps({(candidate) => (candidate.sourceFile || activeCompPath || "index.html") === targetPath,);try {- // 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++}`;+ // Shared with the ripple move below so a folded ripple is one undo step with the delete.+ const step = timingGestureStep("main-track-ripple-delete");const deleteHistoryLabel = "Delete timeline clip";let rollbackDuration = () => {};try {@@ -118,7 +111,7 @@ export function useTimelineDeleteOps({projectId: pid,path: targetPath,label: deleteHistoryLabel,- coalesceKey,+ ...step,writeFile: writeProjectFile,recordEdit,rewrite: async (originalContent) => {@@ -189,8 +182,7 @@ export function useTimelineDeleteOps({if (rippleChanges) {try {await handleTimelineGroupMove(rippleChanges, {- coalesceKey,- coalesceMs: Number.POSITIVE_INFINITY,+ coalesceKey: step.coalesceKey,// Coalescing keeps the LAST entry's label; without this the undo// toast reads "Undid Move timeline clips" after a delete, naming// the ripple's mechanics instead of what the user actually did.diff --git a/packages/studio/src/hooks/useTimelineEditing.test.tsx b/packages/studio/src/hooks/useTimelineEditing.test.tsxindex 65bdd3dcc6..3d3af8d2a9 100644--- a/packages/studio/src/hooks/useTimelineEditing.test.tsx+++ b/packages/studio/src/hooks/useTimelineEditing.test.tsx@@ -306,9 +306,10 @@ function stubProjectFetch(files: string | Record<string, string>, gsapBody?: unk(url) => jsonResponse({ content: fileContent(pathAfter(url, "/files/")) }),],[- "/api/projects/p1/gsap-mutations/",+ "/api/projects/p1/gsap-mutations",(url) => {- const content = fileContent(pathAfter(url, "/gsap-mutations/")) ?? "";+ const content =+ fileContent(pathAfter(url, url.includes("-batch/") ? "-batch/" : "s/")) ?? "";return jsonResponse(gsapBody ?? { mutated: false, scriptText: null, before: content, after: content },);@@ -1166,6 +1167,41 @@ describe("useTimelineEditing timeline z-index reorder", () => {expect(groupWrite.mock.calls[0]![1]).toBe(singleWrite.mock.calls[0]![1]);group.unmount();});++ it("gives each single-clip move and resize its own undo step, which its GSAP rewrite joins", async () => {+ const source = '<div id="clip" data-start="0" data-duration="1"></div>';+ const clip = timelineElement({ id: "clip", track: 0, zIndex: 0, start: 0, duration: 1 });+ stubProjectFetch(source, {+ mutated: true,+ scriptText: null,+ before: "tweens at 0",+ after: source,+ });+ const recordEdit = vi.fn(async (_edit: { coalesceKey?: string; coalesceMs?: number }) => {});+ const h = renderTimelineEditingHook({+ timelineElements: [clip],+ iframe: createPreviewIframe([{ id: "clip", track: 0 }]),+ onZIndexCommit: vi.fn().mockResolvedValue(undefined),+ projectId: "p1",+ writeProjectFile: vi.fn(async () => {}),+ recordEdit,+ });++ await act(async () => {+ await h.move(clip, { start: 0.5, track: clip.track });+ await h.move(clip, { start: 1, track: clip.track });+ await h.resize(clip, { start: 0, duration: 2 });+ });++ const steps = recordEdit.mock.calls.map(([edit]) => edit);+ expect(steps.map((edit) => edit.coalesceMs)).toEqual(Array(6).fill(Infinity));+ const [move, fold, again, foldAgain, resize, resizeFold] = steps.map(+ (edit) => edit.coalesceKey,+ );+ expect([fold, foldAgain, resizeFold]).toEqual([move, again, resize]);+ expect(new Set([move, again, resize]).size).toBe(3);+ h.unmount();+ });});describe("useTimelineEditing duration rollback on failed persist", () => {@@ -1936,8 +1972,11 @@ function setupNestedHarness() {const fetchMock = stubProjectFetch(NESTED_FILES);const scaleCalls = () =>fetchMock.mock.calls- .filter((call) => requestUrl(call[0]).includes("/gsap-mutations/"))- .map((call) => JSON.parse(String((call[1] as RequestInit).body)))+ .filter((call) => requestUrl(call[0]).includes("/gsap-mutations"))+ .flatMap((call) => {+ const body = JSON.parse(String((call[1] as RequestInit).body));+ return body.mutations ?? [body];+ }).filter((body) => body.type === "scale-positions");usePlayerStore.getState().setDuration(20);const hook = renderTimelineEditingHook({@@ -2285,6 +2324,19 @@ describe("clip timing edits sync GSAP exactly once", () => {applyServerMutation(pathAfter(url, "/gsap-mutations/"), JSON.parse(String(init?.body))),);}+ if (url.includes("/gsap-mutations-batch/")) {+ const path = pathAfter(url, "/gsap-mutations-batch/");+ const steps = (+ JSON.parse(String(init?.body)) as { mutations: Record<string, unknown>[] }+ ).mutations.map((mutation) => applyServerMutation(path, mutation));+ const last = steps[steps.length - 1]!;+ return jsonResponse({+ ...last,+ before: steps[0]!.before,+ mutated: steps[0]!.before !== last.after,+ changed: steps[0]!.before !== last.after,+ });+ }if (url.includes("/files/"))return jsonResponse({ content: files[pathAfter(url, "/files/")] });throw new Error(`Unexpected fetch: ${url}`);@@ -2404,6 +2456,13 @@ describe("clip timing edits sync GSAP exactly once", () => {`tl.from("#scene h1", { y: 20, duration: 1 }, 3.5);`,`tl.to("#side", { x: 5, duration: 1 }, 3);`,]);+ if (!withSdk) {+ const gsapUrls = h.fetchMock.mock.calls+ .map((call) => requestUrl(call[0]))+ .filter((url) => url.includes("/gsap-mutations"));+ // Both clips live in one file, so their rewrites travel as one request.+ expect(gsapUrls).toEqual([expect.stringContaining("/gsap-mutations-batch/")]);+ }h.hook.unmount();});}diff --git a/packages/studio/src/hooks/useTimelineEditing.ts b/packages/studio/src/hooks/useTimelineEditing.tsindex 427f874c89..56fd039c5d 100644--- a/packages/studio/src/hooks/useTimelineEditing.ts+++ b/packages/studio/src/hooks/useTimelineEditing.ts@@ -1,30 +1,10 @@// fallow-ignore-file complexity-import { useCallback, useRef } from "react";+import { useRef } from "react";import { useStableHandlers } from "./useStableHandlers";import { usePlayerStore, type TimelineElement } from "../player";-import { toAuthoredStart, toCompositionTime } from "../player/store/timelineElement";import { useRazorSplit } from "./useRazorSplit";import { selectSplittableElements } from "../utils/timelineElementSplit";import { useTimelineAssetDropOps } from "./useTimelineAssetDropOps";-import {- applyTimelineStackingReorder,- patchIframeDomTiming,- persistTimelineEdit,- formatTimelineAttributeNumber,- formatTimelineMediaOffset,- extendRootDurationIfNeeded,- buildTimelineMoveTimingPatch,- buildTimelineResizeTimingPatch,-} from "./timelineEditingHelpers";-import { playbackStartAttributeForElement } from "../player/lib/timelineElementHelpers";-import {- captureDurationRollback,- finishClipTimingFallback,- sdkTimingGsapSync,- readFileContent,- syncPreviewContentDuration,-} from "./timelineTimingSync";-import type { PersistTimelineEditInput } from "./timelineEditingHelpers";import { useSetAudioGroupAttribute } from "./timelineAudioGroupVolume";import { useSetElementAttribute } from "./timelineElementFxAttribute";import { useSetElementsAttribute } from "./timelineElementsAttribute";@@ -42,12 +22,10 @@ import {useTimelineTrackVisibilityEditing,} from "./timelineTrackVisibility";import { useTimelineGroupEditing } from "./useTimelineGroupEditing";+import { useTimelineClipTimingEditing } from "./useTimelineClipTimingEditing";import { useBlockedTimelineEditToast } from "./useBlockedTimelineEditToast";import { useTimelineEditGate, type TimelineEditOutcome } from "./timelineEditPermission";-import { serializeZLaneGesture } from "../components/nle/zLaneGesture";-import { cutoverCommittedOrThrow, sdkTimingPersist } from "../utils/sdkCutover";-import type { TimelineMoveUpdates, UseTimelineEditingOptions } from "./useTimelineEditingTypes";-import { getStudioSaveErrorMessage } from "../utils/studioSaveDiagnostics";+import type { UseTimelineEditingOptions } from "./useTimelineEditingTypes";export function useTimelineEditing({projectId,@@ -76,51 +54,6 @@ export function useTimelineEditing({const checkEditable = useTimelineEditGate(canEdit, showToast);const guard = useTimelineEditGuard(canEdit, showToast);- const enqueueEdit = useCallback(- (- element: TimelineElement,- label: string,- buildPatches: PersistTimelineEditInput["buildPatches"],- coalesceKey?: string,- ): Promise<void> => {- if (isRecordingRef?.current) {- showToast("Cannot edit timeline while recording", "error");- return Promise.resolve();- }- const pid = projectIdRef.current;- if (!pid) return Promise.resolve();- const queued = editQueueRef.current- .then(() =>- persistTimelineEdit({- projectId: pid,- element,- activeCompPath,- label,- buildPatches,- writeProjectFile,- recordEdit,- pendingTimelineEditPathRef,- coalesceKey,- }),- )- .then(() => {- forceReloadSdkSession?.();- });- editQueueRef.current = queued.catch((error) => {- console.error(`[Timeline] Failed to persist: ${label}`, error);- });- return queued;- },- [- activeCompPath,- recordEdit,- writeProjectFile,- pendingTimelineEditPathRef,- showToast,- isRecordingRef,- forceReloadSdkSession,- ],- );const groupEditing = useTimelineGroupEditing({activeCompPath,editQueueRef,@@ -137,231 +70,24 @@ export function useTimelineEditing({showToast,writeProjectFile,});- const handleTimelineElementMove = useCallback(- // fallow-ignore-next-line complexity- (element: TimelineElement, updates: TimelineMoveUpdates) => {- const commitMove = () => {- const targetPath = element.sourceFile || activeCompPath || "index.html";- const startChanged = updates.start !== element.start;- // A vertical-only lane move arrives with start unchanged but track changed- // (on this single-element path the drag commit has already folded the- // AUTHORED persist track into updates.track). It must persist like any- // other move — early-returning on !startChanged alone silently dropped- // the file write, so the lane snapped back on reload.- const trackChanged = updates.track !== element.track;- const authoredStart = toAuthoredStart(element, updates.start);- if (startChanged || trackChanged) {- const liveAttrs: Array<[string, string]> = [];- if (startChanged)- liveAttrs.push(["data-start", formatTimelineAttributeNumber(authoredStart)]);- if (trackChanged) {- liveAttrs.push(["data-track-index", formatTimelineAttributeNumber(updates.track)]);- }- patchIframeDomTiming(previewIframeRef.current, element, liveAttrs, activeCompPath);- }-- const reorderDone = applyTimelineStackingReorder({- element,- stackingReorder: updates.stackingReorder,- timelineElements,- iframe: previewIframeRef.current,- activeCompPath,- commit: handleDomZIndexReorderCommitRef?.current,- });-- if (!startChanged && !trackChanged) return reorderDone;-- // Snapshot the duration BEFORE the optimistic updates below so a failed- // persist can roll the readout + live root back (see captureDurationRollback).- const rollbackDuration = captureDurationRollback(previewIframeRef.current);- // needsExtension gates the SDK path (setTiming can't grow the root duration), so read the store BEFORE the readout sync below optimistically updates it.- const needsExtension = extendRootDurationIfNeeded(updates.start + element.duration);- // Optimistic duration readout: content-driven (grow AND shrink), from the just-patched live DOM. See syncPreviewContentDuration.- syncPreviewContentDuration(previewIframeRef.current);-- const buildMovePatches: PersistTimelineEditInput["buildPatches"] = (original, target) => {- // Persist lane changes too — data-start-only writes let reload snap the lane back.- const track = trackChanged ? updates.track : undefined;- return buildTimelineMoveTimingPatch(- original,- target,- authoredStart,- element.duration,- track,- );- };- const coalesceKey = `timeline-move:${element.hfId ?? element.id}`;- const finishMoveGsapSync = (sdkGsap?: ReturnType<typeof sdkTimingGsapSync>) =>- // One GSAP sync per edit: the SDK commit's own (sdkGsap), else the server rewrite here.- finishClipTimingFallback({- iframe: previewIframeRef.current,- reloadPreview,- projectId: projectIdRef.current,- targetPath,- domId: element.domId,- label: "Move timeline clip",- coalesceKey,- recordEdit,- writeProjectFile,- edit: { kind: "shift", delta: updates.start - element.start },- sdkGsap,- }).finally(() => invalidateGsapCache?.());- const moveFallback = () =>- enqueueEdit(element, "Move timeline clip", buildMovePatches, coalesceKey).then(() =>- finishMoveGsapSync(),- );- return reorderDone- .then(() => {- // SDK setTiming writes start only; a lane change needs the fallback's track patch.- if (sdkSession && element.hfId && !element.link && !needsExtension && !trackChanged) {- return sdkTimingPersist(- element.hfId,- targetPath,- { start: authoredStart },- sdkSession,- {- editHistory: { recordEdit },- writeProjectFile,- reloadPreview,- compositionPath: activeCompPath,- // Capture on-disk bytes as the undo `before` so undoing a timing move- // restores the file verbatim, not a normalized full-DOM re-emit.- readProjectFile: (path) => readFileContent(projectIdRef.current ?? "", path),- publishSession: publishSdkSession,- },- { label: "Move timeline clip", coalesceKey, skipRefresh: true },- ).then((result) => {- if (!cutoverCommittedOrThrow(result)) return moveFallback();- return finishMoveGsapSync(sdkTimingGsapSync(result));- });- }- return moveFallback();- })- .catch((error) => {- // Failed persist: revert the optimistic duration readout + live root.- rollbackDuration();- showToast(getStudioSaveErrorMessage(error), "error");- throw error;- });- };- return updates.stackingReorder ? serializeZLaneGesture(commitMove) : commitMove();- },- [- previewIframeRef,- enqueueEdit,- activeCompPath,- sdkSession,- publishSdkSession,- recordEdit,- writeProjectFile,- reloadPreview,- timelineElements,- handleDomZIndexReorderCommitRef,- showToast,- invalidateGsapCache,- ],- );-- const handleTimelineElementResize = useCallback(- // fallow-ignore-next-line complexity- (- element: TimelineElement,- updates: Pick<TimelineElement, "start" | "duration" | "playbackStart">,- ) => {- const authoredStart = toAuthoredStart(element, updates.start);- const liveAttrs: Array<[string, string]> = [- ["data-start", formatTimelineAttributeNumber(authoredStart)],- ["data-duration", formatTimelineAttributeNumber(updates.duration)],- ];- if (updates.playbackStart != null) {- const liveAttr = playbackStartAttributeForElement(element);- liveAttrs.push([liveAttr, formatTimelineMediaOffset(updates.playbackStart)]);- }- patchIframeDomTiming(previewIframeRef.current, element, liveAttrs, activeCompPath);- // Snapshot the duration BEFORE the optimistic updates below so a failed- // persist can roll the readout + live root back (see captureDurationRollback).- const rollbackDuration = captureDurationRollback(previewIframeRef.current);- // needsExtension gates the SDK path (setTiming can't grow the root duration), so read the store BEFORE the readout sync below optimistically updates it.- const needsExtension = extendRootDurationIfNeeded(updates.start + updates.duration);- // Optimistic duration readout: content-driven (grow AND shrink), from the just-patched live DOM. See syncPreviewContentDuration.- syncPreviewContentDuration(previewIframeRef.current);- const targetPath = element.sourceFile || activeCompPath || "index.html";- const buildResizePatches: PersistTimelineEditInput["buildPatches"] = (original, target) => {- return buildTimelineResizeTimingPatch(original, target, element, updates);- };- const hasPbsAdjustment =- updates.playbackStart != null ||- (updates.start !== element.start && element.playbackStart != null);- // Server-path fallback: after persisting the attr patch, scale GSAP tween- // positions/durations on the server, then soft-reload with the rewritten- // script (timing-only resize) — same no-flash path as move; full reload is- // the fallback.- const coalesceKey = `timeline-resize:${element.hfId ?? element.id}`;- const finishResizeGsapSync = (sdkGsap?: ReturnType<typeof sdkTimingGsapSync>) =>- finishClipTimingFallback({- iframe: previewIframeRef.current,- reloadPreview,- projectId: projectIdRef.current,- targetPath,- domId: element.domId,- label: "Resize timeline clip",- coalesceKey,- recordEdit,- writeProjectFile,- edit: {- kind: "scale",- from: { start: toCompositionTime(element, element.start), duration: element.duration },- to: { start: toCompositionTime(element, updates.start), duration: updates.duration },- },- sdkGsap,- }).finally(() => invalidateGsapCache?.());- const resizeFallback = () =>- enqueueEdit(element, "Resize timeline clip", buildResizePatches, coalesceKey).then(() =>- finishResizeGsapSync(),- );- const persistDone =- sdkSession && element.hfId && !element.link && !hasPbsAdjustment && !needsExtension- ? sdkTimingPersist(- element.hfId,- targetPath,- { start: authoredStart, duration: updates.duration },- sdkSession,- {- editHistory: { recordEdit },- writeProjectFile,- reloadPreview,- compositionPath: activeCompPath,- // Capture on-disk bytes as the undo `before` so undoing a timing- // resize restores the file verbatim, not a normalized full-DOM re-emit.- readProjectFile: (path) => readFileContent(projectIdRef.current ?? "", path),- publishSession: publishSdkSession,- },- { label: "Resize timeline clip", coalesceKey, skipRefresh: true },- ).then((result) => {- if (!cutoverCommittedOrThrow(result)) return resizeFallback();- return finishResizeGsapSync(sdkTimingGsapSync(result));- })- : resizeFallback();- return persistDone.catch((error) => {- // Failed persist: revert the optimistic duration readout + live root.- rollbackDuration();- showToast(getStudioSaveErrorMessage(error), "error");- throw error;- });- },- [- previewIframeRef,- enqueueEdit,- activeCompPath,- sdkSession,- publishSdkSession,- recordEdit,- writeProjectFile,- reloadPreview,- showToast,- invalidateGsapCache,- ],- );+ const { handleTimelineElementMove, handleTimelineElementResize } = useTimelineClipTimingEditing({+ activeCompPath,+ timelineElements,+ showToast,+ writeProjectFile,+ recordEdit,+ reloadPreview,+ previewIframeRef,+ pendingTimelineEditPathRef,+ isRecordingRef,+ sdkSession,+ publishSdkSession,+ forceReloadSdkSession,+ invalidateGsapCache,+ handleDomZIndexReorderCommitRef,+ editQueueRef,+ projectIdRef,+ });const handleToggleTrackHidden = useTimelineTrackVisibilityEditing({projectIdRef,diff --git a/packages/studio/src/hooks/useTimelineGroupEditing.test.tsx b/packages/studio/src/hooks/useTimelineGroupEditing.test.tsxindex a8bbf75d63..9ec6dc9aff 100644--- a/packages/studio/src/hooks/useTimelineGroupEditing.test.tsx+++ b/packages/studio/src/hooks/useTimelineGroupEditing.test.tsx@@ -1,11 +1,20 @@// @vitest-environment happy-domimport { act } from "react";+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import {+ createStudioApi,+ openProjectHistory,+ type StudioApiAdapter,+} from "@hyperframes/studio-server";import { afterEach, describe, expect, it, vi } from "vitest";import type { Root } from "react-dom/client";import type { TimelineElement } from "../player";import { persistTimelineMoveEditsAtomically } from "./timelineMoveAdapter";import { useTimelineGroupEditing } from "./useTimelineGroupEditing";+import { usePersistentEditHistory } from "./usePersistentEditHistory";import { installReactActEnvironment, mountReactHarness } from "./domSelectionTestHarness";installReactActEnvironment();@@ -149,3 +158,85 @@ it.each([false, true])(}},);++const SLOWER_THAN_THE_DEFAULT_WINDOW_MS = 400;++it("undoes each group move with its GSAP rewrite in one step, however long the rewrite takes", async () => {+ vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });+ const dir = mkdtempSync(join(tmpdir(), "hf-group-move-undo-"));+ const historyRoot = mkdtempSync(join(tmpdir(), "hf-group-move-undo-history-"));+ const before = [+ '<div data-composition-id="root" data-duration="4">',+ '<div id="a" data-start="0" data-duration="2"></div>',+ '<div id="b" data-start="0" data-duration="2"></div>',+ "</div>",+ '<script>const tl = gsap.timeline({ paused: true }); tl.to("#a", { x: 10, duration: 1 }, 0); tl.to("#b", { x: 10, duration: 1 }, 0); window.__timelines["root"] = tl;</script>',+ ].join("");+ writeFileSync(join(dir, "index.html"), before);+ const history = await openProjectHistory({ projectDir: dir, historyRoot });+ const api = createStudioApi({+ listProjects: () => [],+ resolveProject: (id: string) => (id === "demo" ? { id, dir } : null),+ history: () => history,+ } as unknown as StudioApiAdapter);+ let rewriteAsked = () => {};+ vi.stubGlobal("fetch", async (url: string, init?: RequestInit) => {+ if (url.includes("/gsap-mutations")) {+ rewriteAsked();+ await new Promise((wait) => setTimeout(wait, SLOWER_THAN_THE_DEFAULT_WINDOW_MS));+ }+ return api.request(url.replace(/^\/api/, ""), init);+ });+ let editHistory!: ReturnType<typeof usePersistentEditHistory>;+ let editing!: ReturnType<typeof useTimelineGroupEditing>;+ function Harness() {+ editHistory = usePersistentEditHistory({ projectId: "demo" });+ editing = useTimelineGroupEditing({+ activeCompPath: "index.html",+ editQueueRef: { current: Promise.resolve() },+ pendingTimelineEditPathRef: { current: new Set() },+ previewIframeRef: { current: null },+ projectIdRef: { current: "demo" },+ recordEdit: editHistory.recordEdit,+ reloadPreview: vi.fn(),+ showToast: vi.fn(),+ writeProjectFile: async (path, content) => writeFileSync(join(dir, path), content),+ });+ return null;+ }+ const root = mountReactHarness(<Harness />);+ const file = () => readFileSync(join(dir, "index.html"), "utf8");+ const moveTo = (from: number, to: number) =>+ act(async () => {+ const rewriting = new Promise<void>((resolve) => (rewriteAsked = resolve));+ const moved = editing.handleTimelineGroupMove([+ { element: el("a", from, 2), start: to },+ { element: el("b", from, 2), start: to },+ ]);+ await rewriting;+ await vi.advanceTimersByTimeAsync(SLOWER_THAN_THE_DEFAULT_WINDOW_MS);+ await moved;+ });+ const undo = () =>+ act(() =>+ editHistory.undo({ readFile: async (path) => readFileSync(join(dir, path), "utf8") }),+ );+ try {+ await moveTo(0, 1);+ const once = file();+ await moveTo(1, 2);+ expect(file()).toContain('tl.to("#a", { x: 10, duration: 1 }, 2)');++ await undo();+ expect(file()).toBe(once);+ await undo();+ expect(file()).toBe(before);+ } finally {+ act(() => root.unmount());+ await history.close();+ vi.useRealTimers();+ vi.unstubAllGlobals();+ rmSync(dir, { recursive: true, force: true });+ rmSync(historyRoot, { recursive: true, force: true });+ }+});diff --git a/packages/studio/src/hooks/useTimelineGroupEditing.ts b/packages/studio/src/hooks/useTimelineGroupEditing.tsindex 9eb124252d..19b98415c7 100644--- a/packages/studio/src/hooks/useTimelineGroupEditing.ts+++ b/packages/studio/src/hooks/useTimelineGroupEditing.ts@@ -10,8 +10,8 @@ import {type PublishSdkSession,} from "../utils/sdkCutover";import {- buildTimelineMoveTimingPatch,- buildTimelineResizeTimingPatch,+ applyTimelineMoveAttributes,+ applyTimelineResizeAttributes,extendRootDurationIfNeeded,formatTimelineAttributeNumber,formatTimelineMediaOffset,@@ -24,10 +24,11 @@ import { playbackStartAttributeForElement } from "../player/lib/timelineElementHimport {captureDurationRollback,finishGroupTimingGsapFallback,+ timingGestureStep,sdkTimingGsapSync,readFileContent,- scaleGsapPositions,- shiftGsapPositions,+ scaleGsapMutation,+ shiftGsapMutation,syncPreviewContentDuration,} from "./timelineTimingSync";import type { GsapMutationStatus } from "./gsapMutationClient";@@ -50,8 +51,6 @@ export interface TimelineGroupResizeChange {export interface TimelineGroupCommitOptions {beforeTiming?: Promise<void>;coalesceKey?: string;- /** Per-entry undo coalesce window override (ms) — see EditHistoryEntry.coalesceMs. */- coalesceMs?: number;/** Overrides the default "Move timeline clips" undo-history label. Coalescing* keeps the LAST entry's label (editHistory.ts), so a mechanical follow-up* move folded into another gesture's coalesceKey (e.g. the ripple after a@@ -95,14 +94,6 @@ function allChangesSharePath(: null;}-function moveCoalesceKey(changes: readonly TimelineGroupMoveChange[]): string {- return `timeline-group-move:${changes.map((change) => change.element.hfId ?? change.element.id).join(",")}`;-}--function resizeCoalesceKey(changes: readonly TimelineGroupResizeChange[]): string {- return `timeline-group-resize:${changes.map((change) => change.element.hfId ?? change.element.id).join(",")}`;-}-function toSdkTimingChanges<T extends { element: TimelineElement }>(changes: readonly T[],timingUpdate: (change: T) => { start: number; duration?: number },@@ -287,8 +278,7 @@ export function useTimelineGroupEditing({// Optimistic duration readout: content-driven (grow AND shrink), read from// the just-patched live DOM. See syncPreviewContentDuration.syncPreviewContentDuration(previewIframeRef.current);- const coalesceKey = options?.coalesceKey ?? moveCoalesceKey(changes);- const coalesceMs = options?.coalesceMs;+ const { coalesceKey, coalesceMs } = timingGestureStep("timeline-group-move", options);const label = options?.label ?? "Move timeline clips";return enqueueGroupOperation(label, async (projectId) => {await options?.beforeTiming;@@ -312,7 +302,7 @@ export function useTimelineGroupEditing({changes.map((change) => ({element: change.element,buildPatches: (original, target) =>- buildTimelineMoveTimingPatch(+ applyTimelineMoveAttributes(original,target,toAuthoredStart(change.element, change.start),@@ -347,12 +337,8 @@ export function useTimelineGroupEditing({changes,sdkGsap: sdk?.sdkGsap,resolveChangePath: (element) => targetPathFor(element, activeCompPath),- mutateChange: (change, changePath) => {- const delta = change.start - change.element.start;- const domId = change.element.domId;- if (delta === 0 || !domId) return null;- return shiftGsapPositions(projectId, changePath, domId, delta);- },+ mutationFor: (change) =>+ shiftGsapMutation(change.element.domId, change.start - change.element.start),});} finally {invalidateGsapCache?.();@@ -411,8 +397,7 @@ export function useTimelineGroupEditing({// Optimistic duration readout: content-driven (grow AND shrink), read from// the just-patched live DOM. See syncPreviewContentDuration.syncPreviewContentDuration(previewIframeRef.current);- const coalesceKey = options?.coalesceKey ?? resizeCoalesceKey(changes);- const coalesceMs = options?.coalesceMs;+ const { coalesceKey, coalesceMs } = timingGestureStep("timeline-group-resize", options);return enqueueGroupOperation("Resize timeline clips", async (projectId) => {await options?.beforeTiming;const sdk = await trySdkBatchPersist({@@ -434,7 +419,7 @@ export function useTimelineGroupEditing({changes.map((change) => ({element: change.element,buildPatches: (original, target) =>- buildTimelineResizeTimingPatch(original, target, change.element, {+ applyTimelineResizeAttributes(original, target, change.element, {start: change.start,duration: change.duration,playbackStart: change.playbackStart,@@ -460,22 +445,14 @@ export function useTimelineGroupEditing({changes,sdkGsap: sdk?.sdkGsap,resolveChangePath: (element) => targetPathFor(element, activeCompPath),- mutateChange: (change, changePath) => {- const domId = change.element.domId;- const timingChanged =- change.start !== change.element.start ||- change.duration !== change.element.duration;- if (!timingChanged || !domId) return null;- return scaleGsapPositions(- projectId,- changePath,- domId,+ mutationFor: (change) =>+ scaleGsapMutation(+ change.element.domId,toCompositionTime(change.element, change.element.start),change.element.duration,toCompositionTime(change.element, change.start),change.duration,- );- },+ ),});} finally {invalidateGsapCache?.();diff --git a/packages/studio/src/player/components/Timeline.test.ts b/packages/studio/src/player/components/Timeline.test.tsindex d7aa1f7921..43275fb645 100644--- a/packages/studio/src/player/components/Timeline.test.ts+++ b/packages/studio/src/player/components/Timeline.test.ts@@ -87,10 +87,17 @@ describe("timeline viewport geometry", () => {});});+/** The track's content row: a clip's parent, past its `display: contents` wrapper. */+function trackContentOf(clip: HTMLElement | null | undefined): HTMLElement | null {+ let row = clip?.parentElement ?? null;+ while (row?.style.display === "contents") row = row.parentElement;+ return row;+}+function getHorizontalGeometry(host: HTMLElement, clipId: string, tickLabel: string) {const clip = host.querySelector<HTMLElement>(`[data-el-id="${clipId}"]`);if (!clip) throw new Error(`Missing timeline clip ${clipId}`);- const trackContent = clip.parentElement;+ const trackContent = trackContentOf(clip);if (!trackContent) throw new Error(`Missing content row for ${clipId}`);const trackHeader = trackContent.previousElementSibling;if (!(trackHeader instanceof HTMLElement)) throw new Error(`Missing track header for ${clipId}`);@@ -708,7 +715,7 @@ describe("Timeline provider boundary", () => {expect(host.querySelector('button[aria-label="Hide clip-2 lanes"]')).toBeNull();const clip = host.querySelector<HTMLElement>('[data-el-id="clip-1"]');- const row = clip?.parentElement?.parentElement;+ const row = trackContentOf(clip)?.parentElement;expectTrackExpansion(row, ["clip-1"], TRACK_H + 2 * LANE_H);// Collapsing sticks (does not bounce back open via auto-expand).@@ -731,8 +738,9 @@ describe("Timeline provider boundary", () => {it("expands and collapses every clip on a shared track together", () => {const { host, root } = renderSharedAutomationTimeline();- const row = host.querySelector<HTMLElement>('[data-el-id="narration-1"]')?.parentElement- ?.parentElement;+ const row = trackContentOf(+ host.querySelector<HTMLElement>('[data-el-id="narration-1"]'),+ )?.parentElement;// A row of several clips is named for the track, so the caret is too.const caret = () => host.querySelector<HTMLButtonElement>('button[aria-label$=" lanes"]');expect(caret()?.getAttribute("aria-label")).toBe("Show Track 1 lanes");diff --git a/packages/studio/src/player/components/TimelineClip.tsx b/packages/studio/src/player/components/TimelineClip.tsxindex 9bf880a3df..0766bd76ab 100644--- a/packages/studio/src/player/components/TimelineClip.tsx+++ b/packages/studio/src/player/components/TimelineClip.tsx@@ -20,6 +20,7 @@ import { clipSpeedSuffix } from "./clipToolAttrs";interface TimelineClipProps {el: TimelineElement;pps: number;+ passengerStyle?: CSSProperties;clipY: number;clipHeight?: number;isSelected: boolean;@@ -46,6 +47,7 @@ interface TimelineClipProps {export const TimelineClip = memo(function TimelineClip({el,pps,+ passengerStyle,clipY,clipHeight,isSelected,@@ -123,6 +125,7 @@ export const TimelineClip = memo(function TimelineClip({padding: 0,textAlign: "left",transform: isDragging ? "translateY(-1px)" : undefined,+ ...passengerStyle,};return (diff --git a/packages/studio/src/player/components/TimelineCompactDiamonds.tsx b/packages/studio/src/player/components/TimelineCompactDiamonds.tsxindex 9104280d38..de99b07010 100644--- a/packages/studio/src/player/components/TimelineCompactDiamonds.tsx+++ b/packages/studio/src/player/components/TimelineCompactDiamonds.tsx@@ -1,3 +1,4 @@+import type { CSSProperties } from "react";import type { KeyframeCacheEntry, TimelineElement } from "../store/playerStore";import { CLIP_Y } from "./timelineLayout";import type { TimelineLaneBaseProps } from "./timelineLaneProps";@@ -22,6 +23,7 @@ interface TimelineCompactDiamondsProps extends Pick<beatsActive: boolean;accentColor: string;isSelected: boolean;+ passengerStyle?: CSSProperties;rovingTargetId: string | null;}@@ -35,6 +37,7 @@ export function TimelineCompactDiamonds({beatsActive,accentColor,isSelected,+ passengerStyle,currentTime,selectedKeyframes,rovingTargetId,@@ -55,6 +58,7 @@ export function TimelineCompactDiamonds({width,height: rowHeight - 2 * CLIP_Y,zIndex: isSelected ? 11 : 6,+ ...passengerStyle,}}><TimelineClipDiamondsdiff --git a/packages/studio/src/player/components/TimelineLanes.test.tsx b/packages/studio/src/player/components/TimelineLanes.test.tsxindex 8a2e6834f9..deab4d5721 100644--- a/packages/studio/src/player/components/TimelineLanes.test.tsx+++ b/packages/studio/src/player/components/TimelineLanes.test.tsx@@ -10,7 +10,11 @@ import { defaultTimelineTheme } from "./timelineTheme";import { TRACK_H, getTimelineRowGeometry } from "./timelineLayout";import { createTimelineClipIndex } from "../lib/timelineClipIndex";import { buildTimelineLogicalRows } from "./timelineKeyboardNavigation";-import { usePlayerStore, type TimelineElement } from "../store/playerStore";+import {+ usePlayerStore,+ type KeyframeCacheEntry,+ type TimelineElement,+} from "../store/playerStore";import type { MultiDragPreviewInput } from "./timelineMultiDragPreview";import type { TimelineEditCallbacks } from "./timelineCallbacks";import type { DraggedClipState, BlockedClipState } from "./useTimelineClipDrag";@@ -73,6 +77,7 @@ function positionTween(id: string): GsapAnimation {interface RenderLanesOptions {elements?: TimelineElement[];+ keyframeCache?: Map<string, KeyframeCacheEntry>;animations?: Map<string, GsapAnimation[]>;expandedClipIds?: string[];selectedElementIds?: Set<string>;@@ -172,6 +177,7 @@ function renderLanes(options: RenderLanesOptions = {}): {getPreviewElement={(el) => el}getTrackStyle={getTrackStyle}gsapAnimations={gsapAnimations}+ keyframeCache={next.keyframeCache}selectedKeyframes={new Set()}currentTime={0}onContextMenuLane={next.onContextMenuLane}@@ -389,9 +395,54 @@ describe("TimelineLanes disclosure target", () => {act(() => second.root.unmount());});- // The passenger branch wraps [clip, lanes] in a transformed div that re-renders- // on every pointer move. An unstable key there remounts the lanes and drops the- // in-flight drag.+ it("does not remount a clip when it becomes, then stops being, a drag passenger", () => {+ const elements = [element("clip-a", TRACK_A), element("clip-b", TRACK_A)];+ const selectedElementIds = new Set(["clip-a", "clip-b"]);+ const dragging: MultiDragPreviewInput = {+ dragStarted: true,+ draggedKey: "clip-b",+ draggedOriginStart: 0,+ draggedPreviewStart: 0.5,+ selectedKeys: selectedElementIds,+ };+ const keyframeCache = new Map<string, KeyframeCacheEntry>([+ [+ "clip-a",+ {+ format: "percentage",+ keyframes: [+ { percentage: 0, properties: { x: 0 } },+ { percentage: 100, properties: { x: 50 } },+ ],+ },+ ],+ ]);+ const view = renderLanes({ elements, selectedElementIds, keyframeCache });+ const clipA = view.host.querySelector<HTMLElement>('[data-el-id="clip-a"]');+ const diamonds = () =>+ view.host+ .querySelector('[data-el-id="clip-a"] ~ div button[aria-label*="keyframe at"]')+ ?.closest<HTMLElement>("div.pointer-events-none");+ expect(clipA).not.toBeNull();+ expect(clipA?.parentElement).toBe(+ view.host.querySelector('[data-el-id="clip-b"]')?.parentElement,+ );++ expect(diamonds()).not.toBeNull();+ view.rerender({ elements, selectedElementIds, keyframeCache, multiDragPreview: dragging });+ expect(view.host.querySelector('[data-el-id="clip-a"]')).toBe(clipA);+ expect(clipA?.style.transform).toMatch(/^translateX\([1-9]/);+ // Its keyframe diamonds ride with it.+ expect(diamonds()?.style.transform).toBe(clipA?.style.transform);++ view.rerender({ elements, selectedElementIds, keyframeCache });+ expect(view.host.querySelector('[data-el-id="clip-a"]')).toBe(clipA);+ expect(clipA?.style.transform).toBe("");+ act(() => view.root.unmount());+ });++ // A passenger re-renders on every pointer move. An unstable key there remounts+ // the lanes and drops the in-flight drag.it("does not remount the lanes while a multi-clip drag slides the formation", () => {const elements = [element("clip-a", TRACK_A), element("clip-b", TRACK_A)];const selectedElementIds = new Set(["clip-a", "clip-b"]);@@ -411,9 +462,11 @@ describe("TimelineLanes disclosure target", () => {});const before = ariaControlsTarget(view.host);- const beforeLane = before?.querySelector("[data-timeline-property-lane]");+ const beforeLane = before?.querySelector<HTMLElement>("[data-timeline-property-lane]");expect(before).not.toBeNull();expect(beforeLane).not.toBeNull();+ const startOffset = beforeLane?.style.transform;+ expect(startOffset).toMatch(/^translateX\([1-9]/);view.rerender({elements,@@ -426,6 +479,9 @@ describe("TimelineLanes disclosure target", () => {// Node identity, not just presence: a remount replaces these nodes.expect(ariaControlsTarget(view.host)).toBe(before);expect(before?.querySelector("[data-timeline-property-lane]")).toBe(beforeLane);+ // The lanes ride with the formation, not just the clip.+ expect(beforeLane?.style.transform).toMatch(/^translateX\([1-9]/);+ expect(beforeLane?.style.transform).not.toBe(startOffset);act(() => view.root.unmount());});});diff --git a/packages/studio/src/player/components/TimelineLanes.tsx b/packages/studio/src/player/components/TimelineLanes.tsxindex 6cf8af5a7f..b9a22f610f 100644--- a/packages/studio/src/player/components/TimelineLanes.tsx+++ b/packages/studio/src/player/components/TimelineLanes.tsx@@ -1,4 +1,4 @@-import { Fragment, useId, useMemo } from "react";+import { Fragment, useId, useMemo, type CSSProperties } from "react";import { BeatStrip, BeatBackgroundLines } from "./BeatStrip";import { TimelineClip } from "./TimelineClip";import { TimelineCompactDiamonds } from "./TimelineCompactDiamonds";@@ -35,6 +35,15 @@ import { useTimelineKeyboardActor } from "./useTimelineKeyboardActor";import { TimelineTransitionOverlays } from "./TimelineTransitionOverlays";import { deriveTimelineTransitionSeamsByTrack } from "./timelineTransitionSeams";+function passengerStyleAt(offsetPx: number): CSSProperties {+ return {+ transform: `translateX(${offsetPx}px)`,+ opacity: 0.85,+ zIndex: 20,+ pointerEvents: "none",+ };+}+export function TimelineLanes({pps,contentOrigin,@@ -390,9 +399,9 @@ export function TimelineLanes({// the passenger's timeline data until the owning drag commits.const isPassenger =multiDragPreview != null && isMultiDragPassenger(clipKey, multiDragPreview);- const passengerOffsetPx = isPassenger- ? multiDragPassengerOffsetPx(clipKey, pps, multiDragPreview)- : 0;+ const passengerStyle = isPassenger+ ? passengerStyleAt(multiDragPassengerOffsetPx(clipKey, pps, multiDragPreview))+ : undefined;const clipGestures = createClipGestureHandlers(el,elementKey,@@ -424,6 +433,7 @@ export function TimelineLanes({}}el={previewElement}pps={pps}+ passengerStyle={passengerStyle}clipY={CLIP_Y}clipHeight={clipBarHeight}isSelected={isSelected}@@ -469,6 +479,7 @@ export function TimelineLanes({beatsActive={beatStripOnTrack}accentColor={clipStyle.accent}isSelected={isSelected}+ passengerStyle={passengerStyle}currentTime={currentTime}selectedKeyframes={selectedKeyframes}rovingTargetId={keyboard.rovingTargetId}@@ -494,6 +505,7 @@ export function TimelineLanes({clipDuration={previewElement.duration}clipLeftPx={previewElement.start * pps}clipWidthPx={Math.max(previewElement.duration * pps, 4)}+ passengerStyle={passengerStyle}accentColor={clipStyle.accent}isSelected={isSelected}currentPercentage={@@ -520,34 +532,14 @@ export function TimelineLanes({/>);- // Keep one keyed top-level child per element. Returning an- // array here makes React reconcile the outer array by- // position, so a window shift remounts otherwise stable- // clip keys and can tear down focus mid-reveal.- if (!isPassenger) {- return (- <Fragment key={clipKey}>- {clip}- {compactDiamonds}- {propertyLanes}- </Fragment>- );- }+ // No wrapper node per clip, and the same Fragment whether or not it rides a+ // drag, so joining or leaving one restyles it, never remounts it.return (- <div- key={clipKey}- className="absolute inset-0"- style={{- transform: `translateX(${passengerOffsetPx}px)`,- opacity: 0.85,- zIndex: 20,- pointerEvents: "none",- }}- >+ <Fragment key={clipKey}>{clip}{compactDiamonds}{propertyLanes}- </div>+ </Fragment>);})}diff --git a/packages/studio/src/player/components/TimelinePropertyLanes.tsx b/packages/studio/src/player/components/TimelinePropertyLanes.tsxindex 31dd97962d..c3ea89dac9 100644--- a/packages/studio/src/player/components/TimelinePropertyLanes.tsx+++ b/packages/studio/src/player/components/TimelinePropertyLanes.tsx@@ -1,4 +1,9 @@-import { useMemo, type MouseEvent as ReactMouseEvent, type RefObject } from "react";+import {+ useMemo,+ type CSSProperties,+ type MouseEvent as ReactMouseEvent,+ type RefObject,+} from "react";import {classifyPropertyGroup,type GsapAnimation,@@ -23,6 +28,7 @@ export interface TimelinePropertyLanesProps {clipDuration: number;clipLeftPx: number;clipWidthPx: number;+ passengerStyle?: CSSProperties;accentColor: string;isSelected: boolean;currentPercentage: number;@@ -184,6 +190,7 @@ export function TimelinePropertyLanes({clipDuration,clipLeftPx,clipWidthPx,+ passengerStyle,accentColor,isSelected,currentPercentage,@@ -239,6 +246,7 @@ export function TimelinePropertyLanes({top: getTimelineLaneTop(laneIndex),width: clipWidthPx,height: LANE_H,+ ...passengerStyle,}}><TimelineDiamondLanediff --git a/packages/studio/src/player/components/timelineCallbacks.ts b/packages/studio/src/player/components/timelineCallbacks.tsindex 911c79723c..dcc5074002 100644--- a/packages/studio/src/player/components/timelineCallbacks.ts+++ b/packages/studio/src/player/components/timelineCallbacks.ts@@ -56,14 +56,11 @@ export interface TimelineEditCallbacks {) => Promise<void> | void;/** Atomic multi-clip move (single undo) for main-track ripple + track-insert.* `coalesceKey` (drag-commit gesture id) merges the move history entry with a- * lane change's follow-up z-reorder entry into one undo step; `coalesceMs`- * widens that entry's fold window when a server round-trip separates the- * gesture's records (per-gesture-unique keys keep the fold gesture-scoped). */+ * lane change's follow-up z-reorder entry into one undo step. */onMoveElements?: (edits: Array<{ element: TimelineElement; updates: TimelineAtomicMoveUpdates }>,coalesceKey?: string,operation?: TimelineMoveOperation,- coalesceMs?: number,) => Promise<void> | void;onResizeElement?: (element: TimelineElement,diff --git a/packages/studio/src/player/components/timelineClipDragCommit.test.ts b/packages/studio/src/player/components/timelineClipDragCommit.test.tsindex c5c7cc2b32..41501ae97e 100644--- a/packages/studio/src/player/components/timelineClipDragCommit.test.ts+++ b/packages/studio/src/player/components/timelineClipDragCommit.test.ts@@ -11,6 +11,7 @@ import {import { normalizeToZones } from "./timelineZones";import { resolveZMirrorLaneMove } from "./timelineZMirror";import type { StackingPatch } from "./timelineStackingSync";+import { isStudioEditSaving, revertNewestStudioPendingEdit } from "../../utils/studioPendingEdits";function el(id: string,@@ -1534,6 +1535,36 @@ describe("persistMoveEdits convergence", () => {},);+ it("registers a revert for the save in flight, and a reverted move is not reasserted", async () => {+ let current = el("clip", 0, 1, 2);+ let releaseSave!: () => void;+ const pendingSave = new Promise<void>((resolve) => {+ releaseSave = resolve;+ });+ const updateElement = (_key: string, updates: Partial<TimelineElement>) => {+ current = { ...current, ...updates };+ };+ const persisted = persistMoveEdits([{ element: current, updates: { start: 4, track: 0 } }], {+ elements: [current],+ trackOrder: [0],+ updateElement,+ onMoveElements: () => pendingSave,+ });+ expect(current.start).toBe(4);+ expect(isStudioEditSaving()).toBe(true);++ const reapply = revertNewestStudioPendingEdit();+ expect(reapply).not.toBeNull();+ expect(current.start).toBe(1);++ releaseSave();+ await expect(persisted).resolves.toBe(true);+ expect(current.start).toBe(1);+ expect(isStudioEditSaving()).toBe(false);+ reapply?.();+ expect(current.start).toBe(4);+ });+it("reasserts a saved lane after a stale runtime sync", async () => {const clip = { ...el("headline", 2, 0.5, 4.9), authoredTrack: 2 };let releaseSave: (() => void) | undefined;diff --git a/packages/studio/src/player/components/timelineClipDragCommit.ts b/packages/studio/src/player/components/timelineClipDragCommit.tsindex 44be26c90d..1078cdc9d2 100644--- a/packages/studio/src/player/components/timelineClipDragCommit.ts+++ b/packages/studio/src/player/components/timelineClipDragCommit.ts@@ -25,6 +25,8 @@ import { runLaneZGesture } from "../../components/nle/zLaneGesture";import { refreshAfterDurableLaneMove } from "./timelineLaneMoveRefresh";import { authoredTrackForLane } from "./timelineAuthoredTrack";import { resolveGroupMovers } from "./timelineMultiDragPreview";+import { beginStudioPendingEdit } from "../../utils/studioPendingEdits";+import { batchElementUpdates } from "../store/batchElementUpdates";type StartTrack = TimelineAtomicMoveUpdates;export interface TimelineMoveEdit extends TimelineAtomicMoveEdit {@@ -47,14 +49,11 @@ export interface DragCommitDeps {/** Atomic multi-clip persist (single undo) for lane changes + track inserts.* `coalesceKey`, when supplied, tags the resulting "Move timeline clips"* history entry so it merges with the lane change's z-reorder entry (see the- * lane-change branch below). `coalesceMs` widens that entry's fold window- * (per-gesture-unique keys make an unbounded window safe) — required when a- * server round-trip sits between the gesture's two records. */+ * lane-change branch below). */onMoveElements?: (edits: TimelineMoveEdit[],coalesceKey?: string,operation?: TimelineMoveOperation,- coalesceMs?: number,) => Promise<void> | void;/*** The current multi-selection (store.selectedElementIds). When the dragged@@ -121,7 +120,6 @@ export function persistMoveEdits(deps: DragCommitDeps,coalesceKey?: string,operation: TimelineMoveOperation = "timing",- coalesceMs?: number,): Promise<boolean> {if (edits.length === 0) return Promise.resolve(true);edits = edits.map((e) => {@@ -175,7 +173,9 @@ export function persistMoveEdits(}if (Object.keys(updates).length) updateElement(key, updates);};- for (const e of edits) applyEdit(e);+ const applyEdits = (reassert = false) =>+ batchElementUpdates(() => edits.forEach((e) => applyEdit(e, reassert)));+ applyEdits();// The store above gets DISPLAY lanes; the file below gets the authored-space// track when one was resolved (see TimelineMoveEdit.persistTrack).const persistEdits = edits.map((e) =>@@ -183,19 +183,8 @@ export function persistMoveEdits(? e: { element: e.element, updates: { ...e.updates, track: e.persistTrack } },);- const persisted = onMoveElements- ? onMoveElements(persistEdits, coalesceKey, operation, coalesceMs)- : Promise.all(persistEdits.map((e) => Promise.resolve(onMoveElement?.(e.element, e.updates))));- return Promise.resolve(persisted).then(- () => {- // Runtime timeline messages can arrive while the save is in flight and- // restore the preview manifest's pre-gesture lane. Reassert the durable- // result after persistence, but only while this remains the latest- // optimistic gesture so an older save can never clobber a newer drag.- for (const e of edits) applyEdit(e, true);- return true;- },- (error) => {+ const restorePrev = () =>+ batchElementUpdates(() => {for (const p of prev) {const { audioGroup, ...timing } = p.updates;const updates: Partial<TimelineElement> = {};@@ -208,10 +197,38 @@ export function persistMoveEdits(updates.audioGroup = audioGroup;if (Object.keys(updates).length) updateElement(p.key, updates);}+ });+ // Cmd+Z while the save is in flight shows the old lanes at once; the returned fn re-applies the move.+ const saving = onMoveElements+ ? beginStudioPendingEdit(() => {+ restorePrev();+ return () => applyEdits(true);+ })+ : null;+ const start = () =>+ onMoveElements+ ? onMoveElements(persistEdits, coalesceKey, operation)+ : Promise.all(+ persistEdits.map((e) => Promise.resolve(onMoveElement?.(e.element, e.updates))),+ );+ const persisted = saving ? saving.adopt(start) : start();+ const done = Promise.resolve(persisted).then(+ () => {+ // Runtime timeline messages can arrive while the save is in flight and+ // restore the preview manifest's pre-gesture lane. Reassert the durable+ // result after persistence, but only while this remains the latest+ // optimistic gesture so an older save can never clobber a newer drag.+ if (!saving?.reverted()) applyEdits(true);+ return true;+ },+ (error) => {+ if (!saving?.reverted()) restorePrev();console.error("[Timeline] Failed to persist clip edits", error);return false;},);+ saving?.settle(done);+ return done;}/**@@ -481,12 +498,7 @@ function commitTrackInsert(* useCanvasZOrderTimelineMirror).** `coalesceKey` MUST be the z persist's key (`z-reorder:<action>:<ids>:g<seq>`)- * so editHistory folds the z write and this track write into ONE undo entry, and- * `coalesceMs` MUST widen this record's fold window: the mirror only runs after- * the z persist's server round-trip resolved, so under real network latency the- * gap between the two records exceeds the reducer's 300ms default and the fold- * would never happen live. The key is unique per gesture, so an unbounded- * window can never merge distinct gestures.+ * so editHistory folds the z write and this track write into ONE undo entry.** Resolves `true` once the move persisted, `false` on rollback / refused insert.*/@@ -495,7 +507,6 @@ export function commitZMirrorLaneMove(move: NonNullable<ZMirrorLaneMove>,deps: DragCommitDeps,coalesceKey: string,- coalesceMs?: number,): Promise<boolean> {if (move.kind === "move") {const edit: TimelineMoveEdit = {@@ -504,14 +515,14 @@ export function commitZMirrorLaneMove(persistTrack: move.persistTrack,};return refreshAfterDurableLaneMove(- persistMoveEdits([edit], deps, coalesceKey, "lane-reorder", coalesceMs),+ persistMoveEdits([edit], deps, coalesceKey, "lane-reorder"),deps,);}const built = buildTrackInsertEdits(element, element.start, move.insertRow, null, deps);if (!built || built.edits.length === 0) return Promise.resolve(false);return refreshAfterDurableLaneMove(- persistMoveEdits(built.edits, deps, coalesceKey, "track-insert", coalesceMs),+ persistMoveEdits(built.edits, deps, coalesceKey, "track-insert"),deps,);}diff --git a/packages/studio/src/player/components/timelineClipDragGestureLifecycle.ts b/packages/studio/src/player/components/timelineClipDragGestureLifecycle.tsindex 096d68c180..eec421f1a0 100644--- a/packages/studio/src/player/components/timelineClipDragGestureLifecycle.ts+++ b/packages/studio/src/player/components/timelineClipDragGestureLifecycle.ts@@ -195,7 +195,7 @@ export function mountTimelineClipDragGestureLifecycle({event.clientX - blocked.originClientX,event.clientY - blocked.originClientY,);- const threshold = blocked.intent === "move" || blocked.intent === "edit-many" ? 4 : 2;+ const threshold = blocked.intent === "move" ? 4 : 2;if (!blocked.started && distance < threshold) return;if (!blocked.started) {blocked.started = true;diff --git a/packages/studio/src/player/components/timelineClipGestureHandlers.test.ts b/packages/studio/src/player/components/timelineClipGestureHandlers.test.tsindex 1e9a732b51..6eca78ceda 100644--- a/packages/studio/src/player/components/timelineClipGestureHandlers.test.ts+++ b/packages/studio/src/player/components/timelineClipGestureHandlers.test.ts@@ -4,7 +4,6 @@ import { afterEach, describe, expect, it, vi } from "vitest";import type { PointerEvent as ReactPointerEvent } from "react";import { usePlayerStore, type TimelineElement } from "../store/playerStore";import { createClipGestureHandlers, type ClipGestureDeps } from "./timelineClipGestureHandlers";-import { MAX_HAND_EDIT_CLIPS } from "./timelineEditing";afterEach(() => usePlayerStore.getState().reset());@@ -18,11 +17,9 @@ const clips: TimelineElement[] = Array.from({ length: 6 }, (_, i) => ({}));const capabilities = { canMove: true, canTrimStart: true, canTrimEnd: true, readOnly: false };-function grabFirstClip(count: number, gesture: "move" | "resize", locked: number[] = []) {+function grabFirstClip(count: number, gesture: "move" | "resize") {const store = usePlayerStore.getState();- store.setElements(- clips.map((clip, i) => (locked.includes(i) ? { ...clip, timelineLocked: true } : clip)),- );+ store.setElements(clips);store.setSelectedElementIds(new Set(clips.slice(0, count).map((c) => c.id)));const setDraggedClip = vi.fn();const setResizingClip = vi.fn();@@ -55,40 +52,15 @@ function grabFirstClip(count: number, gesture: "move" | "resize", locked: number}describe("hand-editing a multi-selection", () => {- it("moves up to the limit by hand", () => {- const { setDraggedClip, blockedClipRef } = grabFirstClip(MAX_HAND_EDIT_CLIPS, "move");+ it.each([1, 3, 4, 6])("moves %i selected clips by hand", (count) => {+ const { setDraggedClip, blockedClipRef } = grabFirstClip(count, "move");expect(setDraggedClip).toHaveBeenCalledOnce();expect(blockedClipRef.current).toBeNull();});- it("refuses to start a drag above the limit and asks for the toast", () => {- const { setDraggedClip, blockedClipRef } = grabFirstClip(MAX_HAND_EDIT_CLIPS + 1, "move");- expect(setDraggedClip).not.toHaveBeenCalled();- expect(blockedClipRef.current?.intent).toBe("edit-many");- });-- it("resizes up to the limit by hand", () => {- const { setResizingClip, blockedClipRef } = grabFirstClip(MAX_HAND_EDIT_CLIPS, "resize");+ it.each([1, 3, 4, 6])("resizes %i selected clips by hand", (count) => {+ const { setResizingClip, blockedClipRef } = grabFirstClip(count, "resize");expect(setResizingClip).toHaveBeenCalledOnce();expect(blockedClipRef.current).toBeNull();});-- it("refuses to start a resize above the limit and asks for the toast", () => {- const { setResizingClip, blockedClipRef } = grabFirstClip(MAX_HAND_EDIT_CLIPS + 1, "resize");- expect(setResizingClip).not.toHaveBeenCalled();- expect(blockedClipRef.current?.intent).toBe("edit-many");- });-- it("counts the clips a move would change: locked ones in the selection stay put", () => {- const allowed = grabFirstClip(MAX_HAND_EDIT_CLIPS + 2, "move", [3, 4]);- expect(allowed.setDraggedClip).toHaveBeenCalledOnce();- const refused = grabFirstClip(MAX_HAND_EDIT_CLIPS + 2, "move", [4]);- expect(refused.setDraggedClip).not.toHaveBeenCalled();- });-- it("counts the clips a trim would change: a locked member leaves a trim of the grabbed clip alone", () => {- const allowed = grabFirstClip(MAX_HAND_EDIT_CLIPS + 1, "resize", [3]);- expect(allowed.setResizingClip).toHaveBeenCalledOnce();- expect(allowed.blockedClipRef.current).toBeNull();- });});diff --git a/packages/studio/src/player/components/timelineClipGestureHandlers.ts b/packages/studio/src/player/components/timelineClipGestureHandlers.tsindex 29ffd28bdb..4d69d460fb 100644--- a/packages/studio/src/player/components/timelineClipGestureHandlers.ts+++ b/packages/studio/src/player/components/timelineClipGestureHandlers.ts@@ -8,11 +8,7 @@ import {import type { TimelineEditCapabilities } from "./timelineEditCapabilities";import type { TimelineEditCallbacks } from "./timelineCallbacks";import { CLIP_HANDLE_W } from "./timelineLayout";-import {- exceedsHandEditLimit,- selectClipWithLinks,- toggleClipWithLinks,-} from "./timelineLinkSelection";+import { selectClipWithLinks, toggleClipWithLinks } from "./timelineLinkSelection";import { SPLIT_BOUNDARY_EPSILON_S } from "../../utils/timelineElementSplit";export interface ClipGestureDeps {@@ -77,7 +73,6 @@ function isIntentBlocked(*/function resolvePointerDownAction(e: ReactPointerEvent,- grabbed: TimelineElement,capabilities: TimelineEditCapabilities,onResizeElement: ClipGestureDeps["onResizeElement"],onMoveElement: ClipGestureDeps["onMoveElement"],@@ -98,8 +93,6 @@ function resolvePointerDownAction(}if (!onMoveElement || !capabilities.canMove) return { kind: "ignore" };- if (exceedsHandEditLimit(grabbed, e.altKey, null))- return { kind: "block", intent: "edit-many", rect };return { kind: "move", rect };}@@ -136,17 +129,6 @@ export function createClipGestureHandlers(const onResizeStart = (edge: "start" | "end", e: ReactPointerEvent): void => {if (!canStartResize(edge, e, capabilities, onResizeElement)) return;e.stopPropagation();- if (exceedsHandEditLimit(el, e.altKey, edge)) {- blockedClipRef.current = {- pointerId: e.pointerId,- element: el,- intent: "edit-many",- originClientX: e.clientX,- originClientY: e.clientY,- started: false,- };- return;- }blockedClipRef.current = null;setShowPopover(false);setRangeSelection(null);@@ -165,7 +147,7 @@ export function createClipGestureHandlers(};const onPointerDown = (e: ReactPointerEvent): void => {- const action = resolvePointerDownAction(e, el, capabilities, onResizeElement, onMoveElement);+ const action = resolvePointerDownAction(e, capabilities, onResizeElement, onMoveElement);if (action.kind === "ignore") return;if (action.kind === "block") {diff --git a/packages/studio/src/player/components/timelineEditing.ts b/packages/studio/src/player/components/timelineEditing.tsindex dc57741044..e6cea2885a 100644--- a/packages/studio/src/player/components/timelineEditing.ts+++ b/packages/studio/src/player/components/timelineEditing.ts@@ -248,9 +248,7 @@ export interface TimelinePromptElement {track: number;}-export type BlockedTimelineEditIntent = "move" | "edit-many" | "resize-start" | "resize-end";--export const MAX_HAND_EDIT_CLIPS = 3;+export type BlockedTimelineEditIntent = "move" | "resize-start" | "resize-end";export interface TimelineRangeSelection {start: number;diff --git a/packages/studio/src/player/components/timelineGroupResizeCommit.ts b/packages/studio/src/player/components/timelineGroupResizeCommit.tsindex 0ccac01f1a..bbfca5e841 100644--- a/packages/studio/src/player/components/timelineGroupResizeCommit.ts+++ b/packages/studio/src/player/components/timelineGroupResizeCommit.ts@@ -1,6 +1,7 @@import type { TimelineElement } from "../store/playerStore";import type { TimelineEditCallbacks } from "./timelineCallbacks";import type { TimelineGroupResizeSession } from "./timelineGroupEditing";+import { batchElementUpdates } from "../store/batchElementUpdates";import {beginTimelineOptimisticGesture,rollbackLatestTimelineOptimisticGesture,@@ -17,13 +18,15 @@ export function commitTimelineGroupResize(updateElement,changes.map((change) => change.key),);- for (const change of changes) {- updateElement(change.key, {- start: change.start,- duration: change.duration,- playbackStart: change.playbackStart,- });- }+ batchElementUpdates(() => {+ for (const change of changes) {+ updateElement(change.key, {+ start: change.start,+ duration: change.duration,+ playbackStart: change.playbackStart,+ });+ }+ });if (!persist) {rollbackLatestTimelineOptimisticGesture(updateElement,@@ -32,7 +35,6 @@ export function commitTimelineGroupResize();return;}- const coalesceKey = `clip-group-resize:${changes.map((change) => change.key).join(":")}`;Promise.resolve(persist(changes.map((change) => ({@@ -41,7 +43,6 @@ export function commitTimelineGroupResize(duration: change.duration,playbackStart: change.playbackStart,})),- { coalesceKey },),).catch((error) => {rollbackLatestTimelineOptimisticGesture(diff --git a/packages/studio/src/player/components/timelineLinkSelection.ts b/packages/studio/src/player/components/timelineLinkSelection.tsindex 3b8ea61439..3d5db3de61 100644--- a/packages/studio/src/player/components/timelineLinkSelection.ts+++ b/packages/studio/src/player/components/timelineLinkSelection.ts@@ -1,13 +1,5 @@import { usePlayerStore, type TimelineElement } from "../store/playerStore";-import {- dropMisalignedTrimPartners,- expandToLinkedMembers,- linkedGestureKeys,- linkedMembersOf,-} from "./audioClipLink";-import { buildTimelineGroupResizeMembers } from "./timelineGroupEditing";-import { resolveGroupMovers } from "./timelineMultiDragPreview";-import { MAX_HAND_EDIT_CLIPS } from "./timelineEditing";+import { expandToLinkedMembers, linkedMembersOf } from "./audioClipLink";import { isLinkedSelectionOn } from "../../utils/linkedClipPreferences";/**@@ -47,29 +39,3 @@ export function toggleClipWithLinks(key: string, altKey: boolean): TimelineElemeconst primary = usePlayerStore.getState().selectedElementId;return state.elements.find((el) => (el.key ?? el.id) === primary) ?? null;}--/** Whether a hand drag on `grabbed` (trimming `edge`, or null to move) would change more clips than allowed. */-export function exceedsHandEditLimit(- grabbed: TimelineElement,- altKey: boolean,- edge: "start" | "end" | null,-): boolean {- const { selectedElementIds, elements } = usePlayerStore.getState();- const grabbedKey = grabbed.key ?? grabbed.id;- const keys = linkedGestureKeys(- selectedElementIds,- grabbed,- elements,- altKey,- isLinkedSelectionOn(),- );- const changed = edge- ? buildTimelineGroupResizeMembers(- elements,- dropMisalignedTrimPartners(keys, grabbed, elements, edge),- grabbedKey,- edge,- )- : resolveGroupMovers(elements, keys, grabbedKey);- return (changed?.length ?? 1) > MAX_HAND_EDIT_CLIPS;-}diff --git a/packages/studio/src/player/components/timelineOptimisticRevision.ts b/packages/studio/src/player/components/timelineOptimisticRevision.tsindex 9716c9362c..ea6dbecae6 100644--- a/packages/studio/src/player/components/timelineOptimisticRevision.ts+++ b/packages/studio/src/player/components/timelineOptimisticRevision.ts@@ -1,4 +1,5 @@import type { TimelineElement } from "../store/playerStore";+import { batchElementUpdates } from "../store/batchElementUpdates";type UpdateElement = (key: string, updates: Partial<TimelineElement>) => void;type RevisionScope = "timing" | "membership";@@ -45,9 +46,11 @@ export function rollbackLatestTimelineOptimisticGesture(gesture: ReadonlyMap<string, number>,rollbacks: ReadonlyArray<{ key: string; updates: Partial<TimelineElement> }>,): void {- for (const rollback of rollbacks) {- if (isLatestTimelineOptimisticGesture(updateElement, gesture, rollback.key)) {- updateElement(rollback.key, rollback.updates);+ batchElementUpdates(() => {+ for (const rollback of rollbacks) {+ if (isLatestTimelineOptimisticGesture(updateElement, gesture, rollback.key)) {+ updateElement(rollback.key, rollback.updates);+ }}- }+ });}diff --git a/packages/studio/src/player/components/useTimelineClipDrag.keyboard.test.tsx b/packages/studio/src/player/components/useTimelineClipDrag.keyboard.test.tsxindex 9b338a7f85..7bd2dcd576 100644--- a/packages/studio/src/player/components/useTimelineClipDrag.keyboard.test.tsx+++ b/packages/studio/src/player/components/useTimelineClipDrag.keyboard.test.tsx@@ -165,13 +165,11 @@ it("leaves Space on a nested fade slider to the slider", () => {act(() => view.root.unmount());});-it("does not pick up a clip held in a selection above the hand-move limit", () => {+it("picks up a clip held in a selection of any size", () => {const view = mount();usePlayerStore.getState().setSelection(["top", "hero", "tail", "bottom"], "hero");view.key(" ");- expect(view.drag).toBeNull();- expect(view.onBlockedEditAttempt).toHaveBeenCalledWith(- expect.objectContaining({ id: "hero" }),- "edit-many",- );+ expect(view.drag).not.toBeNull();+ expect(view.onBlockedEditAttempt).not.toHaveBeenCalled();+ act(() => view.root.unmount());});diff --git a/packages/studio/src/player/components/useTimelineClipDrag.resize.test.tsx b/packages/studio/src/player/components/useTimelineClipDrag.resize.test.tsxindex 882302903a..86770eaa88 100644--- a/packages/studio/src/player/components/useTimelineClipDrag.resize.test.tsx+++ b/packages/studio/src/player/components/useTimelineClipDrag.resize.test.tsx@@ -380,13 +380,10 @@ describe("useTimelineClipDrag — multi-select group resize (restored)", () => {expect(h.onResizeElement).not.toHaveBeenCalled();expect(h.onResizeElements).toHaveBeenCalledTimes(1);- expect(h.onResizeElements).toHaveBeenCalledWith(- [- expect.objectContaining({ element: a, duration: 2.5 }),- expect.objectContaining({ element: b, duration: 3.5 }),- ],- { coalesceKey: expect.stringMatching(/^clip-group-resize:/) },- );+ expect(h.onResizeElements).toHaveBeenCalledWith([+ expect.objectContaining({ element: a, duration: 2.5 }),+ expect.objectContaining({ element: b, duration: 3.5 }),+ ]);expect(h.storeById("a").duration).toBe(2.5);expect(h.getResizeProjection()).toHaveLength(0);expect(h.storeById("b").duration).toBe(3.5);diff --git a/packages/studio/src/player/components/useTimelineClipDrag.ts b/packages/studio/src/player/components/useTimelineClipDrag.tsindex 48025b730e..c6ff55df72 100644--- a/packages/studio/src/player/components/useTimelineClipDrag.ts+++ b/packages/studio/src/player/components/useTimelineClipDrag.ts@@ -31,7 +31,6 @@ import type {} from "./timelineClipDragTypes";import { getTimelineElementIndexes } from "../lib/timelineElementIndexes";import { dropMisalignedTrimPartners, linkedGestureKeys } from "./audioClipLink";-import { exceedsHandEditLimit } from "./timelineLinkSelection";import { isLinkedSelectionOn } from "../../utils/linkedClipPreferences";import { useTimelineClipCapabilities } from "./timelineReadOnly";import { timelineClipFocusId } from "./timelineNavigationIdentity";@@ -526,8 +525,6 @@ export function useTimelineClipDrag({if (!element || !getClipCapabilities(element).canMove) return;event.preventDefault();event.stopImmediatePropagation();- if (exceedsHandEditLimit(element, false, null))- return void onBlockedEditAttemptRef.current?.(element, "edit-many");setShowPopover(false);setRangeSelectionRef.current?.(null);const row = keyboardPickupInsertRow(diff --git a/packages/studio/src/player/store/batchElementUpdates.test.ts b/packages/studio/src/player/store/batchElementUpdates.test.tsnew file mode 100644index 0000000000..20f1454a30--- /dev/null+++ b/packages/studio/src/player/store/batchElementUpdates.test.ts@@ -0,0 +1,43 @@+// @vitest-environment happy-dom+import { beforeEach, describe, expect, it } from "vitest";+import { batchElementUpdates } from "./batchElementUpdates";+import { usePlayerStore, type TimelineElement } from "./playerStore";++const clips = (n: number): TimelineElement[] =>+ Array.from({ length: n }, (_, i) => ({+ id: `c${i}`,+ tag: "div",+ start: i,+ duration: 1,+ track: 0,+ }));++describe("batchElementUpdates", () => {+ beforeEach(() => {+ usePlayerStore.getState().reset();+ usePlayerStore.getState().setElements(clips(4));+ });++ it("lands every update of a batch as one store change, as the same calls one by one would", () => {+ const { updateElement } = usePlayerStore.getState();+ let notified = 0;+ const stop = usePlayerStore.subscribe(() => notified++);+ batchElementUpdates(() => {+ updateElement("c0", { start: 10 });+ batchElementUpdates(() => updateElement("c2", { start: 12 }));+ updateElement("c0", { track: 3 });+ });+ stop();++ expect(notified).toBe(1);+ const byId = new Map(usePlayerStore.getState().elements.map((el) => [el.id, el]));+ expect(byId.get("c0")).toMatchObject({ start: 10, track: 3 });+ expect(byId.get("c1")?.start).toBe(1);+ expect(byId.get("c2")?.start).toBe(12);+ });++ it("applies updates outside a batch at once", () => {+ usePlayerStore.getState().updateElement("c1", { start: 7 });+ expect(usePlayerStore.getState().elements[1]?.start).toBe(7);+ });+});diff --git a/packages/studio/src/player/store/batchElementUpdates.ts b/packages/studio/src/player/store/batchElementUpdates.tsnew file mode 100644index 0000000000..50b1c1f467--- /dev/null+++ b/packages/studio/src/player/store/batchElementUpdates.ts@@ -0,0 +1,9 @@+import { collectElementPatches, patchElements } from "./elementPatchQueue";+import { usePlayerStore } from "./playerStore";++/** `updateElement` calls inside `run` land as one store update: one pass over the list, one notification. */+export function batchElementUpdates(run: () => void): void {+ const patches = collectElementPatches(run);+ if (!patches || patches.size === 0) return;+ usePlayerStore.setState((state) => ({ elements: patchElements(state.elements, patches) }));+}diff --git a/packages/studio/src/player/store/elementPatchQueue.ts b/packages/studio/src/player/store/elementPatchQueue.tsnew file mode 100644index 0000000000..251cc9cabf--- /dev/null+++ b/packages/studio/src/player/store/elementPatchQueue.ts@@ -0,0 +1,35 @@+import type { TimelineElement, TimelineElementPatch } from "./timelineElement";++let queued: Map<string, TimelineElementPatch> | null = null;++/** Queues `updates` while a batch is collecting; false means the caller applies it now. */+export function queueElementPatch(key: string, updates: TimelineElementPatch): boolean {+ if (!queued) return false;+ queued.set(key, { ...queued.get(key), ...updates });+ return true;+}++/** Runs `run`, returning the patches it queued; null when an outer batch already collects them. */+export function collectElementPatches(run: () => void): Map<string, TimelineElementPatch> | null {+ if (queued) {+ run();+ return null;+ }+ const patches = (queued = new Map());+ try {+ run();+ } finally {+ queued = null;+ }+ return patches;+}++export function patchElements(+ elements: TimelineElement[],+ patches: ReadonlyMap<string, TimelineElementPatch>,+): TimelineElement[] {+ return elements.map((el) => {+ const patch = patches.get(el.key ?? el.id);+ return patch ? { ...el, ...patch } : el;+ });+}diff --git a/packages/studio/src/player/store/playerStore.ts b/packages/studio/src/player/store/playerStore.tsindex 70187afbe9..0b2b516518 100644--- a/packages/studio/src/player/store/playerStore.ts+++ b/packages/studio/src/player/store/playerStore.ts@@ -21,6 +21,7 @@ import { createThumbnailSlice, type ThumbnailSlice } from "./thumbnailSlice";import { createPlaybackReadinessSlice } from "./readinessSlice";import { createRangeSelectionSlice, type RangeSelectionSlice } from "./rangeSelectionSlice";import { createTimelineResetState } from "./timelineResetState";+import { patchElements, queueElementPatch } from "./elementPatchQueue";export type { KeyframeCacheEntry } from "./keyframeSlice";export { liveTime } from "./liveTime";import { liveTime } from "./liveTime";@@ -547,12 +548,10 @@ export const usePlayerStore = create<PlayerState>((set, get) => ({focusedEaseSegment: id === s.selectedElementId ? s.focusedEaseSegment : null,};}),- updateElement: (elementId, updates) =>- set((state) => ({- elements: state.elements.map((el) =>- (el.key ?? el.id) === elementId ? { ...el, ...updates } : el,- ),- })),+ updateElement: (elementId, updates) => {+ if (queueElementPatch(elementId, updates)) return;+ set((state) => ({ elements: patchElements(state.elements, new Map([[elementId, updates]])) }));+ },// UI preferences intentionally survive reset. So do timelineSessionEpoch and// focusedEaseRequestNonce: the epoch advances only when project identity// changes, while a monotonic nonce prevents collisions with stale consumers.diff --git a/packages/studio/src/utils/domEditHelpers.ts b/packages/studio/src/utils/domEditHelpers.tsindex 7c015676a2..f75a52d817 100644--- a/packages/studio/src/utils/domEditHelpers.ts+++ b/packages/studio/src/utils/domEditHelpers.ts@@ -1,5 +1,6 @@import type { DomEditSelection } from "../components/editor/domEditing";import { getDomEditTargetKey } from "../components/editor/domEditing";+import { sameData } from "./sameData";export function domEditSelectionsTargetSame(a: DomEditSelection | null,@@ -10,6 +11,10 @@ export function domEditSelectionsTargetSame(return getDomEditTargetKey(a) === getDomEditTargetKey(b);}+export function domEditSelectionsEqual(a: DomEditSelection, b: DomEditSelection): boolean {+ return sameData(a, b);+}+export function domEditSelectionInGroup(group: DomEditSelection[],selection: DomEditSelection | null,diff --git a/packages/studio/src/utils/sameData.ts b/packages/studio/src/utils/sameData.tsnew file mode 100644index 0000000000..6962172ec4--- /dev/null+++ b/packages/studio/src/utils/sameData.ts@@ -0,0 +1,9 @@+/** Structural equality for plain data; DOM nodes (from any realm) compare by identity. */+export function sameData(a: unknown, b: unknown): boolean {+ if (Object.is(a, b)) return true;+ if (!a || !b || typeof a !== "object" || typeof b !== "object") return false;+ if ("nodeType" in a || "nodeType" in b || Array.isArray(a) !== Array.isArray(b)) return false;+ const keys = Object.keys(a);+ if (keys.length !== Object.keys(b).length) return false;+ return keys.every((key) => sameData((a as never)[key], (b as never)[key]));+}diff --git a/packages/studio/src/utils/studioFileHistory.ts b/packages/studio/src/utils/studioFileHistory.tsindex ac07bb09c6..e1cefcdc33 100644--- a/packages/studio/src/utils/studioFileHistory.ts+++ b/packages/studio/src/utils/studioFileHistory.ts@@ -81,6 +81,7 @@ export async function saveServerRewriteWithHistory(input: {path: string;label: string;coalesceKey?: string;+ coalesceMs?: number;writeFile: ProjectFileWriter;recordEdit: (entry: RecordEditInput) => Promise<void>;rewrite: (original: string) => Promise<{ disk: string; after?: string } | null>;diff --git a/packages/studio/src/utils/studioPendingEdits.ts b/packages/studio/src/utils/studioPendingEdits.tsindex e0842ec643..58ed78710d 100644--- a/packages/studio/src/utils/studioPendingEdits.ts+++ b/packages/studio/src/utils/studioPendingEdits.ts@@ -16,6 +16,7 @@ interface PendingEdit {landed: () => Promise<boolean>;redraws: Array<() => void>;showAgain: (() => void) | null;+ claimsAtBegin: number;}export interface StudioEditInFlight {@@ -27,6 +28,11 @@ export interface StudioEditInFlight {}const pendingEdits = new Map<Promise<unknown>, PendingEdit>();+let historyClaims: () => number = () => 0;++export function setStudioPendingEditClaimClock(read: (() => number) | null): void {+ historyClaims = read ?? (() => 0);+}const NOT_SAVED = () => Promise.resolve(false);let adopting: StudioEditInFlight | null = null;@@ -87,7 +93,13 @@ export function trackStudioPendingEdit(if (!result) return undefined;const promise = Promise.resolve(result);if (adopting) return promise;- pendingEdits.set(promise, { revert: null, landed: NOT_SAVED, redraws: [], showAgain: null });+ pendingEdits.set(promise, {+ revert: null,+ landed: NOT_SAVED,+ redraws: [],+ showAgain: null,+ claimsAtBegin: historyClaims(),+ });promise.then(() => pendingEdits.delete(promise),() => pendingEdits.delete(promise),@@ -162,6 +174,7 @@ export function beginStudioPendingEdit(revert: StudioEditRevert | null) {export function paintBackNewestStudioPendingEdit(): {showAgain: () => void;landed: () => Promise<boolean>;+ claimsAtBegin: number;} | null {const newest = [...pendingEdits.values()].at(-1);const revert = newest?.revert;@@ -174,6 +187,7 @@ export function paintBackNewestStudioPendingEdit(): {for (const redraw of newest.redraws.splice(0)) redraw();},landed: newest.landed,+ claimsAtBegin: newest.claimsAtBegin,};}diff --git a/packages/studio/tests/e2e/timeline-bulk-actions.mjs b/packages/studio/tests/e2e/timeline-bulk-actions.mjsindex 4845c52e2e..9aafc536d2 100644--- a/packages/studio/tests/e2e/timeline-bulk-actions.mjs+++ b/packages/studio/tests/e2e/timeline-bulk-actions.mjs@@ -1,12 +1,13 @@#!/usr/bin/env node-/** Times select-all, move 3 and delete-all in a real browser on a real project; see USAGE. */+// fallow-ignore-file complexity+/** Times bulk timeline actions (select, move, resize, delete) in a real browser on a real project; see USAGE. */const USAGE = `BULK_PROJECT_DIR=<project> node packages/studio/tests/e2e/timeline-bulk-actions.mjsRuns the built CLI's preview server, so build first:bun run --filter @hyperframes/studio build && bun run --filter @hyperframes/cli buildBULK_PROJECT_DIR is copied, never modified. Optional: BULK_RUNS (default 5), BULK_PORT,-BULK_ONLY (action name substring), BULK_PROFILE=1 (CPU profile and request summary).+BULK_ONLY (action name substring), BULK_THROTTLE (CPU slowdown rate for drag actions), BULK_PROFILE=1 (CPU profile and request summary; "drag" profiles the pointer moves of the drag actions).An action is done when no foreground request is in flight and no long task ran for 500 ms.Thumbnail and lint requests are background and not awaited. Each run starts a fresh server.`;@@ -37,6 +38,13 @@ if (!chrome) {}const median = (xs) => [...xs].sort((a, b) => a - b)[Math.floor(xs.length / 2)];+/** `median<Key>` for each numeric key that every run reported. */+const medians = (results, keys) =>+ Object.fromEntries(+ keys+ .filter((key) => results.every((r) => typeof r[key] === "number"))+ .map((key) => [`median_${key}`, Math.round(median(results.map((r) => r[key])) * 10) / 10]),+ );const sleep = (ms) => new Promise((r) => setTimeout(r, ms));const projectId = `bulk-${basename(SOURCE)}`;@@ -83,6 +91,8 @@ function installProbe(backgroundSource) {} finally {probe.inflight--;probe.lastBusy = performance.now();+ if (/\/(files|gsap-mutations[^/]*|file-mutations\/(?!probe))/.test(url) && init?.method)+ probe.lastWriteDone = probe.lastBusy;}};}@@ -143,7 +153,6 @@ const requestKind = (url) =>// Runs `action` (returns the page time it considers done); returns ms since its start.// BULK_PROFILE=1 also prints the CPU profile and a request summary of that action to stderr.-// fallow-ignore-next-line complexityasync function measure(page, name, action) {const profile = Boolean(process.env.BULK_PROFILE);const cdp = profile ? await page.createCDPSession() : null;@@ -152,6 +161,7 @@ async function measure(page, name, action) {const onRequest = (r) => started.set(r, Date.now());const onFinished = (r) =>requests.push({+ at: started.get(r) - startedAt,ms: Date.now() - started.get(r),kind: `${r.method()} ${requestKind(r.url())}`,});@@ -161,9 +171,12 @@ async function measure(page, name, action) {page.on("request", onRequest);page.on("requestfinished", onFinished);}+ const startedAt = Date.now();+ await page.evaluate(() => (window.__bulk.lastWriteDone = 0));const t0 = await now(page);const doneAt = await action();const ms = doneAt - t0;+ const lastWrite = await page.evaluate(() => window.__bulk.lastWriteDone);if (profile) {page.off("request", onRequest);page.off("requestfinished", onFinished);@@ -172,13 +185,52 @@ async function measure(page, name, action) {}return {ms,+ saveMs: lastWrite > 0 ? lastWrite - t0 : undefined,thumbnailRequests: profile? requests.filter((r) => r.kind.includes("thumbnail")).length: undefined,};}-// fallow-ignore-next-line complexity+// Inclusive time per function (self plus callees), the costliest first (BULK_STACKS=1).+function printInclusive(cpu, byId) {+ const parent = new Map();+ for (const n of cpu.nodes) for (const c of n.children ?? []) parent.set(c, n.id);+ const total = new Map();+ cpu.samples.forEach((id, i) => {+ const seen = new Set();+ for (let n = id; n !== undefined; n = parent.get(n)) {+ const f = byId.get(n).callFrame;+ const key = `${f.functionName || "(anon)"} ${f.url.split("/").pop()}:${f.lineNumber}`;+ if (f.url && !seen.has(key)) {+ seen.add(key);+ total.set(key, (total.get(key) ?? 0) + cpu.timeDeltas[i] / 1000);+ }+ }+ });+ for (const [k, v] of [...total].sort((a, b) => b[1] - a[1]).slice(0, 14))+ console.error(`incl ${Math.round(v)}ms ${k}`);+}++// Call chain of the node with the most self time among real functions (BULK_STACKS=1).+function printHeaviestStack(cpu, byId) {+ const parent = new Map();+ for (const n of cpu.nodes) for (const c of n.children ?? []) parent.set(c, n.id);+ const selfById = new Map();+ cpu.samples.forEach((id, i) =>+ selfById.set(id, (selfById.get(id) ?? 0) + cpu.timeDeltas[i] / 1000),+ );+ const real = [...selfById].filter(([id]) => byId.get(id).callFrame.url);+ const [top] = real.sort((a, b) => b[1] - a[1]);+ if (!top) return;+ const chain = [];+ for (let id = top[0]; id !== undefined && chain.length < 14; id = parent.get(id)) {+ const f = byId.get(id).callFrame;+ chain.push(`${f.functionName || "(anon)"}:${f.lineNumber}`);+ }+ console.error(`heaviest ${Math.round(top[1])}ms: ${chain.join(" <- ")}`);+}+function printProfile(name, cpu, requests) {const self = new Map();const byId = new Map(cpu.nodes.map((n) => [n.id, n]));@@ -190,6 +242,10 @@ function printProfile(name, cpu, requests) {console.error(`--- ${name}`);for (const [k, v] of [...self].sort((a, b) => b[1] - a[1]).slice(0, 15))console.error(`${Math.round(v)}ms ${k}`);+ if (process.env.BULK_STACKS) {+ printHeaviestStack(cpu, byId);+ printInclusive(cpu, byId);+ }const kinds = new Map();for (const { ms, kind } of requests) {const k = kinds.get(kind) ?? { n: 0, totalMs: 0, maxMs: 0 };@@ -259,10 +315,86 @@ async function selectN(page, name, n) {return { ...result, selected: await selectedCount(page) };}+const clipTimes = (page) =>+ page.evaluate(() =>+ Object.fromEntries(+ [...document.querySelectorAll("button[data-clip]")].map((c) => [+ c.dataset.elId,+ `${c.dataset.clipStart}-${c.dataset.clipEnd}`,+ ]),+ ),+ );++const taskMs = async (cdp) =>+ (await cdp.send("Performance.getMetrics")).metrics.find((m) => m.name === "TaskDuration").value *+ 1000;++const percentile = (xs, q) =>+ [...xs].sort((a, b) => a - b)[Math.min(xs.length - 1, Math.floor(xs.length * q))];++// Drags with every clip selected: main-thread task time per pointermove, then the drop settle time.+async function dragAll(page, name, { edge, dx, steps }) {+ const cdp = await page.createCDPSession();+ await cdp.send("Performance.enable");+ const throttle = Number(process.env.BULK_THROTTLE || 1);+ if (throttle > 1) await cdp.send("Emulation.setCPUThrottlingRate", { rate: throttle });+ await page.click("[data-studio-timeline]", { offset: { x: 5, y: 5 } }).catch(() => {});+ await settle(page);+ await page.keyboard.press("]");+ await page.waitForFunction(+ () => Number(document.body.innerText.match(/(\d+) elements selected/)?.[1] ?? 0) > 3,+ );+ await settle(page);+ const selected = await selectedCount(page);+ const before = await clipTimes(page);+ const box = await (await page.$("button[data-clip]")).boundingBox();+ const cy = box.y + box.height / 2;+ const cx = edge ? box.x + box.width - 2 : box.x + box.width / 2;+ await page.mouse.move(cx - 20, cy);+ await page.mouse.move(cx, cy);+ await page.mouse.down();+ const profileDrag = process.env.BULK_PROFILE === "drag";+ if (profileDrag) {+ await cdp.send("Profiler.enable");+ await cdp.send("Profiler.start");+ }+ const frames = [];+ for (let i = 1; i <= steps; i++) {+ const t0 = await taskMs(cdp);+ await page.mouse.move(cx + i * dx, cy);+ await nextPaint(page);+ frames.push((await taskMs(cdp)) - t0);+ }+ if (profileDrag) printProfile(`${name} (drag)`, (await cdp.send("Profiler.stop")).profile, []);+ const dropTask0 = await taskMs(cdp);+ const result = await measure(page, name, async () => {+ await page.mouse.up();+ return settle(page);+ });+ const dropTaskMs = (await taskMs(cdp)) - dropTask0;+ const after = await clipTimes(page);+ const changed = Object.keys(before).filter((id) => before[id] !== after[id]).length;+ const round = (n) => Math.round(n * 10) / 10;+ return {+ ...result,+ selected,+ changed,+ dropTaskMs: round(dropTaskMs),+ firstFrameMs: round(frames[0]),+ steadyP95Ms: round(percentile(frames.slice(1), 0.95)),+ frameP95Ms: round(percentile(frames, 0.95)),+ frameMaxMs: round(Math.max(...frames)),+ throttle,+ };+}+const actions = {"select-all": selectAll,"move-3": move3,"delete-all": deleteAll,+ "move-all-small": (p, name) => dragAll(p, name, { edge: null, dx: 4, steps: 20 }),+ "move-all-past-end": (p, name) => dragAll(p, name, { edge: null, dx: 40, steps: 20 }),+ "resize-all-end": (p, name) => dragAll(p, name, { edge: "end", dx: -6, steps: 20 }),"ctrl-click-5": (p, name) => selectN(p, name, 5),};@@ -298,12 +430,14 @@ try {browser = await puppeteer.launch({executablePath: chrome,headless: true,+ timeout: TIMEOUT_MS,args: ["--no-sandbox", "--disable-dev-shm-usage", "--disable-gpu"],});const rows = [];for (const [name, run] of Object.entries(actions)) {if (process.env.BULK_ONLY && !name.includes(process.env.BULK_ONLY)) continue;const samples = [];+ const results = [];let detail = {};for (let i = 0; i < RUNS; i++) {await startFreshServer();@@ -312,7 +446,12 @@ try {const result = await run(page, name).catch(async (error) => {await page.screenshot({ path: join(tmpdir(), `bulk-failed-${name}.png`) });console.error(`${name} failed, screenshot in ${tmpdir()}: ${error.message}`);- console.error(page.pageErrors.slice(0, 8).join("\n"));+ console.error(+ page.pageErrors+ .filter((e) => !e.startsWith("Failed to load resource"))+ .slice(0, 8)+ .join("\n"),+ );console.error(await page.evaluate(() =>@@ -322,6 +461,7 @@ try {throw error;});samples.push(result.ms);+ results.push(result);detail = { visibleClips: clips, ...result };await page.close();await stopServer();@@ -331,6 +471,14 @@ try {medianMs: Math.round(median(samples)),samplesMs: samples.map(Math.round),...detail,+ ...medians(results, [+ "saveMs",+ "dropTaskMs",+ "firstFrameMs",+ "steadyP95Ms",+ "frameP95Ms",+ "frameMaxMs",+ ]),});}console.log(JSON.stringify({ project: basename(SOURCE), runs: RUNS, rows }, null, 2));