Skip to content

Write HTML. Render video. Built for agents.

perf(studio): keep timeline bulk actions under a second, hand-move at most 3 clips (#4932)

Miguel Ángel70dde41b5c83
diff --git a/packages/studio-server/src/helpers/compositionInputs.test.ts b/packages/studio-server/src/helpers/compositionInputs.test.ts
index 4a12f1233c..c2cdcfd4a4 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,57 @@ describe("compositionsAffectedBy", () => {
]);
});
});
+
+describe("a root write", () => {
+ const html = (head: string, body: string) =>
+ `<html><head>${head}</head><body>${body}${mount("compositions/a.html")}</body></html>`;
+ const files = (head: string, body: string) => ({
+ "index.html": html(head, body),
+ "compositions/a.html": "<template>a</template>",
+ });
+ 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("<style>a{}</style>", "x"));
+ expect(compositionsAffectedBy(dir, "index.html")).toBeNull();
+
+ compositionInputSignature(dir, "compositions/a.html", "s1");
+ rewrite(dir, "<style>b{}</style>", "x");
+ expect(compositionsAffectedBy(dir, "index.html")).toBeNull();
+ });
+
+ it("moves only the root when the head is as it was", () => {
+ const dir = project(files("<style>a{}</style>", "x"));
+ compositionInputSignature(dir, "compositions/a.html", "s1");
+ rewrite(dir, "<style>a{}</style>", "moved");
+ expect(compositionsAffectedBy(dir, "index.html")).toEqual(["index.html"]);
+ rewrite(dir, "<style>a{}</style>", "moved again");
+ 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("<style>a{}</style>", "x"));
+ compositionInputSignature(dir, "compositions/a.html", "s1");
+ rewrite(dir, "<style>b{}</style>", "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("<style>a{}</style>", "x"));
+ const before = compositionInputSignature(dir, "compositions/a.html", "s1");
+ rewrite(dir, "<style>a{}</style>", "moved");
+ expect(compositionInputSignature(dir, "compositions/a.html", "s2")).toBe(before);
+ rewrite(dir, "<style>b{}</style>", "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("<style>a{}</style>", "x"));
+ const before = compositionInputSignature(dir, "index.html", "s1");
+ rewrite(dir, "<style>a{}</style>", "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 7075afe0ab..8ca9ee1da7 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,23 @@ function closureOf(read: SourceReader, compPath: string): Set<string> {
// composition) ever thumbnailed, never evicted; LRU them if a server ever holds thousands.
const inputSignatures = new Map<string, { projectSignature: string; inputSignature: string }>();
+interface RootMemo {
+ root: string;
+ head: string;
+ affected: string[] | null;
+}
+
+const rootMemos = new Map<string, RootMemo>();
+
+const sha1 = (text: string) => createHash("sha1").update(text).digest("hex");
+
+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
-// mounts that `compPath` does not. The root always counts (previews use its head).
+// mounts that `compPath` does not; for a scene the root counts as its head alone.
export function compositionInputSignature(
projectDir: string,
compPath: string,
@@ -62,21 +79,40 @@ 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)),
+ );
+ let inputSignature: string;
+ if (comp === ROOT_COMPOSITION) {
+ 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}`;
+ }
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 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, "/");
const read = projectReader(projectDir);
+ if (changed === ROOT_COMPOSITION) {
+ 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 (changed === ROOT_COMPOSITION || !mounted.has(changed)) return 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 bed0d7ec21..d5bbecd55d 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 = `<!doctype html><html><body><div data-composition-id="main"><div id="parent"><span id="child"></span></div><div id="a"></div><div id="b"></div><div id="keep"></div></div></body></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 = `<!doctype html><html><body><div data-composition-id="main"><img id="photo" src="asset.png" /><div id="rest"></div></div></body></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, true, false]);
+ });
+
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 ccf8216846..a5b90e1188 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 937bf082da..ba4cc14e28 100644
--- a/packages/studio-server/src/helpers/subComposition.ts
+++ b/packages/studio-server/src/helpers/subComposition.ts
@@ -236,6 +236,10 @@ function tagRootCompositionFile(bodyHtml: string, compPath: string): string {
);
}
+export function rootHeadContent(rootHtml: string): string {
+ return rootHtml.match(/<head[^>]*>([\s\S]*?)<\/head>/i)?.[1] ?? "";
+}
+
/**
* Build a standalone HTML page for a sub-composition.
*
@@ -318,11 +322,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(/<head[^>]*>([\s\S]*?)<\/head>/i);
- headContent = headMatch?.[1] ?? "";
- }
+ if (existsSync(indexPath)) headContent = rootHeadContent(readFileSync(indexPath, "utf-8"));
// Inject <base> 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 de2deb0c7c..c8e02c8718 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("</template>", "<!-- edited --></template>"),
+ );
+ 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 = `<!DOCTYPE html><html><body data-duration="3">
<div id="box" data-start="0" data-duration="3" style="opacity:0"></div>
diff --git a/packages/studio-server/src/routes/files.ts b/packages/studio-server/src/routes/files.ts
index 6dcafa22db..9202fd74fa 100644
--- a/packages/studio-server/src/routes/files.ts
+++ b/packages/studio-server/src/routes/files.ts
@@ -81,8 +81,10 @@ import {
} from "@hyperframes/parsers/gsap-writer-acorn";
import {
removeElementFromHtml,
+ removeElementsFromHtml,
patchElementInHtml,
probeElementInSource,
+ probeElementsInSource,
splitElementInHtml,
relinkSplitHalvesInHtml,
wrapElementsInHtml,
@@ -2802,15 +2804,16 @@ 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.
- let next = originalContent;
- for (const target of targets) {
- next = removeElementFromHtml(next, target);
- }
- return writeIfChanged(c, ctx.project.dir, ctx.filePath, ctx.absPath, originalContent, next);
+ // 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,
+ ctx.filePath,
+ ctx.absPath,
+ originalContent,
+ removeElementsFromHtml(originalContent, targets),
+ );
});
api.post("/projects/:id/file-mutations/split-batch", async (c) => {
@@ -3309,6 +3312,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) => {
@@ -3419,19 +3438,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 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).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 });
+
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/package.json b/packages/studio/package.json
index 6c6877b6cd..6fc2d4016c 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/components/editor/manualEdits.ts b/packages/studio/src/components/editor/manualEdits.ts
index 031aae549d..190027ad84 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 99e0a9afa3..f2964d6910 100644
--- a/packages/studio/src/components/editor/manualEditsParsing.ts
+++ b/packages/studio/src/components/editor/manualEditsParsing.ts
@@ -43,3 +43,10 @@ export function readFileChangeAffectedCompositions(payload: unknown): readonly s
if (!Array.isArray(value) || !value.every((path) => typeof path === "string")) return null;
return value.map(normalizeStudioFileChangePath);
}
+
+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/components/editor/probeSourceElement.test.ts b/packages/studio/src/components/editor/probeSourceElement.test.ts
new file mode 100644
index 0000000000..ccdcfb4393
--- /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 32d56496e3..4312e2becb 100644
--- a/packages/studio/src/components/editor/probeSourceElement.ts
+++ b/packages/studio/src/components/editor/probeSourceElement.ts
@@ -1,29 +1,53 @@
import { buildProjectApiPath } from "../../utils/projectRouting";
-export async function probeSourceElement(
- projectId: string,
- sourceFile: string,
- target: { id?: string; hfId?: string; selector?: string; selectorIndex?: number },
-): Promise<boolean> {
+type ProbeTarget = { id?: string; hfId?: string; selector?: string; selectorIndex?: number };
+
+interface PendingProbe {
+ target: ProbeTarget;
+ resolve: (exists: boolean) => void;
+}
+
+const pending = new Map<string, PendingProbe[]>();
+
+async function sendBatch(projectId: string, sourceFile: string, probes: PendingProbe[]) {
+ 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;
+ }
+ } catch {}
+ probes.forEach((probe, index) => probe.resolve(exists[index] !== false));
+}
+
+export function probeSourceElement(
+ projectId: string,
+ sourceFile: string,
+ target: ProbeTarget,
+): Promise<boolean> {
+ return new Promise((resolve) => {
+ const key = `${projectId}\0${sourceFile}`;
+ let probes = pending.get(key);
+ if (!probes) {
+ const batch: PendingProbe[] = [];
+ probes = batch;
+ pending.set(key, batch);
+ setTimeout(() => {
+ pending.delete(key);
+ void sendBatch(projectId, sourceFile, batch);
+ }, 0);
}
- return true;
- } catch {
- return true;
- }
+ probes.push({ target, resolve });
+ });
}
diff --git a/packages/studio/src/hooks/keyframeCacheAstLoad.ts b/packages/studio/src/hooks/keyframeCacheAstLoad.ts
index 9bafb53adf..d36b0a3b34 100644
--- a/packages/studio/src/hooks/keyframeCacheAstLoad.ts
+++ b/packages/studio/src/hooks/keyframeCacheAstLoad.ts
@@ -81,9 +81,9 @@ 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; an unchanged file answers 304. No per-call timestamp
+ // (a deterministic-render no-no).
+ { cache: "no-cache" },
);
if (!res.ok) return null;
const parsed: unknown = await res.json();
@@ -106,9 +106,9 @@ export async function populateKeyframeCacheFromAst(
projectId: string,
sf: string,
doc: Document | null | undefined,
-): Promise<void> {
+): Promise<boolean> {
const parsed = await fetchParsedAnimations(projectId, sf);
- if (!parsed) return;
+ if (!parsed) return false;
const { elements, domClipChildren } = usePlayerStore.getState();
const mergedByElement = new Map<string, GsapKeyframesData<MergeableKeyframe>>();
const sourceByElement = new Map<string, GsapAnimation[]>();
@@ -136,4 +136,5 @@ export async function populateKeyframeCacheFromAst(
}
}
replaceKeyframeCacheForFile(sf, mergedByElement, sourceByElement);
+ return true;
}
diff --git a/packages/studio/src/hooks/useBlockedTimelineEditToast.ts b/packages/studio/src/hooks/useBlockedTimelineEditToast.ts
index 0ad69388da..5bbd4d4f06 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_EDIT_CLIPS,
+ type BlockedTimelineEditIntent,
+} from "../player/components/timelineEditing";
const BLOCKED_TOAST_INTERVAL_MS = 1500;
export function useBlockedTimelineEditToast(
showToast: (message: string, tone?: "info" | "error") => void,
-): (element: TimelineElement) => 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 === "edit-many"
+ ? `Select ${MAX_HAND_EDIT_CLIPS} or fewer clips to move or resize by hand, or describe the change.`
+ : "This clip can't be moved or resized from the timeline yet.",
+ "info",
+ );
},
[showToast],
);
diff --git a/packages/studio/src/hooks/useExternalFileChangeCoordinator.test.tsx b/packages/studio/src/hooks/useExternalFileChangeCoordinator.test.tsx
index ce42ce6b00..3215bb5699 100644
--- a/packages/studio/src/hooks/useExternalFileChangeCoordinator.test.tsx
+++ b/packages/studio/src/hooks/useExternalFileChangeCoordinator.test.tsx
@@ -143,6 +143,85 @@ 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<void>((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("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("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 });
@@ -333,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 fc148c9a2b..0ab33dc30f 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,
@@ -163,7 +164,7 @@ export function useExternalFileChangeCoordinator({
onAcceptedPersistedFileChange,
refreshFileTree,
}: ExternalFileChangeCoordinatorOptions): ExternalFileChangeCoordinatorHandle {
- const [blocked, setBlocked] = useState<ExternalFileChangeBlockedState | null>(null);
+ const [blocked, setBlockedState] = useState<ExternalFileChangeBlockedState | null>(null);
const generationRef = useRef(0);
const mountedRef = useRef(true);
const lastEventIdentityRef = useRef<string | null>(null);
@@ -172,6 +173,14 @@ 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) => {
+ setBlockedState((held) =>
+ next && held
+ ? { ...next, payload: mergeFileChangeAffectedCompositions(held.payload, next.payload) }
+ : next,
+ );
+ }, []);
useEffect(() => {
mountedRef.current = true;
@@ -185,7 +194,7 @@ export function useExternalFileChangeCoordinator({
generationRef.current += 1;
setBlocked(null);
lastEventIdentityRef.current = null;
- }, [projectId, activeCompPath]);
+ }, [projectId, activeCompPath, setBlocked]);
useEffect(() => {
if (!projectId || !recoveryFilePath || !loadConflictSnapshot) return;
@@ -229,7 +238,7 @@ export function useExternalFileChangeCoordinator({
return () => {
cancelled = true;
};
- }, [loadConflictSnapshot, projectId, recoveryFilePath]);
+ }, [loadConflictSnapshot, projectId, recoveryFilePath, setBlocked]);
const reloadAcceptedGeneration = useCallback(
(path: string, affectsPreview = true) => {
@@ -275,14 +284,22 @@ export function useExternalFileChangeCoordinator({
await deleteConflictSnapshot(projectId!, path);
} catch (error) {
if (mountedRef.current && generation === generationRef.current) {
- setBlocked({ ...previousBlocked, generation, error });
+ setBlocked({
+ ...previousBlocked,
+ generation,
+ error,
+ payload: mergeFileChangeAffectedCompositions(payload, previousBlocked.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;
}
@@ -344,6 +361,7 @@ export function useExternalFileChangeCoordinator({
},
[
drainPendingChanges,
+ setBlocked,
projectId,
deleteConflictSnapshot,
getPendingCandidate,
@@ -419,7 +437,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],
@@ -469,6 +492,7 @@ export function useExternalFileChangeCoordinator({
},
[
deleteConflictSnapshot,
+ setBlocked,
discardPendingChanges,
onUseExternalFile,
onAcceptedPersistedFileChange,
@@ -527,6 +551,7 @@ export function useExternalFileChangeCoordinator({
reloadAcceptedGeneration(conflict.filePath);
}, [
deleteConflictSnapshot,
+ setBlocked,
discardPendingChanges,
overwriteConflict,
projectId,
diff --git a/packages/studio/src/hooks/useGsapTweenCache.ts b/packages/studio/src/hooks/useGsapTweenCache.ts
index e7862869fe..da976f7b96 100644
--- a/packages/studio/src/hooks/useGsapTweenCache.ts
+++ b/packages/studio/src/hooks/useGsapTweenCache.ts
@@ -290,17 +290,15 @@ export function usePopulateKeyframeCacheForFile(
const domClipChildrenKey = usePlayerStore((s) =>
s.domClipChildren.map((c) => `${c.id}<${c.hostId}`).join("|"),
);
- const lastFetchKeyRef = useRef("");
+ const loadedRef = useRef<{ dataKey: string; files: Set<string> }>({
+ 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 +307,21 @@ 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;
+ 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;
- });
+ if (!sameData) pruneKeyframeCacheToFiles(files);
+ if (stale.length === 0) return;
+ runtimeScanDoneRef.current = "";
+ const doc = iframeRef?.current?.contentDocument;
+ for (const sf of stale) {
+ void populateKeyframeCacheFromAst(projectId, sf, doc).then((loaded) => {
+ 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 114a72a616..4d08b1ed8d 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,78 @@ 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(<HookHost {...props} />);
+ });
+ 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);
+ });
+
+ 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(<HookHost sourceFile={sourceFile} />);
+ });
+ 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);
+ });
});
diff --git a/packages/studio/src/hooks/useTimelineDeleteOps.test.tsx b/packages/studio/src/hooks/useTimelineDeleteOps.test.tsx
index 8bef8f57e0..df155ebfab 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 = `<!DOCTYPE html><html data-composition-variables='[]'><body>
<div data-hf-id="hf-stage" data-hf-root data-duration="6">
@@ -38,16 +49,7 @@ describe("useTimelineDeleteOps: ripple undo label", () => {
</body></html>`;
beforeEach(() => {
- vi.stubGlobal(
- "fetch",
- vi.fn(async (input: RequestInfo | URL) => {
- const url = String(input);
- if (url.includes("/file-mutations/remove-element/")) {
- return new Response(JSON.stringify({ changed: true, content: html }), { status: 200 });
- }
- return new Response(JSON.stringify({ content: html }), { status: 200 });
- }),
- );
+ stubRemoveElementsFetch(html, html);
});
afterEach(() => {
@@ -118,6 +120,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();
@@ -162,18 +181,7 @@ describe("useTimelineDeleteOps: undo race", () => {
</body></html>`;
beforeEach(() => {
- vi.stubGlobal(
- "fetch",
- vi.fn(async (input: RequestInfo | URL) => {
- const url = String(input);
- if (url.includes("/file-mutations/remove-element/")) {
- 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/hooks/useTimelineDeleteOps.ts b/packages/studio/src/hooks/useTimelineDeleteOps.ts
index 79ec4baee7..b4ff3bec82 100644
--- a/packages/studio/src/hooks/useTimelineDeleteOps.ts
+++ b/packages/studio/src/hooks/useTimelineDeleteOps.ts
@@ -121,38 +121,32 @@ 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 { 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 d6c933d547..65bdd3dcc6 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 eec421f1a0..096d68c180 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 === "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
new file mode 100644
index 0000000000..1e9a732b51
--- /dev/null
+++ b/packages/studio/src/player/components/timelineClipGestureHandlers.test.ts
@@ -0,0 +1,94 @@
+// @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_EDIT_CLIPS } from "./timelineEditing";
+
+afterEach(() => usePlayerStore.getState().reset());
+
+const clips: TimelineElement[] = Array.from({ length: 6 }, (_, i) => ({
+ id: `clip-${i}`,
+ domId: `clip-${i}`,
+ tag: "div",
+ start: i,
+ duration: 1,
+ track: i,
+}));
+const capabilities = { canMove: true, canTrimStart: true, canTrimEnd: true, readOnly: false };
+
+function grabFirstClip(count: number, gesture: "move" | "resize", locked: number[] = []) {
+ const store = usePlayerStore.getState();
+ 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();
+ 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,
+ setDraggedClip,
+ setSelectedElementId: vi.fn(),
+ } as unknown as ClipGestureDeps;
+ 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;
+ if (gesture === "move") handlers.onPointerDown(event);
+ else handlers.onResizeStart("end", event);
+ return { setDraggedClip, setResizingClip, blockedClipRef };
+}
+
+describe("hand-editing a multi-selection", () => {
+ it("moves up to the limit by hand", () => {
+ 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 } = grabFirstClip(MAX_HAND_EDIT_CLIPS + 1, "move");
+ expect(setDraggedClip).not.toHaveBeenCalled();
+ expect(blockedClipRef.current?.intent).toBe("edit-many");
+ });
+
+ it("resizes up to the limit by hand", () => {
+ const { setResizingClip, blockedClipRef } = grabFirstClip(MAX_HAND_EDIT_CLIPS, "resize");
+ expect(setResizingClip).toHaveBeenCalledOnce();
+ expect(blockedClipRef.current).toBeNull();
+ });
+
+ it("refuses to start a resize above the limit and asks for the toast", () => {
+ const { setResizingClip, blockedClipRef } = grabFirstClip(MAX_HAND_EDIT_CLIPS + 1, "resize");
+ expect(setResizingClip).not.toHaveBeenCalled();
+ expect(blockedClipRef.current?.intent).toBe("edit-many");
+ });
+
+ it("counts the clips a move would change: locked ones in the selection stay put", () => {
+ const allowed = grabFirstClip(MAX_HAND_EDIT_CLIPS + 2, "move", [3, 4]);
+ expect(allowed.setDraggedClip).toHaveBeenCalledOnce();
+ const refused = grabFirstClip(MAX_HAND_EDIT_CLIPS + 2, "move", [4]);
+ expect(refused.setDraggedClip).not.toHaveBeenCalled();
+ });
+
+ it("counts the clips a trim would change: a locked member leaves a trim of the grabbed clip alone", () => {
+ const allowed = grabFirstClip(MAX_HAND_EDIT_CLIPS + 1, "resize", [3]);
+ expect(allowed.setResizingClip).toHaveBeenCalledOnce();
+ expect(allowed.blockedClipRef.current).toBeNull();
+ });
+});
diff --git a/packages/studio/src/player/components/timelineClipGestureHandlers.ts b/packages/studio/src/player/components/timelineClipGestureHandlers.ts
index 4d69d460fb..29ffd28bdb 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 {
+ exceedsHandEditLimit,
+ 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,8 @@ function resolvePointerDownAction(
}
if (!onMoveElement || !capabilities.canMove) return { kind: "ignore" };
+ if (exceedsHandEditLimit(grabbed, e.altKey, null))
+ return { kind: "block", intent: "edit-many", rect };
return { kind: "move", rect };
}
@@ -129,6 +136,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, edge)) {
+ blockedClipRef.current = {
+ pointerId: e.pointerId,
+ element: el,
+ intent: "edit-many",
+ originClientX: e.clientX,
+ originClientY: e.clientY,
+ started: false,
+ };
+ return;
+ }
blockedClipRef.current = null;
setShowPopover(false);
setRangeSelection(null);
@@ -147,7 +165,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 e6cea2885a..dc57741044 100644
--- a/packages/studio/src/player/components/timelineEditing.ts
+++ b/packages/studio/src/player/components/timelineEditing.ts
@@ -248,7 +248,9 @@ export interface TimelinePromptElement {
track: number;
}
-export type BlockedTimelineEditIntent = "move" | "resize-start" | "resize-end";
+export type BlockedTimelineEditIntent = "move" | "edit-many" | "resize-start" | "resize-end";
+
+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 3d5db3de61..3b8ea61439 100644
--- a/packages/studio/src/player/components/timelineLinkSelection.ts
+++ b/packages/studio/src/player/components/timelineLinkSelection.ts
@@ -1,5 +1,13 @@
import { usePlayerStore, type TimelineElement } from "../store/playerStore";
-import { expandToLinkedMembers, 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";
/**
@@ -39,3 +47,29 @@ 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 a hand drag on `grabbed` (trimming `edge`, or null to move) would change more clips than allowed. */
+export function exceedsHandEditLimit(
+ grabbed: TimelineElement,
+ altKey: boolean,
+ edge: "start" | "end" | null,
+): boolean {
+ const { selectedElementIds, elements } = usePlayerStore.getState();
+ const grabbedKey = grabbed.key ?? grabbed.id;
+ const keys = linkedGestureKeys(
+ selectedElementIds,
+ grabbed,
+ elements,
+ altKey,
+ isLinkedSelectionOn(),
+ );
+ const changed = edge
+ ? buildTimelineGroupResizeMembers(
+ elements,
+ dropMisalignedTrimPartners(keys, grabbed, elements, edge),
+ grabbedKey,
+ edge,
+ )
+ : resolveGroupMovers(elements, keys, grabbedKey);
+ return (changed?.length ?? 1) > MAX_HAND_EDIT_CLIPS;
+}
diff --git a/packages/studio/src/player/components/useTimelineClipDrag.keyboard.test.tsx b/packages/studio/src/player/components/useTimelineClipDrag.keyboard.test.tsx
index 5c3587f98e..9b338a7f85 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<typeof useTimelineClipDrag>;
@@ -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" }),
+ "edit-many",
+ );
+});
diff --git a/packages/studio/src/player/components/useTimelineClipDrag.ts b/packages/studio/src/player/components/useTimelineClipDrag.ts
index 3e4610e7ce..3ae3516c87 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 { exceedsHandEditLimit } from "./timelineLinkSelection";
import { isLinkedSelectionOn } from "../../utils/linkedClipPreferences";
import { useTimelineClipCapabilities } from "./timelineReadOnly";
import { timelineClipFocusId } from "./timelineNavigationIdentity";
@@ -158,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<Map<string, TimelineSnapTarget[]>>(new Map());
const dragAudioTracksRef = useRef<ReadonlySet<number> | null>(null);
@@ -272,8 +270,7 @@ export function useTimelineClipDrag({
const blockedClipRef = useRef<BlockedClipState | null>(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<TimelineGroupResizeSession | null>(null);
const onMoveElementRef = useRef(onMoveElement);
@@ -541,6 +538,8 @@ export function useTimelineClipDrag({
if (!element || !getClipCapabilities(element).canMove) return;
event.preventDefault();
event.stopImmediatePropagation();
+ if (exceedsHandEditLimit(element, false, null))
+ return void onBlockedEditAttemptRef.current?.(element, "edit-many");
setShowPopover(false);
setRangeSelectionRef.current?.(null);
const row = keyboardPickupInsertRow(
diff --git a/packages/studio/tests/e2e/timeline-bulk-actions.mjs b/packages/studio/tests/e2e/timeline-bulk-actions.mjs
new file mode 100644
index 0000000000..4845c52e2e
--- /dev/null
+++ b/packages/studio/tests/e2e/timeline-bulk-actions.mjs
@@ -0,0 +1,341 @@
+#!/usr/bin/env node
+/** Times select-all, move 3 and delete-all in a real browser on a real project; see USAGE. */
+const USAGE = `
+BULK_PROJECT_DIR=<project> 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";
+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.\n${USAGE}`);
+ 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 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/<id>/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` (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);
+ 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,
+ };
+}
+
+// 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]));
+ 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();
+}