Skip to content

Write HTML. Render video. Built for agents.

perf(studio): re-render only the edited scene's thumbnails after an edit (#4315)

Miguel Ángel8cb7d06db66f
diff --git a/packages/cli/src/server/studioServer.ts b/packages/cli/src/server/studioServer.ts
index cdc6c5a313..4ac7c8dec1 100644
--- a/packages/cli/src/server/studioServer.ts
+++ b/packages/cli/src/server/studioServer.ts
@@ -39,6 +39,7 @@ import {
fileContentVersion,
getMimeType,
affectsProjectSignature,
+ compositionsAffectedBy,
type PreviewApiAdapter,
thumbnailDeviceScaleFactor,
type ResolvedProject,
@@ -834,7 +835,14 @@ export function createStudioServer(options: StudioServerOptions): StudioServer {
stream
.writeSSE({
event: "file-change",
- data: JSON.stringify({ path, version, projectId: project.id, ...receipt }),
+ data: JSON.stringify({
+ path,
+ version,
+ projectId: project.id,
+ // Which thumbnails this write can change; null means all of them.
+ affectedCompositions: compositionsAffectedBy(projectDir, path),
+ ...receipt,
+ }),
})
.catch(() => {});
};
diff --git a/packages/studio-server/src/helpers/compositionInputs.test.ts b/packages/studio-server/src/helpers/compositionInputs.test.ts
new file mode 100644
index 0000000000..4a12f1233c
--- /dev/null
+++ b/packages/studio-server/src/helpers/compositionInputs.test.ts
@@ -0,0 +1,59 @@
+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";
+
+const dirs: string[] = [];
+afterEach(() => {
+ for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true });
+});
+
+function project(files: Record<string, string>): string {
+ const dir = mkdtempSync(join(tmpdir(), "hf-composition-inputs-"));
+ dirs.push(dir);
+ for (const [path, content] of Object.entries(files)) {
+ mkdirSync(join(dir, path, ".."), { recursive: true });
+ writeFileSync(join(dir, path), content);
+ }
+ return dir;
+}
+
+const mount = (src: string) => `<div data-composition-src="${src}"></div>`;
+
+describe("compositionsAffectedBy", () => {
+ const dir = () =>
+ project({
+ "index.html": mount("compositions/a.html") + mount("./compositions/b.html"),
+ "compositions/a.html": `<template>${mount("compositions/nested.html")}</template>`,
+ "compositions/b.html": "<template>b</template>",
+ "compositions/nested.html": "<template>nested</template>",
+ "compositions/unmounted.html": "<template>draft</template>",
+ "assets/logo.svg": "<svg/>",
+ });
+
+ it("names a scene and the compositions that mount it, not its siblings", () => {
+ expect(compositionsAffectedBy(dir(), "compositions/b.html")).toEqual([
+ "index.html",
+ "compositions/b.html",
+ ]);
+ expect(compositionsAffectedBy(dir(), "compositions/nested.html")).toEqual([
+ "index.html",
+ "compositions/a.html",
+ "compositions/nested.html",
+ ]);
+ });
+
+ it("reaches every composition from the root, an asset, or a file the root does not mount", () => {
+ expect(compositionsAffectedBy(dir(), "index.html")).toBeNull();
+ expect(compositionsAffectedBy(dir(), "assets/logo.svg")).toBeNull();
+ expect(compositionsAffectedBy(dir(), "compositions/unmounted.html")).toBeNull();
+ });
+
+ it("reads watcher paths with either separator", () => {
+ expect(compositionsAffectedBy(dir(), "compositions\\b.html")).toEqual([
+ "index.html",
+ "compositions/b.html",
+ ]);
+ });
+});
diff --git a/packages/studio-server/src/helpers/compositionInputs.ts b/packages/studio-server/src/helpers/compositionInputs.ts
new file mode 100644
index 0000000000..7075afe0ab
--- /dev/null
+++ b/packages/studio-server/src/helpers/compositionInputs.ts
@@ -0,0 +1,82 @@
+import { readFileSync } from "node:fs";
+import { createProjectSignature } from "./projectSignature.js";
+import { resolveWithinProject } from "./safePath.js";
+
+const ROOT_COMPOSITION = "index.html";
+// A regex, not a parser: a stray match (say, inside a script string) only widens what a
+// change invalidates, never narrows it.
+const COMPOSITION_SRC = /\bdata-composition-src\s*=\s*(["'])(.*?)\1/g;
+
+type SourceReader = (compPath: string) => string | null;
+
+function projectReader(projectDir: string): SourceReader {
+ const sources = new Map<string, string | null>();
+ return (compPath) => {
+ if (!sources.has(compPath)) {
+ const file = resolveWithinProject(projectDir, compPath);
+ let source: string | null = null;
+ try {
+ source = file ? readFileSync(file, "utf-8") : null;
+ } catch {
+ // Missing or unreadable: it mounts nothing, and still counts as mounted by its host.
+ }
+ sources.set(compPath, source);
+ }
+ return sources.get(compPath) ?? null;
+ };
+}
+
+function normalizeSource(src: string): string | null {
+ if (/^[a-z][a-z0-9+.-]*:/i.test(src) || src.startsWith("//")) return null;
+ const path = src.split(/[?#]/)[0]?.replace(/^\.?\//, "") ?? "";
+ return path || null;
+}
+
+/** `compPath` plus every composition it mounts, transitively, resolved from the project root as the bundler does. */
+function closureOf(read: SourceReader, compPath: string): Set<string> {
+ const closure = new Set<string>();
+ const visit = (path: string) => {
+ if (closure.has(path)) return;
+ closure.add(path);
+ for (const match of (read(path) ?? "").matchAll(COMPOSITION_SRC)) {
+ const mounted = normalizeSource(match[2] ?? "");
+ if (mounted) visit(mounted);
+ }
+ };
+ visit(compPath);
+ return closure;
+}
+
+// ponytail: this and projectSignature's per-exclusion cache keep one small entry per (project,
+// composition) ever thumbnailed, never evicted; LRU them if a server ever holds thousands.
+const inputSignatures = new Map<string, { projectSignature: string; inputSignature: string }>();
+
+// 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).
+export function compositionInputSignature(
+ projectDir: string,
+ compPath: string,
+ projectSignature: string,
+): string {
+ const key = `${projectDir}\0${compPath}`;
+ 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));
+ 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.
+ */
+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;
+ return [...mounted].filter((path) => closureOf(read, path).has(changed));
+}
diff --git a/packages/studio-server/src/helpers/projectSignature.ts b/packages/studio-server/src/helpers/projectSignature.ts
index c0a1bd5201..8336919797 100644
--- a/packages/studio-server/src/helpers/projectSignature.ts
+++ b/packages/studio-server/src/helpers/projectSignature.ts
@@ -197,16 +197,28 @@ export async function resolveProjectAndSignature(
/**
* Creates a stable preview cache-busting signature for project source plus Studio manifests.
+ * `excluding` (project-relative paths) leaves those files out.
*/
-export function createProjectSignature(projectDir: string): string {
+export function createProjectSignature(
+ projectDir: string,
+ excluding: ReadonlySet<string> = new Set(),
+): string {
const normalizedProjectDir = resolve(projectDir);
- const files: ProjectSignatureFile[] = [];
- collectProjectSignatureFiles(normalizedProjectDir, normalizedProjectDir, files);
- collectProjectSignatureManifestFiles(normalizedProjectDir, files);
+ const collected: ProjectSignatureFile[] = [];
+ collectProjectSignatureFiles(normalizedProjectDir, normalizedProjectDir, collected);
+ collectProjectSignatureManifestFiles(normalizedProjectDir, collected);
+ const files = collected.filter(
+ (entry) => !excluding.has(relative(normalizedProjectDir, entry.file).split(sep).join("/")),
+ );
files.sort((a, b) => a.file.localeCompare(b.file));
const fingerprint = createProjectFingerprint(normalizedProjectDir, files);
- const cached = projectSignatureCache.get(normalizedProjectDir);
+ const cacheKey = excluding.size
+ ? `${normalizedProjectDir}\0${createHash("sha256")
+ .update([...excluding].sort().join("\0"))
+ .digest("hex")}`
+ : normalizedProjectDir;
+ const cached = projectSignatureCache.get(cacheKey);
if (cached?.fingerprint === fingerprint) return cached.signature;
const hash = createHash("sha256");
@@ -228,6 +240,6 @@ export function createProjectSignature(projectDir: string): string {
hash.update("\0");
}
const signature = hash.digest("hex").slice(0, 24);
- projectSignatureCache.set(normalizedProjectDir, { fingerprint, signature });
+ projectSignatureCache.set(cacheKey, { fingerprint, signature });
return signature;
}
diff --git a/packages/studio-server/src/index.ts b/packages/studio-server/src/index.ts
index 4424cc191a..47567bca87 100644
--- a/packages/studio-server/src/index.ts
+++ b/packages/studio-server/src/index.ts
@@ -1,5 +1,6 @@
export { createStudioApi } from "./createStudioApi.js";
export { createProjectSignature, affectsProjectSignature } from "./helpers/projectSignature.js";
+export { compositionsAffectedBy } from "./helpers/compositionInputs.js";
export type {
StudioApiAdapter,
ResolvedProject,
diff --git a/packages/studio-server/src/routes/thumbnail.test.ts b/packages/studio-server/src/routes/thumbnail.test.ts
index cef84b0c2b..2490495cfc 100644
--- a/packages/studio-server/src/routes/thumbnail.test.ts
+++ b/packages/studio-server/src/routes/thumbnail.test.ts
@@ -4,6 +4,7 @@ import {
existsSync,
mkdirSync,
mkdtempSync,
+ readFileSync,
readdirSync,
rmSync,
truncateSync,
@@ -317,6 +318,54 @@ describe("registerThumbnailRoutes", () => {
expect(adapter.generateThumbnail).toHaveBeenCalledTimes(2);
});
+ function writeTwoScenes(dir: string): { sceneA: string; sceneB: string } {
+ writeFileSync(
+ join(dir, "index.html"),
+ `<head><style>body { margin: 0 }</style></head><div data-width="640" data-height="360">` +
+ `<div data-composition-src="compositions/a.html"></div>` +
+ `<div data-composition-src="compositions/b.html"></div></div>`,
+ );
+ mkdirSync(join(dir, "compositions"), { recursive: true });
+ const sceneA = join(dir, "compositions", "a.html");
+ const sceneB = join(dir, "compositions", "b.html");
+ writeFileSync(sceneA, `<template><div data-composition-id="a">A</div></template>`);
+ writeFileSync(sceneB, `<template><div data-composition-id="b">B</div></template>`);
+ return { sceneA, sceneB };
+ }
+
+ it("keeps a scene's cached thumbnail when a sibling scene changes", async () => {
+ const adapter = createAdapter();
+ const project = await adapter.resolveProject("demo");
+ if (!project) throw new Error("missing project");
+ const app = new Hono();
+ registerThumbnailRoutes(app, adapter);
+ const { sceneA } = writeTwoScenes(project.dir);
+ const url = "http://localhost/projects/demo/thumbnail/compositions/b.html?t=2&v=test";
+
+ await app.request(url);
+ writeFileSync(sceneA, `<template><div data-composition-id="a">A, edited</div></template>`);
+ await app.request(url);
+
+ expect(adapter.generateThumbnail).toHaveBeenCalledTimes(1);
+ });
+
+ it("regenerates a scene thumbnail when the root it is built on changes", async () => {
+ const adapter = createAdapter();
+ const project = await adapter.resolveProject("demo");
+ if (!project) throw new Error("missing project");
+ const app = new Hono();
+ registerThumbnailRoutes(app, adapter);
+ writeTwoScenes(project.dir);
+ const url = "http://localhost/projects/demo/thumbnail/compositions/b.html?t=2&v=test";
+
+ await app.request(url);
+ const root = join(project.dir, "index.html");
+ writeFileSync(root, readFileSync(root, "utf-8").replace("margin: 0", "margin: 4px"));
+ await app.request(url);
+
+ expect(adapter.generateThumbnail).toHaveBeenCalledTimes(2);
+ });
+
it("regenerates a thumbnail when imported CSS changes", async () => {
const adapter = createAdapter();
const project = await adapter.resolveProject("demo");
@@ -365,26 +414,51 @@ describe("registerThumbnailRoutes", () => {
expect(getProjectSignature).toHaveBeenNthCalledWith(1, project.dir);
});
- it("does not cache generated pixels under a signature that changed in flight", async () => {
+ it("does not cache generated pixels when the composition's inputs changed in flight", async () => {
const adapter = createAdapter();
const project = await adapter.resolveProject("demo");
if (!project) throw new Error("missing project");
- const signatures = ["old", "new", "old", "old"];
- adapter.getProjectSignature = vi.fn(() => signatures.shift() ?? "old");
+ const { sceneB } = writeTwoScenes(project.dir);
adapter.generateThumbnail = vi
.fn()
- .mockResolvedValueOnce(Buffer.from("rendered-after-change"))
- .mockResolvedValueOnce(Buffer.from("rendered-old"));
+ .mockImplementationOnce(async () => {
+ writeFileSync(sceneB, `<template><div data-composition-id="b">B, edited</div></template>`);
+ return Buffer.from("rendered-after-change");
+ })
+ .mockResolvedValueOnce(Buffer.from("rendered-current"));
const app = new Hono();
registerThumbnailRoutes(app, adapter);
- const url = "http://localhost/projects/demo/thumbnail/index.html?t=3";
+ const url = "http://localhost/projects/demo/thumbnail/compositions/b.html?t=3";
expect(await (await app.request(url)).text()).toBe("rendered-after-change");
expect(existsSync(join(project.dir, ".thumbnails"))).toBe(false);
- expect(await (await app.request(url)).text()).toBe("rendered-old");
+ expect(await (await app.request(url)).text()).toBe("rendered-current");
expect(adapter.generateThumbnail).toHaveBeenCalledTimes(2);
});
+ it("does not cache pixels changed in flight behind a stale adapter signature", async () => {
+ const adapter = createAdapter();
+ const project = await adapter.resolveProject("demo");
+ if (!project) throw new Error("missing project");
+ const { sceneB } = writeTwoScenes(project.dir);
+ const stale = createProjectSignature(project.dir);
+ adapter.getProjectSignature = () => stale;
+ adapter.generateThumbnail = vi
+ .fn()
+ .mockImplementationOnce(async () => {
+ writeFileSync(sceneB, `<template><div data-composition-id="b">B, edited</div></template>`);
+ return Buffer.from("rendered-after-change");
+ })
+ .mockResolvedValueOnce(Buffer.from("rendered-again"));
+ const app = new Hono();
+ registerThumbnailRoutes(app, adapter);
+ const url = "http://localhost/projects/demo/thumbnail/compositions/b.html?t=3";
+
+ expect(await (await app.request(url)).text()).toBe("rendered-after-change");
+ expect(existsSync(join(project.dir, ".thumbnails"))).toBe(false);
+ expect(await (await app.request(url)).text()).toBe("rendered-again");
+ });
+
it("keeps changed studio motion separated in the disk cache", async () => {
const adapter = createAdapter();
const project = await adapter.resolveProject("demo");
diff --git a/packages/studio-server/src/routes/thumbnail.ts b/packages/studio-server/src/routes/thumbnail.ts
index fd94338cac..68787f0803 100644
--- a/packages/studio-server/src/routes/thumbnail.ts
+++ b/packages/studio-server/src/routes/thumbnail.ts
@@ -14,6 +14,7 @@ import { join } from "node:path";
import { createHash, randomUUID } from "node:crypto";
import type { StudioApiAdapter } from "../types.js";
import { STUDIO_MANUAL_EDITS_PATH } from "../helpers/manualEditsRenderScript.js";
+import { compositionInputSignature } from "../helpers/compositionInputs.js";
import { createProjectSignature, resolveProjectAndSignature } from "../helpers/projectSignature.js";
import { STUDIO_MOTION_PATH } from "../helpers/studioMotionRenderScript.js";
import { thumbnailGenerationCoordinator } from "./thumbnailGenerationCoordinator.js";
@@ -86,6 +87,8 @@ export function registerThumbnailRoutes(api: Hono, adapter: StudioApiAdapter): v
c.req.path.replace(`/projects/${project.id}/thumbnail/`, "").split("?")[0] ?? "",
);
if (compPath && !compPath.includes(".")) compPath += ".html";
+ // Keyed on what this composition renders from, so editing one scene leaves the others cached.
+ const inputSignature = compositionInputSignature(project.dir, compPath, projectSignature);
const url = new URL(c.req.url, `http://${c.req.header("host") || "localhost"}`);
const rawSeekTime = url.searchParams.get("t");
@@ -159,14 +162,14 @@ export function registerThumbnailRoutes(api: Hono, adapter: StudioApiAdapter): v
const urlVersionKey = urlVersion
? `_${urlVersion.replace(/[^a-zA-Z0-9_-]+/g, "_").slice(0, 32)}`
: "";
- const projectSignatureKey = `_${createHash("sha1").update(projectSignature).digest("hex").slice(0, 16)}`;
+ const inputSignatureKey = `_${createHash("sha1").update(inputSignature).digest("hex").slice(0, 16)}`;
const outputScale =
outputMode === "source"
? 1
: Math.min(1, THUMBNAIL_MAX_OUTPUT_WIDTH / compW, THUMBNAIL_MAX_OUTPUT_HEIGHT / compH);
const outputWidth = Math.max(1, Math.round(compW * outputScale));
const outputHeight = Math.max(1, Math.round(compH * outputScale));
- const cacheKey = `${THUMBNAIL_CACHE_VERSION}${urlVersionKey}${projectSignatureKey}${manualEditsKey}${motionKey}${sourceKey}_${format}_${outputMode}_${compPath.replace(/\//g, "_")}_${compW}x${compH}_${outputWidth}x${outputHeight}_${sourceMtime}_${seekTime.toFixed(2)}${selectorKey}.${format === "png" ? "png" : "jpg"}`;
+ const cacheKey = `${THUMBNAIL_CACHE_VERSION}${urlVersionKey}${inputSignatureKey}${manualEditsKey}${motionKey}${sourceKey}_${format}_${outputMode}_${compPath.replace(/\//g, "_")}_${compW}x${compH}_${outputWidth}x${outputHeight}_${sourceMtime}_${seekTime.toFixed(2)}${selectorKey}.${format === "png" ? "png" : "jpg"}`;
const cachePath = join(cacheDir, cacheKey);
if (!prunedCacheDirs.has(cacheDir)) {
prunedCacheDirs.add(cacheDir);
@@ -202,12 +205,13 @@ export function registerThumbnailRoutes(api: Hono, adapter: StudioApiAdapter): v
});
if (!generated) return null;
const afterGeneration = await resolveProjectAndSignature(adapter, project.id);
- const freshSignature = createProjectSignature(project.dir);
+ const inputsUnchanged = (signature: string) =>
+ compositionInputSignature(project.dir, compPath, signature) === inputSignature;
+ // Both the adapter's signature and a fresh one: the adapter's can lag the watcher.
if (
- !afterGeneration ||
- afterGeneration.project.dir !== project.dir ||
- afterGeneration.signature !== projectSignature ||
- freshSignature !== projectSignature
+ afterGeneration?.project.dir !== project.dir ||
+ !inputsUnchanged(afterGeneration.signature) ||
+ !inputsUnchanged(createProjectSignature(project.dir))
) {
// The browser may have rendered content written after this request
// captured its cache identity. Return the pixels to this caller,
diff --git a/packages/studio/src/components/editor/manualEdits.ts b/packages/studio/src/components/editor/manualEdits.ts
index f3c1b140fb..464e451fdb 100644
--- a/packages/studio/src/components/editor/manualEdits.ts
+++ b/packages/studio/src/components/editor/manualEdits.ts
@@ -9,7 +9,11 @@ export {
type StudioPathOffsetSnapshot,
} from "./manualEditsTypes";
-export { readFileChangeField, readStudioFileChangePath } from "./manualEditsParsing";
+export {
+ readFileChangeAffectedCompositions,
+ readFileChangeField,
+ readStudioFileChangePath,
+} from "./manualEditsParsing";
export {
beginStudioManualEditGesture,
diff --git a/packages/studio/src/components/editor/manualEditsParsing.ts b/packages/studio/src/components/editor/manualEditsParsing.ts
index 457cd512c8..e01816d09f 100644
--- a/packages/studio/src/components/editor/manualEditsParsing.ts
+++ b/packages/studio/src/components/editor/manualEditsParsing.ts
@@ -15,15 +15,17 @@ function normalizeStudioFileChangePath(path: string): string {
.replace(/^\.?\//, "");
}
+function asPayloadRecord(payload: unknown): Record<string, unknown> | null {
+ return payload && typeof payload === "object" ? (payload as Record<string, unknown>) : null;
+}
+
/**
* Read one string field out of an ALREADY-DECODED file-change payload. Every
* reader of that payload goes through here, so no reader can disagree with its
* siblings about the shape. Decoding a raw delivery is the transport's job.
*/
export function readFileChangeField(payload: unknown, key: string): string | null {
- if (!payload || typeof payload !== "object") return null;
- const record = payload as Record<string, unknown>;
- const value = record[key];
+ const value = asPayloadRecord(payload)?.[key];
return typeof value === "string" ? value : null;
}
@@ -31,3 +33,13 @@ export function readStudioFileChangePath(payload: unknown): string | null {
const path = readFileChangeField(payload, "path") ?? readFileChangeField(payload, "filePath");
return path === null ? null : normalizeStudioFileChangePath(path);
}
+
+/**
+ * The compositions whose thumbnails a change can alter, or `null` for all of them. Anything
+ * but a list of paths (an older server, the Vite dev host) reads as "all".
+ */
+export function readFileChangeAffectedCompositions(payload: unknown): readonly string[] | null {
+ const value = asPayloadRecord(payload)?.affectedCompositions;
+ if (!Array.isArray(value) || !value.every((path) => typeof path === "string")) return null;
+ return value.map(normalizeStudioFileChangePath);
+}
diff --git a/packages/studio/src/components/sidebar/CompositionsPanel.masterComposition.test.tsx b/packages/studio/src/components/sidebar/CompositionsPanel.masterComposition.test.tsx
index 6f6495d58f..59cc885781 100644
--- a/packages/studio/src/components/sidebar/CompositionsPanel.masterComposition.test.tsx
+++ b/packages/studio/src/components/sidebar/CompositionsPanel.masterComposition.test.tsx
@@ -17,7 +17,7 @@ afterEach(() => {
if (root) act(() => root?.unmount());
root = null;
document.body.innerHTML = "";
- usePlayerStore.setState({ thumbnailContentRevision: 0 });
+ usePlayerStore.setState({ thumbnailRevisions: {} });
});
describe("CompositionsPanel root badge source", () => {
diff --git a/packages/studio/src/components/sidebar/CompositionsTab.drag.test.tsx b/packages/studio/src/components/sidebar/CompositionsTab.drag.test.tsx
index d244167b53..4536a90eb0 100644
--- a/packages/studio/src/components/sidebar/CompositionsTab.drag.test.tsx
+++ b/packages/studio/src/components/sidebar/CompositionsTab.drag.test.tsx
@@ -18,7 +18,7 @@ afterEach(() => {
if (root) act(() => root?.unmount());
root = null;
document.body.innerHTML = "";
- usePlayerStore.setState({ thumbnailContentRevision: 0 });
+ usePlayerStore.setState({ thumbnailRevisions: {} });
});
function mount(onSelect = vi.fn(), onAddToTimeline = vi.fn()) {
@@ -68,7 +68,7 @@ describe("composition card drag", () => {
act(() => thumbnail.dispatchEvent(new Event("error")));
expect(host.textContent).toContain("Preview unavailable");
- act(() => usePlayerStore.getState().bumpThumbnailContentRevision());
+ act(() => usePlayerStore.getState().bumpThumbnailRevisions(null));
const retry = host.querySelector<HTMLImageElement>('img[src*="/thumbnail/"]');
expect(retry).not.toBeNull();
diff --git a/packages/studio/src/components/sidebar/CompositionsTab.rootBadge.test.tsx b/packages/studio/src/components/sidebar/CompositionsTab.rootBadge.test.tsx
index b87ebfbdcb..b0ae5848c0 100644
--- a/packages/studio/src/components/sidebar/CompositionsTab.rootBadge.test.tsx
+++ b/packages/studio/src/components/sidebar/CompositionsTab.rootBadge.test.tsx
@@ -18,7 +18,7 @@ afterEach(() => {
if (root) act(() => root?.unmount());
root = null;
document.body.innerHTML = "";
- usePlayerStore.setState({ thumbnailContentRevision: 0 });
+ usePlayerStore.setState({ thumbnailRevisions: {} });
});
function mount(compositions: string[], masterCompositionPath: string | null) {
diff --git a/packages/studio/src/components/sidebar/CompositionsTab.tsx b/packages/studio/src/components/sidebar/CompositionsTab.tsx
index bd61c90dbd..909a8033be 100644
--- a/packages/studio/src/components/sidebar/CompositionsTab.tsx
+++ b/packages/studio/src/components/sidebar/CompositionsTab.tsx
@@ -3,6 +3,7 @@ import { memo, useCallback, useEffect, useRef, useState } from "react";
import { buildCompositionThumbnailUrl } from "../../player/components/CompositionThumbnail";
import { setPreviewMediaMuted } from "../../player/lib/timelineIframeHelpers";
import { usePlayerStore } from "../../player/store/playerStore";
+import { thumbnailRevisionOf } from "../../player/store/thumbnailSlice";
import { TIMELINE_COMPOSITION_MIME } from "../../utils/timelineCompositionDrop";
import { Tooltip } from "../ui/Tooltip";
@@ -388,7 +389,7 @@ export const CompositionsTab = memo(function CompositionsTab({
isRendering,
lintFindingsByFile,
}: CompositionsTabProps) {
- const contentRevision = usePlayerStore((state) => state.thumbnailContentRevision);
+ const thumbnailRevisions = usePlayerStore((state) => state.thumbnailRevisions);
if (compositions.length === 0) {
return (
<div className="flex-1 flex items-center justify-center px-4">
@@ -411,7 +412,7 @@ export const CompositionsTab = memo(function CompositionsTab({
onAddToTimeline={onAddToTimeline ? () => onAddToTimeline(comp) : undefined}
isRendering={isRendering}
lintInfo={lintFindingsByFile?.get(comp)}
- contentRevision={contentRevision}
+ contentRevision={thumbnailRevisionOf(thumbnailRevisions, comp)}
/>
))}
</div>
diff --git a/packages/studio/src/hooks/useExternalFileChangeCoordinator.test.tsx b/packages/studio/src/hooks/useExternalFileChangeCoordinator.test.tsx
index 4f4fcc7138..9a8c8e7188 100644
--- a/packages/studio/src/hooks/useExternalFileChangeCoordinator.test.tsx
+++ b/packages/studio/src/hooks/useExternalFileChangeCoordinator.test.tsx
@@ -104,7 +104,7 @@ describe("external file change coordinator", () => {
expect(reloadPreview).not.toHaveBeenCalled();
expect(reloadSdkSession).not.toHaveBeenCalled();
expect(onAcceptedPersistedFileChange).toHaveBeenCalledOnce();
- expect(onAcceptedPersistedFileChange).toHaveBeenCalledWith("index.html");
+ expect(onAcceptedPersistedFileChange).toHaveBeenCalledWith("index.html", null);
});
it("accepts a matching content echo without a write token and suppresses every reload", async () => {
@@ -125,7 +125,7 @@ describe("external file change coordinator", () => {
);
expect(onAcceptedPersistedFileChange).toHaveBeenCalledOnce();
- expect(onAcceptedPersistedFileChange).toHaveBeenCalledWith("index.html");
+ expect(onAcceptedPersistedFileChange).toHaveBeenCalledWith("index.html", null);
expect(drainPendingChanges).not.toHaveBeenCalled();
expect(reloadPreview).not.toHaveBeenCalled();
expect(reloadSdkSession).not.toHaveBeenCalled();
@@ -345,7 +345,34 @@ describe("external file change coordinator", () => {
expect(drainPendingChanges).not.toHaveBeenCalled();
expect(reloadPreview).not.toHaveBeenCalled();
- expect(onAcceptedPersistedFileChange).toHaveBeenCalledWith("index.html");
+ expect(onAcceptedPersistedFileChange).toHaveBeenCalledWith("index.html", null);
+ });
+
+ it("hands the server's affected compositions to the thumbnail refresh", async () => {
+ const onAcceptedPersistedFileChange = vi.fn();
+ await mountCoordinator({ onAcceptedPersistedFileChange });
+
+ await act(async () =>
+ handler?.(
+ sseDelivery({
+ path: "compositions/scene-a.html",
+ version: "v3",
+ affectedCompositions: ["index.html", "compositions/scene-a.html"],
+ }),
+ ),
+ );
+ await act(async () =>
+ handler?.(
+ sseDelivery({ path: "assets/logo.svg", version: "v4", affectedCompositions: "all" }),
+ ),
+ );
+
+ expect(onAcceptedPersistedFileChange).toHaveBeenNthCalledWith(
+ 1,
+ "compositions/scene-a.html",
+ ["index.html", "compositions/scene-a.html"],
+ );
+ expect(onAcceptedPersistedFileChange).toHaveBeenNthCalledWith(2, "assets/logo.svg", null);
});
it("reloads once when one watcher event reaches two subscribers", async () => {
diff --git a/packages/studio/src/hooks/useExternalFileChangeCoordinator.ts b/packages/studio/src/hooks/useExternalFileChangeCoordinator.ts
index f09c1b1035..3c0bd11a98 100644
--- a/packages/studio/src/hooks/useExternalFileChangeCoordinator.ts
+++ b/packages/studio/src/hooks/useExternalFileChangeCoordinator.ts
@@ -1,5 +1,9 @@
import { useCallback, useEffect, useRef, useState, type MutableRefObject } from "react";
-import { readFileChangeField, readStudioFileChangePath } from "../components/editor/manualEdits";
+import {
+ readFileChangeAffectedCompositions,
+ readFileChangeField,
+ readStudioFileChangePath,
+} from "../components/editor/manualEdits";
import { StudioFileConflictError } from "../utils/studioSaveDiagnostics";
import type { ExternalConflictSnapshot } from "../utils/externalConflictStorage";
import { isSelfWriteEcho } from "./sdkSelfWriteRegistry";
@@ -56,7 +60,10 @@ interface ExternalFileChangeCoordinatorOptions {
readProjectFile: (path: string) => Promise<string>;
onUseExternalFile?: (path: string, content: string) => void;
resetSaveQueues?: () => void;
- onAcceptedPersistedFileChange: (path: string) => void;
+ onAcceptedPersistedFileChange: (
+ path: string,
+ affectedCompositions: readonly string[] | null,
+ ) => void;
}
export interface ExternalFileChangeCoordinatorHandle {
@@ -253,7 +260,7 @@ export function useExternalFileChangeCoordinator({
}
if (!mountedRef.current || generation !== generationRef.current) return;
setBlocked(null);
- onAcceptedPersistedFileChange(path);
+ onAcceptedPersistedFileChange(path, readFileChangeAffectedCompositions(payload));
reloadAcceptedGeneration(path);
return;
}
@@ -377,7 +384,7 @@ export function useExternalFileChangeCoordinator({
const ownWriteToken = consumeStudioWriteToken(token);
const ownContentEcho = content != null && isSelfWriteEcho(path, content);
if (ownWriteToken || ownContentEcho) {
- onAcceptedPersistedFileChange(path);
+ onAcceptedPersistedFileChange(path, readFileChangeAffectedCompositions(payload));
logReload("suppressed", {
path,
why: ownWriteToken ? "own write token" : "own content echo",
@@ -430,7 +437,7 @@ export function useExternalFileChangeCoordinator({
onUseExternalFile?.(path, external);
await deleteConflictSnapshot?.(projectId, path);
setBlocked(null);
- onAcceptedPersistedFileChange(path);
+ onAcceptedPersistedFileChange(path, readFileChangeAffectedCompositions(current.payload));
reloadAcceptedGeneration(path);
},
[
diff --git a/packages/studio/src/hooks/useRenderClipContent.test.ts b/packages/studio/src/hooks/useRenderClipContent.test.ts
index 01ce7349b5..901db7fdc3 100644
--- a/packages/studio/src/hooks/useRenderClipContent.test.ts
+++ b/packages/studio/src/hooks/useRenderClipContent.test.ts
@@ -271,11 +271,29 @@ describe("useRenderClipContent", () => {
}
});
+ it("finds the revision of a composition mounted with a ./ path", () => {
+ usePlayerStore.setState({
+ thumbnailMode: "adaptive",
+ thumbnailRevisions: { "compositions/nested.html": 2 },
+ });
+
+ const content = renderClipContent({
+ id: "nested",
+ tag: "div",
+ start: 0,
+ duration: 4,
+ track: 0,
+ compositionSrc: "./compositions/nested.html",
+ });
+
+ expect(isValidElement(content) && content.props).toMatchObject({ contentRevision: 2 });
+ });
+
it("forwards persisted content revision to mounted composition thumbnails", () => {
usePlayerStore.setState({
thumbnailMode: "adaptive",
timelineSessionEpoch: 7,
- thumbnailContentRevision: 11,
+ thumbnailRevisions: { "*": 11, "compositions/nested.html": 2, "compositions/other.html": 5 },
});
const content = renderClipContent({
@@ -293,7 +311,8 @@ describe("useRenderClipContent", () => {
expect(content.props).toMatchObject({
projectId: "my-project",
sessionEpoch: 7,
- contentRevision: 11,
+ // its own composition's revision plus the all-compositions one, not a sibling's
+ contentRevision: 13,
});
}
});
diff --git a/packages/studio/src/hooks/useRenderClipContent.ts b/packages/studio/src/hooks/useRenderClipContent.ts
index 2103cfee45..8e74481b35 100644
--- a/packages/studio/src/hooks/useRenderClipContent.ts
+++ b/packages/studio/src/hooks/useRenderClipContent.ts
@@ -2,6 +2,7 @@ import { buildProjectApiPath } from "../utils/projectRouting";
import { useCallback, type ReactNode } from "react";
import { createElement } from "react";
import { CompositionThumbnail, VideoThumbnail } from "../player";
+import { compositionPathOfPreviewUrl } from "../player/components/CompositionThumbnail";
import type { TimelineElement } from "../player";
import type { TimelineClipRenderContext } from "../player/components/TimelineTypes";
import { audioPillFlags } from "../player/components/audioClipLink";
@@ -9,6 +10,7 @@ import { AudioWaveform } from "../player/components/AudioWaveform";
import { ImageThumbnail } from "../player/components/ImageThumbnail";
import { encodePreviewPath, resolveMediaPreviewUrl } from "../player/components/thumbnailUtils";
import { usePlayerStore } from "../player/store/playerStore";
+import { thumbnailRevisionOf } from "../player/store/thumbnailSlice";
import { effectiveThumbnailMode } from "../player/lib/thumbnailPolicy";
export function normalizeCompositionSrc(
@@ -114,7 +116,7 @@ export function useRenderClipContent({
const thumbnailMode = usePlayerStore((s) => s.thumbnailMode);
const effectiveMode = effectiveThumbnailMode(thumbnailMode);
const sessionEpoch = usePlayerStore((s) => s.timelineSessionEpoch);
- const contentRevision = usePlayerStore((s) => s.thumbnailContentRevision);
+ const thumbnailRevisions = usePlayerStore((s) => s.thumbnailRevisions);
const elements = usePlayerStore((s) => s.elements);
return useCallback(
// Pre-existing clip-content dispatcher; reduced by extracting renderAudioClip.
@@ -159,7 +161,7 @@ export function useRenderClipContent({
duration: el.duration,
projectId: pid,
sessionEpoch,
- contentRevision,
+ contentRevision: thumbnailRevisionOf(thumbnailRevisions, compSrc),
priority: context.priority,
rich: context.rich,
});
@@ -186,7 +188,10 @@ export function useRenderClipContent({
duration: el.duration,
projectId: pid,
sessionEpoch,
- contentRevision,
+ contentRevision: thumbnailRevisionOf(
+ thumbnailRevisions,
+ compositionPathOfPreviewUrl(activePreviewUrl),
+ ),
priority: context.priority,
rich: context.rich,
});
@@ -239,7 +244,7 @@ export function useRenderClipContent({
duration: el.duration,
projectId: pid,
sessionEpoch,
- contentRevision,
+ contentRevision: thumbnailRevisionOf(thumbnailRevisions, "index.html"),
priority: context.priority,
rich: context.rich,
});
@@ -254,7 +259,7 @@ export function useRenderClipContent({
effectiveTimelineDuration,
effectiveMode,
sessionEpoch,
- contentRevision,
+ thumbnailRevisions,
elements,
],
);
diff --git a/packages/studio/src/hooks/useStudioExternalFileChanges.ts b/packages/studio/src/hooks/useStudioExternalFileChanges.ts
index 0469c9abbf..17dd07921d 100644
--- a/packages/studio/src/hooks/useStudioExternalFileChanges.ts
+++ b/packages/studio/src/hooks/useStudioExternalFileChanges.ts
@@ -49,8 +49,11 @@ export function useStudioExternalFileChanges({
}: UseStudioExternalFileChangesOptions) {
const { flushPendingSourceSave, discardPendingSourceSave } = fileManager;
const { drainPendingDomEditSaves, resetDomEditSaveQueueBreaker } = previewPersistence;
- const bumpThumbnailContentRevision = usePlayerStore(
- (state) => state.bumpThumbnailContentRevision,
+ const bumpThumbnailRevisions = usePlayerStore((state) => state.bumpThumbnailRevisions);
+ const onAcceptedPersistedFileChange = useCallback(
+ (_path: string, affectedCompositions: readonly string[] | null) =>
+ bumpThumbnailRevisions(affectedCompositions),
+ [bumpThumbnailRevisions],
);
const drainPendingChanges = useCallback(async () => {
const source = await flushPendingSourceSave();
@@ -81,6 +84,6 @@ export function useStudioExternalFileChanges({
readProjectFile: fileManager.readProjectFile,
onUseExternalFile: fileManager.updateEditingFileContent,
resetSaveQueues: resetDomEditSaveQueueBreaker,
- onAcceptedPersistedFileChange: bumpThumbnailContentRevision,
+ onAcceptedPersistedFileChange,
});
}
diff --git a/packages/studio/src/player/components/CompositionThumbnail.tsx b/packages/studio/src/player/components/CompositionThumbnail.tsx
index b4340a423e..65ca2a48cd 100644
--- a/packages/studio/src/player/components/CompositionThumbnail.tsx
+++ b/packages/studio/src/player/components/CompositionThumbnail.tsx
@@ -66,6 +66,12 @@ export function buildCompositionThumbnailUrl({
return thumbnailUrl.toString();
}
+/** The composition a preview URL renders: `/preview/comp/<path>`, or the root for `/preview`. */
+export function compositionPathOfPreviewUrl(previewUrl: string): string {
+ const match = /\/preview\/comp\/([^?#]+)/.exec(previewUrl);
+ return match?.[1] ? decodeURIComponent(match[1]) : "index.html";
+}
+
async function loadCompositionImage(url: string, signal: AbortSignal) {
const response = await fetch(url, { signal });
if (!response.ok) throw new Error(`Composition thumbnail failed (${response.status})`);
diff --git a/packages/studio/src/player/hooks/useShadowPreviewReload.ts b/packages/studio/src/player/hooks/useShadowPreviewReload.ts
index b813ef497a..500c339eef 100644
--- a/packages/studio/src/player/hooks/useShadowPreviewReload.ts
+++ b/packages/studio/src/player/hooks/useShadowPreviewReload.ts
@@ -13,6 +13,7 @@ import {
type UseTimelineSyncCallbacksParams,
} from "./useTimelineSyncCallbacks";
import type { PlaybackAdapter } from "../lib/playbackTypes";
+import { thumbnailScheduler } from "../lib/thumbnailScheduler";
// The single wait budget for a shadow: the player's 8s asset cap plus its 0.42s loader fade
// leaves about 6.5s for the document load and runtime boot. Nothing shorter may fail the swap.
@@ -82,6 +83,7 @@ export function useShadowPreviewReload({
isRefreshingRef.current = false;
pendingSeekRef.current = null;
setPreviewSlots(planShadowDiscard);
+ thumbnailScheduler.setPreviewReloading(false);
const message = `The preview did not reload (${cause}). The previous preview is still showing.`;
logReload("shadow-failed", { cause });
console.error(`[studio] ${message}`);
@@ -105,6 +107,7 @@ export function useShadowPreviewReload({
applyPreviewAudioState();
setPreviewSlots((prev) => planShadowPromotion(prev, gen));
onPromotedRef.current?.();
+ thumbnailScheduler.setPreviewReloading(false);
},
[stopPendingShadow, iframeRef, attachIframeShortcutListeners, applyPreviewAudioState],
);
@@ -175,6 +178,8 @@ export function useShadowPreviewReload({
budgetGenRef.current = gen;
armReadyTimer(gen);
setPreviewSlots((prev) => planShadowReload(prev, gen, url));
+ // Thumbnails of the edit wait for the new preview instead of competing with it.
+ thumbnailScheduler.setPreviewReloading(true);
},
[stopPendingShadow, armReadyTimer],
);
@@ -187,6 +192,7 @@ export function useShadowPreviewReload({
isRefreshingRef.current = false;
pendingSeekRef.current = null;
setPreviewSlots(planShadowDiscard);
+ thumbnailScheduler.setPreviewReloading(false);
}, [stopPendingShadow, isRefreshingRef, pendingSeekRef]);
// Hiding the tab pauses the budget; showing it again restarts the full budget for a pending shadow.
@@ -203,6 +209,7 @@ export function useShadowPreviewReload({
return () => {
document.removeEventListener("visibilitychange", onVisibilityChange);
stopPendingShadow();
+ thumbnailScheduler.setPreviewReloading(false);
};
});
diff --git a/packages/studio/src/player/lib/thumbnailScheduler.test.ts b/packages/studio/src/player/lib/thumbnailScheduler.test.ts
index 5e31ad6b1e..ee98c98d7c 100644
--- a/packages/studio/src/player/lib/thumbnailScheduler.test.ts
+++ b/packages/studio/src/player/lib/thumbnailScheduler.test.ts
@@ -153,6 +153,39 @@ describe("ThumbnailScheduler", () => {
expect(richLoad).toHaveBeenCalledTimes(1);
});
+ it("holds composition renders while the preview reloads and re-runs the ones it preempted", async () => {
+ const scheduler = new ThumbnailScheduler();
+ const signals: AbortSignal[] = [];
+ const composition = vi.fn((signal: AbortSignal) => {
+ signals.push(signal);
+ return new Promise<ThumbnailLoadedResult>((resolve, reject) => {
+ signal.addEventListener("abort", () => reject(new DOMException("Aborted", "AbortError")));
+ if (signals.length > 1) resolve(result("scene"));
+ });
+ });
+ const image = vi.fn(async () => result("still"));
+ const scene = request("scene", composition, "visible", { kind: "composition" });
+ const still = request("still", image);
+
+ scheduler.acquire(scene, vi.fn());
+ expect(composition).toHaveBeenCalledTimes(1);
+ scheduler.setPreviewReloading(true);
+ await flush();
+ expect(signals[0]?.aborted).toBe(true);
+ expect(scheduler.getSnapshot(scene)).toEqual({ status: "queued" });
+ scheduler.acquire(still, vi.fn());
+ expect(image).toHaveBeenCalledTimes(1);
+ expect(composition).toHaveBeenCalledTimes(1);
+
+ scheduler.setPreviewReloading(false);
+ await flush();
+ expect(composition).toHaveBeenCalledTimes(2);
+ expect(scheduler.getSnapshot(scene)).toMatchObject({
+ status: "ready",
+ value: { url: "scene" },
+ });
+ });
+
it("aborts queued and active jobs after the final release", async () => {
const scheduler = new ThumbnailScheduler(
resolveTimelineViewportBudgets({ concurrentVideoDecodes: 1 }),
diff --git a/packages/studio/src/player/lib/thumbnailScheduler.ts b/packages/studio/src/player/lib/thumbnailScheduler.ts
index d3ca347f55..53393dbb49 100644
--- a/packages/studio/src/player/lib/thumbnailScheduler.ts
+++ b/packages/studio/src/player/lib/thumbnailScheduler.ts
@@ -65,6 +65,8 @@ interface ThumbnailEntry {
cached: boolean;
lastAccess: number;
snapshot: ThumbnailSnapshot;
+ /** Aborted by the preview-reload hold, to run again once the hold lifts. */
+ preempted: boolean;
}
const PRIORITY_SCORE: Readonly<Record<ThumbnailPriority, number>> = {
@@ -112,6 +114,7 @@ export class ThumbnailScheduler {
private nextLeaseId = 1;
private nextSequence = 1;
private scrolling = false;
+ private previewReloading = false;
private cacheBytes = 0;
private waveformCacheBytes = 0;
private readonly activeByBucket = { video: 0, composition: 0, general: 0 };
@@ -155,6 +158,7 @@ export class ThumbnailScheduler {
cached: false,
lastAccess: this.nextSequence++,
snapshot: Object.freeze({ status: "queued" }),
+ preempted: false,
};
this.entries.set(scopedKey, entry);
}
@@ -210,6 +214,24 @@ export class ThumbnailScheduler {
if (!scrolling) this.pump();
}
+ /**
+ * Hold server-rendered composition thumbnails while the preview loads a new document: both
+ * are served by the same Studio server, and the preview is what the person is waiting for.
+ */
+ setPreviewReloading(reloading: boolean): void {
+ if (this.previewReloading === reloading) return;
+ this.previewReloading = reloading;
+ if (!reloading) {
+ this.pump();
+ return;
+ }
+ for (const entry of this.entries.values()) {
+ if (entry.state !== "loading" || entry.request.kind !== "composition") continue;
+ entry.preempted = true;
+ entry.controller?.abort();
+ }
+ }
+
/** Evict project cache entries that are no longer owned by mounted consumers. */
invalidateProject(projectId: string): void {
for (const [key, entry] of this.entries) {
@@ -257,6 +279,7 @@ export class ThumbnailScheduler {
for (const entry of queued) {
if (this.scrolling && entry.request.rich) continue;
+ if (this.previewReloading && entry.request.kind === "composition") continue;
const bucket = concurrencyBucket(entry.request.kind);
if (this.activeByBucket[bucket] >= this.bucketLimit(bucket)) continue;
this.start(entry, bucket);
@@ -281,6 +304,7 @@ export class ThumbnailScheduler {
this.deleteEntry(entry.scopedKey, entry);
return;
}
+ if (this.requeuePreempted(entry)) return;
entry.state = "error";
entry.error = errorFrom(reason);
entry.failedAt = this.now();
@@ -303,6 +327,7 @@ export class ThumbnailScheduler {
): void {
if (controller.signal.aborted || this.entries.get(entry.scopedKey) !== entry) {
this.safeDispose(result.dispose);
+ this.requeuePreempted(entry);
return;
}
this.validateResult(result);
@@ -317,6 +342,15 @@ export class ThumbnailScheduler {
if (!entry.cached && entry.leases.size === 0) this.deleteEntry(entry.scopedKey, entry);
}
+ private requeuePreempted(entry: ThumbnailEntry): boolean {
+ if (!entry.preempted || this.entries.get(entry.scopedKey) !== entry) return false;
+ entry.preempted = false;
+ entry.state = "queued";
+ entry.snapshot = Object.freeze({ status: "queued" });
+ this.notify(entry);
+ return true;
+ }
+
private validateResult(result: ThumbnailLoadedResult): void {
if (Number.isFinite(result.weight) && result.weight >= 0) return;
this.safeDispose(result.dispose);
diff --git a/packages/studio/src/player/store/playerStore.test.ts b/packages/studio/src/player/store/playerStore.test.ts
index 0b9ffff79e..edcb912a75 100644
--- a/packages/studio/src/player/store/playerStore.test.ts
+++ b/packages/studio/src/player/store/playerStore.test.ts
@@ -1,6 +1,7 @@
// @vitest-environment happy-dom
import { describe, it, expect, beforeEach, vi } from "vitest";
import { usePlayerStore, liveTime, type TimelineElement } from "./playerStore";
+import { thumbnailRevisionOf } from "./thumbnailSlice";
/** The playback/selection state `reset()` restores (persistent prefs asserted separately). */
function expectResettableDefaults(state: ReturnType<typeof usePlayerStore.getState>): void {
@@ -32,25 +33,38 @@ describe("usePlayerStore", () => {
});
describe("thumbnail content revision", () => {
- it("advances once per accepted persisted file event", () => {
- const before = usePlayerStore.getState().thumbnailContentRevision;
+ const revisionOf = (path: string) =>
+ thumbnailRevisionOf(usePlayerStore.getState().thumbnailRevisions, path);
- usePlayerStore.getState().bumpThumbnailContentRevision();
+ it("advances only the compositions an accepted file event names", () => {
+ const scene = revisionOf("compositions/scene-a.html");
+ const sibling = revisionOf("compositions/scene-b.html");
- expect(usePlayerStore.getState().thumbnailContentRevision).toBe(before + 1);
+ usePlayerStore.getState().bumpThumbnailRevisions(["compositions/scene-a.html"]);
+
+ expect(revisionOf("compositions/scene-a.html")).toBe(scene + 1);
+ expect(revisionOf("compositions/scene-b.html")).toBe(sibling);
+ });
+
+ it("advances every composition when the event names none", () => {
+ const sibling = revisionOf("compositions/scene-b.html");
+
+ usePlayerStore.getState().bumpThumbnailRevisions(null);
+
+ expect(revisionOf("compositions/scene-b.html")).toBe(sibling + 1);
});
it("remains monotonic across soft resets while project identity stays with the session epoch", () => {
const store = usePlayerStore.getState();
store.beginTimelineSession("project-a");
- store.bumpThumbnailContentRevision();
- const revision = usePlayerStore.getState().thumbnailContentRevision;
+ store.bumpThumbnailRevisions(null);
+ const revision = revisionOf("index.html");
const firstEpoch = usePlayerStore.getState().timelineSessionEpoch;
store.reset();
- expect(usePlayerStore.getState().thumbnailContentRevision).toBe(revision);
+ expect(revisionOf("index.html")).toBe(revision);
store.beginTimelineSession("project-b");
- expect(usePlayerStore.getState().thumbnailContentRevision).toBe(revision);
+ expect(revisionOf("index.html")).toBe(revision);
expect(usePlayerStore.getState().timelineSessionEpoch).toBe(firstEpoch + 1);
});
});
diff --git a/packages/studio/src/player/store/thumbnailSlice.ts b/packages/studio/src/player/store/thumbnailSlice.ts
index 42b3717124..6439966754 100644
--- a/packages/studio/src/player/store/thumbnailSlice.ts
+++ b/packages/studio/src/player/store/thumbnailSlice.ts
@@ -2,23 +2,45 @@ import type { StoreApi } from "zustand";
import { readStudioUiPreferences, writeStudioUiPreferences } from "../../utils/studioUiPreferences";
import { defaultThumbnailMode, type ThumbnailMode } from "../lib/thumbnailPolicy";
+/** Revision that moves every composition's thumbnails at once. */
+const EVERY_COMPOSITION = "*";
+
+/** Mounts may be written `./scene.html`; the server reports `scene.html`. */
+function revisionKey(path: string): string {
+ return (path.split(/[?#]/)[0] ?? "").replace(/\\/g, "/").replace(/^\.?\//, "");
+}
+
export interface ThumbnailSlice {
thumbnailMode: ThumbnailMode;
- /** Monotonic identity for persisted project content shown by mounted thumbnails. */
- thumbnailContentRevision: number;
+ /** Monotonic identity, per composition path, for persisted content shown by mounted thumbnails. */
+ thumbnailRevisions: Readonly<Record<string, number>>;
setThumbnailMode: (mode: ThumbnailMode) => void;
- bumpThumbnailContentRevision: () => void;
+ /** `null` moves every composition, e.g. after a root or asset change. */
+ bumpThumbnailRevisions: (compositions: readonly string[] | null) => void;
+}
+
+export function thumbnailRevisionOf(
+ revisions: Readonly<Record<string, number>>,
+ compositionPath: string,
+): number {
+ return (revisions[EVERY_COMPOSITION] ?? 0) + (revisions[revisionKey(compositionPath)] ?? 0);
}
export function createThumbnailSlice(set: StoreApi<ThumbnailSlice>["setState"]): ThumbnailSlice {
return {
thumbnailMode: defaultThumbnailMode(readStudioUiPreferences().thumbnailMode),
- thumbnailContentRevision: 0,
+ thumbnailRevisions: {},
setThumbnailMode: (mode) => {
writeStudioUiPreferences({ thumbnailMode: mode });
set({ thumbnailMode: mode });
},
- bumpThumbnailContentRevision: () =>
- set((state) => ({ thumbnailContentRevision: state.thumbnailContentRevision + 1 })),
+ bumpThumbnailRevisions: (compositions) =>
+ set(({ thumbnailRevisions }) => {
+ const next = { ...thumbnailRevisions };
+ for (const path of compositions?.map(revisionKey) ?? [EVERY_COMPOSITION]) {
+ next[path] = (next[path] ?? 0) + 1;
+ }
+ return { thumbnailRevisions: next };
+ }),
};
}