From f6ba7db59f26684a6298f0adfba38e191858ce5a Mon Sep 17 00:00:00 2001 From: Miguel Angel Simon Sierra Date: Fri, 2 Oct 2026 20:32:28 -0700 Subject: [PATCH 01/12] perf(studio): keep timeline bulk actions under a second, hand-move at most 3 clips Dragging or keyboard-moving a selection of 4 or more clips is refused with a toast pointing at the prompt box; 1 to 3 clips move as before. Root causes of the multi-second waits on large projects: - every selected clip fired its own source-existence probe; they now leave as one request per file - a timeline delete sent one request per clip, each re-parsing the file; it is now one request that parses once - each click on a clip from another file re-fetched GSAP data for every composition; covered files are kept and unchanged files answer 304 - any root index.html write re-captured every composition thumbnail; only a root head edit does now, since a scene page borrows nothing else from it Adds timeline-bulk-actions.mjs, a browser benchmark of select-all, move 3 and delete-all on a real project. --- .../src/helpers/compositionInputs.test.ts | 50 ++- .../src/helpers/compositionInputs.ts | 41 ++- .../src/helpers/sourceMutation.test.ts | 29 ++ .../src/helpers/sourceMutation.ts | 43 ++- .../src/helpers/subComposition.ts | 11 +- .../studio-server/src/routes/files.test.ts | 24 ++ packages/studio-server/src/routes/files.ts | 52 ++- .../editor/probeSourceElement.test.ts | 45 +++ .../components/editor/probeSourceElement.ts | 61 +++- .../studio/src/hooks/keyframeCacheAstLoad.ts | 7 +- .../src/hooks/useBlockedTimelineEditToast.ts | 15 +- .../studio/src/hooks/useGsapTweenCache.ts | 30 +- .../usePopulateKeyframeCacheForFile.test.tsx | 40 +- .../src/hooks/useTimelineDeleteOps.test.tsx | 21 +- .../studio/src/hooks/useTimelineDeleteOps.ts | 51 ++- .../src/hooks/useTimelineEditing.test.tsx | 2 +- .../timelineClipDragGestureLifecycle.ts | 2 +- .../timelineClipGestureHandlers.test.ts | 67 ++++ .../components/timelineClipGestureHandlers.ts | 10 +- .../src/player/components/timelineEditing.ts | 5 +- .../components/timelineLinkSelection.ts | 16 +- .../useTimelineClipDrag.keyboard.test.tsx | 14 + .../player/components/useTimelineClipDrag.ts | 5 + .../tests/e2e/timeline-bulk-actions.mjs | 343 ++++++++++++++++++ 24 files changed, 880 insertions(+), 104 deletions(-) create mode 100644 packages/studio/src/components/editor/probeSourceElement.test.ts create mode 100644 packages/studio/src/player/components/timelineClipGestureHandlers.test.ts create mode 100644 packages/studio/tests/e2e/timeline-bulk-actions.mjs diff --git a/packages/studio-server/src/helpers/compositionInputs.test.ts b/packages/studio-server/src/helpers/compositionInputs.test.ts index 4a12f1233c1..51f50d8a6ed 100644 --- a/packages/studio-server/src/helpers/compositionInputs.test.ts +++ b/packages/studio-server/src/helpers/compositionInputs.test.ts @@ -2,7 +2,7 @@ import { afterEach, describe, expect, it } from "vitest"; import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; -import { compositionsAffectedBy } from "./compositionInputs"; +import { compositionInputSignature, compositionsAffectedBy } from "./compositionInputs"; const dirs: string[] = []; afterEach(() => { @@ -44,8 +44,7 @@ describe("compositionsAffectedBy", () => { ]); }); - it("reaches every composition from the root, an asset, or a file the root does not mount", () => { - expect(compositionsAffectedBy(dir(), "index.html")).toBeNull(); + it("reaches every composition from an asset or a file the root does not mount", () => { expect(compositionsAffectedBy(dir(), "assets/logo.svg")).toBeNull(); expect(compositionsAffectedBy(dir(), "compositions/unmounted.html")).toBeNull(); }); @@ -57,3 +56,48 @@ describe("compositionsAffectedBy", () => { ]); }); }); + +describe("a root write", () => { + const html = (head: string, body: string) => + `${head}${body}${mount("compositions/a.html")}`; + const files = (head: string, body: string) => ({ + "index.html": html(head, body), + "compositions/a.html": "", + }); + const rewrite = (dir: string, head: string, body: string) => + writeFileSync(join(dir, "index.html"), html(head, body)); + + it("moves every composition when the head changed, or when no head was seen yet", () => { + const dir = project(files("", "x")); + expect(compositionsAffectedBy(dir, "index.html")).toBeNull(); + + compositionInputSignature(dir, "compositions/a.html", "s1"); + rewrite(dir, "", "x"); + expect(compositionsAffectedBy(dir, "index.html")).toBeNull(); + }); + + it("moves only the root when the head is as it was", () => { + const dir = project(files("", "x")); + compositionInputSignature(dir, "compositions/a.html", "s1"); + rewrite(dir, "", "moved"); + expect(compositionsAffectedBy(dir, "index.html")).toEqual(["index.html"]); + rewrite(dir, "", "moved again"); + expect(compositionsAffectedBy(dir, "index.html")).toEqual(["index.html"]); + }); + + it("leaves a scene's input signature alone for a body edit, not for a head edit", () => { + const dir = project(files("", "x")); + const before = compositionInputSignature(dir, "compositions/a.html", "s1"); + rewrite(dir, "", "moved"); + expect(compositionInputSignature(dir, "compositions/a.html", "s2")).toBe(before); + rewrite(dir, "", "moved"); + expect(compositionInputSignature(dir, "compositions/a.html", "s3")).not.toBe(before); + }); + + it("changes the root's own input signature for a body edit", () => { + const dir = project(files("", "x")); + const before = compositionInputSignature(dir, "index.html", "s1"); + rewrite(dir, "", "moved"); + expect(compositionInputSignature(dir, "index.html", "s2")).not.toBe(before); + }); +}); diff --git a/packages/studio-server/src/helpers/compositionInputs.ts b/packages/studio-server/src/helpers/compositionInputs.ts index 7075afe0ab4..274fda6d1ec 100644 --- a/packages/studio-server/src/helpers/compositionInputs.ts +++ b/packages/studio-server/src/helpers/compositionInputs.ts @@ -1,5 +1,7 @@ import { readFileSync } from "node:fs"; +import { createHash } from "node:crypto"; import { createProjectSignature } from "./projectSignature.js"; +import { rootHeadContent } from "./subComposition.js"; import { resolveWithinProject } from "./safePath.js"; const ROOT_COMPOSITION = "index.html"; @@ -51,8 +53,19 @@ function closureOf(read: SourceReader, compPath: string): Set { // composition) ever thumbnailed, never evicted; LRU them if a server ever holds thousands. const inputSignatures = new Map(); +/** The root's head last seen per project, to tell a head edit from a body-only root write. */ +const rootHeads = new Map(); + +function rootHeadHash(projectDir: string): string { + const source = projectReader(projectDir)(ROOT_COMPOSITION) ?? ""; + const hash = createHash("sha1").update(rootHeadContent(source)).digest("hex"); + rootHeads.set(projectDir, hash); + return hash; +} + // What a thumbnail of `compPath` renders from: the project minus the compositions the root -// mounts that `compPath` does not. The root always counts (previews use its head). +// mounts that `compPath` does not. A scene's page borrows only the root's head, so for a scene +// the root counts as its head alone; the root's own thumbnail renders all of it. export function compositionInputSignature( projectDir: string, compPath: string, @@ -62,21 +75,37 @@ export function compositionInputSignature( const known = inputSignatures.get(key); if (known?.projectSignature === projectSignature) return known.inputSignature; const read = projectReader(projectDir); - const inputs = closureOf(read, normalizeSource(compPath) ?? compPath).add(ROOT_COMPOSITION); - const siblings = [...closureOf(read, ROOT_COMPOSITION)].filter((path) => !inputs.has(path)); - const inputSignature = createProjectSignature(projectDir, new Set(siblings)); + const comp = normalizeSource(compPath) ?? compPath; + const inputs = closureOf(read, comp).add(ROOT_COMPOSITION); + const excluded = new Set( + [...closureOf(read, ROOT_COMPOSITION)].filter((path) => !inputs.has(path)), + ); + if (comp === ROOT_COMPOSITION) { + const inputSignature = createProjectSignature(projectDir, excluded); + inputSignatures.set(key, { projectSignature, inputSignature }); + return inputSignature; + } + excluded.add(ROOT_COMPOSITION); + const inputSignature = `${createProjectSignature(projectDir, excluded)}:${rootHeadHash(projectDir)}`; inputSignatures.set(key, { projectSignature, inputSignature }); return inputSignature; } /** * Compositions whose rendered frames a write at `changedPath` can change, or `null` for all - * of them: the root, assets and any file the root does not mount reach every composition. + * of them: assets, a root head edit, and any file the root does not mount reach every + * composition. A root write that leaves the head as it was changes only the root's own frames. */ export function compositionsAffectedBy(projectDir: string, changedPath: string): string[] | null { const changed = changedPath.replace(/\\/g, "/"); const read = projectReader(projectDir); const mounted = closureOf(read, ROOT_COMPOSITION); - if (changed === ROOT_COMPOSITION || !mounted.has(changed)) return null; + if (changed === ROOT_COMPOSITION) { + const previous = rootHeads.get(projectDir); + return previous !== undefined && previous === rootHeadHash(projectDir) + ? [ROOT_COMPOSITION] + : null; + } + if (!mounted.has(changed)) return null; return [...mounted].filter((path) => closureOf(read, path).has(changed)); } diff --git a/packages/studio-server/src/helpers/sourceMutation.test.ts b/packages/studio-server/src/helpers/sourceMutation.test.ts index bed0d7ec21b..8ea5aa74804 100644 --- a/packages/studio-server/src/helpers/sourceMutation.test.ts +++ b/packages/studio-server/src/helpers/sourceMutation.test.ts @@ -4,10 +4,33 @@ import { ensureHfIds } from "@hyperframes/parsers/hf-ids"; import { describe, expect, it } from "vitest"; import { removeElementFromHtml, + removeElementsFromHtml, patchElementInHtml, probeElementInSource, + probeElementsInSource, } from "./sourceMutation.js"; +describe("removeElementsFromHtml", () => { + const html = `
`; + + it("matches removing the targets one at a time", () => { + const targets = [{ id: "a" }, { id: "b" }]; + const oneByOne = targets.reduce( + (source, target) => removeElementFromHtml(source, target), + html, + ); + expect(removeElementsFromHtml(html, targets)).toBe(oneByOne); + expect(oneByOne).toContain(`id="keep"`); + }); + + it("treats a target nested in an already removed one as done, and an unknown id as a no-op", () => { + const updated = removeElementsFromHtml(html, [{ id: "parent" }, { id: "child" }, { id: "x" }]); + expect(updated).not.toContain(`id="child"`); + expect(updated).toContain(`id="keep"`); + expect(removeElementsFromHtml(html, [{ id: "x" }])).toBe(html); + }); +}); + describe("removeElementFromHtml", () => { it("removes a self-closing element by id", () => { const html = `
`; @@ -460,6 +483,12 @@ describe("probeElementInSource", () => { expect(probeElementInSource(FIXTURE, { id: "hero" })).toBe(true); }); + it("answers every target of a batch in order from one parse", () => { + expect( + probeElementsInSource(FIXTURE, [{ id: "hero" }, { id: "gone" }, {}, { selector: ".brand" }]), + ).toEqual([true, false, false, true]); + }); + it("returns true for an element found by class selector", () => { expect(probeElementInSource(FIXTURE, { selector: ".hero-heading" })).toBe(true); }); diff --git a/packages/studio-server/src/helpers/sourceMutation.ts b/packages/studio-server/src/helpers/sourceMutation.ts index ccf82168463..a5b90e11885 100644 --- a/packages/studio-server/src/helpers/sourceMutation.ts +++ b/packages/studio-server/src/helpers/sourceMutation.ts @@ -137,15 +137,30 @@ export function findTargetElement( } } -export function removeElementFromHtml(source: string, target: SourceMutationTarget): string { +/** + * Removes every target in one parse and one serialization. A target nested inside one already + * removed no longer matches, which is a normal outcome rather than a failure. + */ +export function removeElementsFromHtml( + source: string, + targets: readonly SourceMutationTarget[], +): string { const { document, wrappedFragment } = parseSourceDocument(source); - const element = findTargetElement(document, target); - if (!element) return source; - - removeElementWithGsapCascade(document, element); + let removed = false; + for (const target of targets) { + const element = findTargetElement(document, target); + if (!element) continue; + removeElementWithGsapCascade(document, element); + removed = true; + } + if (!removed) return source; return wrappedFragment ? document.body.innerHTML || "" : document.toString(); } +export function removeElementFromHtml(source: string, target: SourceMutationTarget): string { + return removeElementsFromHtml(source, [target]); +} + export function isHTMLElement(el: Node): el is HTMLElement { const HTMLEl = el.ownerDocument?.defaultView?.HTMLElement; return HTMLEl ? el instanceof HTMLEl : el.nodeType === 1 && "style" in el; @@ -296,11 +311,21 @@ export function patchElementInHtml( return { html: ensureHfIds(html), matched: true }; } -export function probeElementInSource(source: string, target: SourceMutationTarget): boolean { - if (!target.id && !target.hfId && !target.selector) return false; +/** Whether each target exists in `source`; the document is parsed once however many targets ask. */ +export function probeElementsInSource( + source: string, + targets: readonly SourceMutationTarget[], +): boolean[] { const { document } = parseSourceDocument(source); - const el = findTargetElement(document, target); - return el != null && isHTMLElement(el); + return targets.map((target) => { + if (!target.id && !target.hfId && !target.selector) return false; + const el = findTargetElement(document, target); + return el != null && isHTMLElement(el); + }); +} + +export function probeElementInSource(source: string, target: SourceMutationTarget): boolean { + return probeElementsInSource(source, [target])[0] ?? false; } export interface SplitElementResult { diff --git a/packages/studio-server/src/helpers/subComposition.ts b/packages/studio-server/src/helpers/subComposition.ts index 937bf082dac..ac684780154 100644 --- a/packages/studio-server/src/helpers/subComposition.ts +++ b/packages/studio-server/src/helpers/subComposition.ts @@ -236,6 +236,11 @@ function tagRootCompositionFile(bodyHtml: string, compPath: string): string { ); } +/** The root document's `` content: the only part of the root a sub-composition page borrows. */ +export function rootHeadContent(rootHtml: string): string { + return rootHtml.match(/]*>([\s\S]*?)<\/head>/i)?.[1] ?? ""; +} + /** * Build a standalone HTML page for a sub-composition. * @@ -318,11 +323,7 @@ export function buildSubCompositionHtml( const indexPath = join(projectDir, "index.html"); let headContent = ""; - if (existsSync(indexPath)) { - const indexHtml = readFileSync(indexPath, "utf-8"); - const headMatch = indexHtml.match(/]*>([\s\S]*?)<\/head>/i); - headContent = headMatch?.[1] ?? ""; - } + if (existsSync(indexPath)) headContent = rootHeadContent(readFileSync(indexPath, "utf-8")); // Inject for relative asset resolution (before other tags) if (baseHref && !hasBaseElement(headContent)) { diff --git a/packages/studio-server/src/routes/files.test.ts b/packages/studio-server/src/routes/files.test.ts index bb60b5b7ccf..f2e9124c781 100644 --- a/packages/studio-server/src/routes/files.test.ts +++ b/packages/studio-server/src/routes/files.test.ts @@ -1358,6 +1358,30 @@ describe("registerFileRoutes", () => { expect(payload.animations[0].targetSelector).toBe(".kicker"); }); + it("answers a revalidating read of an unchanged composition with a 304, and a changed one in full", async () => { + const projectDir = createProjectDir(); + writeComp(projectDir, "scene.html", TEMPLATE_COMP); + const app = new Hono(); + registerFileRoutes(app, createAdapter(projectDir)); + const url = "http://localhost/projects/demo/gsap-animations/compositions/scene.html"; + + const first = await app.request(url); + const etag = first.headers.get("ETag"); + expect(etag).toBeTruthy(); + + const unchanged = await app.request(url, { headers: { "If-None-Match": etag ?? "" } }); + expect(unchanged.status).toBe(304); + + writeComp( + projectDir, + "scene.html", + TEMPLATE_COMP.replace("", ""), + ); + const changed = await app.request(url, { headers: { "If-None-Match": etag ?? "" } }); + expect(changed.status).toBe(200); + expect(changed.headers.get("ETag")).not.toBe(etag); + }); + // A composition with a fromTo tween — used by the fromProperties mutation tests. const FROMTO_COMP = `
diff --git a/packages/studio-server/src/routes/files.ts b/packages/studio-server/src/routes/files.ts index 585bb38e233..6108a908daf 100644 --- a/packages/studio-server/src/routes/files.ts +++ b/packages/studio-server/src/routes/files.ts @@ -19,6 +19,7 @@ import { readdirSync, type Dirent, } from "node:fs"; +import { createHash } from "node:crypto"; import { resolve, dirname, join } from "node:path"; import type { StudioApiAdapter } from "../types.js"; import { isAudioFile } from "../helpers/mime.js"; @@ -80,8 +81,10 @@ import { } from "@hyperframes/parsers/gsap-writer-acorn"; import { removeElementFromHtml, + removeElementsFromHtml, patchElementInHtml, probeElementInSource, + probeElementsInSource, splitElementInHtml, relinkSplitHalvesInHtml, wrapElementsInHtml, @@ -2708,11 +2711,14 @@ export function registerFileRoutes(api: Hono, adapter: StudioApiAdapter): void { // is a normal outcome here rather than a failure. The response says whether // the file changed, not how many of the targets landed — so a caller can // tell a no-op from a write, but not a partial pass from a complete one. - let next = originalContent; - for (const target of targets) { - next = removeElementFromHtml(next, target); - } - return writeIfChanged(c, ctx.project.dir, ctx.filePath, ctx.absPath, originalContent, next); + return writeIfChanged( + c, + ctx.project.dir, + ctx.filePath, + ctx.absPath, + originalContent, + removeElementsFromHtml(originalContent, targets), + ); }); api.post("/projects/:id/file-mutations/split-batch", async (c) => { @@ -3211,6 +3217,22 @@ export function registerFileRoutes(api: Hono, adapter: StudioApiAdapter): void { return c.json({ exists }); }); + api.post("/projects/:id/file-mutations/probe-elements/*", async (c) => { + const ctx = await resolveFileMutationContext(c, adapter, "probe-elements"); + if ("error" in ctx) return ctx.error; + + const body = (await c.req.json().catch(() => null)) as { targets?: MutationTarget[] } | null; + if (!Array.isArray(body?.targets)) return c.json({ error: "targets required" }, 400); + + let content: string; + try { + content = readFileSync(ctx.absPath, "utf-8"); + } catch { + return c.json({ exists: body.targets.map(() => false) }); + } + return c.json({ exists: probeElementsInSource(content, body.targets) }); + }); + // ── Rename / Move ── api.patch("/projects/:id/files/*", async (c) => { @@ -3320,19 +3342,23 @@ export function registerFileRoutes(api: Hono, adapter: StudioApiAdapter): void { }); if ("error" in res) return res.error; + // The parse is a pure function of the file, so a client that revalidates on every read + // (Studio does, after any write) gets a 304 for every file that did not change. const html = readFileSync(res.absPath, "utf-8"); + const etag = `"gsap-animations:${createHash("sha1").update(html).digest("hex").slice(0, 16)}"`; + const headers = { ETag: etag, "Cache-Control": "no-cache" }; + if (c.req.header("If-None-Match") === etag) return new Response(null, { status: 304, headers }); + const block = extractGsapScriptBlock(html); if (!block) { - return c.json({ - animations: [], - timelineVar: "tl", - preamble: "", - postamble: "", - }); + return c.json( + { animations: [], timelineVar: "tl", preamble: "", postamble: "" }, + 200, + headers, + ); } - const parsed = parseGsapScriptAcorn(block.scriptText); - return c.json(parsed); + return c.json(parseGsapScriptAcorn(block.scriptText), 200, headers); }); // ── GSAP Mutations ── diff --git a/packages/studio/src/components/editor/probeSourceElement.test.ts b/packages/studio/src/components/editor/probeSourceElement.test.ts new file mode 100644 index 00000000000..ccdcfb43934 --- /dev/null +++ b/packages/studio/src/components/editor/probeSourceElement.test.ts @@ -0,0 +1,45 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; +import { probeSourceElement } from "./probeSourceElement"; + +afterEach(() => vi.unstubAllGlobals()); + +const answer = (body: unknown, ok = true) => + vi.fn(() => Promise.resolve({ ok, json: () => Promise.resolve(body) })); + +describe("probeSourceElement", () => { + it("sends the asks for one file in one tick as a single request", async () => { + const fetchMock = answer({ exists: [true, false, true] }); + vi.stubGlobal("fetch", fetchMock); + + const results = await Promise.all([ + probeSourceElement("p", "index.html", { id: "a" }), + probeSourceElement("p", "index.html", { id: "b" }), + probeSourceElement("p", "index.html", { id: "c" }), + ]); + + expect(results).toEqual([true, false, true]); + expect(fetchMock).toHaveBeenCalledOnce(); + const [, init] = fetchMock.mock.calls[0] as unknown as [string, RequestInit]; + expect(JSON.parse(String(init.body)).targets).toEqual([{ id: "a" }, { id: "b" }, { id: "c" }]); + }); + + it("keeps one request per file", async () => { + const fetchMock = answer({ exists: [true] }); + vi.stubGlobal("fetch", fetchMock); + await Promise.all([ + probeSourceElement("p", "index.html", { id: "a" }), + probeSourceElement("p", "compositions/x.html", { id: "a" }), + ]); + expect(fetchMock).toHaveBeenCalledTimes(2); + }); + + it("reads a failed or malformed answer as existing", async () => { + vi.stubGlobal("fetch", answer({}, false)); + expect(await probeSourceElement("p", "index.html", { id: "a" })).toBe(true); + vi.stubGlobal( + "fetch", + vi.fn(() => Promise.reject(new Error("offline"))), + ); + expect(await probeSourceElement("p", "index.html", { id: "a" })).toBe(true); + }); +}); diff --git a/packages/studio/src/components/editor/probeSourceElement.ts b/packages/studio/src/components/editor/probeSourceElement.ts index 32d56496e3f..adb6b6cd489 100644 --- a/packages/studio/src/components/editor/probeSourceElement.ts +++ b/packages/studio/src/components/editor/probeSourceElement.ts @@ -1,29 +1,64 @@ import { buildProjectApiPath } from "../../utils/projectRouting"; -export async function probeSourceElement( - projectId: string, - sourceFile: string, - target: { id?: string; hfId?: string; selector?: string; selectorIndex?: number }, -): Promise { +type ProbeTarget = { id?: string; hfId?: string; selector?: string; selectorIndex?: number }; + +interface PendingProbe { + target: ProbeTarget; + resolve: (exists: boolean) => void; +} + +/** Probes asked for in the same tick, one batch per project file. */ +const pending = new Map< + string, + { projectId: string; sourceFile: string; probes: PendingProbe[] } +>(); + +async function sendBatch(projectId: string, sourceFile: string, probes: PendingProbe[]) { + // Any failure reads as "exists": a probe that cannot answer must not strip capabilities. + let exists: boolean[] = []; try { const response = await fetch( buildProjectApiPath( projectId, - `/file-mutations/probe-element/${encodeURIComponent(sourceFile)}`, + `/file-mutations/probe-elements/${encodeURIComponent(sourceFile)}`, ), { method: "POST", headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ target }), + body: JSON.stringify({ targets: probes.map((probe) => probe.target) }), }, ); - if (!response.ok) return true; - const data = await response.json(); - if (data && typeof data === "object" && "exists" in data && data.exists === false) { - return false; + if (response.ok) { + const data = await response.json(); + if (Array.isArray(data?.exists)) exists = data.exists; } - return true; } catch { - return true; + // Falls through to the all-exist answer below. } + probes.forEach((probe, index) => probe.resolve(exists[index] !== false)); +} + +/** + * Whether the element still exists in its source file. A selection of N elements asks N times + * in one tick; the asks for one file leave as a single request. + */ +export function probeSourceElement( + projectId: string, + sourceFile: string, + target: ProbeTarget, +): Promise { + return new Promise((resolve) => { + const key = `${projectId}\0${sourceFile}`; + let batch = pending.get(key); + if (!batch) { + batch = { projectId, sourceFile, probes: [] }; + pending.set(key, batch); + const flushing = batch; + setTimeout(() => { + pending.delete(key); + void sendBatch(flushing.projectId, flushing.sourceFile, flushing.probes); + }, 0); + } + batch.probes.push({ target, resolve }); + }); } diff --git a/packages/studio/src/hooks/keyframeCacheAstLoad.ts b/packages/studio/src/hooks/keyframeCacheAstLoad.ts index 9bafb53adfc..fc45aad7101 100644 --- a/packages/studio/src/hooks/keyframeCacheAstLoad.ts +++ b/packages/studio/src/hooks/keyframeCacheAstLoad.ts @@ -81,9 +81,10 @@ async function requestParsedAnimations( try { const res = await fetch( `/api/projects/${encodeURIComponent(projectId)}/gsap-animations/${encodeURIComponent(sourceFile)}`, - // Always re-read the freshly-parsed source; no per-call timestamp (which - // would defeat caching forever and is a deterministic-render no-no). - { cache: "no-store" }, + // Always revalidate against the source; the server answers 304 for a file that did not + // change, so a write elsewhere costs no re-parse here. No per-call timestamp (a + // deterministic-render no-no). + { cache: "no-cache" }, ); if (!res.ok) return null; const parsed: unknown = await res.json(); diff --git a/packages/studio/src/hooks/useBlockedTimelineEditToast.ts b/packages/studio/src/hooks/useBlockedTimelineEditToast.ts index 0ad69388dad..7fe2447a402 100644 --- a/packages/studio/src/hooks/useBlockedTimelineEditToast.ts +++ b/packages/studio/src/hooks/useBlockedTimelineEditToast.ts @@ -8,19 +8,28 @@ import { useCallback, useRef } from "react"; import type { TimelineElement } from "../player"; +import { + MAX_HAND_MOVE_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) => void { +): (element: TimelineElement, intent: BlockedTimelineEditIntent) => void { const lastAtRef = useRef(0); return useCallback( - (_element: TimelineElement) => { + (_element: TimelineElement, intent: BlockedTimelineEditIntent) => { const now = Date.now(); if (now - lastAtRef.current < BLOCKED_TOAST_INTERVAL_MS) return; lastAtRef.current = now; - showToast("This clip can't be moved or resized from the timeline yet.", "info"); + showToast( + intent === "move-many" + ? `Select ${MAX_HAND_MOVE_CLIPS} or fewer clips to move by hand, or describe the change.` + : "This clip can't be moved or resized from the timeline yet.", + "info", + ); }, [showToast], ); diff --git a/packages/studio/src/hooks/useGsapTweenCache.ts b/packages/studio/src/hooks/useGsapTweenCache.ts index e7862869fec..7ecf5401d3e 100644 --- a/packages/studio/src/hooks/useGsapTweenCache.ts +++ b/packages/studio/src/hooks/useGsapTweenCache.ts @@ -290,17 +290,17 @@ export function usePopulateKeyframeCacheForFile( const domClipChildrenKey = usePlayerStore((s) => s.domClipChildren.map((c) => `${c.id}<${c.hostId}`).join("|"), ); - const lastFetchKeyRef = useRef(""); + // What each file's cache entries were last loaded for. Switching `sourceFile` to a + // file that is already loaded for the current data must not refetch the others. + const loadedRef = useRef<{ dataKey: string; files: Set }>({ + dataKey: "", + files: new Set(), + }); const runtimeScanDoneRef = useRef(""); - const astFetchDoneRef = useRef(""); useEffect(() => { - const fetchKey = `kf-cache:${projectId}:${sourceFile}:${version}:${elementCount}:${domClipChildrenKey}:${compositionSrcKey}`; - if (fetchKey === lastFetchKeyRef.current) return; - lastFetchKeyRef.current = fetchKey; - runtimeScanDoneRef.current = ""; - astFetchDoneRef.current = ""; + const dataKey = `kf-cache:${projectId}:${version}:${elementCount}:${domClipChildrenKey}:${compositionSrcKey}`; if (!projectId) return; // The active file first: it owns the selection, and each file clears only @@ -309,13 +309,19 @@ export function usePopulateKeyframeCacheForFile( const files = Array.from( new Set([sourceFile, ...(compositionSrcKey ? compositionSrcKey.split("|") : [])]), ); - const doc = iframeRef?.current?.contentDocument; + const sameData = loadedRef.current.dataKey === dataKey; + const stale = sameData ? files.filter((sf) => !loadedRef.current.files.has(sf)) : files; + // Flipping `sourceFile` among files already covered keeps all of them; only new data + // (another composition, a write) narrows the set back to what is on screen. + const covered = sameData ? new Set([...loadedRef.current.files, ...files]) : new Set(files); + loadedRef.current = { dataKey, files: covered }; // Everything the previous scan cached for a file this one no longer covers // (the composition just switched away from) has no owner left to clear it. - pruneKeyframeCacheToFiles(files); - Promise.all(files.map((sf) => populateKeyframeCacheFromAst(projectId, sf, doc))).then(() => { - astFetchDoneRef.current = fetchKey; - }); + pruneKeyframeCacheToFiles([...covered]); + if (stale.length === 0) return; + runtimeScanDoneRef.current = ""; + const doc = iframeRef?.current?.contentDocument; + void Promise.all(stale.map((sf) => populateKeyframeCacheFromAst(projectId, sf, doc))); // elementCount is in the deps because new timeline elements (e.g. after a // sub-composition expand) need their keyframe cache populated immediately; // without it the effect won't re-run when elements appear/disappear. diff --git a/packages/studio/src/hooks/usePopulateKeyframeCacheForFile.test.tsx b/packages/studio/src/hooks/usePopulateKeyframeCacheForFile.test.tsx index 114a72a6168..75cd58ea190 100644 --- a/packages/studio/src/hooks/usePopulateKeyframeCacheForFile.test.tsx +++ b/packages/studio/src/hooks/usePopulateKeyframeCacheForFile.test.tsx @@ -8,8 +8,8 @@ import { usePlayerStore } from "../player/store/playerStore"; Reflect.set(globalThis, "IS_REACT_ACT_ENVIRONMENT", true); -function HookHost() { - usePopulateKeyframeCacheForFile("demo", "index.html", 1); +function HookHost({ sourceFile = "index.html", version = 1 }) { + usePopulateKeyframeCacheForFile("demo", sourceFile, version); return null; } @@ -67,4 +67,40 @@ describe("usePopulateKeyframeCacheForFile", () => { expect(urls.some((u) => u.endsWith("/index.html"))).toBe(true); expect(urls.some((u) => u.includes("keyframe-lab.html"))).toBe(true); }); + + it("keeps every covered file when the selection switches between them, and refetches all on new data", async () => { + // Every click on a clip from another file flips `sourceFile`; a flip must not + // re-read every composition file, or a multi-select pays files x clicks fetches. + const urls: string[] = []; + vi.stubGlobal( + "fetch", + vi.fn((input: RequestInfo | URL) => { + urls.push(String(input)); + return Promise.resolve({ ok: true, json: () => Promise.resolve({ animations: [] }) }); + }), + ); + const render = async (props: { sourceFile: string; version: number }) => { + await act(async () => { + if (!root) { + container = document.createElement("div"); + document.body.appendChild(container); + root = createRoot(container); + } + root.render(); + }); + await act(async () => { + await Promise.resolve(); + }); + }; + + await render({ sourceFile: "index.html", version: 1 }); + const loaded = urls.length; + await render({ sourceFile: "compositions/keyframe-lab.html", version: 1 }); + expect(urls.length).toBe(loaded); + await render({ sourceFile: "index.html", version: 1 }); + expect(urls.length).toBe(loaded); + + await render({ sourceFile: "index.html", version: 2 }); + expect(urls.length).toBe(loaded * 2); + }); }); diff --git a/packages/studio/src/hooks/useTimelineDeleteOps.test.tsx b/packages/studio/src/hooks/useTimelineDeleteOps.test.tsx index 8bef8f57e09..6d1a783ea4c 100644 --- a/packages/studio/src/hooks/useTimelineDeleteOps.test.tsx +++ b/packages/studio/src/hooks/useTimelineDeleteOps.test.tsx @@ -42,7 +42,7 @@ describe("useTimelineDeleteOps: ripple undo label", () => { "fetch", vi.fn(async (input: RequestInfo | URL) => { const url = String(input); - if (url.includes("/file-mutations/remove-element/")) { + if (url.includes("/file-mutations/remove-elements/")) { return new Response(JSON.stringify({ changed: true, content: html }), { status: 200 }); } return new Response(JSON.stringify({ content: html }), { status: 200 }); @@ -118,6 +118,23 @@ describe("useTimelineDeleteOps: ripple undo label", () => { ); }); + 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 }); + + await act(async () => { + await getHook().handleTimelineElementsDelete(elements); + }); + + const removals = vi + .mocked(fetch) + .mock.calls.filter(([url]) => String(url).includes("/file-mutations/remove-element")); + expect(removals).toHaveLength(1); + const [, init] = removals[0] as [unknown, RequestInit]; + const body = JSON.parse(String(init.body)); + expect(body.targets).toHaveLength(elements.length); + }); + it("shows exactly one toast when a ripple fails to persist after a committed delete", async () => { const handleTimelineGroupMove = vi.fn().mockRejectedValue(new Error("persist failed")); const showToast = vi.fn(); @@ -166,7 +183,7 @@ describe("useTimelineDeleteOps: undo race", () => { "fetch", vi.fn(async (input: RequestInfo | URL) => { const url = String(input); - if (url.includes("/file-mutations/remove-element/")) { + if (url.includes("/file-mutations/remove-elements/")) { return new Response(JSON.stringify({ changed: true, content: htmlAfterDeletingC }), { status: 200, }); diff --git a/packages/studio/src/hooks/useTimelineDeleteOps.ts b/packages/studio/src/hooks/useTimelineDeleteOps.ts index 79ec4baee70..27098383357 100644 --- a/packages/studio/src/hooks/useTimelineDeleteOps.ts +++ b/packages/studio/src/hooks/useTimelineDeleteOps.ts @@ -121,38 +121,35 @@ export function useTimelineDeleteOps({ writeFile: writeProjectFile, recordEdit, rewrite: async (originalContent) => { - // Remove every selected element before saving once. The server rewrites - // the file per call, so `removedContent` after the last one holds them - // all — which is what makes this a single history entry, and a single - // undo, rather than one per clip. - let removedContent = originalContent; - for (const target of sameFile) { + // One request removes every selected element and rewrites the file once, so a + // large selection is a single round trip and a single history entry. + const patchTargets = sameFile.map((target) => { const patchTarget = buildPatchTarget(target); if (!patchTarget) { throw new Error(`Timeline element ${target.id} is missing a patchable target`); } - - const removeResponse = await fetch( - buildProjectApiPath( - pid, - `/file-mutations/remove-element/${encodeURIComponent(targetPath)}`, - ), - { - method: "POST", - headers: { "Content-Type": "application/json", ...studioWriteHeaders() }, - body: JSON.stringify({ target: patchTarget }), - }, - ); - if (!removeResponse.ok) { - throw new Error(`Failed to delete ${target.id} from ${targetPath}`); - } - - const removeData = (await removeResponse.json()) as { - changed?: boolean; - content?: string; - }; - if (typeof removeData.content === "string") removedContent = removeData.content; + return patchTarget; + }); + const removeResponse = await fetch( + buildProjectApiPath( + pid, + `/file-mutations/remove-elements/${encodeURIComponent(targetPath)}`, + ), + { + method: "POST", + headers: { "Content-Type": "application/json", ...studioWriteHeaders() }, + body: JSON.stringify({ targets: patchTargets }), + }, + ); + if (!removeResponse.ok) { + throw new Error(`Failed to delete ${sameFile.length} clips from ${targetPath}`); } + const removeData = (await removeResponse.json()) as { + changed?: boolean; + content?: string; + }; + const removedContent = + typeof removeData.content === "string" ? removeData.content : originalContent; // Shrink to the furthest remaining clip end, read from the post-removal source: // store durations are runtime-truncated. const deleteContentEnd = furthestClipEndFromSource(removedContent); diff --git a/packages/studio/src/hooks/useTimelineEditing.test.tsx b/packages/studio/src/hooks/useTimelineEditing.test.tsx index d6c933d5477..65bdd3dcc66 100644 --- a/packages/studio/src/hooks/useTimelineEditing.test.tsx +++ b/packages/studio/src/hooks/useTimelineEditing.test.tsx @@ -1296,7 +1296,7 @@ describe("useTimelineEditing duration rollback on failed persist", () => { if (url.includes("/api/projects/p1/files/")) { return jsonResponse({ content: DELETE_SOURCE }); } - if (url.includes("/api/projects/p1/file-mutations/remove-element/")) { + if (url.includes("/api/projects/p1/file-mutations/remove-elements/")) { return jsonResponse({ changed: true, content: DELETE_REMOVED_SOURCE }); } throw new Error(`Unexpected fetch: ${url}`); diff --git a/packages/studio/src/player/components/timelineClipDragGestureLifecycle.ts b/packages/studio/src/player/components/timelineClipDragGestureLifecycle.ts index eec421f1a0c..0cf3c8e0941 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" ? 4 : 2; + const threshold = blocked.intent === "move" || blocked.intent === "move-many" ? 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.ts new file mode 100644 index 00000000000..a3850308e90 --- /dev/null +++ b/packages/studio/src/player/components/timelineClipGestureHandlers.test.ts @@ -0,0 +1,67 @@ +// @vitest-environment happy-dom + +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_MOVE_CLIPS } from "./timelineEditing"; + +afterEach(() => usePlayerStore.getState().reset()); + +const clips: TimelineElement[] = Array.from({ length: 6 }, (_, i) => ({ + id: `clip-${i}`, + tag: "div", + start: i, + duration: 1, + track: i, +})); +const capabilities = { canMove: true, canTrimStart: true, canTrimEnd: true, readOnly: false }; + +function pressFirstClipWithSelection(count: number) { + const store = usePlayerStore.getState(); + store.setElements(clips); + store.setSelectedElementIds(new Set(clips.slice(0, count).map((c) => c.id))); + const setDraggedClip = vi.fn(); + const blockedClipRef = { current: null as { intent: string } | null }; + const deps = { + pps: 100, + onMoveElement: vi.fn(), + blockedClipRef, + suppressClickRef: { current: false }, + scrollRef: { current: null }, + setShowPopover: vi.fn(), + setRangeSelection: vi.fn(), + setResizingClip: vi.fn(), + setDraggedClip, + setSelectedElementId: vi.fn(), + } as unknown as ClipGestureDeps; + const { onPointerDown } = createClipGestureHandlers( + clips[0], + clips[0].id, + clips[0], + capabilities, + deps, + ); + onPointerDown({ + button: 0, + clientX: 50, + clientY: 5, + pointerId: 1, + currentTarget: { getBoundingClientRect: () => ({ left: 0, width: 100 }) }, + } as unknown as ReactPointerEvent); + return { setDraggedClip, blockedClipRef }; +} + +describe("hand-moving a multi-selection", () => { + it("moves up to the limit by hand", () => { + const { setDraggedClip, blockedClipRef } = pressFirstClipWithSelection(MAX_HAND_MOVE_CLIPS); + expect(setDraggedClip).toHaveBeenCalledOnce(); + expect(blockedClipRef.current).toBeNull(); + }); + + it("refuses to start a drag above the limit and asks for the toast", () => { + const { setDraggedClip, blockedClipRef } = pressFirstClipWithSelection(MAX_HAND_MOVE_CLIPS + 1); + expect(setDraggedClip).not.toHaveBeenCalled(); + expect(blockedClipRef.current?.intent).toBe("move-many"); + }); +}); diff --git a/packages/studio/src/player/components/timelineClipGestureHandlers.ts b/packages/studio/src/player/components/timelineClipGestureHandlers.ts index 4d69d460fb6..9c9cbddd862 100644 --- a/packages/studio/src/player/components/timelineClipGestureHandlers.ts +++ b/packages/studio/src/player/components/timelineClipGestureHandlers.ts @@ -8,7 +8,11 @@ import { import type { TimelineEditCapabilities } from "./timelineEditCapabilities"; import type { TimelineEditCallbacks } from "./timelineCallbacks"; import { CLIP_HANDLE_W } from "./timelineLayout"; -import { selectClipWithLinks, toggleClipWithLinks } from "./timelineLinkSelection"; +import { + exceedsHandMoveLimit, + selectClipWithLinks, + toggleClipWithLinks, +} from "./timelineLinkSelection"; import { SPLIT_BOUNDARY_EPSILON_S } from "../../utils/timelineElementSplit"; export interface ClipGestureDeps { @@ -73,6 +77,7 @@ function isIntentBlocked( */ function resolvePointerDownAction( e: ReactPointerEvent, + grabbed: TimelineElement, capabilities: TimelineEditCapabilities, onResizeElement: ClipGestureDeps["onResizeElement"], onMoveElement: ClipGestureDeps["onMoveElement"], @@ -93,6 +98,7 @@ function resolvePointerDownAction( } if (!onMoveElement || !capabilities.canMove) return { kind: "ignore" }; + if (exceedsHandMoveLimit(grabbed, e.altKey)) return { kind: "block", intent: "move-many", rect }; return { kind: "move", rect }; } @@ -147,7 +153,7 @@ export function createClipGestureHandlers( }; const onPointerDown = (e: ReactPointerEvent): void => { - const action = resolvePointerDownAction(e, capabilities, onResizeElement, onMoveElement); + const action = resolvePointerDownAction(e, el, 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.ts index e6cea2885af..262bf71e680 100644 --- a/packages/studio/src/player/components/timelineEditing.ts +++ b/packages/studio/src/player/components/timelineEditing.ts @@ -248,7 +248,10 @@ export interface TimelinePromptElement { track: number; } -export type BlockedTimelineEditIntent = "move" | "resize-start" | "resize-end"; +export type BlockedTimelineEditIntent = "move" | "move-many" | "resize-start" | "resize-end"; + +/** Most clips a hand drag moves at once; a larger selection goes through the prompt box. */ +export const MAX_HAND_MOVE_CLIPS = 3; export interface TimelineRangeSelection { start: number; diff --git a/packages/studio/src/player/components/timelineLinkSelection.ts b/packages/studio/src/player/components/timelineLinkSelection.ts index 3d5db3de61b..d39d74238f3 100644 --- a/packages/studio/src/player/components/timelineLinkSelection.ts +++ b/packages/studio/src/player/components/timelineLinkSelection.ts @@ -1,5 +1,6 @@ import { usePlayerStore, type TimelineElement } from "../store/playerStore"; -import { expandToLinkedMembers, linkedMembersOf } from "./audioClipLink"; +import { expandToLinkedMembers, linkedGestureKeys, linkedMembersOf } from "./audioClipLink"; +import { MAX_HAND_MOVE_CLIPS } from "./timelineEditing"; import { isLinkedSelectionOn } from "../../utils/linkedClipPreferences"; /** @@ -39,3 +40,16 @@ export function toggleClipWithLinks(key: string, altKey: boolean): TimelineEleme const primary = usePlayerStore.getState().selectedElementId; return state.elements.find((el) => (el.key ?? el.id) === primary) ?? null; } + +/** Whether grabbing `grabbed` would move more clips by hand than a hand drag allows. */ +export function exceedsHandMoveLimit(grabbed: TimelineElement, altKey: boolean): boolean { + const { selectedElementIds, elements } = usePlayerStore.getState(); + const moved = linkedGestureKeys( + selectedElementIds, + grabbed, + elements, + altKey, + isLinkedSelectionOn(), + ); + return moved.size > MAX_HAND_MOVE_CLIPS; +} diff --git a/packages/studio/src/player/components/useTimelineClipDrag.keyboard.test.tsx b/packages/studio/src/player/components/useTimelineClipDrag.keyboard.test.tsx index 5c3587f98e7..b910084fc6b 100644 --- a/packages/studio/src/player/components/useTimelineClipDrag.keyboard.test.tsx +++ b/packages/studio/src/player/components/useTimelineClipDrag.keyboard.test.tsx @@ -49,6 +49,7 @@ function mount(order = [0, 1, 2]) { const host = document.createElement("div"); const root = createRoot(host); const onMoveElements = vi.fn(); + const onBlockedEditAttempt = vi.fn(); const trackOrderRef = { current: order }; const trackInsertLayoutRef = { current: buildTimelineTrackInsertLayout(order, groups) }; let state: ReturnType; @@ -68,6 +69,7 @@ function mount(order = [0, 1, 2]) { }, onMoveElement: vi.fn(), onMoveElements, + onBlockedEditAttempt, setShowPopover: () => {}, setRangeSelectionRef: { current: null }, }); @@ -83,6 +85,7 @@ function mount(order = [0, 1, 2]) { key, clip, onMoveElements, + onBlockedEditAttempt, root, elements, changeOrder(next: number[]) { @@ -161,3 +164,14 @@ it("leaves Space on a nested fade slider to the slider", () => { expect(event.defaultPrevented).toBe(false); act(() => view.root.unmount()); }); + +it("does not pick up a clip held in a selection above the hand-move limit", () => { + 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" }), + "move-many", + ); +}); diff --git a/packages/studio/src/player/components/useTimelineClipDrag.ts b/packages/studio/src/player/components/useTimelineClipDrag.ts index 3e4610e7ce3..a20497f8b89 100644 --- a/packages/studio/src/player/components/useTimelineClipDrag.ts +++ b/packages/studio/src/player/components/useTimelineClipDrag.ts @@ -29,6 +29,7 @@ import type { } from "./timelineClipDragTypes"; import { getTimelineElementIndexes } from "../lib/timelineElementIndexes"; import { dropMisalignedTrimPartners, linkedGestureKeys } from "./audioClipLink"; +import { exceedsHandMoveLimit } from "./timelineLinkSelection"; import { isLinkedSelectionOn } from "../../utils/linkedClipPreferences"; import { useTimelineClipCapabilities } from "./timelineReadOnly"; import { timelineClipFocusId } from "./timelineNavigationIdentity"; @@ -541,6 +542,10 @@ export function useTimelineClipDrag({ if (!element || !getClipCapabilities(element).canMove) return; event.preventDefault(); event.stopImmediatePropagation(); + if (exceedsHandMoveLimit(element, false)) { + onBlockedEditAttemptRef.current?.(element, "move-many"); + return; + } setShowPopover(false); setRangeSelectionRef.current?.(null); const row = keyboardPickupInsertRow( diff --git a/packages/studio/tests/e2e/timeline-bulk-actions.mjs b/packages/studio/tests/e2e/timeline-bulk-actions.mjs new file mode 100644 index 00000000000..63e35dc49f2 --- /dev/null +++ b/packages/studio/tests/e2e/timeline-bulk-actions.mjs @@ -0,0 +1,343 @@ +#!/usr/bin/env node +/** + * Times the timeline's bulk actions in a real browser on a real project: + * select-all, move 3 by hand, delete N, and the multi-select prompt box for N. + * Each action is the median of RUNS (default 5), fresh Studio page per run. + * + * BULK_PROJECT_DIR=/path/to/launch-project node packages/studio/tests/e2e/timeline-bulk-actions.mjs + * + * Runs the built CLI's preview server (what users ship), so build first: + * bun run --filter @hyperframes/studio build && bun run --filter @hyperframes/cli build + * BULK_PROJECT_DIR is copied, never modified. BULK_PORT, BULK_RUNS, BULK_ONLY (action name + * substring) and BULK_PROFILE=1 (CPU profile and request summary per action) are optional. + * "Settled" = no request in flight, no long task and no network for QUIET_MS. + */ +import { cpSync, mkdtempSync, rmSync, existsSync } from "node:fs"; +import { spawn } from "node:child_process"; +import { tmpdir } from "node:os"; +import { basename, dirname, join, resolve } from "node:path"; +import { fileURLToPath } from "node:url"; +import puppeteer from "puppeteer-core"; +import { resolveChromeExecutable } from "./chrome-executable.mjs"; + +const CLI = resolve(dirname(fileURLToPath(import.meta.url)), "../../../cli/dist/cli.js"); +const SOURCE = process.env.BULK_PROJECT_DIR; +const RUNS = Number(process.env.BULK_RUNS || 5); +const PORT = Number(process.env.BULK_PORT || 5291); +const QUIET_MS = 500; +const TIMEOUT_MS = 120_000; +const ORIGIN = `http://127.0.0.1:${PORT}`; + +if (!SOURCE || !existsSync(join(SOURCE, "index.html"))) { + console.error("BULK_PROJECT_DIR must point at a project directory with an index.html"); + process.exit(2); +} +const chrome = resolveChromeExecutable(); +if (!chrome) { + console.error("No Chrome executable found; set PUPPETEER_EXECUTABLE_PATH"); + process.exit(2); +} + +const median = (xs) => [...xs].sort((a, b) => a - b)[Math.floor(xs.length / 2)]; +const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); + +const projectId = `bulk-${basename(SOURCE)}`; +const tempRoot = mkdtempSync(join(tmpdir(), "hf-bulk-")); +let server = null; +let browser = null; + +function cleanup() { + server?.kill(); + rmSync(tempRoot, { recursive: true, force: true }); +} + +async function waitForServer() { + const deadline = Date.now() + TIMEOUT_MS; + while (Date.now() < deadline) { + try { + if ((await fetch(`${ORIGIN}/api/projects`)).ok) return; + } catch { + /* not listening yet */ + } + await sleep(250); + } + throw new Error("Studio server did not start"); +} + +/** Thumbnails and lint are background work the user never waits on; they are counted, not awaited. */ +const BACKGROUND = /\/(thumbnail|lint)(\/|\?|$)/; + +/** Installed before any page script: tracks long tasks and the in-flight foreground fetches. */ +function installProbe(backgroundSource) { + const background = new RegExp(backgroundSource); + const probe = (window.__bulk = { lastBusy: performance.now(), inflight: 0 }); + new PerformanceObserver((list) => { + for (const e of list.getEntries()) + probe.lastBusy = Math.max(probe.lastBusy, e.startTime + e.duration); + }).observe({ type: "longtask", buffered: true }); + const realFetch = window.fetch; + window.fetch = async (input, init) => { + const url = typeof input === "string" ? input : (input.url ?? String(input)); + if (background.test(url)) return realFetch(input, init); + probe.inflight++; + try { + return await realFetch(input, init); + } finally { + probe.inflight--; + probe.lastBusy = performance.now(); + } + }; +} + +async function openStudio() { + const page = await browser.newPage(); + page.setDefaultTimeout(TIMEOUT_MS); + await page.setViewport({ width: 1600, height: 1000 }); + page.pageErrors = []; + page.on("pageerror", (e) => page.pageErrors.push(String(e).slice(0, 300))); + page.on("console", (m) => m.type() === "error" && page.pageErrors.push(m.text().slice(0, 300))); + await page.evaluateOnNewDocument(installProbe, BACKGROUND.source); + await page.goto(`${ORIGIN}/#project/${projectId}`, { waitUntil: "domcontentloaded" }); + await page.waitForSelector("button[data-clip]"); + await settle(page); + return page; +} + +/** Resolves with the page time at which foreground work was last busy, after QUIET_MS of quiet. */ +const settle = (page) => + page.evaluate( + (quiet) => + new Promise((resolveQuiet) => { + const tick = () => { + const p = window.__bulk; + if (p.inflight === 0 && performance.now() - p.lastBusy > quiet) resolveQuiet(p.lastBusy); + else setTimeout(tick, 25); + }; + tick(); + }), + QUIET_MS, + ); + +const now = (page) => page.evaluate(() => performance.now()); +const nextPaint = (page) => + page.evaluate(() => new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(r)))); + +/** Selected-count readout, from the multi-select prompt box. */ +const selectedCount = (page) => + page.evaluate(() => Number(document.body.innerText.match(/(\d+) elements selected/)?.[1] ?? 0)); + +/** Ctrl-clicks the first `count` mounted clips; dispatched, so row virtualization and layout cannot misplace a click. */ +async function clickClips(page, count) { + await page.evaluate((n) => { + for (const clip of [...document.querySelectorAll("button[data-clip]")].slice(0, n)) + clip.dispatchEvent(new MouseEvent("click", { bubbles: true, ctrlKey: true })); + }, count); + await settle(page); +} + +/** `/api/projects//thumbnail/x.html?..` -> `thumbnail`; anything else keeps its first two segments. */ +const requestKind = (url) => + new URL(url).pathname + .replace(/^\/api\/projects\/[^/]+\//, "") + .split("/") + .slice(0, 2) + .join("/"); + +/** + * Runs `action` (which returns the page time it considers done) and returns ms since its start. + * BULK_PROFILE=1 also prints the CPU profile and a request summary of just that action to stderr. + */ +async function measure(page, name, action) { + const profile = Boolean(process.env.BULK_PROFILE); + const cdp = profile ? await page.createCDPSession() : null; + const requests = []; + const started = new Map(); + const onRequest = (r) => started.set(r, Date.now()); + const onFinished = (r) => + requests.push({ + ms: Date.now() - started.get(r), + kind: `${r.method()} ${requestKind(r.url())}`, + }); + if (profile) { + await cdp.send("Profiler.enable"); + await cdp.send("Profiler.start"); + page.on("request", onRequest); + page.on("requestfinished", onFinished); + } + const t0 = await now(page); + const doneAt = await action(); + const ms = doneAt - t0; + if (profile) { + page.off("request", onRequest); + page.off("requestfinished", onFinished); + const { profile: cpu } = await cdp.send("Profiler.stop"); + printProfile(name, cpu, requests); + } + return { + ms, + thumbnailRequests: profile + ? requests.filter((r) => r.kind.includes("thumbnail")).length + : undefined, + }; +} + +function printProfile(name, cpu, requests) { + const self = new Map(); + const byId = new Map(cpu.nodes.map((n) => [n.id, n])); + cpu.samples.forEach((id, i) => { + const f = byId.get(id).callFrame; + const key = `${f.functionName || "(anon)"} ${f.url.split("/").slice(-2).join("/")}:${f.lineNumber}`; + self.set(key, (self.get(key) ?? 0) + cpu.timeDeltas[i] / 1000); + }); + 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}`); + const kinds = new Map(); + for (const { ms, kind } of requests) { + const k = kinds.get(kind) ?? { n: 0, totalMs: 0, maxMs: 0 }; + kinds.set(kind, { n: k.n + 1, totalMs: k.totalMs + ms, maxMs: Math.max(k.maxMs, ms) }); + } + console.error(`requests: ${requests.length}`); + if (process.env.BULK_PROFILE === "timeline") + for (const r of [...requests].sort((a, b) => a.at - b.at)) + console.error(` +${r.at}ms ${r.ms}ms ${r.kind}`); + for (const [k, v] of [...kinds].sort((a, b) => b[1].totalMs - a[1].totalMs).slice(0, 12)) + console.error(` ${v.n}x total ${v.totalMs}ms max ${v.maxMs}ms ${k}`); +} + +async function selectAll(page, name) { + await page.click("[data-studio-timeline]", { offset: { x: 5, y: 5 } }).catch(() => {}); + await settle(page); + const result = await measure(page, name, async () => { + await page.keyboard.press("]"); + await page.waitForFunction( + () => Number(document.body.innerText.match(/(\d+) elements selected/)?.[1] ?? 0) > 3, + ); + await nextPaint(page); + return settle(page); + }); + return { ...result, selected: await selectedCount(page) }; +} + +async function move3(page, name) { + await clickClips(page, 3); + const box = await (await page.$("button[data-clip]")).boundingBox(); + const cx = box.x + box.width / 2; + const cy = box.y + box.height / 2; + await page.mouse.move(cx, cy); + await page.mouse.down(); + for (let i = 1; i <= 8; i++) await page.mouse.move(cx + i * 12, cy); + return measure(page, name, async () => { + await page.mouse.up(); + return settle(page); + }); +} + +async function deleteAll(page, name) { + await page.keyboard.press("]"); + await settle(page); + const selected = await selectedCount(page); + await page.focus("button[data-clip]"); + const result = await measure(page, name, async () => { + await page.keyboard.press("Delete"); + await page.waitForFunction(() => !/(\d+) elements selected/.test(document.body.innerText)); + return settle(page); + }); + return { ...result, selected }; +} + +async function selectN(page, name, n) { + const result = await measure(page, name, async () => { + for (let i = 0; i < n; i++) { + await page.evaluate((index) => { + const clip = document.querySelectorAll("button[data-clip]")[index]; + clip?.dispatchEvent(new MouseEvent("click", { bubbles: true, ctrlKey: true })); + }, i); + await settle(page); + } + await nextPaint(page); + return settle(page); + }); + return { ...result, selected: await selectedCount(page) }; +} + +const actions = { + "select-all": selectAll, + "move-3": move3, + "delete-all": deleteAll, + "ctrl-click-5": (p, name) => selectN(p, name, 5), +}; + +/** A fresh copy of the project under a fresh preview server: every run starts from the same disk state. */ +async function startFreshServer() { + const projectDir = join(tempRoot, projectId); + rmSync(projectDir, { recursive: true, force: true }); + cpSync(SOURCE, projectDir, { recursive: true }); + server = spawn( + "node", + [ + CLI, + "preview", + projectDir, + "--port", + String(PORT), + "--no-open", + "--foreground", + "--force-new", + ], + { env: { ...process.env, HYPERFRAMES_AUTO_PROXY: "false" }, stdio: "ignore" }, + ); + await waitForServer(); +} + +async function stopServer() { + const exited = new Promise((resolveExit) => server.once("exit", resolveExit)); + server.kill(); + await exited; +} + +try { + browser = await puppeteer.launch({ + executablePath: chrome, + headless: true, + 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 = []; + let detail = {}; + for (let i = 0; i < RUNS; i++) { + await startFreshServer(); + const page = await openStudio(); + const clips = (await page.$$("button[data-clip]")).length; + 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( + await page.evaluate( + () => + `pressed clips: ${document.querySelectorAll("button[data-clip][aria-pressed=true]").length}`, + ), + ); + throw error; + }); + samples.push(result.ms); + detail = { visibleClips: clips, ...result }; + await page.close(); + await stopServer(); + } + rows.push({ + action: name, + medianMs: Math.round(median(samples)), + samplesMs: samples.map(Math.round), + ...detail, + }); + } + console.log(JSON.stringify({ project: basename(SOURCE), runs: RUNS, rows }, null, 2)); + console.table(rows.map(({ action, medianMs }) => ({ action, medianMs }))); +} finally { + await browser?.close(); + cleanup(); +} From 321008eafa231c1b0ce882920dae8140841a4119 Mon Sep 17 00:00:00 2001 From: Miguel Angel Simon Sierra Date: Fri, 2 Oct 2026 20:37:09 -0700 Subject: [PATCH 02/12] chore(studio): trim the bulk benchmark header to the comment limit --- .../tests/e2e/timeline-bulk-actions.mjs | 28 +++++++++---------- 1 file changed, 13 insertions(+), 15 deletions(-) diff --git a/packages/studio/tests/e2e/timeline-bulk-actions.mjs b/packages/studio/tests/e2e/timeline-bulk-actions.mjs index 63e35dc49f2..d171860d5c0 100644 --- a/packages/studio/tests/e2e/timeline-bulk-actions.mjs +++ b/packages/studio/tests/e2e/timeline-bulk-actions.mjs @@ -1,17 +1,15 @@ #!/usr/bin/env node -/** - * Times the timeline's bulk actions in a real browser on a real project: - * select-all, move 3 by hand, delete N, and the multi-select prompt box for N. - * Each action is the median of RUNS (default 5), fresh Studio page per run. - * - * BULK_PROJECT_DIR=/path/to/launch-project node packages/studio/tests/e2e/timeline-bulk-actions.mjs - * - * Runs the built CLI's preview server (what users ship), so build first: - * bun run --filter @hyperframes/studio build && bun run --filter @hyperframes/cli build - * BULK_PROJECT_DIR is copied, never modified. BULK_PORT, BULK_RUNS, BULK_ONLY (action name - * substring) and BULK_PROFILE=1 (CPU profile and request summary per action) are optional. - * "Settled" = no request in flight, no long task and no network for QUIET_MS. - */ +/** Times select-all, move 3 and delete-all in a real browser on a real project; see USAGE. */ +const USAGE = ` +BULK_PROJECT_DIR= node packages/studio/tests/e2e/timeline-bulk-actions.mjs + +Runs the built CLI's preview server, so build first: + bun run --filter @hyperframes/studio build && bun run --filter @hyperframes/cli build +BULK_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). +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. +`; import { cpSync, mkdtempSync, rmSync, existsSync } from "node:fs"; import { spawn } from "node:child_process"; import { tmpdir } from "node:os"; @@ -29,7 +27,7 @@ const TIMEOUT_MS = 120_000; const ORIGIN = `http://127.0.0.1:${PORT}`; if (!SOURCE || !existsSync(join(SOURCE, "index.html"))) { - console.error("BULK_PROJECT_DIR must point at a project directory with an index.html"); + console.error(`BULK_PROJECT_DIR must point at a project directory with an index.html.\n${USAGE}`); process.exit(2); } const chrome = resolveChromeExecutable(); @@ -126,7 +124,7 @@ const nextPaint = (page) => const selectedCount = (page) => page.evaluate(() => Number(document.body.innerText.match(/(\d+) elements selected/)?.[1] ?? 0)); -/** Ctrl-clicks the first `count` mounted clips; dispatched, so row virtualization and layout cannot misplace a click. */ +/** Ctrl-clicks the first `count` mounted clips, dispatched so layout cannot misplace a click. */ async function clickClips(page, count) { await page.evaluate((n) => { for (const clip of [...document.querySelectorAll("button[data-clip]")].slice(0, n)) From f400afadcdbf275460a3757dc90dd8b11c24c2b1 Mon Sep 17 00:00:00 2001 From: Miguel Angel Simon Sierra Date: Fri, 2 Oct 2026 21:10:41 -0700 Subject: [PATCH 03/12] refactor(studio): tidy the bulk-action fixes after review Root head memo is keyed by the root file's content so every subscriber of one write gets one answer, and a thumbnail request can no longer overwrite it. The GSAP read reuses the shared content version as its ETag. --- .../src/helpers/compositionInputs.test.ts | 9 ++++ .../src/helpers/compositionInputs.ts | 46 ++++++++++++------- packages/studio-server/src/routes/files.ts | 9 ++-- .../components/editor/probeSourceElement.ts | 19 ++++---- .../studio/src/hooks/useGsapTweenCache.ts | 2 +- .../studio/src/hooks/useTimelineDeleteOps.ts | 5 +- 6 files changed, 51 insertions(+), 39 deletions(-) diff --git a/packages/studio-server/src/helpers/compositionInputs.test.ts b/packages/studio-server/src/helpers/compositionInputs.test.ts index 51f50d8a6ed..c2cdcfd4a4b 100644 --- a/packages/studio-server/src/helpers/compositionInputs.test.ts +++ b/packages/studio-server/src/helpers/compositionInputs.test.ts @@ -85,6 +85,15 @@ describe("a root write", () => { expect(compositionsAffectedBy(dir, "index.html")).toEqual(["index.html"]); }); + it("tells every subscriber of one head edit the same thing, even after a thumbnail request", () => { + const dir = project(files("", "x")); + compositionInputSignature(dir, "compositions/a.html", "s1"); + rewrite(dir, "", "x"); + expect(compositionsAffectedBy(dir, "index.html")).toBeNull(); + compositionInputSignature(dir, "compositions/a.html", "s2"); + expect(compositionsAffectedBy(dir, "index.html")).toBeNull(); + }); + it("leaves a scene's input signature alone for a body edit, not for a head edit", () => { const dir = project(files("", "x")); const before = compositionInputSignature(dir, "compositions/a.html", "s1"); diff --git a/packages/studio-server/src/helpers/compositionInputs.ts b/packages/studio-server/src/helpers/compositionInputs.ts index 274fda6d1ec..1137fb2730a 100644 --- a/packages/studio-server/src/helpers/compositionInputs.ts +++ b/packages/studio-server/src/helpers/compositionInputs.ts @@ -53,14 +53,22 @@ function closureOf(read: SourceReader, compPath: string): Set { // composition) ever thumbnailed, never evicted; LRU them if a server ever holds thousands. const inputSignatures = new Map(); -/** The root's head last seen per project, to tell a head edit from a body-only root write. */ -const rootHeads = new Map(); +interface RootMemo { + /** Hash of the whole root file this memo answers for. */ + root: string; + head: string; + /** What `compositionsAffectedBy` told every subscriber for that root content. */ + affected: string[] | null; +} + +/** Per project, the last root content announced to watchers; thumbnail requests only seed it. */ +const rootMemos = new Map(); + +const sha1 = (text: string) => createHash("sha1").update(text).digest("hex"); -function rootHeadHash(projectDir: string): string { - const source = projectReader(projectDir)(ROOT_COMPOSITION) ?? ""; - const hash = createHash("sha1").update(rootHeadContent(source)).digest("hex"); - rootHeads.set(projectDir, hash); - return hash; +function rootHashes(read: SourceReader) { + const source = read(ROOT_COMPOSITION) ?? ""; + return { root: sha1(source), head: sha1(rootHeadContent(source)) }; } // What a thumbnail of `compPath` renders from: the project minus the compositions the root @@ -80,13 +88,14 @@ export function compositionInputSignature( const excluded = new Set( [...closureOf(read, ROOT_COMPOSITION)].filter((path) => !inputs.has(path)), ); + let inputSignature: string; if (comp === ROOT_COMPOSITION) { - const inputSignature = createProjectSignature(projectDir, excluded); - inputSignatures.set(key, { projectSignature, inputSignature }); - return inputSignature; + inputSignature = createProjectSignature(projectDir, excluded); + } else { + const hashes = rootHashes(read); + if (!rootMemos.has(projectDir)) rootMemos.set(projectDir, { ...hashes, affected: null }); + inputSignature = `${createProjectSignature(projectDir, excluded.add(ROOT_COMPOSITION))}:${hashes.head}`; } - excluded.add(ROOT_COMPOSITION); - const inputSignature = `${createProjectSignature(projectDir, excluded)}:${rootHeadHash(projectDir)}`; inputSignatures.set(key, { projectSignature, inputSignature }); return inputSignature; } @@ -95,17 +104,20 @@ export function compositionInputSignature( * Compositions whose rendered frames a write at `changedPath` can change, or `null` for all * of them: assets, a root head edit, and any file the root does not mount reach every * composition. A root write that leaves the head as it was changes only the root's own frames. + * Every subscriber asking about the same root content gets the same answer. */ export function compositionsAffectedBy(projectDir: string, changedPath: string): string[] | null { const changed = changedPath.replace(/\\/g, "/"); const read = projectReader(projectDir); - const mounted = closureOf(read, ROOT_COMPOSITION); if (changed === ROOT_COMPOSITION) { - const previous = rootHeads.get(projectDir); - return previous !== undefined && previous === rootHeadHash(projectDir) - ? [ROOT_COMPOSITION] - : null; + const now = rootHashes(read); + const memo = rootMemos.get(projectDir); + if (memo?.root === now.root) return memo.affected; + const affected = memo?.head === now.head ? [ROOT_COMPOSITION] : null; + rootMemos.set(projectDir, { ...now, affected }); + return affected; } + const mounted = closureOf(read, ROOT_COMPOSITION); if (!mounted.has(changed)) return null; return [...mounted].filter((path) => closureOf(read, path).has(changed)); } diff --git a/packages/studio-server/src/routes/files.ts b/packages/studio-server/src/routes/files.ts index 6108a908daf..9cde4d1ea3e 100644 --- a/packages/studio-server/src/routes/files.ts +++ b/packages/studio-server/src/routes/files.ts @@ -19,7 +19,6 @@ import { readdirSync, type Dirent, } from "node:fs"; -import { createHash } from "node:crypto"; import { resolve, dirname, join } from "node:path"; import type { StudioApiAdapter } from "../types.js"; import { isAudioFile } from "../helpers/mime.js"; @@ -2707,10 +2706,8 @@ export function registerFileRoutes(api: Hono, adapter: StudioApiAdapter): void { } const originalContent = readFileSync(ctx.absPath, "utf-8"); - // A member nested inside one already removed simply no longer matches, which - // is a normal outcome here rather than a failure. The response says whether - // the file changed, not how many of the targets landed — so a caller can - // tell a no-op from a write, but not a partial pass from a complete one. + // The response says whether the file changed, not how many of the targets landed, so a + // caller can tell a no-op from a write, but not a partial pass from a complete one. return writeIfChanged( c, ctx.project.dir, @@ -3345,7 +3342,7 @@ export function registerFileRoutes(api: Hono, adapter: StudioApiAdapter): void { // The parse is a pure function of the file, so a client that revalidates on every read // (Studio does, after any write) gets a 304 for every file that did not change. const html = readFileSync(res.absPath, "utf-8"); - const etag = `"gsap-animations:${createHash("sha1").update(html).digest("hex").slice(0, 16)}"`; + const etag = fileContentVersion(html); const headers = { ETag: etag, "Cache-Control": "no-cache" }; if (c.req.header("If-None-Match") === etag) return new Response(null, { status: 304, headers }); diff --git a/packages/studio/src/components/editor/probeSourceElement.ts b/packages/studio/src/components/editor/probeSourceElement.ts index adb6b6cd489..8dbca15fb9e 100644 --- a/packages/studio/src/components/editor/probeSourceElement.ts +++ b/packages/studio/src/components/editor/probeSourceElement.ts @@ -8,10 +8,7 @@ interface PendingProbe { } /** Probes asked for in the same tick, one batch per project file. */ -const pending = new Map< - string, - { projectId: string; sourceFile: string; probes: PendingProbe[] } ->(); +const pending = new Map(); async function sendBatch(projectId: string, sourceFile: string, probes: PendingProbe[]) { // Any failure reads as "exists": a probe that cannot answer must not strip capabilities. @@ -33,7 +30,7 @@ async function sendBatch(projectId: string, sourceFile: string, probes: PendingP if (Array.isArray(data?.exists)) exists = data.exists; } } catch { - // Falls through to the all-exist answer below. + // Network failure reads as "exists" too. } probes.forEach((probe, index) => probe.resolve(exists[index] !== false)); } @@ -49,16 +46,16 @@ export function probeSourceElement( ): Promise { return new Promise((resolve) => { const key = `${projectId}\0${sourceFile}`; - let batch = pending.get(key); - if (!batch) { - batch = { projectId, sourceFile, probes: [] }; + let probes = pending.get(key); + if (!probes) { + const batch: PendingProbe[] = []; + probes = batch; pending.set(key, batch); - const flushing = batch; setTimeout(() => { pending.delete(key); - void sendBatch(flushing.projectId, flushing.sourceFile, flushing.probes); + void sendBatch(projectId, sourceFile, batch); }, 0); } - batch.probes.push({ target, resolve }); + probes.push({ target, resolve }); }); } diff --git a/packages/studio/src/hooks/useGsapTweenCache.ts b/packages/studio/src/hooks/useGsapTweenCache.ts index 7ecf5401d3e..cf2223bef17 100644 --- a/packages/studio/src/hooks/useGsapTweenCache.ts +++ b/packages/studio/src/hooks/useGsapTweenCache.ts @@ -317,7 +317,7 @@ export function usePopulateKeyframeCacheForFile( loadedRef.current = { dataKey, files: covered }; // Everything the previous scan cached for a file this one no longer covers // (the composition just switched away from) has no owner left to clear it. - pruneKeyframeCacheToFiles([...covered]); + if (!sameData) pruneKeyframeCacheToFiles(files); if (stale.length === 0) return; runtimeScanDoneRef.current = ""; const doc = iframeRef?.current?.contentDocument; diff --git a/packages/studio/src/hooks/useTimelineDeleteOps.ts b/packages/studio/src/hooks/useTimelineDeleteOps.ts index 27098383357..b4ff3bec82b 100644 --- a/packages/studio/src/hooks/useTimelineDeleteOps.ts +++ b/packages/studio/src/hooks/useTimelineDeleteOps.ts @@ -144,10 +144,7 @@ export function useTimelineDeleteOps({ if (!removeResponse.ok) { throw new Error(`Failed to delete ${sameFile.length} clips from ${targetPath}`); } - const removeData = (await removeResponse.json()) as { - changed?: boolean; - content?: string; - }; + const removeData = (await removeResponse.json()) as { content?: string }; const removedContent = typeof removeData.content === "string" ? removeData.content : originalContent; // Shrink to the furthest remaining clip end, read from the post-removal source: From 095559fcd986fb7fa14bf20065d2f5d6a479cc12 Mon Sep 17 00:00:00 2001 From: Miguel Angel Simon Sierra Date: Fri, 2 Oct 2026 22:14:33 -0700 Subject: [PATCH 04/12] fix(studio): keep a head edit's thumbnail refresh when a later write replaces it File changes coalesce to the newest while a drain is in flight, so the affected-composition lists are merged instead of replaced. A failed GSAP read stays unloaded and is retried, and the GSAP read's ETag is salted with the parser version. --- .../src/helpers/sourceMutation.test.ts | 4 +- packages/studio-server/src/routes/files.ts | 6 +-- .../src/components/editor/manualEdits.ts | 1 + .../components/editor/manualEditsParsing.ts | 11 ++++++ .../studio/src/hooks/keyframeCacheAstLoad.ts | 9 +++-- .../useExternalFileChangeCoordinator.test.tsx | 26 +++++++++++++ .../hooks/useExternalFileChangeCoordinator.ts | 8 +++- .../studio/src/hooks/useGsapTweenCache.ts | 7 +++- .../usePopulateKeyframeCacheForFile.test.tsx | 38 +++++++++++++++++++ 9 files changed, 99 insertions(+), 11 deletions(-) diff --git a/packages/studio-server/src/helpers/sourceMutation.test.ts b/packages/studio-server/src/helpers/sourceMutation.test.ts index 8ea5aa74804..d5bbecd55d6 100644 --- a/packages/studio-server/src/helpers/sourceMutation.test.ts +++ b/packages/studio-server/src/helpers/sourceMutation.test.ts @@ -485,8 +485,8 @@ describe("probeElementInSource", () => { it("answers every target of a batch in order from one parse", () => { expect( - probeElementsInSource(FIXTURE, [{ id: "hero" }, { id: "gone" }, {}, { selector: ".brand" }]), - ).toEqual([true, false, false, true]); + probeElementsInSource(FIXTURE, [{ id: "hero" }, { id: "gone" }, { selector: ".brand" }, {}]), + ).toEqual([true, false, true, false]); }); it("returns true for an element found by class selector", () => { diff --git a/packages/studio-server/src/routes/files.ts b/packages/studio-server/src/routes/files.ts index 9cde4d1ea3e..b95ae054e5c 100644 --- a/packages/studio-server/src/routes/files.ts +++ b/packages/studio-server/src/routes/files.ts @@ -3339,10 +3339,10 @@ export function registerFileRoutes(api: Hono, adapter: StudioApiAdapter): void { }); if ("error" in res) return res.error; - // The parse is a pure function of the file, so a client that revalidates on every read - // (Studio does, after any write) gets a 304 for every file that did not change. + // The parse is a pure function of the file and the parser, so a client that revalidates on + // every read gets a 304 for every unchanged file; bump the `v1` salt when the parser changes. const html = readFileSync(res.absPath, "utf-8"); - const etag = fileContentVersion(html); + const etag = `${fileContentVersion(html).slice(0, -1)}:gsap-animations:v1"`; const headers = { ETag: etag, "Cache-Control": "no-cache" }; if (c.req.header("If-None-Match") === etag) return new Response(null, { status: 304, headers }); diff --git a/packages/studio/src/components/editor/manualEdits.ts b/packages/studio/src/components/editor/manualEdits.ts index 031aae549d1..190027ad84b 100644 --- a/packages/studio/src/components/editor/manualEdits.ts +++ b/packages/studio/src/components/editor/manualEdits.ts @@ -10,6 +10,7 @@ export { } from "./manualEditsTypes"; export { + mergeFileChangeAffectedCompositions, readFileChangeAffectedCompositions, readFileChangeAffectsPreview, readFileChangeField, diff --git a/packages/studio/src/components/editor/manualEditsParsing.ts b/packages/studio/src/components/editor/manualEditsParsing.ts index 99e0a9afa3c..2c3e96ecb87 100644 --- a/packages/studio/src/components/editor/manualEditsParsing.ts +++ b/packages/studio/src/components/editor/manualEditsParsing.ts @@ -43,3 +43,14 @@ export function readFileChangeAffectedCompositions(payload: unknown): readonly s if (!Array.isArray(value) || !value.every((path) => typeof path === "string")) return null; return value.map(normalizeStudioFileChangePath); } + +/** + * `incoming` replacing a `waiting` change must not forget what `waiting` invalidated: the + * result carries both lists, or "all" when either said so. + */ +export function mergeFileChangeAffectedCompositions(waiting: unknown, incoming: unknown): unknown { + const before = readFileChangeAffectedCompositions(waiting); + const after = readFileChangeAffectedCompositions(incoming); + const merged = before && after ? [...new Set([...before, ...after])] : null; + return { ...asPayloadRecord(incoming), affectedCompositions: merged }; +} diff --git a/packages/studio/src/hooks/keyframeCacheAstLoad.ts b/packages/studio/src/hooks/keyframeCacheAstLoad.ts index fc45aad7101..381a79eb569 100644 --- a/packages/studio/src/hooks/keyframeCacheAstLoad.ts +++ b/packages/studio/src/hooks/keyframeCacheAstLoad.ts @@ -99,17 +99,17 @@ async function requestParsedAnimations( } /** - * Read one composition file's tweens into the keyframe cache. Split out of the - * hook so the effect can run it per file without re-nesting the whole body. + * Read one composition file's tweens into the keyframe cache; false when the read failed. + * Split out of the hook so the effect can run it per file without re-nesting the whole body. */ // fallow-ignore-next-line complexity export async function populateKeyframeCacheFromAst( projectId: string, sf: string, doc: Document | null | undefined, -): Promise { +): Promise { const parsed = await fetchParsedAnimations(projectId, sf); - if (!parsed) return; + if (!parsed) return false; const { elements, domClipChildren } = usePlayerStore.getState(); const mergedByElement = new Map>(); const sourceByElement = new Map(); @@ -137,4 +137,5 @@ export async function populateKeyframeCacheFromAst( } } replaceKeyframeCacheForFile(sf, mergedByElement, sourceByElement); + return true; } diff --git a/packages/studio/src/hooks/useExternalFileChangeCoordinator.test.tsx b/packages/studio/src/hooks/useExternalFileChangeCoordinator.test.tsx index ce42ce6b008..a5e70d1f721 100644 --- a/packages/studio/src/hooks/useExternalFileChangeCoordinator.test.tsx +++ b/packages/studio/src/hooks/useExternalFileChangeCoordinator.test.tsx @@ -143,6 +143,32 @@ describe("external file change coordinator", () => { expect(onAcceptedPersistedFileChange).toHaveBeenLastCalledWith("scene.html", ["scene.html"]); }); + it("keeps a waiting head edit's thumbnail refresh when a later write replaces it", async () => { + let release = () => {}; + const inFlight = new Promise((resolve) => (release = resolve)); + const onAcceptedPersistedFileChange = vi.fn(); + let drains = 0; + await mountCoordinator({ + onAcceptedPersistedFileChange, + drainPendingChanges: async () => { + if (drains++ === 0) await inFlight; + return { status: "clean" as const }; + }, + }); + await act(async () => handler?.({ path: "other.html", content: "a", version: "v1" })); + await act(async () => handler?.({ path: "index.html", content: "b", version: "v2" })); + await act(async () => + handler?.({ + path: "index.html", + content: "c", + version: "v3", + affectedCompositions: ["index.html"], + }), + ); + await act(async () => release()); + expect(onAcceptedPersistedFileChange).toHaveBeenLastCalledWith("index.html", null); + }); + it("does not refresh the tree for a suppressed self-write echo", async () => { const refreshFileTree = vi.fn(); await mountCoordinator({ refreshFileTree }); diff --git a/packages/studio/src/hooks/useExternalFileChangeCoordinator.ts b/packages/studio/src/hooks/useExternalFileChangeCoordinator.ts index fc148c9a2b6..b731f5b17f0 100644 --- a/packages/studio/src/hooks/useExternalFileChangeCoordinator.ts +++ b/packages/studio/src/hooks/useExternalFileChangeCoordinator.ts @@ -1,5 +1,6 @@ import { useCallback, useEffect, useRef, useState, type MutableRefObject } from "react"; import { + mergeFileChangeAffectedCompositions, readFileChangeAffectedCompositions, readFileChangeAffectsPreview, readFileChangeField, @@ -419,7 +420,12 @@ export function useExternalFileChangeCoordinator({ waiting != null && readFileChangeAffectsPreview(waiting) && !readFileChangeAffectsPreview(payload); - if (!waitingChangeOutranksThis) pendingPayloadRef.current = { payload }; + if (!waitingChangeOutranksThis) { + pendingPayloadRef.current = { + payload: + waiting == null ? payload : mergeFileChangeAffectedCompositions(waiting, payload), + }; + } void startDrainLoop(); }, [projectId, pendingTimelineEditPathRef, startDrainLoop, onAcceptedPersistedFileChange], diff --git a/packages/studio/src/hooks/useGsapTweenCache.ts b/packages/studio/src/hooks/useGsapTweenCache.ts index cf2223bef17..26c0d345ab4 100644 --- a/packages/studio/src/hooks/useGsapTweenCache.ts +++ b/packages/studio/src/hooks/useGsapTweenCache.ts @@ -321,7 +321,12 @@ export function usePopulateKeyframeCacheForFile( if (stale.length === 0) return; runtimeScanDoneRef.current = ""; const doc = iframeRef?.current?.contentDocument; - void Promise.all(stale.map((sf) => populateKeyframeCacheFromAst(projectId, sf, doc))); + for (const sf of stale) { + void populateKeyframeCacheFromAst(projectId, sf, doc).then((loaded) => { + // A failed read is not loaded: the next selection flip asks for it again. + if (!loaded && loadedRef.current.dataKey === dataKey) loadedRef.current.files.delete(sf); + }); + } // elementCount is in the deps because new timeline elements (e.g. after a // sub-composition expand) need their keyframe cache populated immediately; // without it the effect won't re-run when elements appear/disappear. diff --git a/packages/studio/src/hooks/usePopulateKeyframeCacheForFile.test.tsx b/packages/studio/src/hooks/usePopulateKeyframeCacheForFile.test.tsx index 75cd58ea190..4d08b1ed8de 100644 --- a/packages/studio/src/hooks/usePopulateKeyframeCacheForFile.test.tsx +++ b/packages/studio/src/hooks/usePopulateKeyframeCacheForFile.test.tsx @@ -103,4 +103,42 @@ describe("usePopulateKeyframeCacheForFile", () => { await render({ sourceFile: "index.html", version: 2 }); expect(urls.length).toBe(loaded * 2); }); + + it("asks again for a covered file whose first read failed", async () => { + const urls: string[] = []; + vi.stubGlobal( + "fetch", + vi.fn((input: RequestInfo | URL) => { + const url = String(input); + urls.push(url); + const failed = + url.includes("keyframe-lab.html") && urls.filter((u) => u === url).length === 1; + return Promise.resolve({ + ok: !failed, + json: () => Promise.resolve({ animations: [] }), + }); + }), + ); + const render = async (sourceFile: string) => { + await act(async () => { + if (!root) { + container = document.createElement("div"); + document.body.appendChild(container); + root = createRoot(container); + } + root.render(); + }); + await act(async () => { + await Promise.resolve(); + }); + }; + + await render("index.html"); + const labReads = () => urls.filter((u) => u.includes("keyframe-lab.html")).length; + expect(labReads()).toBe(1); + await render("compositions/keyframe-lab.html"); + expect(labReads()).toBe(2); + await render("index.html"); + expect(labReads()).toBe(2); + }); }); From 81a7c3a37c5de3e6d22d921bc0ddb142009fbff0 Mon Sep 17 00:00:00 2001 From: Miguel Angel Simon Sierra Date: Fri, 2 Oct 2026 22:22:35 -0700 Subject: [PATCH 05/12] feat(studio): cap hand-resizing a multi-selection at 3 clips like moving Dragging a resize edge with 4 or more clips selected is refused with the same toast as a move; the rule is one constant and one helper shared by pointer move, pointer resize and keyboard pickup. --- .../src/hooks/useBlockedTimelineEditToast.ts | 6 +-- .../timelineClipDragGestureLifecycle.ts | 2 +- .../timelineClipGestureHandlers.test.ts | 45 ++++++++++++------- .../components/timelineClipGestureHandlers.ts | 15 ++++++- .../src/player/components/timelineEditing.ts | 6 +-- .../components/timelineLinkSelection.ts | 8 ++-- .../useTimelineClipDrag.keyboard.test.tsx | 2 +- .../player/components/useTimelineClipDrag.ts | 6 +-- 8 files changed, 56 insertions(+), 34 deletions(-) diff --git a/packages/studio/src/hooks/useBlockedTimelineEditToast.ts b/packages/studio/src/hooks/useBlockedTimelineEditToast.ts index 7fe2447a402..5bbd4d4f06d 100644 --- a/packages/studio/src/hooks/useBlockedTimelineEditToast.ts +++ b/packages/studio/src/hooks/useBlockedTimelineEditToast.ts @@ -9,7 +9,7 @@ import { useCallback, useRef } from "react"; import type { TimelineElement } from "../player"; import { - MAX_HAND_MOVE_CLIPS, + MAX_HAND_EDIT_CLIPS, type BlockedTimelineEditIntent, } from "../player/components/timelineEditing"; @@ -25,8 +25,8 @@ export function useBlockedTimelineEditToast( if (now - lastAtRef.current < BLOCKED_TOAST_INTERVAL_MS) return; lastAtRef.current = now; showToast( - intent === "move-many" - ? `Select ${MAX_HAND_MOVE_CLIPS} or fewer clips to move by hand, or describe the change.` + 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", ); diff --git a/packages/studio/src/player/components/timelineClipDragGestureLifecycle.ts b/packages/studio/src/player/components/timelineClipDragGestureLifecycle.ts index 0cf3c8e0941..096d68c180c 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 === "move-many" ? 4 : 2; + const threshold = blocked.intent === "move" || blocked.intent === "edit-many" ? 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.ts index a3850308e90..085d0e544df 100644 --- a/packages/studio/src/player/components/timelineClipGestureHandlers.test.ts +++ b/packages/studio/src/player/components/timelineClipGestureHandlers.test.ts @@ -4,7 +4,7 @@ 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_MOVE_CLIPS } from "./timelineEditing"; +import { MAX_HAND_EDIT_CLIPS } from "./timelineEditing"; afterEach(() => usePlayerStore.getState().reset()); @@ -17,51 +17,62 @@ const clips: TimelineElement[] = Array.from({ length: 6 }, (_, i) => ({ })); const capabilities = { canMove: true, canTrimStart: true, canTrimEnd: true, readOnly: false }; -function pressFirstClipWithSelection(count: number) { +function grabFirstClip(count: number, gesture: "move" | "resize") { const store = usePlayerStore.getState(); store.setElements(clips); store.setSelectedElementIds(new Set(clips.slice(0, count).map((c) => c.id))); const setDraggedClip = vi.fn(); + const setResizingClip = vi.fn(); const blockedClipRef = { current: null as { intent: string } | null }; const deps = { pps: 100, onMoveElement: vi.fn(), + onResizeElement: vi.fn(), blockedClipRef, suppressClickRef: { current: false }, scrollRef: { current: null }, setShowPopover: vi.fn(), setRangeSelection: vi.fn(), - setResizingClip: vi.fn(), + setResizingClip, setDraggedClip, setSelectedElementId: vi.fn(), } as unknown as ClipGestureDeps; - const { onPointerDown } = createClipGestureHandlers( - clips[0], - clips[0].id, - clips[0], - capabilities, - deps, - ); - onPointerDown({ + const handlers = createClipGestureHandlers(clips[0], clips[0].id, clips[0], capabilities, deps); + const event = { button: 0, clientX: 50, clientY: 5, pointerId: 1, + stopPropagation: vi.fn(), currentTarget: { getBoundingClientRect: () => ({ left: 0, width: 100 }) }, - } as unknown as ReactPointerEvent); - return { setDraggedClip, blockedClipRef }; + } as unknown as ReactPointerEvent; + if (gesture === "move") handlers.onPointerDown(event); + else handlers.onResizeStart("end", event); + return { setDraggedClip, setResizingClip, blockedClipRef }; } -describe("hand-moving a multi-selection", () => { +describe("hand-editing a multi-selection", () => { it("moves up to the limit by hand", () => { - const { setDraggedClip, blockedClipRef } = pressFirstClipWithSelection(MAX_HAND_MOVE_CLIPS); + const { setDraggedClip, blockedClipRef } = grabFirstClip(MAX_HAND_EDIT_CLIPS, "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 } = pressFirstClipWithSelection(MAX_HAND_MOVE_CLIPS + 1); + const { setDraggedClip, blockedClipRef } = grabFirstClip(MAX_HAND_EDIT_CLIPS + 1, "move"); expect(setDraggedClip).not.toHaveBeenCalled(); - expect(blockedClipRef.current?.intent).toBe("move-many"); + expect(blockedClipRef.current?.intent).toBe("edit-many"); + }); + + it("resizes up to the limit by hand", () => { + const { setResizingClip, blockedClipRef } = grabFirstClip(MAX_HAND_EDIT_CLIPS, "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"); }); }); diff --git a/packages/studio/src/player/components/timelineClipGestureHandlers.ts b/packages/studio/src/player/components/timelineClipGestureHandlers.ts index 9c9cbddd862..7926d0151e9 100644 --- a/packages/studio/src/player/components/timelineClipGestureHandlers.ts +++ b/packages/studio/src/player/components/timelineClipGestureHandlers.ts @@ -9,7 +9,7 @@ import type { TimelineEditCapabilities } from "./timelineEditCapabilities"; import type { TimelineEditCallbacks } from "./timelineCallbacks"; import { CLIP_HANDLE_W } from "./timelineLayout"; import { - exceedsHandMoveLimit, + exceedsHandEditLimit, selectClipWithLinks, toggleClipWithLinks, } from "./timelineLinkSelection"; @@ -98,7 +98,7 @@ function resolvePointerDownAction( } if (!onMoveElement || !capabilities.canMove) return { kind: "ignore" }; - if (exceedsHandMoveLimit(grabbed, e.altKey)) return { kind: "block", intent: "move-many", rect }; + if (exceedsHandEditLimit(grabbed, e.altKey)) return { kind: "block", intent: "edit-many", rect }; return { kind: "move", rect }; } @@ -135,6 +135,17 @@ 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)) { + 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); diff --git a/packages/studio/src/player/components/timelineEditing.ts b/packages/studio/src/player/components/timelineEditing.ts index 262bf71e680..620d71fce6f 100644 --- a/packages/studio/src/player/components/timelineEditing.ts +++ b/packages/studio/src/player/components/timelineEditing.ts @@ -248,10 +248,10 @@ export interface TimelinePromptElement { track: number; } -export type BlockedTimelineEditIntent = "move" | "move-many" | "resize-start" | "resize-end"; +export type BlockedTimelineEditIntent = "move" | "edit-many" | "resize-start" | "resize-end"; -/** Most clips a hand drag moves at once; a larger selection goes through the prompt box. */ -export const MAX_HAND_MOVE_CLIPS = 3; +/** Most clips a hand drag moves or resizes at once; a larger selection goes through the prompt box. */ +export const MAX_HAND_EDIT_CLIPS = 3; export interface TimelineRangeSelection { start: number; diff --git a/packages/studio/src/player/components/timelineLinkSelection.ts b/packages/studio/src/player/components/timelineLinkSelection.ts index d39d74238f3..b93fe715e70 100644 --- a/packages/studio/src/player/components/timelineLinkSelection.ts +++ b/packages/studio/src/player/components/timelineLinkSelection.ts @@ -1,6 +1,6 @@ import { usePlayerStore, type TimelineElement } from "../store/playerStore"; import { expandToLinkedMembers, linkedGestureKeys, linkedMembersOf } from "./audioClipLink"; -import { MAX_HAND_MOVE_CLIPS } from "./timelineEditing"; +import { MAX_HAND_EDIT_CLIPS } from "./timelineEditing"; import { isLinkedSelectionOn } from "../../utils/linkedClipPreferences"; /** @@ -41,8 +41,8 @@ export function toggleClipWithLinks(key: string, altKey: boolean): TimelineEleme return state.elements.find((el) => (el.key ?? el.id) === primary) ?? null; } -/** Whether grabbing `grabbed` would move more clips by hand than a hand drag allows. */ -export function exceedsHandMoveLimit(grabbed: TimelineElement, altKey: boolean): boolean { +/** Whether grabbing `grabbed` would move or resize more clips by hand than a hand drag allows. */ +export function exceedsHandEditLimit(grabbed: TimelineElement, altKey: boolean): boolean { const { selectedElementIds, elements } = usePlayerStore.getState(); const moved = linkedGestureKeys( selectedElementIds, @@ -51,5 +51,5 @@ export function exceedsHandMoveLimit(grabbed: TimelineElement, altKey: boolean): altKey, isLinkedSelectionOn(), ); - return moved.size > MAX_HAND_MOVE_CLIPS; + return moved.size > MAX_HAND_EDIT_CLIPS; } diff --git a/packages/studio/src/player/components/useTimelineClipDrag.keyboard.test.tsx b/packages/studio/src/player/components/useTimelineClipDrag.keyboard.test.tsx index b910084fc6b..9b338a7f85e 100644 --- a/packages/studio/src/player/components/useTimelineClipDrag.keyboard.test.tsx +++ b/packages/studio/src/player/components/useTimelineClipDrag.keyboard.test.tsx @@ -172,6 +172,6 @@ it("does not pick up a clip held in a selection above the hand-move limit", () = expect(view.drag).toBeNull(); expect(view.onBlockedEditAttempt).toHaveBeenCalledWith( expect.objectContaining({ id: "hero" }), - "move-many", + "edit-many", ); }); diff --git a/packages/studio/src/player/components/useTimelineClipDrag.ts b/packages/studio/src/player/components/useTimelineClipDrag.ts index a20497f8b89..d13d9d673d7 100644 --- a/packages/studio/src/player/components/useTimelineClipDrag.ts +++ b/packages/studio/src/player/components/useTimelineClipDrag.ts @@ -29,7 +29,7 @@ import type { } from "./timelineClipDragTypes"; import { getTimelineElementIndexes } from "../lib/timelineElementIndexes"; import { dropMisalignedTrimPartners, linkedGestureKeys } from "./audioClipLink"; -import { exceedsHandMoveLimit } from "./timelineLinkSelection"; +import { exceedsHandEditLimit } from "./timelineLinkSelection"; import { isLinkedSelectionOn } from "../../utils/linkedClipPreferences"; import { useTimelineClipCapabilities } from "./timelineReadOnly"; import { timelineClipFocusId } from "./timelineNavigationIdentity"; @@ -542,8 +542,8 @@ export function useTimelineClipDrag({ if (!element || !getClipCapabilities(element).canMove) return; event.preventDefault(); event.stopImmediatePropagation(); - if (exceedsHandMoveLimit(element, false)) { - onBlockedEditAttemptRef.current?.(element, "move-many"); + if (exceedsHandEditLimit(element, false)) { + onBlockedEditAttemptRef.current?.(element, "edit-many"); return; } setShowPopover(false); From b986c4499c232976f391558681c6988e9d7701c4 Mon Sep 17 00:00:00 2001 From: Miguel Angel Simon Sierra Date: Fri, 2 Oct 2026 23:06:50 -0700 Subject: [PATCH 06/12] fix(studio): keep a head edit's thumbnail refresh through a replaced conflict A newer blocked change replaces the held one, so it now inherits the thumbnails the held one owed. --- .../useExternalFileChangeCoordinator.test.tsx | 25 +++++++++++++++++++ .../hooks/useExternalFileChangeCoordinator.ts | 18 ++++++++++--- 2 files changed, 40 insertions(+), 3 deletions(-) diff --git a/packages/studio/src/hooks/useExternalFileChangeCoordinator.test.tsx b/packages/studio/src/hooks/useExternalFileChangeCoordinator.test.tsx index a5e70d1f721..8ea0e66f333 100644 --- a/packages/studio/src/hooks/useExternalFileChangeCoordinator.test.tsx +++ b/packages/studio/src/hooks/useExternalFileChangeCoordinator.test.tsx @@ -169,6 +169,31 @@ describe("external file change coordinator", () => { expect(onAcceptedPersistedFileChange).toHaveBeenLastCalledWith("index.html", null); }); + it("keeps a head edit's thumbnail refresh through a conflict that a later write replaces", async () => { + const onAcceptedPersistedFileChange = vi.fn(); + const conflict = new StudioFileConflictError({ + filePath: "index.html", + currentVersion: "v1", + currentContent: "theirs", + attemptedContent: "mine", + }); + const { captured } = await mountCoordinator({ + onAcceptedPersistedFileChange, + drainPendingChanges: async () => ({ status: "conflict" as const, error: conflict }), + }); + await act(async () => handler?.({ path: "index.html", content: "head", version: "v1" })); + await act(async () => + handler?.({ + path: "index.html", + content: "body", + version: "v2", + affectedCompositions: ["index.html"], + }), + ); + await act(async () => captured.handle?.useExternalFile()); + expect(onAcceptedPersistedFileChange).toHaveBeenLastCalledWith("index.html", null); + }); + it("does not refresh the tree for a suppressed self-write echo", async () => { const refreshFileTree = vi.fn(); await mountCoordinator({ refreshFileTree }); diff --git a/packages/studio/src/hooks/useExternalFileChangeCoordinator.ts b/packages/studio/src/hooks/useExternalFileChangeCoordinator.ts index b731f5b17f0..47a00b41ef0 100644 --- a/packages/studio/src/hooks/useExternalFileChangeCoordinator.ts +++ b/packages/studio/src/hooks/useExternalFileChangeCoordinator.ts @@ -164,7 +164,7 @@ export function useExternalFileChangeCoordinator({ onAcceptedPersistedFileChange, refreshFileTree, }: ExternalFileChangeCoordinatorOptions): ExternalFileChangeCoordinatorHandle { - const [blocked, setBlocked] = useState(null); + const [blocked, setBlockedState] = useState(null); const generationRef = useRef(0); const mountedRef = useRef(true); const lastEventIdentityRef = useRef(null); @@ -173,6 +173,15 @@ export function useExternalFileChangeCoordinator({ const drainingRef = useRef(false); const pendingPayloadRef = useRef<{ payload: unknown } | null>(null); blockedRef.current = blocked; + // A newer blocked change replaces the held one, so it inherits the thumbnails the held one owed. + const setBlocked = useCallback((next: ExternalFileChangeBlockedState | null) => { + const held = blockedRef.current; + setBlockedState( + next && held + ? { ...next, payload: mergeFileChangeAffectedCompositions(held.payload, next.payload) } + : next, + ); + }, []); useEffect(() => { mountedRef.current = true; @@ -186,7 +195,7 @@ export function useExternalFileChangeCoordinator({ generationRef.current += 1; setBlocked(null); lastEventIdentityRef.current = null; - }, [projectId, activeCompPath]); + }, [projectId, activeCompPath, setBlocked]); useEffect(() => { if (!projectId || !recoveryFilePath || !loadConflictSnapshot) return; @@ -230,7 +239,7 @@ export function useExternalFileChangeCoordinator({ return () => { cancelled = true; }; - }, [loadConflictSnapshot, projectId, recoveryFilePath]); + }, [loadConflictSnapshot, projectId, recoveryFilePath, setBlocked]); const reloadAcceptedGeneration = useCallback( (path: string, affectsPreview = true) => { @@ -345,6 +354,7 @@ export function useExternalFileChangeCoordinator({ }, [ drainPendingChanges, + setBlocked, projectId, deleteConflictSnapshot, getPendingCandidate, @@ -475,6 +485,7 @@ export function useExternalFileChangeCoordinator({ }, [ deleteConflictSnapshot, + setBlocked, discardPendingChanges, onUseExternalFile, onAcceptedPersistedFileChange, @@ -533,6 +544,7 @@ export function useExternalFileChangeCoordinator({ reloadAcceptedGeneration(conflict.filePath); }, [ deleteConflictSnapshot, + setBlocked, discardPendingChanges, overwriteConflict, projectId, From fa55f68af21de7dda890e802ad1825e61928d131 Mon Sep 17 00:00:00 2001 From: Miguel Angel Simon Sierra Date: Fri, 2 Oct 2026 23:25:52 -0700 Subject: [PATCH 07/12] fix(studio): keep a held head edit's thumbnail refresh when a later write saves cleanly The clean-save path and the failed-cleanup path now merge the held blocked change's affected compositions, and the blocked-state merge runs inside the state update so two conflicts in one tick cannot lose the first. --- .../useExternalFileChangeCoordinator.test.tsx | 28 +++++++++++++++++++ .../hooks/useExternalFileChangeCoordinator.ts | 10 ++++--- 2 files changed, 34 insertions(+), 4 deletions(-) diff --git a/packages/studio/src/hooks/useExternalFileChangeCoordinator.test.tsx b/packages/studio/src/hooks/useExternalFileChangeCoordinator.test.tsx index 8ea0e66f333..f6b52d39b07 100644 --- a/packages/studio/src/hooks/useExternalFileChangeCoordinator.test.tsx +++ b/packages/studio/src/hooks/useExternalFileChangeCoordinator.test.tsx @@ -194,6 +194,34 @@ describe("external file change coordinator", () => { expect(onAcceptedPersistedFileChange).toHaveBeenLastCalledWith("index.html", null); }); + it("keeps a held head edit's thumbnail refresh when a later write saves cleanly", async () => { + const onAcceptedPersistedFileChange = vi.fn(); + const conflict = new StudioFileConflictError({ + filePath: "index.html", + currentVersion: "v1", + currentContent: "theirs", + attemptedContent: "mine", + }); + let drains = 0; + await mountCoordinator({ + onAcceptedPersistedFileChange, + drainPendingChanges: async () => + drains++ === 0 + ? { status: "conflict" as const, error: conflict } + : { status: "clean" as const }, + }); + await act(async () => handler?.({ path: "index.html", content: "head", version: "v1" })); + await act(async () => + handler?.({ + path: "index.html", + content: "body", + version: "v2", + affectedCompositions: ["index.html"], + }), + ); + expect(onAcceptedPersistedFileChange).toHaveBeenLastCalledWith("index.html", null); + }); + it("does not refresh the tree for a suppressed self-write echo", async () => { const refreshFileTree = vi.fn(); await mountCoordinator({ refreshFileTree }); diff --git a/packages/studio/src/hooks/useExternalFileChangeCoordinator.ts b/packages/studio/src/hooks/useExternalFileChangeCoordinator.ts index 47a00b41ef0..a68ce8b40cd 100644 --- a/packages/studio/src/hooks/useExternalFileChangeCoordinator.ts +++ b/packages/studio/src/hooks/useExternalFileChangeCoordinator.ts @@ -175,8 +175,7 @@ export function useExternalFileChangeCoordinator({ blockedRef.current = blocked; // A newer blocked change replaces the held one, so it inherits the thumbnails the held one owed. const setBlocked = useCallback((next: ExternalFileChangeBlockedState | null) => { - const held = blockedRef.current; - setBlockedState( + setBlockedState((held) => next && held ? { ...next, payload: mergeFileChangeAffectedCompositions(held.payload, next.payload) } : next, @@ -285,14 +284,17 @@ export function useExternalFileChangeCoordinator({ await deleteConflictSnapshot(projectId!, path); } catch (error) { if (mountedRef.current && generation === generationRef.current) { - setBlocked({ ...previousBlocked, generation, error }); + setBlocked({ ...previousBlocked, generation, error, payload }); } return; } } if (!mountedRef.current || generation !== generationRef.current) return; setBlocked(null); - onAcceptedPersistedFileChange(path, readFileChangeAffectedCompositions(payload)); + const owed = previousBlocked + ? mergeFileChangeAffectedCompositions(previousBlocked.payload, payload) + : payload; + onAcceptedPersistedFileChange(path, readFileChangeAffectedCompositions(owed)); reloadAcceptedGeneration(path, readFileChangeAffectsPreview(payload)); return; } From 87a97fa02784e1baeab4f08678019a350a99358e Mon Sep 17 00:00:00 2001 From: Miguel Angel Simon Sierra Date: Fri, 2 Oct 2026 23:35:11 -0700 Subject: [PATCH 08/12] chore(studio): keep useTimelineClipDrag under the 600-line cap --- .../src/player/components/useTimelineClipDrag.ts | 16 +++++----------- 1 file changed, 5 insertions(+), 11 deletions(-) diff --git a/packages/studio/src/player/components/useTimelineClipDrag.ts b/packages/studio/src/player/components/useTimelineClipDrag.ts index d13d9d673d7..7a80ee042bd 100644 --- a/packages/studio/src/player/components/useTimelineClipDrag.ts +++ b/packages/studio/src/player/components/useTimelineClipDrag.ts @@ -159,11 +159,8 @@ export function useTimelineClipDrag({ const elementsRef = useRef(elements); elementsRef.current = elements; - // Perf (frozen-per-gesture): the snap-target set and the audio-track set are - // fixed for the duration of one drag/resize (the store is not re-authored mid - // gesture), so build each ONCE and reuse it across every pointermove and every - // auto-scroll frame. Both caches are cleared at gesture teardown - // (stopClipDragAutoScroll), so the next gesture rebuilds against fresh state. + // The snap-target and audio-track sets are fixed for one drag/resize (the store is not + // re-authored mid gesture): built once, reused per pointermove, cleared at teardown. const snapTargetsCacheRef = useRef>(new Map()); const dragAudioTracksRef = useRef | null>(null); @@ -273,8 +270,7 @@ export function useTimelineClipDrag({ const blockedClipRef = useRef(null); const suppressClickRef = useRef(false); - // Active multi-select group-resize session, created lazily on first movement. - // It owns a projection only; canonical store timing changes at commit. + // Group-resize session, created on first movement; a projection only, committed at the end. const groupResizeRef = useRef(null); const onMoveElementRef = useRef(onMoveElement); @@ -542,10 +538,8 @@ export function useTimelineClipDrag({ if (!element || !getClipCapabilities(element).canMove) return; event.preventDefault(); event.stopImmediatePropagation(); - if (exceedsHandEditLimit(element, false)) { - onBlockedEditAttemptRef.current?.(element, "edit-many"); - return; - } + if (exceedsHandEditLimit(element, false)) + return void onBlockedEditAttemptRef.current?.(element, "edit-many"); setShowPopover(false); setRangeSelectionRef.current?.(null); const row = keyboardPickupInsertRow( From d681b7ad619aafbc95b088396cc54cec920f1eaf Mon Sep 17 00:00:00 2001 From: Miguel Angel Simon Sierra Date: Sat, 3 Oct 2026 00:12:59 -0700 Subject: [PATCH 09/12] feat(studio): cap by the clips an edit would change, and cut the added comments The 3-clip rule counts the clips a move or trim would write to: a locked clip swept into a move stays put, and a trim some member cannot take edits only the grabbed clip. Comment share is back at or under the base in every changed file. --- .../src/helpers/compositionInputs.ts | 9 ++---- .../src/helpers/subComposition.ts | 1 - .../components/editor/manualEditsParsing.ts | 4 --- .../components/editor/probeSourceElement.ts | 10 +------ .../studio/src/hooks/keyframeCacheAstLoad.ts | 9 +++--- .../studio/src/hooks/useGsapTweenCache.ts | 5 ---- .../timelineClipGestureHandlers.test.ts | 20 +++++++++++-- .../components/timelineClipGestureHandlers.ts | 5 ++-- .../src/player/components/timelineEditing.ts | 1 - .../components/timelineLinkSelection.ts | 30 +++++++++++++++---- .../player/components/useTimelineClipDrag.ts | 2 +- 11 files changed, 54 insertions(+), 42 deletions(-) diff --git a/packages/studio-server/src/helpers/compositionInputs.ts b/packages/studio-server/src/helpers/compositionInputs.ts index 1137fb2730a..8ca9ee1da77 100644 --- a/packages/studio-server/src/helpers/compositionInputs.ts +++ b/packages/studio-server/src/helpers/compositionInputs.ts @@ -54,14 +54,11 @@ function closureOf(read: SourceReader, compPath: string): Set { const inputSignatures = new Map(); interface RootMemo { - /** Hash of the whole root file this memo answers for. */ root: string; head: string; - /** What `compositionsAffectedBy` told every subscriber for that root content. */ affected: string[] | null; } -/** Per project, the last root content announced to watchers; thumbnail requests only seed it. */ const rootMemos = new Map(); const sha1 = (text: string) => createHash("sha1").update(text).digest("hex"); @@ -72,8 +69,7 @@ function rootHashes(read: SourceReader) { } // What a thumbnail of `compPath` renders from: the project minus the compositions the root -// mounts that `compPath` does not. A scene's page borrows only the root's head, so for a scene -// the root counts as its head alone; the root's own thumbnail renders all of it. +// mounts that `compPath` does not; for a scene the root counts as its head alone. export function compositionInputSignature( projectDir: string, compPath: string, @@ -103,8 +99,7 @@ export function compositionInputSignature( /** * Compositions whose rendered frames a write at `changedPath` can change, or `null` for all * of them: assets, a root head edit, and any file the root does not mount reach every - * composition. A root write that leaves the head as it was changes only the root's own frames. - * Every subscriber asking about the same root content gets the same answer. + * composition. A head-preserving root write changes only the root's own frames. */ export function compositionsAffectedBy(projectDir: string, changedPath: string): string[] | null { const changed = changedPath.replace(/\\/g, "/"); diff --git a/packages/studio-server/src/helpers/subComposition.ts b/packages/studio-server/src/helpers/subComposition.ts index ac684780154..ba4cc14e28a 100644 --- a/packages/studio-server/src/helpers/subComposition.ts +++ b/packages/studio-server/src/helpers/subComposition.ts @@ -236,7 +236,6 @@ function tagRootCompositionFile(bodyHtml: string, compPath: string): string { ); } -/** The root document's `` content: the only part of the root a sub-composition page borrows. */ export function rootHeadContent(rootHtml: string): string { return rootHtml.match(/]*>([\s\S]*?)<\/head>/i)?.[1] ?? ""; } diff --git a/packages/studio/src/components/editor/manualEditsParsing.ts b/packages/studio/src/components/editor/manualEditsParsing.ts index 2c3e96ecb87..f2964d69108 100644 --- a/packages/studio/src/components/editor/manualEditsParsing.ts +++ b/packages/studio/src/components/editor/manualEditsParsing.ts @@ -44,10 +44,6 @@ export function readFileChangeAffectedCompositions(payload: unknown): readonly s return value.map(normalizeStudioFileChangePath); } -/** - * `incoming` replacing a `waiting` change must not forget what `waiting` invalidated: the - * result carries both lists, or "all" when either said so. - */ export function mergeFileChangeAffectedCompositions(waiting: unknown, incoming: unknown): unknown { const before = readFileChangeAffectedCompositions(waiting); const after = readFileChangeAffectedCompositions(incoming); diff --git a/packages/studio/src/components/editor/probeSourceElement.ts b/packages/studio/src/components/editor/probeSourceElement.ts index 8dbca15fb9e..4312e2becb6 100644 --- a/packages/studio/src/components/editor/probeSourceElement.ts +++ b/packages/studio/src/components/editor/probeSourceElement.ts @@ -7,11 +7,9 @@ interface PendingProbe { resolve: (exists: boolean) => void; } -/** Probes asked for in the same tick, one batch per project file. */ const pending = new Map(); async function sendBatch(projectId: string, sourceFile: string, probes: PendingProbe[]) { - // Any failure reads as "exists": a probe that cannot answer must not strip capabilities. let exists: boolean[] = []; try { const response = await fetch( @@ -29,16 +27,10 @@ async function sendBatch(projectId: string, sourceFile: string, probes: PendingP const data = await response.json(); if (Array.isArray(data?.exists)) exists = data.exists; } - } catch { - // Network failure reads as "exists" too. - } + } catch {} probes.forEach((probe, index) => probe.resolve(exists[index] !== false)); } -/** - * Whether the element still exists in its source file. A selection of N elements asks N times - * in one tick; the asks for one file leave as a single request. - */ export function probeSourceElement( projectId: string, sourceFile: string, diff --git a/packages/studio/src/hooks/keyframeCacheAstLoad.ts b/packages/studio/src/hooks/keyframeCacheAstLoad.ts index 381a79eb569..d36b0a3b340 100644 --- a/packages/studio/src/hooks/keyframeCacheAstLoad.ts +++ b/packages/studio/src/hooks/keyframeCacheAstLoad.ts @@ -81,9 +81,8 @@ async function requestParsedAnimations( try { const res = await fetch( `/api/projects/${encodeURIComponent(projectId)}/gsap-animations/${encodeURIComponent(sourceFile)}`, - // Always revalidate against the source; the server answers 304 for a file that did not - // change, so a write elsewhere costs no re-parse here. No per-call timestamp (a - // deterministic-render no-no). + // Always revalidate; an unchanged file answers 304. No per-call timestamp + // (a deterministic-render no-no). { cache: "no-cache" }, ); if (!res.ok) return null; @@ -99,8 +98,8 @@ async function requestParsedAnimations( } /** - * Read one composition file's tweens into the keyframe cache; false when the read failed. - * Split out of the hook so the effect can run it per file without re-nesting the whole body. + * Read one composition file's tweens into the keyframe cache. Split out of the + * hook so the effect can run it per file without re-nesting the whole body. */ // fallow-ignore-next-line complexity export async function populateKeyframeCacheFromAst( diff --git a/packages/studio/src/hooks/useGsapTweenCache.ts b/packages/studio/src/hooks/useGsapTweenCache.ts index 26c0d345ab4..da976f7b962 100644 --- a/packages/studio/src/hooks/useGsapTweenCache.ts +++ b/packages/studio/src/hooks/useGsapTweenCache.ts @@ -290,8 +290,6 @@ export function usePopulateKeyframeCacheForFile( const domClipChildrenKey = usePlayerStore((s) => s.domClipChildren.map((c) => `${c.id}<${c.hostId}`).join("|"), ); - // What each file's cache entries were last loaded for. Switching `sourceFile` to a - // file that is already loaded for the current data must not refetch the others. const loadedRef = useRef<{ dataKey: string; files: Set }>({ dataKey: "", files: new Set(), @@ -311,8 +309,6 @@ export function usePopulateKeyframeCacheForFile( ); const sameData = loadedRef.current.dataKey === dataKey; const stale = sameData ? files.filter((sf) => !loadedRef.current.files.has(sf)) : files; - // Flipping `sourceFile` among files already covered keeps all of them; only new data - // (another composition, a write) narrows the set back to what is on screen. const covered = sameData ? new Set([...loadedRef.current.files, ...files]) : new Set(files); loadedRef.current = { dataKey, files: covered }; // Everything the previous scan cached for a file this one no longer covers @@ -323,7 +319,6 @@ export function usePopulateKeyframeCacheForFile( const doc = iframeRef?.current?.contentDocument; for (const sf of stale) { void populateKeyframeCacheFromAst(projectId, sf, doc).then((loaded) => { - // A failed read is not loaded: the next selection flip asks for it again. if (!loaded && loadedRef.current.dataKey === dataKey) loadedRef.current.files.delete(sf); }); } diff --git a/packages/studio/src/player/components/timelineClipGestureHandlers.test.ts b/packages/studio/src/player/components/timelineClipGestureHandlers.test.ts index 085d0e544df..1e9a732b51e 100644 --- a/packages/studio/src/player/components/timelineClipGestureHandlers.test.ts +++ b/packages/studio/src/player/components/timelineClipGestureHandlers.test.ts @@ -10,6 +10,7 @@ afterEach(() => usePlayerStore.getState().reset()); const clips: TimelineElement[] = Array.from({ length: 6 }, (_, i) => ({ id: `clip-${i}`, + domId: `clip-${i}`, tag: "div", start: i, duration: 1, @@ -17,9 +18,11 @@ 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") { +function grabFirstClip(count: number, gesture: "move" | "resize", locked: number[] = []) { const store = usePlayerStore.getState(); - store.setElements(clips); + store.setElements( + clips.map((clip, i) => (locked.includes(i) ? { ...clip, timelineLocked: true } : clip)), + ); store.setSelectedElementIds(new Set(clips.slice(0, count).map((c) => c.id))); const setDraggedClip = vi.fn(); const setResizingClip = vi.fn(); @@ -75,4 +78,17 @@ describe("hand-editing a multi-selection", () => { 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.ts index 7926d0151e9..29ffd28bdb9 100644 --- a/packages/studio/src/player/components/timelineClipGestureHandlers.ts +++ b/packages/studio/src/player/components/timelineClipGestureHandlers.ts @@ -98,7 +98,8 @@ function resolvePointerDownAction( } if (!onMoveElement || !capabilities.canMove) return { kind: "ignore" }; - if (exceedsHandEditLimit(grabbed, e.altKey)) return { kind: "block", intent: "edit-many", rect }; + if (exceedsHandEditLimit(grabbed, e.altKey, null)) + return { kind: "block", intent: "edit-many", rect }; return { kind: "move", rect }; } @@ -135,7 +136,7 @@ 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)) { + if (exceedsHandEditLimit(el, e.altKey, edge)) { blockedClipRef.current = { pointerId: e.pointerId, element: el, diff --git a/packages/studio/src/player/components/timelineEditing.ts b/packages/studio/src/player/components/timelineEditing.ts index 620d71fce6f..dc57741044e 100644 --- a/packages/studio/src/player/components/timelineEditing.ts +++ b/packages/studio/src/player/components/timelineEditing.ts @@ -250,7 +250,6 @@ export interface TimelinePromptElement { export type BlockedTimelineEditIntent = "move" | "edit-many" | "resize-start" | "resize-end"; -/** Most clips a hand drag moves or resizes at once; a larger selection goes through the prompt box. */ export const MAX_HAND_EDIT_CLIPS = 3; export interface TimelineRangeSelection { diff --git a/packages/studio/src/player/components/timelineLinkSelection.ts b/packages/studio/src/player/components/timelineLinkSelection.ts index b93fe715e70..ba989b27ecb 100644 --- a/packages/studio/src/player/components/timelineLinkSelection.ts +++ b/packages/studio/src/player/components/timelineLinkSelection.ts @@ -1,5 +1,12 @@ import { usePlayerStore, type TimelineElement } from "../store/playerStore"; -import { expandToLinkedMembers, linkedGestureKeys, linkedMembersOf } from "./audioClipLink"; +import { + dropMisalignedTrimPartners, + expandToLinkedMembers, + linkedGestureKeys, + linkedMembersOf, +} from "./audioClipLink"; +import { buildTimelineGroupResizeMembers } from "./timelineGroupEditing"; +import { resolveGroupMovers } from "./timelineMultiDragPreview"; import { MAX_HAND_EDIT_CLIPS } from "./timelineEditing"; import { isLinkedSelectionOn } from "../../utils/linkedClipPreferences"; @@ -41,15 +48,28 @@ export function toggleClipWithLinks(key: string, altKey: boolean): TimelineEleme return state.elements.find((el) => (el.key ?? el.id) === primary) ?? null; } -/** Whether grabbing `grabbed` would move or resize more clips by hand than a hand drag allows. */ -export function exceedsHandEditLimit(grabbed: TimelineElement, altKey: boolean): boolean { +/** Whether a hand drag grabbing `grabbed` (trimming `edge`, or null for a 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 moved = linkedGestureKeys( + const grabbedKey = grabbed.key ?? grabbed.id; + const keys = linkedGestureKeys( selectedElementIds, grabbed, elements, altKey, isLinkedSelectionOn(), ); - return moved.size > MAX_HAND_EDIT_CLIPS; + 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/useTimelineClipDrag.ts b/packages/studio/src/player/components/useTimelineClipDrag.ts index 7a80ee042bd..3ae3516c87e 100644 --- a/packages/studio/src/player/components/useTimelineClipDrag.ts +++ b/packages/studio/src/player/components/useTimelineClipDrag.ts @@ -538,7 +538,7 @@ export function useTimelineClipDrag({ if (!element || !getClipCapabilities(element).canMove) return; event.preventDefault(); event.stopImmediatePropagation(); - if (exceedsHandEditLimit(element, false)) + if (exceedsHandEditLimit(element, false, null)) return void onBlockedEditAttemptRef.current?.(element, "edit-many"); setShowPopover(false); setRangeSelectionRef.current?.(null); From 2672b6ff1afc60d4a6e1823f96b744f7b342d264 Mon Sep 17 00:00:00 2001 From: Miguel Angel Simon Sierra Date: Sat, 3 Oct 2026 00:20:15 -0700 Subject: [PATCH 10/12] fix(studio): clear fallow audit and comment length on the multi-select cap --- packages/studio/package.json | 1 + .../src/hooks/useTimelineDeleteOps.test.tsx | 35 +++++++------------ .../components/timelineLinkSelection.ts | 2 +- .../tests/e2e/timeline-bulk-actions.mjs | 2 ++ 4 files changed, 17 insertions(+), 23 deletions(-) diff --git a/packages/studio/package.json b/packages/studio/package.json index a0ae62f6291..45cafca81ca 100644 --- a/packages/studio/package.json +++ b/packages/studio/package.json @@ -79,6 +79,7 @@ "test:filmstrip-controls": "node tests/e2e/filmstrip-controls.mjs", "test:webmcp-edit-loop": "node tests/e2e/webmcp-edit-loop.mjs", "test:thumbnail-save": "node tests/e2e/thumbnail-save.mjs", + "bench:timeline-bulk-actions": "node tests/e2e/timeline-bulk-actions.mjs", "test:timeline-virtualization": "TIMELINE_ROW_VIRTUALIZATION=on TIMELINE_ELEMENT_COUNT=50000 node tests/e2e/timeline-virtualization.mjs", "test:watch": "vitest", "test:colors:browser": "node tests/e2e/native-css-colors.mjs", diff --git a/packages/studio/src/hooks/useTimelineDeleteOps.test.tsx b/packages/studio/src/hooks/useTimelineDeleteOps.test.tsx index 6d1a783ea4c..df155ebfab2 100644 --- a/packages/studio/src/hooks/useTimelineDeleteOps.test.tsx +++ b/packages/studio/src/hooks/useTimelineDeleteOps.test.tsx @@ -28,6 +28,17 @@ describe("applyRippleShifts", () => { }); }); +function stubRemoveElementsFetch(current: string, afterRemoval: string) { + vi.stubGlobal( + "fetch", + vi.fn(async (input: RequestInfo | URL) => { + const isRemoval = String(input).includes("/file-mutations/remove-elements/"); + const content = isRemoval ? afterRemoval : current; + return new Response(JSON.stringify({ changed: isRemoval, content }), { status: 200 }); + }), + ); +} + describe("useTimelineDeleteOps: ripple undo label", () => { const html = `
@@ -38,16 +49,7 @@ describe("useTimelineDeleteOps: ripple undo label", () => { `; beforeEach(() => { - vi.stubGlobal( - "fetch", - vi.fn(async (input: RequestInfo | URL) => { - const url = String(input); - if (url.includes("/file-mutations/remove-elements/")) { - return new Response(JSON.stringify({ changed: true, content: html }), { status: 200 }); - } - return new Response(JSON.stringify({ content: html }), { status: 200 }); - }), - ); + stubRemoveElementsFetch(html, html); }); afterEach(() => { @@ -179,18 +181,7 @@ describe("useTimelineDeleteOps: undo race", () => { `; beforeEach(() => { - vi.stubGlobal( - "fetch", - vi.fn(async (input: RequestInfo | URL) => { - const url = String(input); - if (url.includes("/file-mutations/remove-elements/")) { - return new Response(JSON.stringify({ changed: true, content: htmlAfterDeletingC }), { - status: 200, - }); - } - return new Response(JSON.stringify({ content: html }), { status: 200 }); - }), - ); + stubRemoveElementsFetch(html, htmlAfterDeletingC); }); afterEach(() => { diff --git a/packages/studio/src/player/components/timelineLinkSelection.ts b/packages/studio/src/player/components/timelineLinkSelection.ts index ba989b27ecb..3b8ea614392 100644 --- a/packages/studio/src/player/components/timelineLinkSelection.ts +++ b/packages/studio/src/player/components/timelineLinkSelection.ts @@ -48,7 +48,7 @@ export function toggleClipWithLinks(key: string, altKey: boolean): TimelineEleme return state.elements.find((el) => (el.key ?? el.id) === primary) ?? null; } -/** Whether a hand drag grabbing `grabbed` (trimming `edge`, or null for a move) would change more clips than allowed. */ +/** 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, diff --git a/packages/studio/tests/e2e/timeline-bulk-actions.mjs b/packages/studio/tests/e2e/timeline-bulk-actions.mjs index d171860d5c0..5e38b4a5ded 100644 --- a/packages/studio/tests/e2e/timeline-bulk-actions.mjs +++ b/packages/studio/tests/e2e/timeline-bulk-actions.mjs @@ -145,6 +145,7 @@ const requestKind = (url) => * Runs `action` (which returns the page time it considers done) and returns ms since its start. * BULK_PROFILE=1 also prints the CPU profile and a request summary of just that action to stderr. */ +// fallow-ignore-next-line complexity async function measure(page, name, action) { const profile = Boolean(process.env.BULK_PROFILE); const cdp = profile ? await page.createCDPSession() : null; @@ -179,6 +180,7 @@ async function measure(page, name, action) { }; } +// fallow-ignore-next-line complexity function printProfile(name, cpu, requests) { const self = new Map(); const byId = new Map(cpu.nodes.map((n) => [n.id, n])); From 2eeb8d6af419c4ed1d62c8af326eee8a9c717b47 Mon Sep 17 00:00:00 2001 From: Miguel Angel Simon Sierra Date: Sat, 3 Oct 2026 00:21:38 -0700 Subject: [PATCH 11/12] fix(studio): keep bench script comments under the block limit --- packages/studio/tests/e2e/timeline-bulk-actions.mjs | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/packages/studio/tests/e2e/timeline-bulk-actions.mjs b/packages/studio/tests/e2e/timeline-bulk-actions.mjs index 5e38b4a5ded..4845c52e2e7 100644 --- a/packages/studio/tests/e2e/timeline-bulk-actions.mjs +++ b/packages/studio/tests/e2e/timeline-bulk-actions.mjs @@ -141,10 +141,8 @@ const requestKind = (url) => .slice(0, 2) .join("/"); -/** - * Runs `action` (which returns the page time it considers done) and returns ms since its start. - * BULK_PROFILE=1 also prints the CPU profile and a request summary of just that action to stderr. - */ +// 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 complexity async function measure(page, name, action) { const profile = Boolean(process.env.BULK_PROFILE); From 77ac21f0b615ecd79596f1631812df34c3c43ce1 Mon Sep 17 00:00:00 2001 From: Miguel Angel Simon Sierra Date: Sat, 3 Oct 2026 00:48:57 -0700 Subject: [PATCH 12/12] fix(studio): keep the failed file's payload when another file's snapshot delete fails --- .../useExternalFileChangeCoordinator.test.tsx | 23 +++++++++++++++++++ .../hooks/useExternalFileChangeCoordinator.ts | 7 +++++- 2 files changed, 29 insertions(+), 1 deletion(-) diff --git a/packages/studio/src/hooks/useExternalFileChangeCoordinator.test.tsx b/packages/studio/src/hooks/useExternalFileChangeCoordinator.test.tsx index f6b52d39b07..3215bb56991 100644 --- a/packages/studio/src/hooks/useExternalFileChangeCoordinator.test.tsx +++ b/packages/studio/src/hooks/useExternalFileChangeCoordinator.test.tsx @@ -412,6 +412,29 @@ describe("external file change coordinator", () => { expect(onAcceptedPersistedFileChange).toHaveBeenCalledOnce(); }); + it("keeps the failed file's payload when a snapshot delete fails for another file", async () => { + const { captured } = await mountCoordinator({ + drainPendingChanges: vi + .fn() + .mockResolvedValueOnce({ status: "failed" as const, error: new Error("offline") }) + .mockResolvedValueOnce({ status: "clean" as const }), + getPendingCandidate: () => ({ path: "scene.html", content: "studio" }), + deleteConflictSnapshot: vi.fn(async () => { + throw new Error("delete failed"); + }), + }); + await act(async () => + handler?.({ path: "scene.html", content: "scene-external", version: "s1" }), + ); + await act(async () => + handler?.({ path: "index.html", content: "index-external", version: "i1" }), + ); + expect(captured.handle?.blocked).toMatchObject({ + status: "failed", + payload: { path: "scene.html", content: "scene-external", version: "s1" }, + }); + }); + it("restores and overwrites from a durable failed draft", async () => { const overwriteConflict = vi.fn(async () => undefined); const onAcceptedPersistedFileChange = vi.fn(); diff --git a/packages/studio/src/hooks/useExternalFileChangeCoordinator.ts b/packages/studio/src/hooks/useExternalFileChangeCoordinator.ts index a68ce8b40cd..0ab33dc30fe 100644 --- a/packages/studio/src/hooks/useExternalFileChangeCoordinator.ts +++ b/packages/studio/src/hooks/useExternalFileChangeCoordinator.ts @@ -284,7 +284,12 @@ export function useExternalFileChangeCoordinator({ await deleteConflictSnapshot(projectId!, path); } catch (error) { if (mountedRef.current && generation === generationRef.current) { - setBlocked({ ...previousBlocked, generation, error, payload }); + setBlocked({ + ...previousBlocked, + generation, + error, + payload: mergeFileChangeAffectedCompositions(payload, previousBlocked.payload), + }); } return; }