Skip to content

Write HTML. Render video. Built for agents.

perf(studio-server): coordinate cancelable thumbnail generation (#2720)

Miguel Ángel96861cbafc33
diff --git a/packages/cli/src/server/studioServer.ts b/packages/cli/src/server/studioServer.ts
index 8d6ebf1e7a..613a3ddb72 100644
--- a/packages/cli/src/server/studioServer.ts
+++ b/packages/cli/src/server/studioServer.ts
@@ -32,6 +32,7 @@ import {
consumeFileWriteReceipt,
getMimeType,
type PreviewApiAdapter,
+ thumbnailDeviceScaleFactor,
type ResolvedProject,
type RenderJobState,
type BackgroundRemovalRender,
@@ -571,9 +572,18 @@ export function createStudioServer(options: StudioServerOptions): StudioServer {
);
}
let page: import("puppeteer-core").Page | null = null;
+ const closePage = () => void page?.close().catch(() => {});
+ opts.signal.addEventListener("abort", closePage, { once: true });
try {
page = await session.browser.newPage();
- await page.setViewport({ width: opts.width || 1920, height: opts.height || 1080 });
+ if (opts.signal.aborted) return null;
+ const width = opts.width || 1920;
+ const height = opts.height || 1080;
+ await page.setViewport({
+ width,
+ height,
+ deviceScaleFactor: thumbnailDeviceScaleFactor(opts),
+ });
await page.goto(opts.previewUrl, { waitUntil: "domcontentloaded", timeout: 10000 });
await page
.waitForFunction(
@@ -621,12 +631,15 @@ export function createStudioServer(options: StudioServerOptions): StudioServer {
)) as Buffer;
return screenshot;
} catch (err) {
- console.warn(
- "[Studio] Thumbnail generation failed:",
- err instanceof Error ? err.message : err,
- );
+ if (!opts.signal.aborted) {
+ console.warn(
+ "[Studio] Thumbnail generation failed:",
+ err instanceof Error ? err.message : err,
+ );
+ }
return null;
} finally {
+ opts.signal.removeEventListener("abort", closePage);
await page?.close().catch(() => {});
}
},
diff --git a/packages/studio-server/src/helpers/thumbnailOutput.test.ts b/packages/studio-server/src/helpers/thumbnailOutput.test.ts
new file mode 100644
index 0000000000..67a265e830
--- /dev/null
+++ b/packages/studio-server/src/helpers/thumbnailOutput.test.ts
@@ -0,0 +1,37 @@
+import { describe, expect, it } from "vitest";
+import { thumbnailDeviceScaleFactor } from "./thumbnailOutput";
+
+describe("thumbnailDeviceScaleFactor", () => {
+ it("preserves source-density captures and bounds landscape and portrait previews", () => {
+ expect(
+ thumbnailDeviceScaleFactor({
+ width: 1920,
+ height: 1080,
+ outputWidth: 1920,
+ outputHeight: 1080,
+ }),
+ ).toBe(1);
+ expect(
+ thumbnailDeviceScaleFactor({
+ width: 1920,
+ height: 1080,
+ outputWidth: 240,
+ outputHeight: 135,
+ }),
+ ).toBe(0.125);
+ expect(
+ thumbnailDeviceScaleFactor({
+ width: 1080,
+ height: 1920,
+ outputWidth: 76,
+ outputHeight: 135,
+ }),
+ ).toBeCloseTo(76 / 1080);
+ });
+
+ it("rejects invalid dimensions instead of silently changing layout", () => {
+ expect(() =>
+ thumbnailDeviceScaleFactor({ width: 0, height: 1080, outputWidth: 240, outputHeight: 135 }),
+ ).toThrow(RangeError);
+ });
+});
diff --git a/packages/studio-server/src/helpers/thumbnailOutput.ts b/packages/studio-server/src/helpers/thumbnailOutput.ts
new file mode 100644
index 0000000000..6138eff42b
--- /dev/null
+++ b/packages/studio-server/src/helpers/thumbnailOutput.ts
@@ -0,0 +1,20 @@
+export interface ThumbnailOutputDimensions {
+ width: number;
+ height: number;
+ outputWidth: number;
+ outputHeight: number;
+}
+
+/** Sole adapter rule for capturing authored layout at bounded physical dimensions. */
+export function thumbnailDeviceScaleFactor({
+ width,
+ height,
+ outputWidth,
+ outputHeight,
+}: ThumbnailOutputDimensions): number {
+ const dimensions = [width, height, outputWidth, outputHeight];
+ if (dimensions.some((value) => !Number.isFinite(value) || value <= 0)) {
+ throw new RangeError("Thumbnail dimensions must be positive finite numbers");
+ }
+ return Math.min(1, outputWidth / width, outputHeight / height);
+}
diff --git a/packages/studio-server/src/index.ts b/packages/studio-server/src/index.ts
index 88e8f236a6..834b3459c8 100644
--- a/packages/studio-server/src/index.ts
+++ b/packages/studio-server/src/index.ts
@@ -20,6 +20,10 @@ export {
} from "./helpers/fileVersion.js";
export { buildSubCompositionHtml } from "./helpers/subComposition.js";
export { getElementScreenshotClip, type ScreenshotClip } from "./helpers/screenshotClip.js";
+export {
+ thumbnailDeviceScaleFactor,
+ type ThumbnailOutputDimensions,
+} from "./helpers/thumbnailOutput.js";
export {
createBackgroundRemovalJob,
type BackgroundRemovalRender,
diff --git a/packages/studio-server/src/routes/thumbnail.test.ts b/packages/studio-server/src/routes/thumbnail.test.ts
index 7946e846ff..5543a9f5ab 100644
--- a/packages/studio-server/src/routes/thumbnail.test.ts
+++ b/packages/studio-server/src/routes/thumbnail.test.ts
@@ -1,9 +1,18 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { Hono } from "hono";
-import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import {
+ existsSync,
+ mkdirSync,
+ mkdtempSync,
+ readdirSync,
+ rmSync,
+ truncateSync,
+ utimesSync,
+ writeFileSync,
+} from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
-import { registerThumbnailRoutes } from "./thumbnail";
+import { pruneThumbnailCache, registerThumbnailRoutes } from "./thumbnail";
import type { StudioApiAdapter } from "../types";
const tempProjectDirs: string[] = [];
@@ -52,10 +61,37 @@ describe("registerThumbnailRoutes", () => {
seekTime: 1.2,
selector: "#title-card",
format: "jpeg",
+ outputWidth: 240,
+ outputHeight: 135,
+ signal: expect.any(AbortSignal),
}),
);
});
+ it("deduplicates concurrent generation and writes one complete cache entry", async () => {
+ const adapter = createAdapter();
+ const project = await adapter.resolveProject("demo");
+ if (!project) throw new Error("missing project");
+ let resolve!: (buffer: Buffer) => void;
+ const generated = new Promise<Buffer>((done) => (resolve = done));
+ adapter.generateThumbnail = vi.fn(async () => generated);
+ const app = new Hono();
+ registerThumbnailRoutes(app, adapter);
+
+ const url = "http://localhost/projects/demo/thumbnail/index.html?t=3";
+ const first = app.request(url);
+ const second = app.request(url);
+ await vi.waitFor(() => expect(adapter.generateThumbnail).toHaveBeenCalledTimes(1));
+ resolve(Buffer.from("shared"));
+
+ expect(await (await first).text()).toBe("shared");
+ expect(await (await second).text()).toBe("shared");
+ expect(adapter.generateThumbnail).toHaveBeenCalledTimes(1);
+ const cached = readdirSync(join(project.dir, ".thumbnails"));
+ expect(cached).toHaveLength(1);
+ expect(cached[0]).not.toContain(".tmp");
+ });
+
it("forwards png capture requests and returns a png content type", async () => {
const adapter = createAdapter();
const app = new Hono();
@@ -72,10 +108,27 @@ describe("registerThumbnailRoutes", () => {
compPath: "compositions/intro.html",
seekTime: 2,
format: "png",
+ outputWidth: 1920,
+ outputHeight: 1080,
}),
);
});
+ it("allows png callers to opt into bounded preview output", async () => {
+ const adapter = createAdapter();
+ const app = new Hono();
+ registerThumbnailRoutes(app, adapter);
+
+ const response = await app.request(
+ "http://localhost/projects/demo/thumbnail/index.html?format=png&output=preview",
+ );
+
+ expect(response.status).toBe(200);
+ expect(adapter.generateThumbnail).toHaveBeenCalledWith(
+ expect.objectContaining({ outputWidth: 240, outputHeight: 135 }),
+ );
+ });
+
it("preserves an explicit zero seek time", async () => {
const adapter = createAdapter();
const app = new Hono();
@@ -220,4 +273,26 @@ describe("registerThumbnailRoutes", () => {
expect(adapter.generateThumbnail).toHaveBeenCalledTimes(2);
});
+
+ it("prunes expired and over-budget files without touching protected work", () => {
+ const cacheDir = mkdtempSync(join(tmpdir(), "hf-thumbnail-cache-test-"));
+ tempProjectDirs.push(cacheDir);
+ const expiredPath = join(cacheDir, "expired.jpg");
+ const protectedPath = join(cacheDir, "protected.jpg");
+ const overflowPath = join(cacheDir, "overflow.jpg");
+ writeFileSync(expiredPath, "expired");
+ writeFileSync(protectedPath, "protected");
+ writeFileSync(overflowPath, "overflow");
+ const now = Date.now();
+ const expiredSeconds = (now - 15 * 24 * 60 * 60 * 1000) / 1000;
+ utimesSync(expiredPath, expiredSeconds, expiredSeconds);
+ truncateSync(protectedPath, 400 * 1024 * 1024);
+ truncateSync(overflowPath, 200 * 1024 * 1024);
+
+ pruneThumbnailCache(cacheDir, new Set([protectedPath]), now);
+
+ expect(existsSync(expiredPath)).toBe(false);
+ expect(existsSync(protectedPath)).toBe(true);
+ expect(existsSync(overflowPath)).toBe(false);
+ });
});
diff --git a/packages/studio-server/src/routes/thumbnail.ts b/packages/studio-server/src/routes/thumbnail.ts
index ab18df5e91..0f2fba697e 100644
--- a/packages/studio-server/src/routes/thumbnail.ts
+++ b/packages/studio-server/src/routes/thumbnail.ts
@@ -1,12 +1,76 @@
import type { Hono } from "hono";
-import { existsSync, readFileSync, writeFileSync, mkdirSync, statSync } from "node:fs";
+import {
+ existsSync,
+ mkdirSync,
+ readFileSync,
+ readdirSync,
+ renameSync,
+ rmSync,
+ statSync,
+ unlinkSync,
+ writeFileSync,
+} from "node:fs";
import { join } from "node:path";
-import { createHash } from "node:crypto";
+import { createHash, randomUUID } from "node:crypto";
import type { StudioApiAdapter } from "../types.js";
import { STUDIO_MANUAL_EDITS_PATH } from "../helpers/manualEditsRenderScript.js";
import { STUDIO_MOTION_PATH } from "../helpers/studioMotionRenderScript.js";
+import { thumbnailGenerationCoordinator } from "./thumbnailGenerationCoordinator.js";
const THUMBNAIL_CACHE_VERSION = "v4";
+const THUMBNAIL_MAX_OUTPUT_WIDTH = 240;
+const THUMBNAIL_MAX_OUTPUT_HEIGHT = 135;
+const THUMBNAIL_CACHE_MAX_BYTES = 512 * 1024 * 1024;
+const THUMBNAIL_CACHE_MAX_AGE_MS = 14 * 24 * 60 * 60 * 1000;
+const prunedCacheDirs = new Set<string>();
+
+export function pruneThumbnailCache(
+ cacheDir: string,
+ protectedPaths: ReadonlySet<string>,
+ now = Date.now(),
+): void {
+ if (!existsSync(cacheDir)) return;
+ const files = readdirSync(cacheDir, { withFileTypes: true }).flatMap((entry) => {
+ if (!entry.isFile()) return [];
+ const path = join(cacheDir, entry.name);
+ try {
+ const stats = statSync(path);
+ return [{ path, bytes: stats.size, mtimeMs: stats.mtimeMs }];
+ } catch {
+ return [];
+ }
+ });
+ const retained = [];
+ for (const file of files) {
+ if (!protectedPaths.has(file.path) && now - file.mtimeMs > THUMBNAIL_CACHE_MAX_AGE_MS) {
+ rmSync(file.path, { force: true });
+ } else {
+ retained.push(file);
+ }
+ }
+
+ let bytes = retained.reduce((total, file) => total + file.bytes, 0);
+ for (const file of retained.sort((left, right) => left.mtimeMs - right.mtimeMs)) {
+ if (bytes <= THUMBNAIL_CACHE_MAX_BYTES) break;
+ if (protectedPaths.has(file.path)) continue;
+ try {
+ unlinkSync(file.path);
+ bytes -= file.bytes;
+ } catch {
+ // Another request may have pruned the same file.
+ }
+ }
+}
+
+function writeThumbnailAtomically(path: string, buffer: Buffer): void {
+ const temporaryPath = `${path}.${process.pid}.${randomUUID()}.tmp`;
+ try {
+ writeFileSync(temporaryPath, buffer, { flag: "wx" });
+ renameSync(temporaryPath, path);
+ } finally {
+ rmSync(temporaryPath, { force: true });
+ }
+}
export function registerThumbnailRoutes(api: Hono, adapter: StudioApiAdapter): void {
api.get("/projects/:id/thumbnail/*", async (c) => {
@@ -30,6 +94,13 @@ export function registerThumbnailRoutes(api: Hono, adapter: StudioApiAdapter): v
const selector = url.searchParams.get("selector") || undefined;
const format = url.searchParams.get("format") === "png" ? "png" : "jpeg";
const contentType = format === "png" ? "image/png" : "image/jpeg";
+ const requestedOutput = url.searchParams.get("output");
+ // PNG is the legacy source-density capture contract. Callers can opt either
+ // format into the bounded preview contract explicitly.
+ const outputMode =
+ requestedOutput === "source" || (requestedOutput !== "preview" && format === "png")
+ ? "source"
+ : "preview";
const rawSelectorIndex = Number.parseInt(url.searchParams.get("selectorIndex") || "0", 10);
const selectorIndex =
Number.isFinite(rawSelectorIndex) && rawSelectorIndex > 0 ? rawSelectorIndex : undefined;
@@ -86,8 +157,21 @@ export function registerThumbnailRoutes(api: Hono, adapter: StudioApiAdapter): v
const urlVersionKey = urlVersion
? `_${urlVersion.replace(/[^a-zA-Z0-9_-]+/g, "_").slice(0, 32)}`
: "";
- const cacheKey = `${THUMBNAIL_CACHE_VERSION}${urlVersionKey}${manualEditsKey}${motionKey}${sourceKey}_${format}_${compPath.replace(/\//g, "_")}_${compW}x${compH}_${sourceMtime}_${seekTime.toFixed(2)}${selectorKey}.${format === "png" ? "png" : "jpg"}`;
+ 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}${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);
+ pruneThumbnailCache(
+ cacheDir,
+ new Set([...thumbnailGenerationCoordinator.protectedKeys(), cachePath]),
+ );
+ }
if (existsSync(cachePath)) {
return new Response(new Uint8Array(readFileSync(cachePath)), {
headers: { "Content-Type": contentType, "Cache-Control": "no-cache" },
@@ -95,29 +179,44 @@ export function registerThumbnailRoutes(api: Hono, adapter: StudioApiAdapter): v
}
try {
- const buffer = await adapter.generateThumbnail({
- project,
- compPath,
- seekTime,
- width: compW,
- height: compH,
- previewUrl,
- selector,
- format,
- selectorIndex,
- });
+ const buffer = await thumbnailGenerationCoordinator.acquire(
+ cachePath,
+ c.req.raw.signal,
+ async (signal) => {
+ const generated = await adapter.generateThumbnail!({
+ project,
+ compPath,
+ seekTime,
+ width: compW,
+ height: compH,
+ outputWidth,
+ outputHeight,
+ previewUrl,
+ selector,
+ format,
+ selectorIndex,
+ signal,
+ });
+ if (!generated) return null;
+ if (!existsSync(cacheDir)) mkdirSync(cacheDir, { recursive: true });
+ writeThumbnailAtomically(cachePath, generated);
+ return generated;
+ },
+ );
if (!buffer) {
return c.json(
{ error: "Thumbnail generation failed — Chrome browser may not be available" },
500,
);
}
- if (!existsSync(cacheDir)) mkdirSync(cacheDir, { recursive: true });
- writeFileSync(cachePath, buffer);
+ pruneThumbnailCache(cacheDir, thumbnailGenerationCoordinator.protectedKeys());
return new Response(new Uint8Array(buffer), {
headers: { "Content-Type": contentType, "Cache-Control": "no-cache" },
});
} catch (err) {
+ if (err instanceof DOMException && err.name === "AbortError") {
+ return new Response(null, { status: 499 });
+ }
const msg = err instanceof Error ? err.message : String(err);
return c.json({ error: `Thumbnail generation failed: ${msg}` }, 500);
}
diff --git a/packages/studio-server/src/routes/thumbnailGenerationCoordinator.test.ts b/packages/studio-server/src/routes/thumbnailGenerationCoordinator.test.ts
new file mode 100644
index 0000000000..3398ef669d
--- /dev/null
+++ b/packages/studio-server/src/routes/thumbnailGenerationCoordinator.test.ts
@@ -0,0 +1,123 @@
+import { describe, expect, it, vi } from "vitest";
+import { ThumbnailGenerationCoordinator } from "./thumbnailGenerationCoordinator";
+
+function deferred() {
+ let resolve!: (value: Buffer | null) => void;
+ let reject!: (reason: unknown) => void;
+ const promise = new Promise<Buffer | null>((done, fail) => {
+ resolve = done;
+ reject = fail;
+ });
+ return { promise, resolve, reject };
+}
+
+describe("ThumbnailGenerationCoordinator", () => {
+ it("deduplicates same-key leases and bounds different-key concurrency", async () => {
+ const coordinator = new ThumbnailGenerationCoordinator(2);
+ const first = deferred();
+ const second = deferred();
+ const starts: string[] = [];
+ const signal = new AbortController().signal;
+ const a = coordinator.acquire("a", signal, async () => {
+ starts.push("a");
+ return first.promise;
+ });
+ const duplicateWork = vi.fn(async () => Buffer.from("wrong"));
+ const duplicate = coordinator.acquire("a", signal, duplicateWork);
+ const b = coordinator.acquire("b", signal, async () => {
+ starts.push("b");
+ return second.promise;
+ });
+ const c = coordinator.acquire("c", signal, async () => {
+ starts.push("c");
+ return Buffer.from("c");
+ });
+
+ expect(starts).toEqual(["a", "b"]);
+ first.resolve(Buffer.from("a"));
+ second.resolve(Buffer.from("b"));
+ await expect(Promise.all([a, duplicate, b, c])).resolves.toEqual([
+ Buffer.from("a"),
+ Buffer.from("a"),
+ Buffer.from("b"),
+ Buffer.from("c"),
+ ]);
+ expect(duplicateWork).not.toHaveBeenCalled();
+ expect(starts).toEqual(["a", "b", "c"]);
+ });
+
+ it("keeps shared work alive until its final lease leaves", async () => {
+ const coordinator = new ThumbnailGenerationCoordinator();
+ const firstController = new AbortController();
+ const secondController = new AbortController();
+ let workSignal: AbortSignal | undefined;
+ const work = deferred();
+ const first = coordinator.acquire("shared", firstController.signal, async (signal) => {
+ workSignal = signal;
+ return work.promise;
+ });
+ const second = coordinator.acquire("shared", secondController.signal, vi.fn());
+
+ firstController.abort();
+ await expect(first).rejects.toMatchObject({ name: "AbortError" });
+ expect(workSignal?.aborted).toBe(false);
+ secondController.abort();
+ await expect(second).rejects.toMatchObject({ name: "AbortError" });
+ expect(workSignal?.aborted).toBe(true);
+ work.reject(new DOMException("Aborted", "AbortError"));
+ await vi.waitFor(() => expect(coordinator.protectedKeys().size).toBe(0));
+ });
+
+ it("removes an unleased queued job without starting it", async () => {
+ const coordinator = new ThumbnailGenerationCoordinator(1);
+ const activeWork = deferred();
+ const active = coordinator.acquire(
+ "active",
+ new AbortController().signal,
+ async () => activeWork.promise,
+ );
+ const queuedController = new AbortController();
+ const queuedWork = vi.fn(async () => Buffer.from("queued"));
+ const queued = coordinator.acquire("queued", queuedController.signal, queuedWork);
+
+ queuedController.abort();
+ await expect(queued).rejects.toMatchObject({ name: "AbortError" });
+ activeWork.resolve(Buffer.from("active"));
+ await expect(active).resolves.toEqual(Buffer.from("active"));
+ expect(queuedWork).not.toHaveBeenCalled();
+ });
+
+ it("does not attach a new lease to work already aborted by its final lease", async () => {
+ const coordinator = new ThumbnailGenerationCoordinator();
+ const firstController = new AbortController();
+ const firstWork = deferred();
+ const first = coordinator.acquire(
+ "same",
+ firstController.signal,
+ async () => firstWork.promise,
+ );
+ firstController.abort();
+ await expect(first).rejects.toMatchObject({ name: "AbortError" });
+
+ const replacementWork = vi.fn(async () => Buffer.from("replacement"));
+ const replacement = coordinator.acquire("same", new AbortController().signal, replacementWork);
+ expect(replacementWork).not.toHaveBeenCalled();
+ firstWork.reject(new DOMException("Aborted", "AbortError"));
+
+ await expect(replacement).resolves.toEqual(Buffer.from("replacement"));
+ expect(replacementWork).toHaveBeenCalledTimes(1);
+ });
+
+ it("does not enqueue work for an already-aborted lease", async () => {
+ const coordinator = new ThumbnailGenerationCoordinator();
+ const controller = new AbortController();
+ const work = vi.fn(async () => Buffer.from("unexpected"));
+ controller.abort();
+
+ await expect(coordinator.acquire("aborted", controller.signal, work)).rejects.toMatchObject({
+ name: "AbortError",
+ });
+ expect(work).not.toHaveBeenCalled();
+ expect(coordinator.protectedKeys().size).toBe(0);
+ });
+});
diff --git a/packages/studio-server/src/routes/thumbnailGenerationCoordinator.ts b/packages/studio-server/src/routes/thumbnailGenerationCoordinator.ts
new file mode 100644
index 0000000000..6804df3b0e
--- /dev/null
+++ b/packages/studio-server/src/routes/thumbnailGenerationCoordinator.ts
@@ -0,0 +1,129 @@
+export type ThumbnailGenerationValue = Buffer | null;
+export type ThumbnailGenerationWork = (signal: AbortSignal) => Promise<ThumbnailGenerationValue>;
+
+interface GenerationEntry {
+ key: string;
+ controller: AbortController;
+ leases: number;
+ state: "queued" | "active";
+ work: ThumbnailGenerationWork;
+ promise: Promise<ThumbnailGenerationValue>;
+ resolve: (value: ThumbnailGenerationValue) => void;
+ reject: (reason: unknown) => void;
+}
+
+/** Sole server owner for same-key dedupe, concurrency, cancellation, and queue order. */
+export class ThumbnailGenerationCoordinator {
+ private readonly entries = new Map<string, GenerationEntry>();
+ private readonly queue: GenerationEntry[] = [];
+ private readonly activeEntries = new Set<GenerationEntry>();
+ private active = 0;
+
+ constructor(private readonly concurrency = 1) {
+ if (!Number.isInteger(concurrency) || concurrency < 1) {
+ throw new RangeError("Thumbnail concurrency must be a positive integer");
+ }
+ }
+
+ acquire(
+ key: string,
+ signal: AbortSignal,
+ work: ThumbnailGenerationWork,
+ ): Promise<ThumbnailGenerationValue> {
+ if (signal.aborted) return Promise.reject(new DOMException("Aborted", "AbortError"));
+
+ let entry = this.entries.get(key);
+ if (!entry) {
+ let resolve!: (value: ThumbnailGenerationValue) => void;
+ let reject!: (reason: unknown) => void;
+ const promise = new Promise<ThumbnailGenerationValue>((resolvePromise, rejectPromise) => {
+ resolve = resolvePromise;
+ reject = rejectPromise;
+ });
+ entry = {
+ key,
+ controller: new AbortController(),
+ leases: 0,
+ state: "queued",
+ work,
+ promise,
+ resolve,
+ reject,
+ };
+ this.entries.set(key, entry);
+ this.queue.push(entry);
+ }
+ entry.leases++;
+ this.pump();
+
+ return this.lease(entry, signal);
+ }
+
+ protectedKeys(): ReadonlySet<string> {
+ return new Set([...this.entries.keys(), ...[...this.activeEntries].map((entry) => entry.key)]);
+ }
+
+ private lease(entry: GenerationEntry, signal: AbortSignal): Promise<ThumbnailGenerationValue> {
+ return new Promise((resolve, reject) => {
+ let released = false;
+ const release = () => {
+ if (released) return;
+ released = true;
+ signal.removeEventListener("abort", onAbort);
+ entry.leases--;
+ if (entry.leases > 0 || !this.entries.has(entry.key)) return;
+
+ entry.controller.abort();
+ if (this.entries.get(entry.key) === entry) this.entries.delete(entry.key);
+ if (entry.state === "queued") {
+ const index = this.queue.indexOf(entry);
+ if (index >= 0) this.queue.splice(index, 1);
+ entry.reject(new DOMException("Aborted", "AbortError"));
+ }
+ };
+ const onAbort = () => {
+ release();
+ reject(new DOMException("Aborted", "AbortError"));
+ };
+
+ signal.addEventListener("abort", onAbort, { once: true });
+ entry.promise.then(
+ (value) => {
+ release();
+ resolve(value);
+ },
+ (reason) => {
+ release();
+ reject(reason);
+ },
+ );
+ });
+ }
+
+ private pump(): void {
+ while (this.active < this.concurrency) {
+ const entry = this.queue.shift();
+ if (!entry) return;
+ if (entry.leases === 0) continue;
+ entry.state = "active";
+ this.activeEntries.add(entry);
+ this.active++;
+ void this.run(entry);
+ }
+ }
+
+ private async run(entry: GenerationEntry): Promise<void> {
+ try {
+ entry.resolve(await entry.work(entry.controller.signal));
+ } catch (error) {
+ entry.reject(error);
+ } finally {
+ this.active--;
+ this.activeEntries.delete(entry);
+ if (this.entries.get(entry.key) === entry) this.entries.delete(entry.key);
+ this.pump();
+ }
+ }
+}
+
+export const thumbnailGenerationCoordinator = new ThumbnailGenerationCoordinator(1);
diff --git a/packages/studio-server/src/types.ts b/packages/studio-server/src/types.ts
index 07bb5cffc3..b569f45ace 100644
--- a/packages/studio-server/src/types.ts
+++ b/packages/studio-server/src/types.ts
@@ -186,17 +186,20 @@ export interface StudioApiAdapter {
jobId: string;
}) => MediaProcessingJobState;
- /** Optional: generate a JPEG thumbnail via Puppeteer or similar. */
+ /** Optional: generate a thumbnail at the route's explicit output dimensions. */
generateThumbnail?: (opts: {
project: ResolvedProject;
compPath: string;
seekTime: number;
width: number;
height: number;
+ outputWidth: number;
+ outputHeight: number;
previewUrl: string;
selector?: string;
format?: "jpeg" | "png";
selectorIndex?: number;
+ signal: AbortSignal;
}) => Promise<Buffer | null>;
/** Optional: resolve session ID to project (multi-project mode). */
diff --git a/packages/studio/src/components/EditorShell.selectionSync.test.tsx b/packages/studio/src/components/EditorShell.selectionSync.test.tsx
new file mode 100644
index 0000000000..8565f5dd40
--- /dev/null
+++ b/packages/studio/src/components/EditorShell.selectionSync.test.tsx
@@ -0,0 +1,109 @@
+// @vitest-environment happy-dom
+
+import React, { act } from "react";
+import { createRoot } from "react-dom/client";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { EditorShell } from "./EditorShell";
+
+const hookMocks = vi.hoisted(() => ({
+ useTimelineSelectionPreviewSync: vi.fn(),
+}));
+
+vi.mock("../hooks/useTimelineSelectionPreviewSync", () => hookMocks);
+vi.mock("../contexts/StudioContext", () => ({
+ useStudioPlaybackContext: () => ({
+ captionEditMode: false,
+ refreshKey: 0,
+ refreshPreviewDocumentVersion: vi.fn(),
+ timelineElements: [],
+ }),
+ useStudioShellContext: () => ({
+ projectId: "project-1",
+ activeCompPath: "index.html",
+ setActiveCompPath: vi.fn(),
+ handlePreviewIframeRef: vi.fn(),
+ showToast: vi.fn(),
+ }),
+}));
+vi.mock("../contexts/DomEditContext", () => ({
+ useDomEditActionsContext: () => ({
+ handleTimelineElementSelect: vi.fn(),
+ buildDomSelectionForTimelineElement: vi.fn(),
+ applyDomSelection: vi.fn(),
+ applyMarqueeSelection: vi.fn(),
+ }),
+ useDomEditSelectionContext: () => ({
+ domEditSelection: null,
+ domEditGroupSelections: [],
+ }),
+}));
+vi.mock("./nle/NLEContext", () => ({
+ NLEProvider: ({ children }: { children: React.ReactNode }) => children,
+ useNLEContext: () => ({
+ compositionStack: [],
+ updateCompositionStack: vi.fn(),
+ containerRef: { current: null },
+ }),
+}));
+vi.mock("./nle/useTimelineEditCallbacks", () => ({
+ useTimelineEditCallbacks: () => ({}),
+}));
+vi.mock("./nle/PreviewPane", () => ({ PreviewPane: () => null }));
+vi.mock("./nle/PreviewOverlays", () => ({ PreviewOverlays: () => null }));
+vi.mock("./nle/TimelinePane", () => ({ TimelinePane: () => null }));
+vi.mock("../captions/components/CaptionTimeline", () => ({ CaptionTimeline: () => null }));
+vi.mock("./StudioFeedbackBar", () => ({ StudioFeedbackBar: () => null }));
+
+Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
+
+afterEach(() => {
+ document.body.innerHTML = "";
+ hookMocks.useTimelineSelectionPreviewSync.mockClear();
+});
+
+describe("EditorShell timeline selection sync", () => {
+ it("keeps the timeline store mirrored into the preview selection", () => {
+ const host = document.createElement("div");
+ document.body.append(host);
+ const root = createRoot(host);
+
+ act(() => {
+ root.render(
+ <EditorShell
+ left={null}
+ right={null}
+ timelineToolbar={null}
+ renderClipContent={() => null}
+ handleTimelineElementDelete={vi.fn()}
+ handleTimelineAssetDrop={vi.fn()}
+ handleTimelineFileDrop={vi.fn()}
+ handleTimelineElementMove={vi.fn()}
+ handleTimelineElementsMove={vi.fn()}
+ handleTimelineElementResize={vi.fn()}
+ handleTimelineGroupResize={vi.fn()}
+ handleToggleTrackHidden={vi.fn()}
+ handleBlockedTimelineEdit={vi.fn()}
+ handleTimelineElementSplit={vi.fn()}
+ handleRazorSplit={vi.fn()}
+ handleRazorSplitAll={vi.fn()}
+ setCompIdToSrc={vi.fn()}
+ setCompositionLoading={vi.fn()}
+ shouldShowMotionPath={false}
+ shouldShowSelectedDomBounds={false}
+ />,
+ );
+ });
+
+ expect(hookMocks.useTimelineSelectionPreviewSync).toHaveBeenCalledOnce();
+ expect(hookMocks.useTimelineSelectionPreviewSync).toHaveBeenCalledWith(
+ expect.objectContaining({
+ activeCompPath: "index.html",
+ timelineElements: [],
+ domEditSelection: null,
+ domEditGroupSelections: [],
+ }),
+ );
+
+ act(() => root.unmount());
+ });
+});
diff --git a/packages/studio/src/components/EditorShell.tsx b/packages/studio/src/components/EditorShell.tsx
index fbf0688713..3e0079a13e 100644
--- a/packages/studio/src/components/EditorShell.tsx
+++ b/packages/studio/src/components/EditorShell.tsx
@@ -10,11 +10,12 @@ import { NLEProvider, useNLEContext } from "./nle/NLEContext";
import { CaptionTimeline } from "../captions/components/CaptionTimeline";
import { StudioFeedbackBar } from "./StudioFeedbackBar";
import { useStudioPlaybackContext, useStudioShellContext } from "../contexts/StudioContext";
-import { useDomEditActionsContext } from "../contexts/DomEditContext";
+import { useDomEditActionsContext, useDomEditSelectionContext } from "../contexts/DomEditContext";
import { TimelineEditProvider } from "../contexts/TimelineEditContext";
-import type { TimelineElement } from "../player";
+import { usePlayerStore, type TimelineElement } from "../player";
import type { BlockPreviewInfo } from "./sidebar/BlocksTab";
import type { GestureRecordingState } from "./editor/GestureRecordControl";
+import { useTimelineSelectionPreviewSync } from "../hooks/useTimelineSelectionPreviewSync";
type RenderClipContent = (
element: TimelineElement,
@@ -99,10 +100,35 @@ export function EditorShell({
blockPreview,
gestureOverlay,
}: EditorShellProps) {
- const { projectId, activeCompPath, setActiveCompPath, handlePreviewIframeRef } =
+ const { projectId, activeCompPath, setActiveCompPath, handlePreviewIframeRef, showToast } =
useStudioShellContext();
- const { refreshKey, captionEditMode, refreshPreviewDocumentVersion } = useStudioPlaybackContext();
- const { handleTimelineElementSelect } = useDomEditActionsContext();
+ const { refreshKey, captionEditMode, refreshPreviewDocumentVersion, timelineElements } =
+ useStudioPlaybackContext();
+ const {
+ handleTimelineElementSelect,
+ buildDomSelectionForTimelineElement,
+ applyDomSelection,
+ applyMarqueeSelection,
+ } = useDomEditActionsContext();
+ const { domEditSelection, domEditGroupSelections } = useDomEditSelectionContext();
+ const selectedElementId = usePlayerStore((state) => state.selectedElementId);
+ const selectedElementIds = usePlayerStore((state) => state.selectedElementIds);
+ const reportTimelineSelectionNotFound = useCallback(() => {
+ showToast("The selected clip is not available in the preview yet.", "info");
+ }, [showToast]);
+
+ useTimelineSelectionPreviewSync({
+ selectedElementId,
+ selectedElementIds,
+ timelineElements,
+ domEditSelection,
+ domEditGroupSelections,
+ activeCompPath,
+ buildDomSelectionForTimelineElement,
+ applyDomSelection,
+ applyMarqueeSelection,
+ onSelectionNotFound: reportTimelineSelectionNotFound,
+ });
const timelineEditCallbacks = useTimelineEditCallbacks({
handleTimelineElementMove,
diff --git a/packages/studio/src/components/TimelineToolbar.test.tsx b/packages/studio/src/components/TimelineToolbar.test.tsx
index 0050dcfc95..2e7900e826 100644
--- a/packages/studio/src/components/TimelineToolbar.test.tsx
+++ b/packages/studio/src/components/TimelineToolbar.test.tsx
@@ -12,7 +12,7 @@ import { TimelineToolbar } from "./TimelineToolbar";
afterEach(() => {
document.body.innerHTML = "";
- usePlayerStore.setState({ autoKeyframeEnabled: true });
+ usePlayerStore.setState({ autoKeyframeEnabled: true, thumbnailMode: "adaptive" });
});
function renderToolbar(
@@ -58,6 +58,25 @@ describe("TimelineToolbar — auto-keyframe toggle (#1808)", () => {
act(() => root.unmount());
});
});
+
+describe("TimelineToolbar — adaptive thumbnails", () => {
+ it("keeps a user-controlled hidden mode as the rollback path", () => {
+ const { host, root } = renderToolbar();
+ const button = host.querySelector<HTMLButtonElement>(
+ 'button[aria-label="Hide thumbnails — labels only"]',
+ );
+ if (!button) throw new Error("thumbnail toggle not rendered");
+
+ act(() => button.click());
+
+ expect(usePlayerStore.getState().thumbnailMode).toBe("hidden");
+ expect(button.getAttribute("aria-label")).toBe(
+ "Show thumbnails — posters stay visible; richer previews appear on interaction",
+ );
+ act(() => root.unmount());
+ });
+});
+
describe("TimelineToolbar — motion path endpoints", () => {
it("does not advertise a destructive keyframe toggle for a required endpoint", () => {
usePlayerStore.setState({ currentTime: 10 });
diff --git a/packages/studio/src/components/TimelineToolbar.tsx b/packages/studio/src/components/TimelineToolbar.tsx
index 5391488000..1417665071 100644
--- a/packages/studio/src/components/TimelineToolbar.tsx
+++ b/packages/studio/src/components/TimelineToolbar.tsx
@@ -1,5 +1,5 @@
import { useEffect, useRef } from "react";
-import { Magnet, MagnifyingGlassMinus, MagnifyingGlassPlus } from "@phosphor-icons/react";
+import { Image, Magnet, MagnifyingGlassMinus, MagnifyingGlassPlus } from "@phosphor-icons/react";
import {
useEnableKeyframes,
isPlayheadWithinTween,
@@ -111,6 +111,9 @@ export function TimelineToolbar({ domEditSession, onSplitElement }: TimelineTool
const setTimelineSnapEnabled = usePlayerStore((s) => s.setTimelineSnapEnabled);
const autoKeyframeEnabled = usePlayerStore((s) => s.autoKeyframeEnabled);
const setAutoKeyframeEnabled = usePlayerStore((s) => s.setAutoKeyframeEnabled);
+ const thumbnailMode = usePlayerStore((s) => s.thumbnailMode);
+ const setThumbnailMode = usePlayerStore((s) => s.setThumbnailMode);
+ const thumbnailsVisible = thumbnailMode === "adaptive";
// Subscribe so the add-beat button reacts to playhead movement and analysis load.
const currentTime = usePlayerStore((s) => s.currentTime);
const beatAnalysisReady = usePlayerStore((s) => s.beatAnalysis !== null);
@@ -403,6 +406,31 @@ export function TimelineToolbar({ domEditSession, onSplitElement }: TimelineTool
})()}
</div>
<div className="flex items-center gap-0.5">
+ <Tooltip
+ label={
+ thumbnailsVisible
+ ? "Hide thumbnails — labels only"
+ : "Show thumbnails — posters stay visible; richer previews appear on interaction"
+ }
+ >
+ <button
+ type="button"
+ aria-label={
+ thumbnailsVisible
+ ? "Hide thumbnails — labels only"
+ : "Show thumbnails — posters stay visible; richer previews appear on interaction"
+ }
+ aria-pressed={thumbnailsVisible}
+ onClick={() => setThumbnailMode(thumbnailsVisible ? "hidden" : "adaptive")}
+ className={`h-7 px-2 rounded-md text-[11px] font-medium transition-colors ${
+ thumbnailsVisible
+ ? "bg-studio-accent/10 text-studio-accent"
+ : "text-neutral-400 hover:bg-white/[0.06] hover:text-neutral-200"
+ }`}
+ >
+ <Image size={16} aria-hidden="true" />
+ </button>
+ </Tooltip>
<Tooltip label="Fit timeline to width">
<button
type="button"
diff --git a/packages/studio/src/hooks/useRenderClipContent.test.ts b/packages/studio/src/hooks/useRenderClipContent.test.ts
index 057cf04824..8342f180b9 100644
--- a/packages/studio/src/hooks/useRenderClipContent.test.ts
+++ b/packages/studio/src/hooks/useRenderClipContent.test.ts
@@ -5,13 +5,15 @@ import { createRoot } from "react-dom/client";
import { afterEach, describe, expect, it } from "vitest";
import { CompositionThumbnail, VideoThumbnail } from "../player";
import { AudioWaveform } from "../player/components/AudioWaveform";
-import type { TimelineElement } from "../player/store/playerStore";
+import type { TimelineClipRenderContext } from "../player/components/TimelineTypes";
+import { usePlayerStore, type TimelineElement } from "../player/store/playerStore";
import { normalizeCompositionSrc } from "./useRenderClipContent";
import { useRenderClipContent } from "./useRenderClipContent";
(globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
afterEach(() => {
+ usePlayerStore.setState({ thumbnailMode: "hidden" });
document.body.innerHTML = "";
});
@@ -67,6 +69,7 @@ describe("useRenderClipContent", () => {
function renderClipContent(
el: TimelineElement,
activePreviewUrl: string | null = "/api/projects/my-project/preview",
+ context?: TimelineClipRenderContext,
): ReactNode {
const host = document.createElement("div");
document.body.append(host);
@@ -80,7 +83,7 @@ describe("useRenderClipContent", () => {
activePreviewUrl,
effectiveTimelineDuration: 12,
});
- content = render(el, { clip: "#222", label: "#fff" });
+ content = render(el, { clip: "#222", label: "#fff" }, context);
return null;
}
@@ -106,6 +109,8 @@ describe("useRenderClipContent", () => {
});
it("passes empty labels to thumbnail content so TimelineClip owns clip names", () => {
+ usePlayerStore.setState({ thumbnailMode: "adaptive" });
+
const cases: Array<{ content: ReactNode; type: unknown }> = [
{
content: renderClipContent({
@@ -166,4 +171,38 @@ describe("useRenderClipContent", () => {
}
}
});
+
+ it("forwards the viewport priority and interaction detail to media work", () => {
+ usePlayerStore.setState({ thumbnailMode: "adaptive", timelineSessionEpoch: 7 });
+
+ const content = renderClipContent(
+ {
+ id: "clip-video",
+ tag: "video",
+ start: 0,
+ duration: 4,
+ track: 0,
+ src: "assets/clip.mp4",
+ },
+ null,
+ { priority: "interaction", rich: true },
+ );
+
+ expect(
+ isValidElement<{
+ projectId: string;
+ sessionEpoch: number;
+ priority: string;
+ rich: boolean;
+ }>(content),
+ ).toBe(true);
+ if (isValidElement(content)) {
+ expect(content.props).toMatchObject({
+ projectId: "my-project",
+ sessionEpoch: 7,
+ priority: "interaction",
+ rich: true,
+ });
+ }
+ });
});
diff --git a/packages/studio/src/hooks/useRenderClipContent.ts b/packages/studio/src/hooks/useRenderClipContent.ts
index 0e01c381fa..14b05a5583 100644
--- a/packages/studio/src/hooks/useRenderClipContent.ts
+++ b/packages/studio/src/hooks/useRenderClipContent.ts
@@ -2,9 +2,12 @@ import { useCallback, type ReactNode } from "react";
import { createElement } from "react";
import { CompositionThumbnail, VideoThumbnail } from "../player";
import type { TimelineElement } from "../player";
+import type { TimelineClipRenderContext } from "../player/components/TimelineTypes";
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 { effectiveThumbnailMode } from "../player/lib/thumbnailPolicy";
export function normalizeCompositionSrc(
compSrc: string,
@@ -51,7 +54,13 @@ function trimFractions(el: TimelineElement): { start?: number; end?: number } {
* Build the waveform element for an audio clip, windowing the rendered peaks to
* the trimmed source slice so the bars track the clip edges.
*/
-function renderAudioClip(el: TimelineElement, pid: string, labelColor: string): ReactNode {
+function renderAudioClip(
+ el: TimelineElement,
+ pid: string,
+ sessionEpoch: number,
+ labelColor: string,
+ context: TimelineClipRenderContext,
+): ReactNode {
const srcRelative = resolvePreviewRelative(el.src, pid);
// Encode each path segment (spaces, parens, U+202F, unicode) so the URL matches
// what the assets panel loads — a raw segment 404s. resolvePreviewRelative
@@ -71,6 +80,9 @@ function renderAudioClip(el: TimelineElement, pid: string, labelColor: string):
labelColor,
trimStartFraction: start,
trimEndFraction: end,
+ projectId: pid,
+ sessionEpoch,
+ priority: context.priority,
});
}
@@ -87,13 +99,29 @@ export function useRenderClipContent({
activePreviewUrl,
effectiveTimelineDuration,
}: UseRenderClipContentOptions) {
+ // Self-sourced so the adaptive policy gates thumbnail generation without App plumbing.
+ const thumbnailMode = usePlayerStore((s) => s.thumbnailMode);
+ const effectiveMode = effectiveThumbnailMode(thumbnailMode);
+ const sessionEpoch = usePlayerStore((s) => s.timelineSessionEpoch);
return useCallback(
// Pre-existing clip-content dispatcher; reduced by extracting renderAudioClip.
// fallow-ignore-next-line complexity
- (el: TimelineElement, style: { clip: string; label: string }): ReactNode => {
+ (
+ el: TimelineElement,
+ style: { clip: string; label: string },
+ context: TimelineClipRenderContext = { priority: "visible", rich: false },
+ ): ReactNode => {
const pid = projectIdRef.current;
if (!pid) return null;
+ // Thumbnail generation disabled (perf) -> plain clip bars. Audio still shows
+ // its waveform (cheap, not a frame thumbnail). Toggle: timeline toolbar.
+ if (effectiveMode === "hidden") {
+ return el.tag === "audio"
+ ? renderAudioClip(el, pid, sessionEpoch, style.label, context)
+ : null;
+ }
+
let compSrc = el.compositionSrc;
if (compSrc) {
compSrc = normalizeCompositionSrc(compSrc, pid, window.location.origin);
@@ -116,6 +144,10 @@ export function useRenderClipContent({
seekTime: 0,
duration: el.duration,
+ projectId: pid,
+ sessionEpoch,
+ priority: context.priority,
+ rich: context.rich,
});
}
@@ -123,7 +155,7 @@ export function useRenderClipContent({
// activePreviewUrl thumbnail branch; audio rows need waveform data, not a
// captured frame from the currently drilled composition preview.
if (el.tag === "audio") {
- return renderAudioClip(el, pid, style.label);
+ return renderAudioClip(el, pid, sessionEpoch, style.label, context);
}
// When drilled into a composition, render all inner elements via
@@ -138,6 +170,10 @@ export function useRenderClipContent({
selectorIndex: el.selectorIndex,
seekTime: el.start,
duration: el.duration,
+ projectId: pid,
+ sessionEpoch,
+ priority: context.priority,
+ rich: context.rich,
});
}
@@ -157,6 +193,10 @@ export function useRenderClipContent({
imageSrc: mediaSrc,
label: "",
labelColor: style.label,
+ projectId: pid,
+ sessionEpoch,
+ priority: context.priority,
+ rich: context.rich,
});
}
return createElement(VideoThumbnail, {
@@ -164,6 +204,12 @@ export function useRenderClipContent({
label: "",
labelColor: style.label,
duration: el.duration,
+ sourceStart: el.playbackStart,
+ sourceRangeDuration: el.duration * (el.playbackRate ?? 1),
+ projectId: pid,
+ sessionEpoch,
+ priority: context.priority,
+ rich: context.rich,
});
}
@@ -177,11 +223,22 @@ export function useRenderClipContent({
selectorIndex: el.selectorIndex,
seekTime: el.start,
duration: el.duration,
+ projectId: pid,
+ sessionEpoch,
+ priority: context.priority,
+ rich: context.rich,
});
}
return null;
},
- [projectIdRef, compIdToSrc, activePreviewUrl, effectiveTimelineDuration],
+ [
+ projectIdRef,
+ compIdToSrc,
+ activePreviewUrl,
+ effectiveTimelineDuration,
+ effectiveMode,
+ sessionEpoch,
+ ],
);
}
diff --git a/packages/studio/src/hooks/useThumbnailLease.test.tsx b/packages/studio/src/hooks/useThumbnailLease.test.tsx
new file mode 100644
index 0000000000..18595f8287
--- /dev/null
+++ b/packages/studio/src/hooks/useThumbnailLease.test.tsx
@@ -0,0 +1,150 @@
+// @vitest-environment happy-dom
+
+import React, { act } from "react";
+import { createRoot } from "react-dom/client";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { ThumbnailScheduler, type ThumbnailRequest } from "../player/lib/thumbnailScheduler";
+import { useThumbnailLease } from "./useThumbnailLease";
+
+(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+afterEach(() => {
+ document.body.innerHTML = "";
+});
+
+describe("useThumbnailLease", () => {
+ it("subscribes once, publishes the result, and releases on unmount", async () => {
+ const scheduler = new ThumbnailScheduler();
+ const load = vi.fn(async () => ({
+ value: { kind: "image" as const, url: "blob:poster", aspect: 16 / 9 },
+ weight: 10,
+ }));
+ const request: ThumbnailRequest = {
+ key: "poster",
+ projectId: "demo",
+ sessionEpoch: 1,
+ kind: "image",
+ priority: "visible",
+ load,
+ };
+ let status = "missing";
+
+ function Probe() {
+ status = useThumbnailLease(request, scheduler).status;
+ return null;
+ }
+
+ const root = createRoot(document.createElement("div"));
+ await act(async () => {
+ root.render(React.createElement(Probe));
+ await Promise.resolve();
+ });
+ expect(load).toHaveBeenCalledTimes(1);
+ expect(status).toBe("ready");
+ expect(scheduler.getDiagnostics().leases).toBe(1);
+
+ act(() => root.unmount());
+ expect(scheduler.getDiagnostics().leases).toBe(0);
+ });
+
+ it("does not acquire work for a null request", () => {
+ const scheduler = new ThumbnailScheduler();
+ let status = "missing";
+ function Probe() {
+ status = useThumbnailLease(null, scheduler).status;
+ return null;
+ }
+ const root = createRoot(document.createElement("div"));
+ act(() => root.render(React.createElement(Probe)));
+ expect(status).toBe("idle");
+ expect(scheduler.getDiagnostics().leases).toBe(0);
+ act(() => root.unmount());
+ });
+
+ it("updates priority without restarting the active request", async () => {
+ const scheduler = new ThumbnailScheduler();
+ let resolve!: (value: {
+ value: { kind: "image"; url: string; aspect: number };
+ weight: number;
+ }) => void;
+ const pending = new Promise<{
+ value: { kind: "image"; url: string; aspect: number };
+ weight: number;
+ }>((accept) => {
+ resolve = accept;
+ });
+ const load = vi.fn(() => pending);
+ let priority: ThumbnailRequest["priority"] = "overscan";
+ function Probe() {
+ useThumbnailLease(
+ {
+ key: "same-content",
+ projectId: "demo",
+ sessionEpoch: 1,
+ kind: "image",
+ priority,
+ load,
+ },
+ scheduler,
+ );
+ return null;
+ }
+ const root = createRoot(document.createElement("div"));
+ act(() => root.render(React.createElement(Probe)));
+ priority = "interaction";
+ act(() => root.render(React.createElement(Probe)));
+ expect(load).toHaveBeenCalledTimes(1);
+
+ await act(async () => {
+ resolve({ value: { kind: "image", url: "blob:done", aspect: 1 }, weight: 1 });
+ await pending;
+ });
+ act(() => root.unmount());
+ });
+
+ it("resubscribes when the request work shape changes", async () => {
+ const scheduler = new ThumbnailScheduler();
+ const imageLoad = vi.fn(async () => ({
+ value: { kind: "image" as const, url: "blob:image", aspect: 1 },
+ weight: 1,
+ }));
+ const videoLoad = vi.fn(async () => ({
+ value: { kind: "image" as const, url: "blob:video", aspect: 1 },
+ weight: 1,
+ }));
+ let kind: ThumbnailRequest["kind"] = "image";
+ let rich = false;
+ function Probe() {
+ useThumbnailLease(
+ {
+ key: "same-content",
+ projectId: "demo",
+ sessionEpoch: 1,
+ kind,
+ rich,
+ priority: "visible",
+ load: kind === "image" ? imageLoad : videoLoad,
+ },
+ scheduler,
+ );
+ return null;
+ }
+ const root = createRoot(document.createElement("div"));
+ await act(async () => {
+ root.render(React.createElement(Probe));
+ await Promise.resolve();
+ });
+
+ kind = "video";
+ rich = true;
+ await act(async () => {
+ root.render(React.createElement(Probe));
+ await Promise.resolve();
+ });
+
+ expect(imageLoad).toHaveBeenCalledTimes(1);
+ expect(videoLoad).toHaveBeenCalledTimes(1);
+ expect(scheduler.getDiagnostics().leases).toBe(1);
+ act(() => root.unmount());
+ });
+});
diff --git a/packages/studio/src/hooks/useThumbnailLease.ts b/packages/studio/src/hooks/useThumbnailLease.ts
new file mode 100644
index 0000000000..01ecd82c39
--- /dev/null
+++ b/packages/studio/src/hooks/useThumbnailLease.ts
@@ -0,0 +1,44 @@
+import { useCallback, useLayoutEffect, useRef, useSyncExternalStore } from "react";
+import {
+ createThumbnailRequestIdentity,
+ thumbnailScheduler,
+ type ThumbnailRequest,
+ type ThumbnailScheduler,
+ type ThumbnailSnapshot,
+} from "../player/lib/thumbnailScheduler";
+
+const IDLE: ThumbnailSnapshot = Object.freeze({ status: "idle" });
+
+export function useThumbnailLease(
+ request: ThumbnailRequest | null,
+ scheduler: ThumbnailScheduler = thumbnailScheduler,
+): ThumbnailSnapshot {
+ const requestRef = useRef(request);
+ requestRef.current = request;
+ const leaseRef = useRef<ReturnType<ThumbnailScheduler["acquire"]> | null>(null);
+ const identity = request ? createThumbnailRequestIdentity(request) : null;
+ const priority = request?.priority;
+ const subscribe = useCallback(
+ (listener: () => void) => {
+ const current = requestRef.current;
+ if (!current || identity === null) return () => {};
+ const lease = scheduler.acquire(current, listener);
+ leaseRef.current = lease;
+ return () => {
+ if (leaseRef.current === lease) leaseRef.current = null;
+ lease.release();
+ };
+ },
+ [identity, scheduler],
+ );
+ const getSnapshot = useCallback(() => {
+ const current = requestRef.current;
+ return current && identity !== null ? scheduler.getSnapshot(current) : IDLE;
+ }, [identity, scheduler]);
+
+ useLayoutEffect(() => {
+ if (priority) leaseRef.current?.updatePriority(priority);
+ }, [priority]);
+
+ return useSyncExternalStore(subscribe, getSnapshot, () => IDLE);
+}
diff --git a/packages/studio/src/hooks/useTimelineSelectionPreviewSync.test.tsx b/packages/studio/src/hooks/useTimelineSelectionPreviewSync.test.tsx
index 038ae30dd5..2ffc3442dd 100644
--- a/packages/studio/src/hooks/useTimelineSelectionPreviewSync.test.tsx
+++ b/packages/studio/src/hooks/useTimelineSelectionPreviewSync.test.tsx
@@ -24,6 +24,7 @@ interface HarnessProps {
options?: { revealPanel?: boolean; additive?: boolean; preserveGroup?: boolean },
) => void;
applyMarqueeSelection: (selections: DomEditSelection[], additive: boolean) => void;
+ onSelectionNotFound: () => void;
}
afterEach(() => {
@@ -67,8 +68,8 @@ function makeSyncFixture() {
const firstSelection = makeSelection("First", firstElement);
const secondSelection = makeSelection("Second", secondElement);
const timelineElements: TimelineElement[] = [
- { id: "clip-1", tag: "div", start: 0, duration: 1, track: 0 },
- { id: "clip-2", tag: "div", start: 1, duration: 1, track: 1 },
+ { id: "clip-1", domId: "clip-1", tag: "div", start: 0, duration: 1, track: 0 },
+ { id: "clip-2", domId: "clip-2", tag: "div", start: 1, duration: 1, track: 1 },
];
const selectionById = new Map([
["clip-1", firstSelection],
@@ -96,6 +97,7 @@ describe("useTimelineSelectionPreviewSync", () => {
buildDomSelectionForTimelineElement,
applyDomSelection,
applyMarqueeSelection,
+ onSelectionNotFound: vi.fn(),
});
expect(applyMarqueeSelection).toHaveBeenCalledWith([secondSelection, firstSelection], false);
@@ -108,6 +110,21 @@ describe("useTimelineSelectionPreviewSync", () => {
const applyDomSelection = vi.fn();
const applyMarqueeSelection = vi.fn();
const harness = renderHarness();
+ const buildDomSelectionForTimelineElement = vi.fn(async (element: TimelineElement) => {
+ return selectionById.get(element.id) ?? null;
+ });
+
+ await harness.rerender({
+ selectedElementId: "clip-1",
+ selectedElementIds: new Set(["clip-1"]),
+ timelineElements,
+ domEditSelection: firstSelection,
+ domEditGroupSelections: [firstSelection],
+ buildDomSelectionForTimelineElement,
+ applyDomSelection,
+ applyMarqueeSelection,
+ onSelectionNotFound: vi.fn(),
+ });
await harness.rerender({
selectedElementId: null,
@@ -115,15 +132,72 @@ describe("useTimelineSelectionPreviewSync", () => {
timelineElements,
domEditSelection: firstSelection,
domEditGroupSelections: [firstSelection],
- buildDomSelectionForTimelineElement: vi.fn(async (element: TimelineElement) => {
- return selectionById.get(element.id) ?? null;
- }),
+ buildDomSelectionForTimelineElement,
applyDomSelection,
applyMarqueeSelection,
+ onSelectionNotFound: vi.fn(),
});
expect(applyDomSelection).toHaveBeenCalledWith(null, { revealPanel: false });
expect(applyMarqueeSelection).not.toHaveBeenCalled();
harness.cleanup();
});
+
+ it("warns once while retrying a timeline selection after preview refreshes", async () => {
+ const { secondSelection, timelineElements } = makeSyncFixture();
+ const applyDomSelection = vi.fn();
+ const applyMarqueeSelection = vi.fn();
+ const onSelectionNotFound = vi.fn();
+ let previewReady = false;
+ const buildDomSelectionForTimelineElement = vi.fn(async () =>
+ previewReady ? secondSelection : null,
+ );
+ const selectedElementIds = new Set(["clip-2"]);
+ const harness = renderHarness();
+
+ await harness.rerender({
+ selectedElementId: "clip-2",
+ selectedElementIds,
+ timelineElements,
+ domEditSelection: null,
+ domEditGroupSelections: [],
+ buildDomSelectionForTimelineElement,
+ applyDomSelection,
+ applyMarqueeSelection,
+ onSelectionNotFound,
+ });
+
+ expect(onSelectionNotFound).toHaveBeenCalledOnce();
+ expect(applyDomSelection).not.toHaveBeenCalled();
+
+ await harness.rerender({
+ selectedElementId: "clip-2",
+ selectedElementIds,
+ timelineElements: [...timelineElements],
+ domEditSelection: null,
+ domEditGroupSelections: [],
+ buildDomSelectionForTimelineElement,
+ applyDomSelection,
+ applyMarqueeSelection,
+ onSelectionNotFound,
+ });
+
+ expect(onSelectionNotFound).toHaveBeenCalledOnce();
+
+ previewReady = true;
+ await harness.rerender({
+ selectedElementId: "clip-2",
+ selectedElementIds,
+ timelineElements: [...timelineElements],
+ domEditSelection: null,
+ domEditGroupSelections: [],
+ buildDomSelectionForTimelineElement,
+ applyDomSelection,
+ applyMarqueeSelection,
+ onSelectionNotFound,
+ });
+
+ expect(applyDomSelection).toHaveBeenCalledWith(secondSelection);
+ harness.cleanup();
+ });
});
diff --git a/packages/studio/src/hooks/useTimelineSelectionPreviewSync.ts b/packages/studio/src/hooks/useTimelineSelectionPreviewSync.ts
index 33281c4df1..656568cb93 100644
--- a/packages/studio/src/hooks/useTimelineSelectionPreviewSync.ts
+++ b/packages/studio/src/hooks/useTimelineSelectionPreviewSync.ts
@@ -1,4 +1,4 @@
-import { useEffect, useMemo } from "react";
+import { useEffect, useMemo, useRef } from "react";
import type { TimelineElement } from "../player";
import type { DomEditSelection } from "../components/editor/domEditing";
import { resolveTimelineIdForSelection } from "../utils/studioHelpers";
@@ -18,6 +18,7 @@ interface UseTimelineSelectionPreviewSyncParams {
options?: { revealPanel?: boolean; additive?: boolean; preserveGroup?: boolean },
) => void;
applyMarqueeSelection: (selections: DomEditSelection[], additive: boolean) => void;
+ onSelectionNotFound: () => void;
}
function orderSelectedIds(ids: Set<string>, anchor: string | null): string[] {
@@ -56,34 +57,51 @@ export function useTimelineSelectionPreviewSync({
buildDomSelectionForTimelineElement,
applyDomSelection,
applyMarqueeSelection,
+ onSelectionNotFound,
}: UseTimelineSelectionPreviewSyncParams): void {
const selectedIds = useMemo(
() => orderSelectedIds(selectedElementIds, selectedElementId),
[selectedElementId, selectedElementIds],
);
const selectedKey = selectedIds.join("\0");
+ const domEditSelectionRef = useRef(domEditSelection);
+ const domEditGroupSelectionsRef = useRef(domEditGroupSelections);
+ const lastSyncedSelectedKeyRef = useRef("");
+ const missingSelectionKeyRef = useRef("");
+ domEditSelectionRef.current = domEditSelection;
+ domEditGroupSelectionsRef.current = domEditGroupSelections;
useEffect(() => {
+ const previousSelectedKey = lastSyncedSelectedKeyRef.current;
+ lastSyncedSelectedKeyRef.current = selectedKey;
+ const currentDomEditSelection = domEditSelectionRef.current;
+ const currentDomEditGroupSelections = domEditGroupSelectionsRef.current;
const currentSelections =
- domEditGroupSelections.length > 1
- ? domEditGroupSelections
- : domEditSelection
- ? [domEditSelection]
+ currentDomEditGroupSelections.length > 1
+ ? currentDomEditGroupSelections
+ : currentDomEditSelection
+ ? [currentDomEditSelection]
: [];
const currentIds = currentSelections
.map((selection) =>
resolveTimelineIdForSelection(selection, timelineElements, activeCompPath),
)
.filter((id): id is string => Boolean(id));
- const currentAnchor = domEditSelection
- ? resolveTimelineIdForSelection(domEditSelection, timelineElements, activeCompPath)
+ const currentAnchor = currentDomEditSelection
+ ? resolveTimelineIdForSelection(currentDomEditSelection, timelineElements, activeCompPath)
: null;
if (selectedIds.length === 0) {
- if (currentSelections.length > 0) applyDomSelection(null, { revealPanel: false });
+ missingSelectionKeyRef.current = "";
+ if (previousSelectedKey.length > 0 && currentIds.length > 0) {
+ applyDomSelection(null, { revealPanel: false });
+ }
+ return;
+ }
+ if (selectionIdsMatch(currentIds, selectedIds, currentAnchor, selectedElementId)) {
+ missingSelectionKeyRef.current = "";
return;
}
- if (selectionIdsMatch(currentIds, selectedIds, currentAnchor, selectedElementId)) return;
let cancelled = false;
const syncSelection = async () => {
@@ -101,11 +119,18 @@ export function useTimelineSelectionPreviewSync({
// shrunk set back and silently drop the members whose DOM node was not ready.
// Bail instead; a later effect run (on timelineElements/DOM change) applies the
// full set once every resolvable member has a live node.
- if (selections.length < resolvableCount) return;
+ if (selections.length < resolvableCount) {
+ if (missingSelectionKeyRef.current !== selectedKey) {
+ missingSelectionKeyRef.current = selectedKey;
+ onSelectionNotFound();
+ }
+ return;
+ }
+ missingSelectionKeyRef.current = "";
if (selections.length === 0) {
applyDomSelection(null, { revealPanel: false });
} else if (selections.length === 1) {
- applyDomSelection(selections[0], { revealPanel: false });
+ applyDomSelection(selections[0]);
} else {
applyMarqueeSelection(selections, false);
}
@@ -115,13 +140,15 @@ export function useTimelineSelectionPreviewSync({
return () => {
cancelled = true;
};
+ // DOM selection changes are read through refs. Depending on them directly
+ // would let the preview-to-timeline echo cancel an in-flight timeline click.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
}, [
activeCompPath,
applyDomSelection,
applyMarqueeSelection,
buildDomSelectionForTimelineElement,
- domEditGroupSelections,
- domEditSelection,
+ onSelectionNotFound,
selectedElementId,
selectedIds,
selectedKey,
diff --git a/packages/studio/src/player/components/AudioWaveform.test.tsx b/packages/studio/src/player/components/AudioWaveform.test.tsx
new file mode 100644
index 0000000000..30e79037bc
--- /dev/null
+++ b/packages/studio/src/player/components/AudioWaveform.test.tsx
@@ -0,0 +1,53 @@
+// @vitest-environment happy-dom
+
+import React, { act } from "react";
+import { createRoot } from "react-dom/client";
+import { afterEach, describe, expect, it, vi } from "vitest";
+const { leaseSpy } = vi.hoisted(() => ({
+ leaseSpy: vi.fn((_request: unknown) => ({ status: "loading" as const })),
+}));
+
+vi.mock("../../hooks/useThumbnailLease", () => ({
+ useThumbnailLease: leaseSpy,
+}));
+
+import { AudioWaveform } from "./AudioWaveform";
+
+(globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+afterEach(() => {
+ leaseSpy.mockClear();
+ document.body.innerHTML = "";
+});
+
+describe("AudioWaveform", () => {
+ it("leases waveform decoding with the clip's project, session, and viewport priority", () => {
+ const host = document.createElement("div");
+ document.body.append(host);
+ const root = createRoot(host);
+
+ act(() => {
+ root.render(
+ <AudioWaveform
+ audioUrl="/media/voice.wav"
+ label=""
+ labelColor="#fff"
+ projectId="project-a"
+ sessionEpoch={9}
+ priority="interaction"
+ />,
+ );
+ });
+
+ expect(leaseSpy).toHaveBeenCalled();
+ expect(leaseSpy.mock.calls.at(-1)?.[0]).toMatchObject({
+ projectId: "project-a",
+ sessionEpoch: 9,
+ kind: "waveform",
+ priority: "interaction",
+ rich: false,
+ });
+
+ act(() => root.unmount());
+ });
+});
diff --git a/packages/studio/src/player/components/AudioWaveform.tsx b/packages/studio/src/player/components/AudioWaveform.tsx
index 2095ee1b6f..b6f10bf051 100644
--- a/packages/studio/src/player/components/AudioWaveform.tsx
+++ b/packages/studio/src/player/components/AudioWaveform.tsx
@@ -1,74 +1,105 @@
-import { memo, useRef, useState, useCallback, useEffect } from "react";
+import { memo, useCallback, useMemo, useRef } from "react";
+import { useMountEffect } from "../../hooks/useMountEffect";
+import { useThumbnailLease } from "../../hooks/useThumbnailLease";
+import { createThumbnailKey, type ThumbnailPriority } from "../lib/thumbnailScheduler";
interface AudioWaveformProps {
audioUrl: string;
waveformUrl?: string;
label: string;
labelColor: string;
- /**
- * Fraction (0–1) of the source the clip starts at, after the media-start
- * trim. Defaults to 0 (no front trim).
- */
trimStartFraction?: number;
- /**
- * Fraction (0–1) of the source the clip ends at. Defaults to 1 (no tail
- * trim). Together these window the rendered peaks to the trimmed slice so the
- * waveform tracks the clip edges instead of squeezing the whole file in.
- */
trimEndFraction?: number;
+ projectId: string;
+ sessionEpoch: number;
+ priority: ThumbnailPriority;
}
-const BAR_W = 2;
-const GAP = 1;
-const STEP = BAR_W + GAP;
+const BAR_WIDTH = 2;
+const BAR_STEP = 3;
-/** Downsample PCM channel data into peak amplitudes (0–1). */
function extractPeaks(channelData: Float32Array, barCount: number): number[] {
const peaks: number[] = [];
const samplesPerBar = Math.floor(channelData.length / barCount);
if (samplesPerBar === 0) return Array(barCount).fill(0);
- for (let i = 0; i < barCount; i++) {
+ for (let index = 0; index < barCount; index++) {
let max = 0;
- const start = i * samplesPerBar;
+ const start = index * samplesPerBar;
const end = Math.min(start + samplesPerBar, channelData.length);
- for (let j = start; j < end; j++) {
- // fallow-ignore-next-line code-duplication
- const abs = Math.abs(channelData[j] ?? 0);
- if (abs > max) max = abs;
+ for (let sample = start; sample < end; sample++) {
+ max = Math.max(max, Math.abs(channelData[sample] ?? 0));
}
peaks.push(max);
}
const maxPeak = Math.max(...peaks, 0.001);
- return peaks.map((p) => p / maxPeak);
+ return peaks.map((peak) => peak / maxPeak);
}
-/** Deterministic fake waveform as fallback (matches demo app). */
function fakePeaks(url: string, count: number): number[] {
let seed = 0;
- for (let i = 0; i < url.length; i++) seed = ((seed << 5) - seed + url.charCodeAt(i)) | 0;
+ for (let index = 0; index < url.length; index++) {
+ seed = ((seed << 5) - seed + url.charCodeAt(index)) | 0;
+ }
seed = Math.abs(seed) || 42;
- const rand = () => {
+ const random = () => {
seed = (seed * 16807) % 2147483647;
return (seed & 0x7fffffff) / 2147483647;
};
- const peaks: number[] = [];
- for (let i = 0; i < count; i++) {
- const t = i / count;
- const envelope = 0.3 + 0.3 * Math.sin(t * Math.PI * 3.2) + 0.2 * Math.sin(t * Math.PI * 7.1);
- peaks.push(Math.max(0.05, Math.min(1, envelope * (0.4 + 0.6 * rand()))));
+ return Array.from({ length: count }, (_, index) => {
+ const time = index / count;
+ const envelope =
+ 0.3 + 0.3 * Math.sin(time * Math.PI * 3.2) + 0.2 * Math.sin(time * Math.PI * 7.1);
+ return Math.max(0.05, Math.min(1, envelope * (0.4 + 0.6 * random())));
+ });
+}
+
+async function loadWaveform(
+ audioUrl: string,
+ waveformUrl: string | undefined,
+ signal: AbortSignal,
+): Promise<number[]> {
+ try {
+ return waveformUrl
+ ? await fetchWaveformPeaks(waveformUrl, signal)
+ : await decodeWaveformPeaks(audioUrl, signal);
+ } catch (error) {
+ if (signal.aborted) throw error;
+ return fakePeaks(waveformUrl ?? audioUrl, 4000);
}
- return peaks;
}
-// Module-level cache so decoded audio persists across re-renders and re-mounts
-const peaksCache = new Map<string, number[]>();
-const decodeInFlight = new Map<string, Promise<number[]>>();
+async function fetchWaveformPeaks(url: string, signal: AbortSignal): Promise<number[]> {
+ const response = await fetch(url, { signal });
+ if (!response.ok) throw new Error(`Waveform request failed (${response.status})`);
+ const data: unknown = await response.json();
+ if (
+ typeof data !== "object" ||
+ data === null ||
+ !("peaks" in data) ||
+ !Array.isArray(data.peaks) ||
+ !data.peaks.every((peak) => typeof peak === "number")
+ ) {
+ throw new Error("Invalid waveform response");
+ }
+ return data.peaks;
+}
-/**
- * Audio waveform rendered from real PCM data via Web Audio API.
- * Falls back to a deterministic fake pattern if decoding fails.
- * Bars grow from bottom to top, rendered as CSS divs for zoom resilience.
- */
+async function decodeWaveformPeaks(url: string, signal: AbortSignal): Promise<number[]> {
+ const response = await fetch(url, { signal });
+ if (!response.ok) throw new Error(`Audio request failed (${response.status})`);
+ const buffer = await response.arrayBuffer();
+ if (signal.aborted) throw new DOMException("Aborted", "AbortError");
+ const context = new AudioContext();
+ try {
+ const decoded = await context.decodeAudioData(buffer);
+ if (signal.aborted) throw new DOMException("Aborted", "AbortError");
+ return extractPeaks(decoded.getChannelData(0), 4000);
+ } finally {
+ await context.close();
+ }
+}
+
+/** Bounded waveform subscriber; cache, cancellation and dedupe live in one scheduler. */
export const AudioWaveform = memo(function AudioWaveform({
audioUrl,
waveformUrl,
@@ -76,130 +107,96 @@ export const AudioWaveform = memo(function AudioWaveform({
labelColor,
trimStartFraction,
trimEndFraction,
+ projectId,
+ sessionEpoch,
+ priority,
}: AudioWaveformProps) {
- const containerRef = useRef<HTMLDivElement | null>(null);
- const barsRef = useRef<HTMLDivElement | null>(null);
- const roRef = useRef<ResizeObserver | null>(null);
+ const canvasRef = useRef<HTMLCanvasElement | null>(null);
+ const observerRef = useRef<ResizeObserver | null>(null);
const cacheKey = waveformUrl ?? audioUrl;
- const [peaks, setPeaks] = useState<number[] | null>(peaksCache.get(cacheKey) ?? null);
-
- useEffect(() => {
- if (peaks || !cacheKey) return;
-
- let cancelled = false;
-
- let promise = decodeInFlight.get(cacheKey);
- if (!promise) {
- promise = (
- waveformUrl
- ? fetch(waveformUrl)
- .then((r) => r.json())
- .then((d: { peaks?: number[] }) => {
- if (!Array.isArray(d.peaks)) throw new Error("bad response");
- return d.peaks;
- })
- : fetch(audioUrl)
- .then((r) => r.arrayBuffer())
- .then((buf) => {
- const ctx = new AudioContext();
- return ctx.decodeAudioData(buf).finally(() => ctx.close());
- })
- .then((decoded) => extractPeaks(decoded.getChannelData(0), 4000))
- )
- .catch(() => fakePeaks(cacheKey, 4000))
- .then((p) => {
- peaksCache.set(cacheKey, p);
- return p;
- })
- .finally(() => decodeInFlight.delete(cacheKey));
-
- decodeInFlight.set(cacheKey, promise);
- }
-
- promise.then((p) => {
- if (!cancelled) setPeaks(p);
- });
- return () => {
- cancelled = true;
- };
- }, [audioUrl, waveformUrl, cacheKey, peaks]);
+ const request = useMemo(
+ () => ({
+ key: createThumbnailKey({ kind: "waveform", source: cacheKey }),
+ projectId,
+ sessionEpoch,
+ kind: "waveform" as const,
+ priority,
+ rich: false,
+ load: async (signal: AbortSignal) => {
+ const peaks = await loadWaveform(audioUrl, waveformUrl, signal);
+ return {
+ value: { kind: "waveform" as const, peaks },
+ weight: peaks.length * Float64Array.BYTES_PER_ELEMENT,
+ };
+ },
+ }),
+ [audioUrl, cacheKey, priority, projectId, sessionEpoch, waveformUrl],
+ );
+ const snapshot = useThumbnailLease(cacheKey ? request : null);
+ const peaks =
+ snapshot.status === "ready" && snapshot.value.kind === "waveform" ? snapshot.value.peaks : null;
- // Draw bars into the container using innerHTML (fast, zoom-resilient)
const draw = useCallback(() => {
- const container = containerRef.current;
- const barsEl = barsRef.current;
- if (!container || !barsEl || !peaks) return;
-
- // Window the peaks to the trimmed slice [start, end) of the source so the
- // bars track the clip edges. Clamp to a valid, non-empty range.
- const winStart = Math.max(0, Math.min(1, trimStartFraction ?? 0));
- const winEnd = Math.max(winStart, Math.min(1, trimEndFraction ?? 1));
- const lo = Math.floor(winStart * peaks.length);
- const hi = Math.max(lo + 1, Math.ceil(winEnd * peaks.length));
- const span = hi - lo;
-
- // Fill the full (possibly zoomed) clip width with STEP-spaced bars, resampling
- // the windowed peaks across them — upsampling (repeating peaks) when the clip
- // is wider than the slice has samples, so the waveform stretches with zoom
- // instead of stopping partway across.
- const w = container.clientWidth || 400;
- const barCount = Math.max(0, Math.floor(w / STEP));
-
- let html = "";
- for (let i = 0; i < barCount; i++) {
- // Map bar index to peak index within the windowed range (resample)
- const peakIdx = lo + Math.min(span - 1, Math.floor((i / barCount) * span));
- const amp = peaks[peakIdx] ?? 0;
- const pct = Math.max(3, Math.round(amp * 100));
- const opacity = (0.45 + amp * 0.4).toFixed(2);
- html += `<div style="position:absolute;bottom:0;left:${i * STEP}px;width:${BAR_W}px;height:${pct}%;background:rgba(75,163,210,${opacity})"></div>`;
+ const canvas = canvasRef.current;
+ if (!canvas || !peaks) return;
+ const width = Math.max(1, canvas.clientWidth);
+ const height = Math.max(1, canvas.clientHeight);
+ const scale = window.devicePixelRatio || 1;
+ canvas.width = Math.ceil(width * scale);
+ canvas.height = Math.ceil(height * scale);
+ const context = canvas.getContext("2d");
+ if (!context) return;
+ context.scale(scale, scale);
+ context.clearRect(0, 0, width, height);
+ const startFraction = Math.max(0, Math.min(1, trimStartFraction ?? 0));
+ const endFraction = Math.max(startFraction, Math.min(1, trimEndFraction ?? 1));
+ const start = Math.floor(startFraction * peaks.length);
+ const end = Math.max(start + 1, Math.ceil(endFraction * peaks.length));
+ const span = end - start;
+ const barCount = Math.floor(width / BAR_STEP);
+ for (let index = 0; index < barCount; index++) {
+ const peakIndex = start + Math.min(span - 1, Math.floor((index / barCount) * span));
+ const amplitude = peaks[peakIndex] ?? 0;
+ const barHeight = Math.max(2, amplitude * height);
+ context.fillStyle = `rgba(75,163,210,${(0.45 + amplitude * 0.4).toFixed(2)})`;
+ context.fillRect(index * BAR_STEP, height - barHeight, BAR_WIDTH, barHeight);
}
- barsEl.innerHTML = html;
- }, [peaks, trimStartFraction, trimEndFraction]);
+ }, [peaks, trimEndFraction, trimStartFraction]);
- // Observe container size and redraw
- const setContainerRef = useCallback(
- (el: HTMLDivElement | null) => {
- roRef.current?.disconnect();
- containerRef.current = el;
- if (!el) return;
+ const setCanvasRef = useCallback(
+ (canvas: HTMLCanvasElement | null) => {
+ observerRef.current?.disconnect();
+ canvasRef.current = canvas;
+ if (!canvas) return;
draw();
- roRef.current = new ResizeObserver(() => draw());
- roRef.current.observe(el);
+ observerRef.current = new ResizeObserver(draw);
+ observerRef.current.observe(canvas);
},
[draw],
);
- // Redraw when peaks arrive
- useEffect(() => {
- draw();
- }, [draw]);
-
- useEffect(
- () => () => {
- roRef.current?.disconnect();
- },
- [],
- );
+ useMountEffect(() => () => observerRef.current?.disconnect());
return (
- <div ref={setContainerRef} className="absolute inset-0 overflow-hidden">
- <div ref={barsRef} className="absolute left-0 right-0 bottom-0" style={{ top: 16 }} />
- {/* Shimmer while decoding */}
- {!peaks && (
+ <div className="absolute inset-0 overflow-hidden">
+ <canvas
+ ref={setCanvasRef}
+ className="absolute inset-x-0 bottom-0 w-full"
+ style={{ top: 16 }}
+ />
+ {snapshot.status === "loading" && (
<div
- className="absolute left-0 right-0 bottom-0 animate-pulse"
+ className="absolute inset-x-0 bottom-0 top-4 animate-pulse"
style={{
- top: 16,
background:
"linear-gradient(90deg, rgba(255,255,255,0.02) 0%, rgba(255,255,255,0.05) 50%, rgba(255,255,255,0.02) 100%)",
}}
/>
)}
{label && (
- <div className="absolute top-0 left-0 right-0 px-1.5 py-0.5 z-10">
+ <div className="absolute inset-x-0 top-0 z-10 px-1.5 py-0.5">
<span
- className="text-[9px] font-semibold truncate block leading-tight"
+ className="block truncate text-[9px] font-semibold leading-tight"
style={{ color: labelColor, textShadow: "0 1px 3px rgba(0,0,0,0.9)" }}
>
{label}
diff --git a/packages/studio/src/player/components/CompositionThumbnail.test.ts b/packages/studio/src/player/components/CompositionThumbnail.test.ts
index 4690a53b39..3ec97bd634 100644
--- a/packages/studio/src/player/components/CompositionThumbnail.test.ts
+++ b/packages/studio/src/player/components/CompositionThumbnail.test.ts
@@ -2,7 +2,8 @@
import React, { act } from "react";
import { createRoot, type Root } from "react-dom/client";
-import { afterEach, beforeEach, describe, expect, it } from "vitest";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { thumbnailScheduler } from "../lib/thumbnailScheduler";
import { buildCompositionThumbnailUrl, CompositionThumbnail } from "./CompositionThumbnail";
Object.defineProperty(globalThis, "IS_REACT_ACT_ENVIRONMENT", {
@@ -31,12 +32,18 @@ class MockImage {
const originalResizeObserver = globalThis.ResizeObserver;
const originalImage = globalThis.Image;
+const originalFetch = globalThis.fetch;
+const originalCreateObjectURL = URL.createObjectURL;
+const originalRevokeObjectURL = URL.revokeObjectURL;
let host: HTMLDivElement;
let root: Root | null = null;
beforeEach(() => {
globalThis.ResizeObserver = MockResizeObserver as unknown as typeof ResizeObserver;
globalThis.Image = MockImage as unknown as typeof Image;
+ globalThis.fetch = vi.fn(async () => new Response(new Blob(["thumbnail"]), { status: 200 }));
+ URL.createObjectURL = vi.fn(() => "blob:composition-thumbnail");
+ URL.revokeObjectURL = vi.fn();
MockImage.instances = [];
host = document.createElement("div");
document.body.append(host);
@@ -45,8 +52,12 @@ beforeEach(() => {
afterEach(() => {
act(() => root?.unmount());
root = null;
+ thumbnailScheduler.invalidateProject("/api/projects/demo/preview");
globalThis.ResizeObserver = originalResizeObserver;
globalThis.Image = originalImage;
+ globalThis.fetch = originalFetch;
+ URL.createObjectURL = originalCreateObjectURL;
+ URL.revokeObjectURL = originalRevokeObjectURL;
document.body.replaceChildren();
});
@@ -68,9 +79,9 @@ describe("buildCompositionThumbnailUrl", () => {
});
describe("CompositionThumbnail", () => {
- function renderThumbnail(): MockImage {
+ async function renderThumbnail(): Promise<MockImage> {
root = createRoot(host);
- act(() => {
+ await act(async () => {
root!.render(
React.createElement(CompositionThumbnail, {
previewUrl: "/api/projects/demo/preview",
@@ -78,19 +89,27 @@ describe("CompositionThumbnail", () => {
labelColor: "#fff",
}),
);
+ await new Promise((resolve) => setTimeout(resolve, 0));
});
const probe = MockImage.instances[0];
if (!probe) throw new Error("Expected an image probe");
return probe;
}
- it("renders visible tiles after the off-DOM probe loads", () => {
- const probe = renderThumbnail();
+ it("renders visible tiles after the scheduled off-DOM probe loads", async () => {
+ const probe = await renderThumbnail();
- act(() => {
+ expect(globalThis.fetch).toHaveBeenCalledWith(
+ expect.stringContaining("/api/projects/demo/thumbnail/index.html"),
+ expect.objectContaining({ signal: expect.any(AbortSignal) }),
+ );
+ expect(probe.src).toBe("blob:composition-thumbnail");
+
+ await act(async () => {
probe.naturalWidth = 1920;
probe.naturalHeight = 1080;
probe.onload?.();
+ await new Promise((resolve) => setTimeout(resolve, 0));
});
const tiles = [...host.querySelectorAll("img")];
@@ -98,16 +117,20 @@ describe("CompositionThumbnail", () => {
expect(tiles.every((tile) => !tile.classList.contains("hidden"))).toBe(true);
});
- it("aborts its off-DOM image probe when unmounted", () => {
- const probe = renderThumbnail();
+ it("aborts its scheduled off-DOM image probe when unmounted", async () => {
+ const probe = await renderThumbnail();
expect(host.querySelector("img")).toBeNull();
- expect(probe.src).toContain("/api/projects/demo/thumbnail/index.html");
+ expect(probe.src).toBe("blob:composition-thumbnail");
- act(() => root?.unmount());
+ await act(async () => {
+ root?.unmount();
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ });
root = null;
expect(probe.onload).toBeNull();
expect(probe.onerror).toBeNull();
expect(probe.src).toBe("");
+ expect(URL.revokeObjectURL).toHaveBeenCalledWith("blob:composition-thumbnail");
});
});
diff --git a/packages/studio/src/player/components/CompositionThumbnail.tsx b/packages/studio/src/player/components/CompositionThumbnail.tsx
index e8e35ec27b..837984ad64 100644
--- a/packages/studio/src/player/components/CompositionThumbnail.tsx
+++ b/packages/studio/src/player/components/CompositionThumbnail.tsx
@@ -1,5 +1,9 @@
-import { memo, useCallback, useEffect, useState, useRef } from "react";
+import { memo, useCallback, useMemo, useRef, useState } from "react";
import { useMountEffect } from "../../hooks/useMountEffect";
+import { useThumbnailLease } from "../../hooks/useThumbnailLease";
+import { createThumbnailKey, type ThumbnailPriority } from "../lib/thumbnailScheduler";
+import { TIMELINE_VIEWPORT_BUDGETS } from "../lib/timelineViewportBudgets";
+import { computeThumbnailStrip, probeImageAspect } from "./thumbnailUtils";
interface CompositionThumbnailProps {
previewUrl: string;
@@ -11,6 +15,10 @@ interface CompositionThumbnailProps {
duration?: number;
width?: number;
height?: number;
+ projectId?: string;
+ sessionEpoch?: number;
+ priority?: ThumbnailPriority;
+ rich?: boolean;
}
const CLIP_HEIGHT = 66;
@@ -34,9 +42,8 @@ export function buildCompositionThumbnailUrl({
const thumbnailBase = previewUrl
.replace("/preview/comp/", "/thumbnail/")
.replace(/\/preview$/, "/thumbnail/index.html");
- const midTime = seekTime + duration / 2;
const thumbnailUrl = new URL(thumbnailBase, origin);
- thumbnailUrl.searchParams.set("t", midTime.toFixed(2));
+ thumbnailUrl.searchParams.set("t", (seekTime + duration / 2).toFixed(2));
thumbnailUrl.searchParams.set("v", THUMBNAIL_URL_VERSION);
if (selector) {
thumbnailUrl.searchParams.set("selector", selector);
@@ -47,6 +54,29 @@ export function buildCompositionThumbnailUrl({
return thumbnailUrl.toString();
}
+async function loadCompositionImage(url: string, signal: AbortSignal) {
+ const response = await fetch(url, { signal });
+ if (!response.ok) throw new Error(`Composition thumbnail failed (${response.status})`);
+ const blob = await response.blob();
+ if (signal.aborted) throw new DOMException("Aborted", "AbortError");
+ const objectUrl = URL.createObjectURL(blob);
+ try {
+ const aspect = await probeImageAspect(objectUrl, signal);
+ return {
+ value: { kind: "image" as const, url: objectUrl, aspect },
+ weight:
+ TIMELINE_VIEWPORT_BUDGETS.posterMaxPhysicalWidth *
+ TIMELINE_VIEWPORT_BUDGETS.posterMaxPhysicalHeight *
+ 4,
+ dispose: () => URL.revokeObjectURL(objectUrl),
+ };
+ } catch (error) {
+ URL.revokeObjectURL(objectUrl);
+ throw error;
+ }
+}
+
+/** Server-rendered composition poster, deduplicated and budgeted by project/session. */
export const CompositionThumbnail = memo(function CompositionThumbnail({
previewUrl,
label,
@@ -55,31 +85,12 @@ export const CompositionThumbnail = memo(function CompositionThumbnail({
selectorIndex,
seekTime = 2,
duration = 5,
+ projectId = previewUrl,
+ sessionEpoch = 0,
+ priority = "visible",
}: CompositionThumbnailProps) {
const [containerWidth, setContainerWidth] = useState(0);
- const [loaded, setLoaded] = useState(false);
- const [aspect, setAspect] = useState(16 / 9);
- const roRef = useRef<ResizeObserver | null>(null);
-
- const setContainerRef = useCallback((el: HTMLDivElement | null) => {
- roRef.current?.disconnect();
- if (!el) return;
-
- const measured = el.parentElement?.clientWidth || el.clientWidth;
- // fallow-ignore-next-line code-duplication
- setContainerWidth(measured);
-
- const target = el.parentElement || el;
- roRef.current = new ResizeObserver(([entry]) => {
- setContainerWidth(entry.contentRect.width);
- });
- roRef.current.observe(target);
- }, []);
-
- useMountEffect(() => () => {
- roRef.current?.disconnect();
- });
-
+ const observerRef = useRef<ResizeObserver | null>(null);
const url = buildCompositionThumbnailUrl({
previewUrl,
seekTime,
@@ -88,52 +99,56 @@ export const CompositionThumbnail = memo(function CompositionThumbnail({
selectorIndex,
origin: window.location.origin,
});
+ const request = useMemo(
+ () => ({
+ key: createThumbnailKey({ kind: "composition", url }),
+ projectId,
+ sessionEpoch,
+ kind: "composition" as const,
+ priority,
+ rich: true,
+ load: (signal: AbortSignal) => loadCompositionImage(url, signal),
+ }),
+ [priority, projectId, sessionEpoch, url],
+ );
+ const snapshot = useThumbnailLease(request);
+ const value =
+ snapshot.status === "ready" && snapshot.value.kind === "image" ? snapshot.value : null;
+ const { frameW, frameCount } = computeThumbnailStrip(
+ containerWidth,
+ value?.aspect ?? 16 / 9,
+ CLIP_HEIGHT,
+ 48,
+ );
- // Probe outside React's DOM and explicitly abort on URL changes/unmount. A
- // hidden React <img> keeps its Fiber reachable from Blink's pending-activity
- // queue while a request is unresolved.
- // eslint-disable-next-line no-restricted-syntax
- useEffect(() => {
- let cancelled = false;
- setLoaded(false);
- const probe = new Image();
- probe.onload = () => {
- if (cancelled) return;
- if (probe.naturalWidth > 0 && probe.naturalHeight > 0) {
- setAspect(probe.naturalWidth / probe.naturalHeight);
- }
- setLoaded(true);
- };
- probe.onerror = () => {
- if (!cancelled) setLoaded(false);
- };
- probe.src = url;
- return () => {
- cancelled = true;
- probe.onload = null;
- probe.onerror = null;
- probe.src = "";
- };
- }, [url]);
+ const setContainerRef = useCallback((element: HTMLDivElement | null) => {
+ observerRef.current?.disconnect();
+ if (!element) return;
+ const target = element.parentElement ?? element;
+ setContainerWidth(target.clientWidth);
+ observerRef.current = new ResizeObserver(([entry]) =>
+ setContainerWidth(entry.contentRect.width),
+ );
+ observerRef.current.observe(target);
+ }, []);
- const frameW = Math.max(48, Math.round(CLIP_HEIGHT * aspect));
- const frameCount = containerWidth > 0 ? Math.max(1, Math.ceil(containerWidth / frameW)) : 1;
+ useMountEffect(() => () => observerRef.current?.disconnect());
return (
<div ref={setContainerRef} className="absolute inset-0 overflow-hidden">
- {loaded && (
+ {value && (
<div
className="absolute inset-0 flex"
style={{ animation: "hf-thumb-fade 200ms ease-out", mixBlendMode: "lighten" }}
>
- {Array.from({ length: frameCount }).map((_, i) => (
+ {Array.from({ length: frameCount }, (_, index) => (
<div
- key={i}
+ key={index}
className="relative h-full flex-shrink-0 overflow-hidden"
style={{ width: frameW }}
>
<img
- src={url}
+ src={value.url}
alt=""
draggable={false}
className="absolute inset-0 h-full w-full object-cover"
@@ -143,14 +158,16 @@ export const CompositionThumbnail = memo(function CompositionThumbnail({
))}
</div>
)}
-
+ {snapshot.status === "loading" && (
+ <div className="absolute inset-0 animate-pulse bg-white/[0.035]" />
+ )}
{label && (
- <div className="absolute left-3 top-0 bottom-0 flex items-center" style={{ zIndex: 10 }}>
+ <div className="absolute inset-y-0 left-3 z-10 flex items-center">
<span
className="block max-w-full truncate text-[10px] font-semibold leading-none"
style={{
color: labelColor,
- textShadow: loaded ? "0 1px 4px rgba(0,0,0,0.9), 0 0 8px rgba(0,0,0,0.6)" : "none",
+ textShadow: value ? "0 1px 4px rgba(0,0,0,0.9), 0 0 8px rgba(0,0,0,0.6)" : "none",
}}
>
{label}
diff --git a/packages/studio/src/player/components/ImageThumbnail.test.tsx b/packages/studio/src/player/components/ImageThumbnail.test.tsx
index f1463a9b40..2f9194ee9f 100644
--- a/packages/studio/src/player/components/ImageThumbnail.test.tsx
+++ b/packages/studio/src/player/components/ImageThumbnail.test.tsx
@@ -3,6 +3,7 @@
import React, { act } from "react";
import { createRoot, type Root } from "react-dom/client";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
+import { thumbnailScheduler } from "../lib/thumbnailScheduler";
import { ImageThumbnail } from "./ImageThumbnail";
Object.defineProperty(globalThis, "IS_REACT_ACT_ENVIRONMENT", {
@@ -68,6 +69,7 @@ beforeEach(() => {
afterEach(() => {
act(() => root?.unmount());
root = null;
+ thumbnailScheduler.invalidateProject("p");
globalThis.IntersectionObserver = originalIO;
globalThis.ResizeObserver = originalRO;
globalThis.Image = originalImage;
@@ -82,6 +84,10 @@ function render(props: { imageSrc: string; label?: string; labelColor?: string }
imageSrc={props.imageSrc}
label={props.label ?? ""}
labelColor={props.labelColor ?? "#fff"}
+ projectId="p"
+ sessionEpoch={1}
+ priority="visible"
+ rich={false}
/>,
);
});
@@ -93,6 +99,13 @@ function lastProbe(): MockImage {
return probe!;
}
+async function resolveProbe(update: (probe: MockImage) => void): Promise<void> {
+ await act(async () => {
+ update(lastProbe());
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ });
+}
+
/** Assert at least one tile rendered and the first tile serves `expectedSrc`. */
function expectFirstTileSrc(expectedSrc: string): void {
const imgs = [...host.querySelectorAll("img")];
@@ -107,15 +120,15 @@ describe("ImageThumbnail", () => {
expect(host.querySelectorAll("img").length).toBe(0);
});
- it("probes the resolved src and renders repeated object-cover tiles on load", () => {
+ it("probes the resolved src and renders repeated object-cover tiles on load", async () => {
render({ imageSrc: "/api/projects/p/preview/assets/pic.png" });
const probe = lastProbe();
expect(probe.src).toBe("/api/projects/p/preview/assets/pic.png");
- act(() => {
- probe.naturalWidth = 1920;
- probe.naturalHeight = 1080;
- probe.onload?.();
+ await resolveProbe((current) => {
+ current.naturalWidth = 1920;
+ current.naturalHeight = 1080;
+ current.onload?.();
});
const imgs = [...host.querySelectorAll("img")];
@@ -127,18 +140,18 @@ describe("ImageThumbnail", () => {
expect(host.querySelector(".animate-pulse")).toBeNull();
});
- it("drops the shimmer and renders no tiles when a raster image fails to load", () => {
+ it("drops the shimmer and renders no tiles when a raster image fails to load", async () => {
render({ imageSrc: "/api/projects/p/preview/assets/missing.png" });
- act(() => lastProbe().onerror?.());
+ await resolveProbe((probe) => probe.onerror?.());
expect(host.querySelectorAll("img").length).toBe(0);
expect(host.querySelector(".animate-pulse")).toBeNull();
});
- it("renders tiles at 16:9 when an SVG has no intrinsic dimensions (naturalWidth=0)", () => {
+ it("renders tiles at 16:9 when an SVG has no intrinsic dimensions (naturalWidth=0)", async () => {
render({ imageSrc: "/api/projects/p/preview/assets/logo.svg" });
const probe = lastProbe();
- act(() => {
+ await resolveProbe(() => {
// naturalWidth stays 0 — SVG with no width/height attribute
probe.onload?.();
});
@@ -147,21 +160,20 @@ describe("ImageThumbnail", () => {
expect(host.querySelector(".animate-pulse")).toBeNull();
});
- it("renders SVG tiles at 16:9 fallback even when the probe fires onerror", () => {
+ it("renders SVG tiles at 16:9 fallback even when the probe fires onerror", async () => {
// Some browser/sandbox environments fire onerror for SVGs even though the
// <img> element itself can render the file — we must not blank the strip.
render({ imageSrc: "/api/projects/p/preview/assets/icon.svg" });
- act(() => lastProbe().onerror?.());
+ await resolveProbe((probe) => probe.onerror?.());
expectFirstTileSrc("/api/projects/p/preview/assets/icon.svg");
expect(host.querySelector(".animate-pulse")).toBeNull();
});
- it("renders the label above the strip when provided", () => {
+ it("renders the label above the strip when provided", async () => {
render({ imageSrc: "/x.png", label: "hero", labelColor: "#abc" });
- act(() => {
- const probe = lastProbe();
+ await resolveProbe((probe) => {
probe.naturalWidth = 100;
probe.naturalHeight = 100;
probe.onload?.();
diff --git a/packages/studio/src/player/components/ImageThumbnail.tsx b/packages/studio/src/player/components/ImageThumbnail.tsx
index 33914ae2c1..a22edaf850 100644
--- a/packages/studio/src/player/components/ImageThumbnail.tsx
+++ b/packages/studio/src/player/components/ImageThumbnail.tsx
@@ -1,135 +1,93 @@
-import { memo, useRef, useState, useCallback, useEffect } from "react";
+import { memo, useCallback, useMemo, useRef, useState } from "react";
import { useMountEffect } from "../../hooks/useMountEffect";
-import { computeThumbnailStrip } from "./thumbnailUtils";
+import { useThumbnailLease } from "../../hooks/useThumbnailLease";
+import { createThumbnailKey, type ThumbnailPriority } from "../lib/thumbnailScheduler";
+import { TIMELINE_VIEWPORT_BUDGETS } from "../lib/timelineViewportBudgets";
+import { computeThumbnailStrip, probeImageAspect } from "./thumbnailUtils";
interface ImageThumbnailProps {
imageSrc: string;
label: string;
labelColor: string;
+ projectId?: string;
+ sessionEpoch?: number;
+ priority?: ThumbnailPriority;
+ rich?: boolean;
}
-/**
- * Renders a film-strip of a still image for a timeline clip. The image is a
- * fixed-width tile (sized by its natural aspect ratio) repeated to fill the
- * clip width — matching VideoThumbnail's visual pattern. Loading is lazy
- * (IntersectionObserver) with the same shimmer fallback while decoding.
- */
+/** A scheduler-backed still-image strip. Mounting is the sole work trigger. */
export const ImageThumbnail = memo(function ImageThumbnail({
imageSrc,
label,
labelColor,
+ projectId = imageSrc,
+ sessionEpoch = 0,
+ priority = "visible",
+ rich = false,
}: ImageThumbnailProps) {
const [containerWidth, setContainerWidth] = useState(0);
- const [visible, setVisible] = useState(false);
- const [status, setStatus] = useState<"loading" | "loaded" | "error">("loading");
- const [aspect, setAspect] = useState(16 / 9);
- const ioRef = useRef<IntersectionObserver | null>(null);
- const roRef = useRef<ResizeObserver | null>(null);
-
- const setContainerRef = useCallback((el: HTMLDivElement | null) => {
- ioRef.current?.disconnect();
- roRef.current?.disconnect();
- if (!el) return;
-
- const measured = el.parentElement?.clientWidth || el.clientWidth;
- setContainerWidth(measured);
-
- ioRef.current = new IntersectionObserver(
- ([entry]) => {
- if (entry.isIntersecting) {
- setVisible(true);
- ioRef.current?.disconnect();
- }
+ const observerRef = useRef<ResizeObserver | null>(null);
+ const request = useMemo(
+ () => ({
+ key: createThumbnailKey({ kind: "image", source: imageSrc, rich: Number(rich) }),
+ projectId,
+ sessionEpoch,
+ kind: "image" as const,
+ priority,
+ rich,
+ load: async (signal: AbortSignal) => {
+ const aspect = await probeImageAspect(imageSrc, signal, true);
+ return {
+ value: { kind: "image" as const, url: imageSrc, aspect },
+ weight:
+ TIMELINE_VIEWPORT_BUDGETS.posterMaxPhysicalWidth *
+ TIMELINE_VIEWPORT_BUDGETS.posterMaxPhysicalHeight *
+ 4,
+ };
},
- { rootMargin: "200px" },
- );
- // fallow-ignore-next-line code-duplication
- ioRef.current.observe(el);
+ }),
+ [imageSrc, priority, projectId, rich, sessionEpoch],
+ );
+ const snapshot = useThumbnailLease(request);
+ const value = snapshot.status === "ready" ? snapshot.value : null;
+ const aspect = value?.kind === "image" ? value.aspect : 16 / 9;
+ const { frameW, frameCount } = computeThumbnailStrip(containerWidth, aspect);
- const target = el.parentElement || el;
- roRef.current = new ResizeObserver(([entry]) => {
- setContainerWidth(entry.contentRect.width);
- });
- roRef.current.observe(target);
+ const setContainerRef = useCallback((element: HTMLDivElement | null) => {
+ observerRef.current?.disconnect();
+ if (!element) return;
+ const target = element.parentElement ?? element;
+ setContainerWidth(target.clientWidth);
+ observerRef.current = new ResizeObserver(([entry]) =>
+ setContainerWidth(entry.contentRect.width),
+ );
+ observerRef.current.observe(target);
}, []);
- useMountEffect(() => () => {
- ioRef.current?.disconnect();
- roRef.current?.disconnect();
- });
-
- // Probe the image once visible — measures the natural aspect ratio so the
- // tile width matches, and flips to the error state (plain clip background)
- // if the src can't load. The browser cache makes the tile <img>s free.
- //
- // SVG handling: SVGs without intrinsic width/height report naturalWidth=0 on
- // load (treat as success with the 16:9 default aspect) and may fire onerror
- // in some environments even though the file is valid and can be displayed —
- // fall back to loaded-at-16:9 rather than hiding the strip entirely.
- // eslint-disable-next-line no-restricted-syntax
- useEffect(() => {
- if (!visible) return;
- let cancelled = false;
- setStatus("loading");
-
- const isSvg = /\.svg($|\?)/i.test(imageSrc);
-
- const probe = new Image();
- probe.onload = () => {
- if (cancelled) return;
- if (probe.naturalWidth > 0 && probe.naturalHeight > 0) {
- setAspect(probe.naturalWidth / probe.naturalHeight);
- }
- // naturalWidth===0 (e.g. SVG with no intrinsic dimensions) falls through
- // to "loaded" with the default 16:9 aspect already set in state.
- setStatus("loaded");
- };
- probe.onerror = () => {
- if (cancelled) return;
- // SVGs can fail the probe in certain browser/sandbox environments even
- // though the <img> tiles themselves render fine (different security
- // context). Show the strip at the 16:9 fallback rather than blanking.
- if (isSvg) {
- setStatus("loaded");
- } else {
- setStatus("error");
- }
- };
- probe.src = imageSrc;
-
- return () => {
- cancelled = true;
- probe.onload = null;
- probe.onerror = null;
- probe.src = "";
- };
- }, [visible, imageSrc]);
-
- const { frameW, frameCount } = computeThumbnailStrip(containerWidth, aspect);
+ useMountEffect(() => () => observerRef.current?.disconnect());
return (
<div ref={setContainerRef} className="absolute inset-0 overflow-hidden">
- {visible && status === "loaded" && (
+ {value?.kind === "image" && (
<div className="absolute inset-0 flex">
- {Array.from({ length: frameCount }).map((_, i) => (
+ {Array.from({ length: frameCount }, (_, index) => (
<div
- key={i}
- className="flex-shrink-0 h-full relative overflow-hidden bg-neutral-900"
+ key={index}
+ className="relative h-full flex-shrink-0 overflow-hidden bg-neutral-900"
style={{ width: frameW }}
>
<img
- src={imageSrc}
+ src={value.url}
alt=""
draggable={false}
loading="lazy"
- className="absolute inset-0 w-full h-full object-cover"
+ className="absolute inset-0 h-full w-full object-cover"
/>
</div>
))}
</div>
)}
-
- {visible && status === "loading" && (
+ {snapshot.status === "loading" && (
<div
className="absolute inset-0 animate-pulse"
style={{
@@ -138,17 +96,16 @@ export const ImageThumbnail = memo(function ImageThumbnail({
}}
/>
)}
-
{label && (
<div
- className="absolute bottom-0 left-0 right-0 z-10 px-1.5 pb-0.5 pt-3"
+ className="absolute inset-x-0 bottom-0 z-10 px-1.5 pb-0.5 pt-3"
style={{
background:
"linear-gradient(to top, rgba(0,0,0,0.85) 0%, rgba(0,0,0,0.4) 60%, transparent 100%)",
}}
>
<span
- className="text-[9px] font-semibold truncate block leading-tight"
+ className="block truncate text-[9px] font-semibold leading-tight"
style={{ color: labelColor, textShadow: "0 1px 2px rgba(0,0,0,0.9)" }}
>
{label}
diff --git a/packages/studio/src/player/components/Timeline.tsx b/packages/studio/src/player/components/Timeline.tsx
index 3b1b61dcbc..b279102c90 100644
--- a/packages/studio/src/player/components/Timeline.tsx
+++ b/packages/studio/src/player/components/Timeline.tsx
@@ -64,7 +64,6 @@ export {
getTimelineScrollTopForGeometryChange,
getTimelineVisibleTimeRange,
} from "./timelineViewportGeometry";
-
export const Timeline = memo(function Timeline({
onSeek,
onDrillDown,
@@ -317,24 +316,25 @@ export const Timeline = memo(function Timeline({
toggleSelectedKeyframe,
});
- const { clipIndex, renderTimeRange, pinnedClipIdentities } = useTimelineClipRenderWindow({
- tracks,
- viewport,
- pixelsPerSecond: pps,
- contentOrigin,
- duration: displayDuration,
- selectedElementId: selectedElementId ?? undefined,
- draggedElementId: draggedClip ? getTimelineElementIdentity(draggedClip.element) : undefined,
- resizingElementIds,
- focusedElementId: timelineFocus.pinnedElementId,
- focusedEaseElementId: focusedEaseSegment?.elementId,
- clipContextMenuElementId: clipContextMenu
- ? getTimelineElementIdentity(clipContextMenu.element)
- : undefined,
- keyframeContextMenuElementId: kfContextMenu
- ? getTimelineElementIdentity(kfContextMenu.element)
- : undefined,
- });
+ const { clipIndex, renderTimeRange, visibleTimeRange, pinnedClipIdentities } =
+ useTimelineClipRenderWindow({
+ tracks,
+ viewport,
+ pixelsPerSecond: pps,
+ contentOrigin,
+ duration: displayDuration,
+ selectedElementId: selectedElementId ?? undefined,
+ draggedElementId: draggedClip ? getTimelineElementIdentity(draggedClip.element) : undefined,
+ resizingElementIds,
+ focusedElementId: timelineFocus.pinnedElementId,
+ focusedEaseElementId: focusedEaseSegment?.elementId,
+ clipContextMenuElementId: clipContextMenu
+ ? getTimelineElementIdentity(clipContextMenu.element)
+ : undefined,
+ keyframeContextMenuElementId: kfContextMenu
+ ? getTimelineElementIdentity(kfContextMenu.element)
+ : undefined,
+ });
useTimelineActiveClips({
scrollRef,
currentTime,
@@ -504,6 +504,7 @@ export const Timeline = memo(function Timeline({
rowsVirtualized={timelineFocus.rowVirtualizationActive}
clipIndex={clipIndex}
renderTimeRange={renderTimeRange}
+ visibleTimeRange={visibleTimeRange}
pinnedClipIdentities={pinnedClipIdentities}
trackOrder={trackOrder}
tracks={tracks}
diff --git a/packages/studio/src/player/components/TimelineGestureOverlay.tsx b/packages/studio/src/player/components/TimelineGestureOverlay.tsx
index 500d2c0ea2..3490f30abf 100644
--- a/packages/studio/src/player/components/TimelineGestureOverlay.tsx
+++ b/packages/studio/src/player/components/TimelineGestureOverlay.tsx
@@ -9,6 +9,7 @@ import { getTimelineDragOverlayPosition } from "./timelineClipDragPreview";
import type { DraggedClipState } from "./timelineClipDragTypes";
import type { TrackVisualStyle } from "./timelineIcons";
import { isTimelineClipActive } from "./useTimelineActiveClips";
+import type { TimelineClipRenderContext } from "./TimelineTypes";
interface TimelineGestureOverlayProps {
drag: DraggedClipState | null;
@@ -22,6 +23,7 @@ interface TimelineGestureOverlayProps {
renderClipContent?: (
element: TimelineElement,
style: { clip: string; label: string },
+ context: TimelineClipRenderContext,
) => ReactNode;
renderClipOverlay?: (element: TimelineElement) => ReactNode;
}
@@ -87,6 +89,7 @@ export const TimelineGestureOverlay = memo(function TimelineGestureOverlay({
getTrackStyle(element.tag),
renderClipContent,
renderClipOverlay,
+ { priority: "interaction", rich: true },
)}
</TimelineClip>
</div>
diff --git a/packages/studio/src/player/components/TimelineLanes.test.tsx b/packages/studio/src/player/components/TimelineLanes.test.tsx
index e066312efb..be2179f0eb 100644
--- a/packages/studio/src/player/components/TimelineLanes.test.tsx
+++ b/packages/studio/src/player/components/TimelineLanes.test.tsx
@@ -76,10 +76,14 @@ function renderLanes(options: RenderLanesOptions = {}): {
host: HTMLDivElement;
root: Root;
rerender: (next: RenderLanesOptions) => void;
+ setSelectedElementId: ReturnType<typeof vi.fn>;
+ onSelectElement: ReturnType<typeof vi.fn>;
} {
const host = document.createElement("div");
document.body.append(host);
const root = createRoot(host);
+ const setSelectedElementId = vi.fn();
+ const onSelectElement = vi.fn();
const render = (next: RenderLanesOptions) => {
const elements = next.elements ?? [element("clip-a", TRACK_A)];
const gsapAnimations = next.animations ?? new Map<string, GsapAnimation[]>();
@@ -118,6 +122,7 @@ function renderLanes(options: RenderLanesOptions = {}): {
})}
clipIndex={createTimelineClipIndex(tracks)}
renderTimeRange={{ start: 0, end: Number.POSITIVE_INFINITY }}
+ visibleTimeRange={{ start: 0, end: Number.POSITIVE_INFINITY }}
pinnedClipIdentities={new Set()}
trackOrder={displayTrackOrder}
tracks={tracks}
@@ -137,7 +142,7 @@ function renderLanes(options: RenderLanesOptions = {}): {
setRangeSelection={vi.fn()}
setResizingClip={vi.fn()}
setDraggedClip={vi.fn()}
- setSelectedElementId={vi.fn()}
+ setSelectedElementId={setSelectedElementId}
shiftClickClipRef={createRef()}
getPreviewElement={(el) => el}
getTrackStyle={getTrackStyle}
@@ -149,6 +154,7 @@ function renderLanes(options: RenderLanesOptions = {}): {
onTogglePropertyGroupKeyframe={vi.fn()}
onResizeElement={vi.fn()}
onMoveElement={vi.fn()}
+ onSelectElement={onSelectElement}
onRazorSplit={vi.fn()}
onRazorSplitAll={vi.fn()}
/>,
@@ -156,7 +162,7 @@ function renderLanes(options: RenderLanesOptions = {}): {
});
};
render(options);
- return { host, root, rerender: render };
+ return { host, root, rerender: render, setSelectedElementId, onSelectElement };
}
function visibilityLabels(host: HTMLElement): (string | null)[] {
@@ -347,3 +353,19 @@ describe("TimelineLanes disclosure target", () => {
act(() => view.root.unmount());
});
});
+
+describe("TimelineLanes selection", () => {
+ it("keeps a selected clip selected when it is clicked again", () => {
+ const selected = element("clip-a", TRACK_A);
+ const view = renderLanes({
+ elements: [selected],
+ selectedElementIds: new Set([selected.id]),
+ });
+
+ act(() => view.host.querySelector<HTMLButtonElement>('[data-el-id="clip-a"]')?.click());
+
+ expect(view.setSelectedElementId).toHaveBeenCalledWith(selected.id);
+ expect(view.onSelectElement).toHaveBeenCalledWith(selected);
+ act(() => view.root.unmount());
+ });
+});
diff --git a/packages/studio/src/player/components/TimelineLanes.tsx b/packages/studio/src/player/components/TimelineLanes.tsx
index 907f9fcacb..b0fe118656 100644
--- a/packages/studio/src/player/components/TimelineLanes.tsx
+++ b/packages/studio/src/player/components/TimelineLanes.tsx
@@ -22,7 +22,7 @@ import type { TimelineEditCallbacks } from "./timelineCallbacks";
import { trackStudioKeyframeLaneExpand } from "../../telemetry/events";
import { SPLIT_BOUNDARY_EPSILON_S } from "../../utils/timelineElementSplit";
import { isAudioTimelineElement, isMusicTrack } from "../../utils/timelineInspector";
-import { renderClipChildren } from "./timelineClipChildren";
+import { renderClipChildren, resolveClipRenderContext } from "./timelineClipChildren";
import { TimelineTrackRow } from "./TimelineTrackRow";
import { isTimelineClipActive } from "./useTimelineActiveClips";
import { queryTimelineClipIndex } from "../lib/timelineClipIndex";
@@ -57,6 +57,7 @@ export function TimelineLanes({
rowsVirtualized,
clipIndex,
renderTimeRange,
+ visibleTimeRange,
pinnedClipIdentities,
trackOrder,
tracks,
@@ -323,8 +324,7 @@ export function TimelineLanes({
const isSelected =
selectedElementId === elementKey || selectedElementIds.has(elementKey);
const isComposition = !!el.compositionSrc;
- // The element identity is already unique per clip. Never fold in the map
- // index, or a splice/reorder remounts every clip at/after the change.
+ // Element identity stays stable across clip splices and reorders.
const clipKey = elementKey;
const isDraggingClip =
draggedClip?.started === true &&
@@ -332,6 +332,11 @@ export function TimelineLanes({
getTimelineElementIdentity(draggedElement) === elementKey;
if (isDraggingClip) return null;
const previewElement = getPreviewElement(el);
+ const renderContext = resolveClipRenderContext(
+ previewElement,
+ visibleTimeRange,
+ isSelected || hoveredClip === clipKey || pinnedClipIdentities.has(clipKey),
+ );
// Passenger of a live multi-drag: preserve the formation without changing
// the passenger's timeline data until the owning drag commits.
const isPassenger =
@@ -475,15 +480,9 @@ export function TimelineLanes({
}
return;
}
- // Plain click single-selects: drop any marquee multi-selection.
- // Only a click on the PRIMARY selection toggles it off — a click
- // on a marquee-selected clip narrows the selection to that clip.
- const hadMultiSelection = selectedElementIds.size > 0;
- usePlayerStore.getState().clearSelectedElementIds();
- const nextElement =
- selectedElementId === elementKey && !hadMultiSelection ? null : el;
- setSelectedElementId(nextElement ? elementKey : null);
- onSelectElement?.(nextElement);
+ // Clip selection is idempotent; empty timeline space owns deselection.
+ setSelectedElementId(elementKey);
+ onSelectElement?.(el);
}
}
onDoubleClick={(e) => {
@@ -497,6 +496,7 @@ export function TimelineLanes({
clipStyle,
renderClipContent,
renderClipOverlay,
+ renderContext,
)}
</TimelineClip>
);
diff --git a/packages/studio/src/player/components/TimelineTypes.ts b/packages/studio/src/player/components/TimelineTypes.ts
index 0838e8dccb..2908f026e6 100644
--- a/packages/studio/src/player/components/TimelineTypes.ts
+++ b/packages/studio/src/player/components/TimelineTypes.ts
@@ -4,6 +4,11 @@ import type { TimelineDropCallbacks } from "./timelineCallbacks";
import type { TimelineTheme } from "./timelineTheme";
import type { TimelineEditOverrides } from "./useResolvedTimelineEditCallbacks";
+export interface TimelineClipRenderContext {
+ priority: "overscan" | "visible" | "interaction";
+ rich: boolean;
+}
+
export interface TimelineProps extends TimelineDropCallbacks, TimelineEditOverrides {
/** Project-scoped reset boundary; soft source refreshes retain the same epoch. */
sessionEpoch?: number;
@@ -12,6 +17,7 @@ export interface TimelineProps extends TimelineDropCallbacks, TimelineEditOverri
renderClipContent?: (
element: TimelineElement,
style: { clip: string; label: string },
+ context: TimelineClipRenderContext,
) => ReactNode;
renderClipOverlay?: (element: TimelineElement) => ReactNode;
onDeleteElement?: (element: TimelineElement) => Promise<void> | void;
diff --git a/packages/studio/src/player/components/VideoThumbnail.test.tsx b/packages/studio/src/player/components/VideoThumbnail.test.tsx
index 82f49d8966..2906ee866b 100644
--- a/packages/studio/src/player/components/VideoThumbnail.test.tsx
+++ b/packages/studio/src/player/components/VideoThumbnail.test.tsx
@@ -2,65 +2,28 @@
import React, { act } from "react";
import { createRoot, type Root } from "react-dom/client";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { thumbnailScheduler } from "../lib/thumbnailScheduler";
+import { decodeVideoThumbnail } from "../lib/thumbnailVideoDecoder";
import { VideoThumbnail } from "./VideoThumbnail";
+vi.mock("../lib/thumbnailVideoDecoder", () => ({ decodeVideoThumbnail: vi.fn() }));
+
Object.defineProperty(globalThis, "IS_REACT_ACT_ENVIRONMENT", {
configurable: true,
value: true,
});
-// Fire "intersecting" immediately on observe so the extraction effect runs.
-class MockIntersectionObserver {
- private cb: IntersectionObserverCallback;
- constructor(cb: IntersectionObserverCallback) {
- this.cb = cb;
- }
- observe() {
- this.cb(
- [{ isIntersecting: true } as IntersectionObserverEntry],
- this as unknown as IntersectionObserver,
- );
- }
- disconnect() {}
- unobserve() {}
- takeRecords(): IntersectionObserverEntry[] {
- return [];
- }
-}
-
class MockResizeObserver {
observe() {}
disconnect() {}
unobserve() {}
}
-const originalIO = globalThis.IntersectionObserver;
-const originalRO = globalThis.ResizeObserver;
-
let host: HTMLDivElement;
let root: Root | null = null;
-let createdVideos: HTMLVideoElement[];
beforeEach(() => {
- globalThis.IntersectionObserver =
- MockIntersectionObserver as unknown as typeof IntersectionObserver;
globalThis.ResizeObserver = MockResizeObserver as unknown as typeof ResizeObserver;
-
- createdVideos = [];
- const origCreate = document.createElement.bind(document);
- vi.spyOn(document, "createElement").mockImplementation((tag: string) => {
- const el = origCreate(tag);
- if (tag === "video") createdVideos.push(el as HTMLVideoElement);
- return el;
- });
-
- // happy-dom's <video>/<canvas> don't decode media; stub the seam the
- // extractor depends on so the effect can run deterministically.
- vi.spyOn(HTMLMediaElement.prototype, "load").mockImplementation(() => {});
- vi.spyOn(HTMLCanvasElement.prototype, "getContext").mockReturnValue({
- drawImage: () => {},
- } as unknown as CanvasRenderingContext2D);
-
host = document.createElement("div");
document.body.append(host);
});
@@ -68,85 +31,68 @@ beforeEach(() => {
afterEach(() => {
act(() => root?.unmount());
root = null;
- vi.restoreAllMocks();
- globalThis.IntersectionObserver = originalIO;
- globalThis.ResizeObserver = originalRO;
+ thumbnailScheduler.invalidateProject("p");
+ vi.clearAllMocks();
document.body.innerHTML = "";
});
-function render(videoSrc: string) {
+async function render(rich = false) {
root = createRoot(host);
- act(() => {
- root!.render(React.createElement(VideoThumbnail, { videoSrc, label: "", labelColor: "#fff" }));
+ await act(async () => {
+ root!.render(
+ <VideoThumbnail
+ videoSrc="/api/projects/p/preview/assets/clip.mp4"
+ label=""
+ labelColor="#fff"
+ projectId="p"
+ sessionEpoch={1}
+ priority="visible"
+ rich={rich}
+ />,
+ );
+ await Promise.resolve();
});
}
-function lastVideo(): HTMLVideoElement {
- const v = createdVideos.at(-1);
- expect(v).toBeDefined();
- return v!;
-}
-
-describe("VideoThumbnail — tainted-canvas fallback", () => {
- it("stops the extractor and drops the shimmer when toDataURL throws a SecurityError", () => {
- vi.spyOn(HTMLCanvasElement.prototype, "toDataURL").mockImplementation(() => {
- throw new DOMException("Tainted canvases may not be exported.", "SecurityError");
+describe("VideoThumbnail", () => {
+ it("renders a scheduler-provided sparse poster", async () => {
+ vi.mocked(decodeVideoThumbnail).mockResolvedValue({
+ value: { kind: "image", url: "blob:poster", aspect: 16 / 9 },
+ weight: 128,
});
- render("https://cdn.example.com/no-cors.mp4");
-
- // The effect ran once visible → a hidden <video> was created.
- const video = lastVideo();
-
- act(() => {
- video.dispatchEvent(new Event("loadedmetadata"));
- });
- act(() => {
- video.dispatchEvent(new Event("seeked"));
- });
+ await render();
- // No frame captured, and crucially the shimmer is gone (not spinning
- // forever) — the clip falls back to its plain background.
- expect(host.querySelectorAll("img").length).toBe(0);
+ expect(decodeVideoThumbnail).toHaveBeenCalledWith(
+ expect.objectContaining({ frameCount: 1 }),
+ expect.any(AbortSignal),
+ );
+ expect(host.querySelector('img[src="blob:poster"]')).not.toBeNull();
expect(host.querySelector(".animate-pulse")).toBeNull();
});
- it("drops the shimmer when a no-CORS load fires the video error event (0 frames) (#2214)", () => {
- render("https://cdn.example.com/no-cors.mp4");
- // Before the load resolves, the shimmer placeholder is up.
- expect(host.querySelector(".animate-pulse")).not.toBeNull();
-
- const video = lastVideo();
- // crossOrigin="anonymous" against a CORS-less server fails the load outright —
- // the error listener fires instead of loadedmetadata/seeked, so no frame is
- // ever captured. The shimmer must stop rather than spin forever.
- act(() => {
- video.dispatchEvent(new Event("error"));
+ it("requests a rich filmstrip only for interaction actors", async () => {
+ vi.mocked(decodeVideoThumbnail).mockResolvedValue({
+ value: { kind: "filmstrip", urls: ["blob:a", "blob:b"], aspect: 16 / 9 },
+ weight: 256,
});
- expect(host.querySelectorAll("img").length).toBe(0);
- expect(host.querySelector(".animate-pulse")).toBeNull();
- });
+ await render(true);
- it("keeps streaming frames while the shimmer is up until a frame arrives", () => {
- vi.spyOn(HTMLCanvasElement.prototype, "toDataURL").mockReturnValue(
- "data:image/jpeg;base64,AAAA",
+ expect(decodeVideoThumbnail).toHaveBeenCalledWith(
+ expect.objectContaining({ frameCount: 6 }),
+ expect.any(AbortSignal),
);
+ expect(host.querySelectorAll("img").length).toBeGreaterThan(0);
+ });
- render("/api/projects/p/preview/assets/clip.mp4");
- // Before any seek resolves, the shimmer placeholder is shown.
- expect(host.querySelector(".animate-pulse")).not.toBeNull();
+ it("clears the loading shimmer when the scheduled decode fails", async () => {
+ vi.mocked(decodeVideoThumbnail).mockRejectedValue(new Error("decode failed"));
- const video = lastVideo();
- act(() => {
- video.dispatchEvent(new Event("loadedmetadata"));
- });
- act(() => {
- video.dispatchEvent(new Event("seeked"));
- });
+ await render();
+ await vi.waitFor(() => expect(thumbnailScheduler.getDiagnostics().active).toBe(0));
- // A frame was captured, so tiles render and the shimmer clears.
- expect(host.querySelectorAll("img").length).toBeGreaterThanOrEqual(1);
expect(host.querySelector(".animate-pulse")).toBeNull();
+ expect(host.querySelector("img")).toBeNull();
});
});
diff --git a/packages/studio/src/player/components/VideoThumbnail.tsx b/packages/studio/src/player/components/VideoThumbnail.tsx
index 2c6df17429..d8b4cb109e 100644
--- a/packages/studio/src/player/components/VideoThumbnail.tsx
+++ b/packages/studio/src/player/components/VideoThumbnail.tsx
@@ -1,5 +1,8 @@
-import { memo, useRef, useState, useCallback, useEffect } from "react";
+import { memo, useCallback, useMemo, useRef, useState } from "react";
import { useMountEffect } from "../../hooks/useMountEffect";
+import { useThumbnailLease } from "../../hooks/useThumbnailLease";
+import { createThumbnailKey, type ThumbnailPriority } from "../lib/thumbnailScheduler";
+import { decodeVideoThumbnail } from "../lib/thumbnailVideoDecoder";
import { computeThumbnailStrip, THUMBNAIL_CLIP_HEIGHT } from "./thumbnailUtils";
interface VideoThumbnailProps {
@@ -7,189 +10,105 @@ interface VideoThumbnailProps {
label: string;
labelColor: string;
duration?: number;
+ sourceStart?: number;
+ sourceRangeDuration?: number;
+ projectId?: string;
+ sessionEpoch?: number;
+ priority?: ThumbnailPriority;
+ rich?: boolean;
}
-const CLIP_HEIGHT = THUMBNAIL_CLIP_HEIGHT;
-const MAX_UNIQUE_FRAMES: number = 6;
-
-/**
- * Renders a film-strip of video frames extracted client-side via a hidden
- * <video> + <canvas>. Each frame is a fixed-width tile; frames repeat to
- * fill the clip width — matching ClipThumbnail's visual pattern.
- */
+/** Sparse, bounded video frames supplied by the shared thumbnail scheduler. */
export const VideoThumbnail = memo(function VideoThumbnail({
videoSrc,
label,
labelColor,
duration = 5,
+ sourceStart,
+ sourceRangeDuration,
+ projectId = videoSrc,
+ sessionEpoch = 0,
+ priority = "visible",
+ rich = false,
}: VideoThumbnailProps) {
const [containerWidth, setContainerWidth] = useState(0);
- const [visible, setVisible] = useState(false);
- const [frames, setFrames] = useState<string[]>([]);
- const [failed, setFailed] = useState(false);
- const [aspect, setAspect] = useState(16 / 9);
- const ioRef = useRef<IntersectionObserver | null>(null);
- const roRef = useRef<ResizeObserver | null>(null);
- const extractingRef = useRef(false);
-
- const setContainerRef = useCallback((el: HTMLDivElement | null) => {
- ioRef.current?.disconnect();
- roRef.current?.disconnect();
- if (!el) return;
-
- const measured = el.parentElement?.clientWidth || el.clientWidth;
- setContainerWidth(measured);
+ const observerRef = useRef<ResizeObserver | null>(null);
+ const request = useMemo(
+ () => ({
+ key: createThumbnailKey({
+ kind: "video",
+ source: videoSrc,
+ start: sourceStart,
+ duration: sourceRangeDuration ?? duration,
+ frames: rich ? 6 : 1,
+ }),
+ projectId,
+ sessionEpoch,
+ kind: "video" as const,
+ priority,
+ rich,
+ load: (signal: AbortSignal) =>
+ decodeVideoThumbnail(
+ {
+ source: videoSrc,
+ sourceStart,
+ sourceRangeDuration: sourceRangeDuration ?? duration,
+ frameCount: rich ? 6 : 1,
+ fit: "cover",
+ },
+ signal,
+ ),
+ }),
+ [duration, priority, projectId, rich, sessionEpoch, sourceRangeDuration, sourceStart, videoSrc],
+ );
+ const snapshot = useThumbnailLease(request);
+ const value = snapshot.status === "ready" ? snapshot.value : null;
+ const urls =
+ value?.kind === "filmstrip" ? value.urls : value?.kind === "image" ? [value.url] : [];
+ const aspect = value?.kind === "image" || value?.kind === "filmstrip" ? value.aspect : 16 / 9;
+ const { frameW, frameCount } = computeThumbnailStrip(
+ containerWidth,
+ aspect,
+ THUMBNAIL_CLIP_HEIGHT,
+ );
- ioRef.current = new IntersectionObserver(
- ([entry]) => {
- if (entry.isIntersecting) {
- setVisible(true);
- ioRef.current?.disconnect();
- }
- },
- { rootMargin: "200px" },
+ const setContainerRef = useCallback((element: HTMLDivElement | null) => {
+ observerRef.current?.disconnect();
+ if (!element) return;
+ const target = element.parentElement ?? element;
+ setContainerWidth(target.clientWidth);
+ observerRef.current = new ResizeObserver(([entry]) =>
+ setContainerWidth(entry.contentRect.width),
);
- // fallow-ignore-next-line code-duplication
- ioRef.current.observe(el);
-
- const target = el.parentElement || el;
- roRef.current = new ResizeObserver(([entry]) => {
- setContainerWidth(entry.contentRect.width);
- });
- roRef.current.observe(target);
+ observerRef.current.observe(target);
}, []);
- useMountEffect(() => () => {
- ioRef.current?.disconnect();
- roRef.current?.disconnect();
- });
-
- // Extract frames progressively — each frame appears as soon as it's ready.
- // Note: useEffect with deps is acceptable — syncs with external video element API,
- // requires cleanup (cancel extraction, revoke URLs) when inputs change.
- // eslint-disable-next-line no-restricted-syntax
- useEffect(() => {
- if (!visible || extractingRef.current) return;
- extractingRef.current = true;
-
- const video = document.createElement("video");
- video.crossOrigin = "anonymous";
- video.muted = true;
- video.preload = "auto";
-
- const canvas = document.createElement("canvas");
- const ctx = canvas.getContext("2d");
- if (!ctx) {
- extractingRef.current = false;
- return;
- }
-
- const timestamps: number[] = [];
- const minSeek = Math.min(0.4, duration * 0.05);
- for (let i = 0; i < MAX_UNIQUE_FRAMES; i++) {
- const raw =
- MAX_UNIQUE_FRAMES === 1 ? duration * 0.15 : (i / (MAX_UNIQUE_FRAMES - 1)) * duration;
- timestamps.push(Math.max(raw, minSeek));
- }
-
- let idx = 0;
- let cancelled = false;
-
- const extractNext = () => {
- if (cancelled || idx >= timestamps.length) {
- if (!cancelled) {
- video.src = "";
- video.load();
- }
- return;
- }
- video.currentTime = timestamps[idx];
- };
-
- video.addEventListener("loadedmetadata", () => {
- if (video.videoWidth > 0 && video.videoHeight > 0) {
- setAspect(video.videoWidth / video.videoHeight);
- const h = CLIP_HEIGHT * 2;
- const w = Math.round(h * (video.videoWidth / video.videoHeight));
- canvas.width = w;
- canvas.height = h;
- }
- extractNext();
- });
-
- video.addEventListener("seeked", () => {
- if (cancelled) return;
- let dataUrl: string;
- try {
- ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
- dataUrl = canvas.toDataURL("image/jpeg", 0.6);
- } catch {
- // An external http(s) video served without CORS headers taints the
- // canvas, so toDataURL throws a SecurityError. Stop the extractor
- // cleanly and fall back to the no-thumbnail rendering (plain clip
- // background), matching ImageThumbnail's error path — otherwise the
- // shimmer placeholder would spin forever.
- cancelled = true;
- setFailed(true);
- video.src = "";
- video.load();
- return;
- }
- // Stream each frame immediately
- setFrames((prev) => [...prev, dataUrl]);
- idx++;
- extractNext();
- });
-
- video.addEventListener("error", () => {
- // A no-CORS load fails outright (crossOrigin="anonymous" rejects a video
- // served without CORS headers), firing this instead of the taint path in
- // "seeked" — so 0 frames are ever extracted. Keep whatever frames we have,
- // but mark failed so the shimmer placeholder stops spinning forever and we
- // fall back to the plain clip background (#2214).
- setFailed(true);
- });
-
- video.src = videoSrc;
- video.load();
-
- return () => {
- cancelled = true;
- extractingRef.current = false;
- setFrames([]);
- setFailed(false);
- video.src = "";
- video.load();
- };
- }, [visible, videoSrc, duration]);
-
- const { frameW, frameCount } = computeThumbnailStrip(containerWidth, aspect, CLIP_HEIGHT);
+ useMountEffect(() => () => observerRef.current?.disconnect());
return (
<div ref={setContainerRef} className="absolute inset-0 overflow-hidden">
- {visible && frames.length > 0 && (
+ {urls.length > 0 && (
<div className="absolute inset-0 flex">
- {Array.from({ length: frameCount }).map((_, i) => {
- const src = frames[i % frames.length];
+ {Array.from({ length: frameCount }, (_, index) => {
+ const src = urls[index % urls.length];
return (
<div
- key={i}
- className="flex-shrink-0 h-full relative overflow-hidden bg-neutral-900"
+ key={index}
+ className="relative h-full flex-shrink-0 overflow-hidden bg-neutral-900"
style={{ width: frameW }}
>
<img
src={src}
alt=""
draggable={false}
- className="absolute inset-0 w-full h-full object-cover"
+ className="absolute inset-0 h-full w-full object-cover"
/>
</div>
);
})}
</div>
)}
-
- {visible && frames.length === 0 && !failed && (
+ {snapshot.status === "loading" && urls.length === 0 && (
<div
className="absolute inset-0 animate-pulse"
style={{
@@ -198,17 +117,16 @@ export const VideoThumbnail = memo(function VideoThumbnail({
}}
/>
)}
-
{label && (
<div
- className="absolute bottom-0 left-0 right-0 z-10 px-1.5 pb-0.5 pt-3"
+ className="absolute inset-x-0 bottom-0 z-10 px-1.5 pb-0.5 pt-3"
style={{
background:
"linear-gradient(to top, rgba(0,0,0,0.85) 0%, rgba(0,0,0,0.4) 60%, transparent 100%)",
}}
>
<span
- className="text-[9px] font-semibold truncate block leading-tight"
+ className="block truncate text-[9px] font-semibold leading-tight"
style={{ color: labelColor, textShadow: "0 1px 2px rgba(0,0,0,0.9)" }}
>
{label}
diff --git a/packages/studio/src/player/components/thumbnailUtils.test.ts b/packages/studio/src/player/components/thumbnailUtils.test.ts
index 38356b2f6c..4e8ac2af8f 100644
--- a/packages/studio/src/player/components/thumbnailUtils.test.ts
+++ b/packages/studio/src/player/components/thumbnailUtils.test.ts
@@ -41,6 +41,13 @@ describe("computeThumbnailStrip", () => {
it("honors a custom clip height", () => {
expect(computeThumbnailStrip(300, 2, 40).frameW).toBe(80);
});
+
+ it("keeps narrow tiles above a caller-owned minimum", () => {
+ expect(computeThumbnailStrip(300, 0.25, 40, 48)).toEqual({
+ frameW: 48,
+ frameCount: 7,
+ });
+ });
});
describe("resolveMediaPreviewUrl", () => {
diff --git a/packages/studio/src/player/components/thumbnailUtils.ts b/packages/studio/src/player/components/thumbnailUtils.ts
index 10561466db..b4bb9e57fc 100644
--- a/packages/studio/src/player/components/thumbnailUtils.ts
+++ b/packages/studio/src/player/components/thumbnailUtils.ts
@@ -8,6 +8,52 @@ export interface ThumbnailStripLayout {
frameCount: number;
}
+/**
+ * Measure an image without mounting it in React's DOM. The scheduler owns the
+ * abort signal, so an unmounted clip cannot leave Blink retaining a pending
+ * image request and its former React tree.
+ */
+export function probeImageAspect(
+ imageSrc: string,
+ signal: AbortSignal,
+ tolerateSvgError = false,
+): Promise<number> {
+ return new Promise((resolve, reject) => {
+ const image = new Image();
+ const cleanup = () => {
+ image.onload = null;
+ image.onerror = null;
+ signal.removeEventListener("abort", onAbort);
+ };
+ const onAbort = () => {
+ cleanup();
+ image.src = "";
+ reject(new DOMException("Aborted", "AbortError"));
+ };
+
+ if (signal.aborted) {
+ onAbort();
+ return;
+ }
+
+ image.onload = () => {
+ cleanup();
+ resolve(
+ image.naturalWidth > 0 && image.naturalHeight > 0
+ ? image.naturalWidth / image.naturalHeight
+ : 16 / 9,
+ );
+ };
+ image.onerror = () => {
+ cleanup();
+ if (tolerateSvgError && /\.svg($|\?)/i.test(imageSrc)) resolve(16 / 9);
+ else reject(new Error("Image thumbnail failed to load"));
+ };
+ signal.addEventListener("abort", onAbort, { once: true });
+ image.src = imageSrc;
+ });
+}
+
/**
* Compute the film-strip tile layout for a clip thumbnail: fixed-height tiles
* sized by the media's aspect ratio, repeated to fill the clip width.
@@ -17,9 +63,10 @@ export function computeThumbnailStrip(
containerWidth: number,
aspect: number,
clipHeight: number = THUMBNAIL_CLIP_HEIGHT,
+ minFrameWidth = 1,
): ThumbnailStripLayout {
const safeAspect = Number.isFinite(aspect) && aspect > 0 ? aspect : 16 / 9;
- const frameW = Math.max(1, Math.round(clipHeight * safeAspect));
+ const frameW = Math.max(minFrameWidth, Math.round(clipHeight * safeAspect));
const frameCount = containerWidth > 0 ? Math.max(1, Math.ceil(containerWidth / frameW)) : 1;
return { frameW, frameCount };
}
diff --git a/packages/studio/src/player/components/timelineClipChildren.test.ts b/packages/studio/src/player/components/timelineClipChildren.test.ts
new file mode 100644
index 0000000000..6a23512618
--- /dev/null
+++ b/packages/studio/src/player/components/timelineClipChildren.test.ts
@@ -0,0 +1,31 @@
+import { describe, expect, it } from "vitest";
+import { resolveClipRenderContext } from "./timelineClipChildren";
+import type { TimelineElement } from "../store/playerStore";
+
+const clip: TimelineElement = {
+ id: "clip",
+ tag: "video",
+ start: 10,
+ duration: 5,
+ track: 0,
+};
+
+describe("resolveClipRenderContext", () => {
+ it("prioritizes interactive clips and enables rich thumbnails", () => {
+ expect(resolveClipRenderContext(clip, { start: 0, end: 1 }, true)).toEqual({
+ priority: "interaction",
+ rich: true,
+ });
+ });
+
+ it("distinguishes visible clips from overscan clips", () => {
+ expect(resolveClipRenderContext(clip, { start: 14, end: 16 }, false)).toEqual({
+ priority: "visible",
+ rich: false,
+ });
+ expect(resolveClipRenderContext(clip, { start: 15, end: 20 }, false)).toEqual({
+ priority: "overscan",
+ rich: false,
+ });
+ });
+});
diff --git a/packages/studio/src/player/components/timelineClipChildren.tsx b/packages/studio/src/player/components/timelineClipChildren.tsx
index 3482fbdc00..39d3e5dd7f 100644
--- a/packages/studio/src/player/components/timelineClipChildren.tsx
+++ b/packages/studio/src/player/components/timelineClipChildren.tsx
@@ -1,6 +1,20 @@
import { type ReactNode } from "react";
import { usePlayerStore, type TimelineElement } from "../store/playerStore";
+import type { TimelineTimeRange } from "../lib/timelineClipIndex";
import type { TrackVisualStyle } from "./timelineIcons";
+import type { TimelineClipRenderContext } from "./TimelineTypes";
+
+export function resolveClipRenderContext(
+ element: TimelineElement,
+ visibleTimeRange: TimelineTimeRange,
+ interactive: boolean,
+): TimelineClipRenderContext {
+ if (interactive) return { priority: "interaction", rich: true };
+ const visible =
+ element.start < visibleTimeRange.end &&
+ element.start + element.duration > visibleTimeRange.start;
+ return { priority: visible ? "visible" : "overscan", rich: false };
+}
function ClipLintDot({ element }: { element: TimelineElement }) {
const lint = usePlayerStore((s) => s.lintFindingsByElement.get(element.key ?? element.id));
@@ -18,9 +32,14 @@ export function renderClipChildren(
element: TimelineElement,
clipStyle: TrackVisualStyle,
renderClipContent:
- | ((element: TimelineElement, style: { clip: string; label: string }) => ReactNode)
+ | ((
+ element: TimelineElement,
+ style: { clip: string; label: string },
+ context: TimelineClipRenderContext,
+ ) => ReactNode)
| undefined,
renderClipOverlay: ((element: TimelineElement) => ReactNode) | undefined,
+ context: TimelineClipRenderContext = { priority: "visible", rich: false },
): ReactNode {
return (
<>
@@ -31,7 +50,7 @@ export function renderClipChildren(
// diamonds hang outside its bounds), so the thumbnail layer must clip
// itself to the clip's rounded corners or sharp corners poke out.
<div className="absolute inset-0 overflow-hidden" style={{ borderRadius: "inherit" }}>
- {renderClipContent(element, clipStyle)}
+ {renderClipContent(element, clipStyle, context)}
</div>
)}
</>
diff --git a/packages/studio/src/player/components/timelineLaneProps.ts b/packages/studio/src/player/components/timelineLaneProps.ts
index e6c1925260..0fff7d6acd 100644
--- a/packages/studio/src/player/components/timelineLaneProps.ts
+++ b/packages/studio/src/player/components/timelineLaneProps.ts
@@ -10,6 +10,7 @@ import type { TimelineClipIndex, TimelineTimeRange } from "../lib/timelineClipIn
import type { TimelineRowGeometry } from "./timelineLayout";
import type { TimelineVirtualRow } from "./useTimelineVirtualRows";
import type { TimelineLogicalRow } from "./timelineKeyboardNavigation";
+import type { TimelineClipRenderContext } from "./TimelineTypes";
/**
* Props shared by the scroll container ({@link import("./TimelineCanvas")}) and
@@ -33,6 +34,7 @@ export interface TimelineLaneBaseProps {
rowsVirtualized: boolean;
clipIndex: TimelineClipIndex;
renderTimeRange: TimelineTimeRange;
+ visibleTimeRange: TimelineTimeRange;
pinnedClipIdentities: ReadonlySet<string>;
trackOrder: number[];
tracks: [number, TimelineElement[]][];
@@ -48,6 +50,7 @@ export interface TimelineLaneBaseProps {
renderClipContent?: (
element: TimelineElement,
style: { clip: string; label: string },
+ context: TimelineClipRenderContext,
) => ReactNode;
renderClipOverlay?: (element: TimelineElement) => ReactNode;
onDrillDown?: (element: TimelineElement) => void;
diff --git a/packages/studio/src/player/components/useTimelineClipRenderWindow.ts b/packages/studio/src/player/components/useTimelineClipRenderWindow.ts
index f48941a401..13d968a095 100644
--- a/packages/studio/src/player/components/useTimelineClipRenderWindow.ts
+++ b/packages/studio/src/player/components/useTimelineClipRenderWindow.ts
@@ -1,6 +1,9 @@
import { useMemo } from "react";
import { createTimelineClipIndex } from "../lib/timelineClipIndex";
-import { getTimelineRenderTimeRange } from "./timelineViewportGeometry";
+import {
+ getTimelineRenderTimeRange,
+ getTimelineVisibleTimeRange,
+} from "./timelineViewportGeometry";
import type { TimelineScrollViewportSnapshot } from "./useTimelineScrollViewport";
interface UseTimelineClipRenderWindowInput {
@@ -37,6 +40,10 @@ export function useTimelineClipRenderWindow({
() => getTimelineRenderTimeRange(viewport, pixelsPerSecond, contentOrigin, duration),
[contentOrigin, duration, pixelsPerSecond, viewport],
);
+ const visibleTimeRange = useMemo(
+ () => getTimelineVisibleTimeRange(viewport, pixelsPerSecond, contentOrigin, duration),
+ [contentOrigin, duration, pixelsPerSecond, viewport],
+ );
const pinnedClipIdentities = useMemo(
() =>
new Set(
@@ -60,5 +67,5 @@ export function useTimelineClipRenderWindow({
selectedElementId,
],
);
- return { clipIndex, renderTimeRange, pinnedClipIdentities };
+ return { clipIndex, renderTimeRange, visibleTimeRange, pinnedClipIdentities };
}
diff --git a/packages/studio/src/player/lib/mediaProbe.test.ts b/packages/studio/src/player/lib/mediaProbe.test.ts
new file mode 100644
index 0000000000..f16e7a5d09
--- /dev/null
+++ b/packages/studio/src/player/lib/mediaProbe.test.ts
@@ -0,0 +1,81 @@
+// @vitest-environment happy-dom
+
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { getMediaProbeDiagnostics, probeMediaUrl, resetMediaProbeRegistry } from "./mediaProbe";
+
+const dispose = vi.fn();
+const getDurationFromMetadata = vi.fn(async () => 5);
+
+vi.mock("mediabunny", () => ({
+ ALL_FORMATS: {},
+ UrlSource: class {
+ constructor(readonly url: string) {}
+ },
+ Input: class {
+ getDurationFromMetadata = getDurationFromMetadata;
+ getPrimaryVideoTrack = vi.fn(async () => ({ displayWidth: 640, displayHeight: 360 }));
+ getAudioTracks = vi.fn(async () => []);
+ dispose = dispose;
+ },
+}));
+
+beforeEach(() => {
+ resetMediaProbeRegistry();
+ vi.clearAllMocks();
+ getDurationFromMetadata.mockResolvedValue(5);
+});
+
+afterEach(() => {
+ vi.useRealTimers();
+});
+
+describe("media probe registry", () => {
+ it("deduplicates and caches successful probes", async () => {
+ const [first, second] = await Promise.all([
+ probeMediaUrl("/video.mp4"),
+ probeMediaUrl("/video.mp4"),
+ ]);
+ expect(first).toEqual(second);
+ expect(getDurationFromMetadata).toHaveBeenCalledTimes(1);
+ expect(dispose).toHaveBeenCalledTimes(1);
+ expect(getMediaProbeDiagnostics()).toEqual({ cached: 1, failed: 0, inflight: 0 });
+ });
+
+ it("bounds retained successes to the configured registry count", async () => {
+ for (let index = 0; index < 513; index++) {
+ await probeMediaUrl(`/video-${index}.mp4`);
+ }
+ expect(getMediaProbeDiagnostics().cached).toBe(512);
+ });
+
+ it("limits concurrent metadata probes and drains the queue", async () => {
+ const resolvers: Array<(duration: number) => void> = [];
+ getDurationFromMetadata.mockImplementation(
+ () => new Promise<number>((resolve) => resolvers.push(resolve)),
+ );
+
+ const probes = Array.from({ length: 5 }, (_, index) => probeMediaUrl(`/queued-${index}.mp4`));
+ await Promise.resolve();
+ await Promise.resolve();
+ expect(getDurationFromMetadata).toHaveBeenCalledTimes(4);
+
+ resolvers[0]?.(5);
+ await vi.waitFor(() => expect(getDurationFromMetadata).toHaveBeenCalledTimes(5));
+
+ for (const resolve of resolvers.slice(1)) resolve(5);
+ await expect(Promise.all(probes)).resolves.toHaveLength(5);
+ expect(getMediaProbeDiagnostics()).toEqual({ cached: 5, failed: 0, inflight: 0 });
+ });
+
+ it("retries failures only after the failure TTL", async () => {
+ vi.useFakeTimers();
+ getDurationFromMetadata.mockRejectedValue(new Error("bad source"));
+ await expect(probeMediaUrl("/bad.mp4")).resolves.toBeNull();
+ await expect(probeMediaUrl("/bad.mp4")).resolves.toBeNull();
+ expect(getDurationFromMetadata).toHaveBeenCalledTimes(1);
+
+ vi.advanceTimersByTime(30_001);
+ await expect(probeMediaUrl("/bad.mp4")).resolves.toBeNull();
+ expect(getDurationFromMetadata).toHaveBeenCalledTimes(2);
+ });
+});
diff --git a/packages/studio/src/player/lib/mediaProbe.ts b/packages/studio/src/player/lib/mediaProbe.ts
index 90b782336d..803d15b269 100644
--- a/packages/studio/src/player/lib/mediaProbe.ts
+++ b/packages/studio/src/player/lib/mediaProbe.ts
@@ -1,4 +1,6 @@
-interface MediaProbeResult {
+import { TIMELINE_VIEWPORT_BUDGETS } from "./timelineViewportBudgets";
+
+export interface MediaProbeResult {
duration: number;
width?: number;
height?: number;
@@ -6,11 +8,24 @@ interface MediaProbeResult {
hasAudio: boolean;
}
-const cache = new Map<string, MediaProbeResult>();
+interface CachedProbe {
+ result: MediaProbeResult;
+ lastAccess: number;
+}
+
+const cache = new Map<string, CachedProbe>();
const inflight = new Map<string, Promise<MediaProbeResult | null>>();
// URLs whose probe failed (CORS, 404, non-media). Remembered so the rAF-driven
// timeline re-derive doesn't re-fetch them every frame and flood the console.
-const failed = new Set<string>();
+const failed = new Map<string, { failedAt: number; lastAccess: number }>();
+let accessSequence = 0;
+let activeProbes = 0;
+let registryEpoch = 0;
+const probeQueue: Array<{
+ key: string;
+ epoch: number;
+ resolve: (result: MediaProbeResult | null) => void;
+}> = [];
let mediabunnyModule: typeof import("mediabunny") | null | false = null;
@@ -65,7 +80,22 @@ async function probeOne(url: string): Promise<MediaProbeResult | null> {
}
function getCachedProbe(url: string): MediaProbeResult | undefined {
- return cache.get(normalizeUrl(url));
+ const cached = cache.get(normalizeUrl(url));
+ if (cached) cached.lastAccess = ++accessSequence;
+ return cached?.result;
+}
+
+function evictMetadataOverflow(): void {
+ const overflow = cache.size + failed.size - TIMELINE_VIEWPORT_BUDGETS.metadataRegistryEntries;
+ if (overflow <= 0) return;
+ const entries = [
+ ...Array.from(cache, ([key, value]) => ({ key, at: value.lastAccess, failed: false })),
+ ...Array.from(failed, ([key, value]) => ({ key, at: value.lastAccess, failed: true })),
+ ].sort((left, right) => left.at - right.at);
+ for (const entry of entries.slice(0, overflow)) {
+ if (entry.failed) failed.delete(entry.key);
+ else cache.delete(entry.key);
+ }
}
/**
@@ -101,32 +131,82 @@ export async function probeMissingSourceDurations<
el.sourceDuration == null &&
["video", "audio"].includes(el.tag.toLowerCase()) &&
!getCachedProbe(el.src) &&
- !failed.has(normalizeUrl(el.src)),
+ !hasFreshFailure(normalizeUrl(el.src)),
);
if (needs.length === 0) return;
await Promise.allSettled(
needs.map(async (el) => {
- const result = await probeMediaUrl(el.src!);
+ const source = el.src;
+ if (!source) return;
+ const result = await probeMediaUrl(source);
if (result) apply(el.key ?? el.id, result.duration);
}),
);
}
-async function probeMediaUrl(url: string): Promise<MediaProbeResult | null> {
+function hasFreshFailure(key: string): boolean {
+ const failedAt = failed.get(key);
+ if (failedAt === undefined) return false;
+ if (Date.now() - failedAt.failedAt < TIMELINE_VIEWPORT_BUDGETS.metadataFailureTtlMs) {
+ failedAt.lastAccess = ++accessSequence;
+ return true;
+ }
+ failed.delete(key);
+ return false;
+}
+
+export async function probeMediaUrl(url: string): Promise<MediaProbeResult | null> {
const key = normalizeUrl(url);
- const cached = cache.get(key);
+ const cached = getCachedProbe(key);
if (cached) return cached;
- if (failed.has(key)) return null;
+ if (hasFreshFailure(key)) return null;
let pending = inflight.get(key);
if (pending) return pending;
- pending = probeOne(key).then((result) => {
- inflight.delete(key);
- if (result) cache.set(key, result);
- else failed.add(key);
- return result;
+ pending = new Promise<MediaProbeResult | null>((resolve) => {
+ probeQueue.push({ key, epoch: registryEpoch, resolve });
+ pumpProbeQueue();
});
inflight.set(key, pending);
return pending;
}
+
+function pumpProbeQueue(): void {
+ while (activeProbes < TIMELINE_VIEWPORT_BUDGETS.concurrentMetadataJobs) {
+ const queued = probeQueue.shift();
+ if (!queued) return;
+ if (queued.epoch !== registryEpoch) {
+ queued.resolve(null);
+ continue;
+ }
+ activeProbes++;
+ void probeOne(queued.key)
+ .then((result) => {
+ if (queued.epoch !== registryEpoch) return null;
+ inflight.delete(queued.key);
+ if (result) cache.set(queued.key, { result, lastAccess: ++accessSequence });
+ else failed.set(queued.key, { failedAt: Date.now(), lastAccess: ++accessSequence });
+ evictMetadataOverflow();
+ return result;
+ })
+ .then(queued.resolve)
+ .finally(() => {
+ activeProbes--;
+ pumpProbeQueue();
+ });
+ }
+}
+
+export function getMediaProbeDiagnostics() {
+ return { cached: cache.size, failed: failed.size, inflight: inflight.size };
+}
+
+export function resetMediaProbeRegistry(): void {
+ registryEpoch++;
+ for (const queued of probeQueue.splice(0)) queued.resolve(null);
+ cache.clear();
+ failed.clear();
+ inflight.clear();
+ accessSequence = 0;
+}
diff --git a/packages/studio/src/player/lib/thumbnailPolicy.test.ts b/packages/studio/src/player/lib/thumbnailPolicy.test.ts
new file mode 100644
index 0000000000..675a49140e
--- /dev/null
+++ b/packages/studio/src/player/lib/thumbnailPolicy.test.ts
@@ -0,0 +1,14 @@
+import { describe, expect, it } from "vitest";
+import { defaultThumbnailMode, effectiveThumbnailMode } from "./thumbnailPolicy";
+
+describe("thumbnail runtime policy", () => {
+ it("defaults missing preferences adaptively after activation", () => {
+ expect(defaultThumbnailMode(undefined, "follow-preference")).toBe("adaptive");
+ expect(defaultThumbnailMode(undefined, "legacy-default")).toBe("hidden");
+ });
+
+ it("forces the safe renderer without overwriting user intent", () => {
+ expect(effectiveThumbnailMode("adaptive", "force-hidden")).toBe("hidden");
+ expect(effectiveThumbnailMode("adaptive", "follow-preference")).toBe("adaptive");
+ });
+});
diff --git a/packages/studio/src/player/lib/thumbnailPolicy.ts b/packages/studio/src/player/lib/thumbnailPolicy.ts
new file mode 100644
index 0000000000..7630784fca
--- /dev/null
+++ b/packages/studio/src/player/lib/thumbnailPolicy.ts
@@ -0,0 +1,24 @@
+export type ThumbnailMode = "adaptive" | "hidden";
+export type ThumbnailRuntimePolicy = "follow-preference" | "force-hidden" | "legacy-default";
+
+// "Adaptive" currently means the scheduler pauses rich work while scrolling.
+// The mode name leaves room for finer-grained runtime heuristics later.
+
+const rawPolicy = import.meta.env.VITE_STUDIO_TIMELINE_THUMBNAIL_POLICY;
+
+const studioThumbnailRuntimePolicy: ThumbnailRuntimePolicy =
+ rawPolicy === "force-hidden" || rawPolicy === "legacy-default" ? rawPolicy : "follow-preference";
+
+export function defaultThumbnailMode(
+ storedMode: ThumbnailMode | undefined,
+ policy: ThumbnailRuntimePolicy = studioThumbnailRuntimePolicy,
+): ThumbnailMode {
+ return storedMode ?? (policy === "legacy-default" ? "hidden" : "adaptive");
+}
+
+export function effectiveThumbnailMode(
+ preferredMode: ThumbnailMode,
+ policy: ThumbnailRuntimePolicy = studioThumbnailRuntimePolicy,
+): ThumbnailMode {
+ return policy === "force-hidden" ? "hidden" : preferredMode;
+}
diff --git a/packages/studio/src/player/lib/thumbnailScheduler.test.ts b/packages/studio/src/player/lib/thumbnailScheduler.test.ts
new file mode 100644
index 0000000000..5e31ad6b1e
--- /dev/null
+++ b/packages/studio/src/player/lib/thumbnailScheduler.test.ts
@@ -0,0 +1,388 @@
+import { describe, expect, it, vi } from "vitest";
+import { resolveTimelineViewportBudgets } from "./timelineViewportBudgets";
+import {
+ createThumbnailKey,
+ createThumbnailRequestIdentity,
+ ThumbnailScheduler,
+ type ThumbnailLoadedResult,
+ type ThumbnailPriority,
+ type ThumbnailRequest,
+} from "./thumbnailScheduler";
+
+function deferred<T>() {
+ let resolve!: (value: T) => void;
+ let reject!: (reason?: unknown) => void;
+ const promise = new Promise<T>((accept, fail) => {
+ resolve = accept;
+ reject = fail;
+ });
+ return { promise, resolve, reject };
+}
+
+function result(name: string, weight = 1, dispose = vi.fn()): ThumbnailLoadedResult {
+ return { value: { kind: "image", url: name, aspect: 1 }, weight, dispose };
+}
+
+function request(
+ key: string,
+ load: ThumbnailRequest["load"],
+ priority: ThumbnailPriority = "visible",
+ overrides: Partial<ThumbnailRequest> = {},
+): ThumbnailRequest {
+ return {
+ key,
+ projectId: "project-a",
+ sessionEpoch: 1,
+ kind: "image",
+ priority,
+ load,
+ ...overrides,
+ };
+}
+
+async function flush(): Promise<void> {
+ await Promise.resolve();
+ await Promise.resolve();
+}
+
+describe("ThumbnailScheduler", () => {
+ it("deduplicates identical requests and releases subscribers independently", async () => {
+ const scheduler = new ThumbnailScheduler();
+ const pending = deferred<ThumbnailLoadedResult>();
+ const load = vi.fn(() => pending.promise);
+ const listenerA = vi.fn();
+ const listenerB = vi.fn();
+
+ const leaseA = scheduler.acquire(request("same", load), listenerA);
+ const leaseB = scheduler.acquire(request("same", load), listenerB);
+ expect(load).toHaveBeenCalledTimes(1);
+
+ leaseA.release();
+ listenerA.mockClear();
+ pending.resolve(result("poster"));
+ await flush();
+ expect(scheduler.getSnapshot(request("same", load))).toMatchObject({
+ status: "ready",
+ value: { url: "poster" },
+ });
+ expect(listenerA).not.toHaveBeenCalled();
+ expect(listenerB).toHaveBeenCalled();
+
+ leaseB.release();
+ expect(scheduler.getDiagnostics().leases).toBe(0);
+ });
+
+ it("keeps snapshots referentially stable and supports independent leases sharing a callback", async () => {
+ const scheduler = new ThumbnailScheduler();
+ const listener = vi.fn();
+ const shared = request("stable", async () => result("stable"));
+ const first = scheduler.acquire(shared, listener);
+ const second = scheduler.acquire(shared, listener);
+ await flush();
+ expect(scheduler.getSnapshot(shared)).toBe(scheduler.getSnapshot(shared));
+ listener.mockClear();
+ scheduler.invalidateProject("project-a");
+ expect(listener).not.toHaveBeenCalled();
+ expect(scheduler.getDiagnostics().leases).toBe(2);
+ first.release();
+ second.release();
+ scheduler.invalidateProject("project-a");
+ expect(scheduler.getSnapshot(shared).status).toBe("idle");
+ });
+
+ it("scopes the same caller key by work shape", async () => {
+ const scheduler = new ThumbnailScheduler();
+ const poster = request("shared", async () => result("poster"));
+ const strip = request("shared", async () => result("strip"), "visible", {
+ kind: "video",
+ rich: true,
+ });
+
+ scheduler.acquire(poster, vi.fn());
+ scheduler.acquire(strip, vi.fn());
+ await flush();
+
+ expect(scheduler.getSnapshot(poster)).toMatchObject({
+ status: "ready",
+ value: { url: "poster" },
+ });
+ expect(scheduler.getSnapshot(strip)).toMatchObject({
+ status: "ready",
+ value: { url: "strip" },
+ });
+ });
+
+ it("orders interaction before visible before overscan when a slot opens", async () => {
+ const scheduler = new ThumbnailScheduler(
+ resolveTimelineViewportBudgets({ concurrentMetadataJobs: 1 }),
+ );
+ const first = deferred<ThumbnailLoadedResult>();
+ const starts: string[] = [];
+ const load = (name: string, pending?: ReturnType<typeof deferred<ThumbnailLoadedResult>>) =>
+ vi.fn(() => {
+ starts.push(name);
+ return pending?.promise ?? Promise.resolve(result(name));
+ });
+
+ scheduler.acquire(request("first", load("first", first)), vi.fn());
+ scheduler.acquire(request("overscan", load("overscan"), "overscan"), vi.fn());
+ scheduler.acquire(request("visible", load("visible"), "visible"), vi.fn());
+ scheduler.acquire(request("interaction", load("interaction"), "interaction"), vi.fn());
+ expect(starts).toEqual(["first"]);
+
+ first.resolve(result("first"));
+ await vi.waitFor(() => {
+ expect(starts).toEqual(["first", "interaction", "visible", "overscan"]);
+ });
+ });
+
+ it("suspends new rich work while scrolling but lets posters proceed", async () => {
+ const scheduler = new ThumbnailScheduler();
+ const richLoad = vi.fn(async () => result("rich"));
+ const posterLoad = vi.fn(async () => result("poster"));
+ scheduler.setScrolling(true);
+
+ scheduler.acquire(request("rich", richLoad, "interaction", { rich: true }), vi.fn());
+ scheduler.acquire(request("poster", posterLoad), vi.fn());
+ await flush();
+ expect(richLoad).not.toHaveBeenCalled();
+ expect(posterLoad).toHaveBeenCalledTimes(1);
+
+ scheduler.setScrolling(false);
+ await flush();
+ expect(richLoad).toHaveBeenCalledTimes(1);
+ });
+
+ it("aborts queued and active jobs after the final release", async () => {
+ const scheduler = new ThumbnailScheduler(
+ resolveTimelineViewportBudgets({ concurrentVideoDecodes: 1 }),
+ );
+ const active = deferred<ThumbnailLoadedResult>();
+ let activeSignal: AbortSignal | undefined;
+ const activeLease = scheduler.acquire(
+ request(
+ "active",
+ (signal) => {
+ activeSignal = signal;
+ return active.promise;
+ },
+ "visible",
+ { kind: "video" },
+ ),
+ vi.fn(),
+ );
+ const queuedLoad = vi.fn(async () => result("queued"));
+ const queuedLease = scheduler.acquire(
+ request("queued", queuedLoad, "visible", { kind: "video" }),
+ vi.fn(),
+ );
+
+ queuedLease.release();
+ activeLease.release();
+ expect(activeSignal?.aborted).toBe(true);
+ expect(queuedLoad).not.toHaveBeenCalled();
+ active.reject(new DOMException("aborted", "AbortError"));
+ await flush();
+ expect(scheduler.getDiagnostics()).toMatchObject({ queued: 0, active: 0, leases: 0 });
+ });
+
+ it("disposes a late result exactly once after its final lease releases", async () => {
+ const scheduler = new ThumbnailScheduler();
+ const pending = deferred<ThumbnailLoadedResult>();
+ const dispose = vi.fn();
+ const lease = scheduler.acquire(
+ request("late", () => pending.promise),
+ vi.fn(),
+ );
+
+ lease.release();
+ pending.resolve(result("late", 1, dispose));
+ await flush();
+ expect(dispose).toHaveBeenCalledTimes(1);
+ expect(scheduler.getSnapshot(request("late", () => pending.promise))).toEqual({
+ status: "idle",
+ });
+ });
+
+ it("preserves a synchronous re-acquire when an expired failure is replaced", async () => {
+ vi.useFakeTimers();
+ const scheduler = new ThumbnailScheduler(
+ resolveTimelineViewportBudgets({ metadataFailureTtlMs: 10 }),
+ );
+ const load = vi
+ .fn<ThumbnailRequest["load"]>()
+ .mockRejectedValueOnce(new Error("temporary"))
+ .mockResolvedValue(result("recovered"));
+ const failed = request("retry", load);
+ let reacquireOnNotify = false;
+ let nestedLease: ReturnType<ThumbnailScheduler["acquire"]> | undefined;
+ const firstLease = scheduler.acquire(failed, () => {
+ if (!reacquireOnNotify) return;
+ reacquireOnNotify = false;
+ nestedLease = scheduler.acquire(failed, vi.fn());
+ });
+ await flush();
+ vi.advanceTimersByTime(11);
+ reacquireOnNotify = true;
+
+ const outerLease = scheduler.acquire(failed, vi.fn());
+ await flush();
+
+ expect(load).toHaveBeenCalledTimes(2);
+ expect(scheduler.getSnapshot(failed)).toMatchObject({
+ status: "ready",
+ value: { url: "recovered" },
+ });
+ expect(scheduler.getDiagnostics().leases).toBe(2);
+ firstLease.release();
+ nestedLease?.release();
+ outerLease.release();
+ vi.useRealTimers();
+ });
+
+ it("times out a hung loader, frees its bucket, and disposes a late result", async () => {
+ vi.useFakeTimers();
+ const scheduler = new ThumbnailScheduler(
+ resolveTimelineViewportBudgets({
+ concurrentVideoDecodes: 1,
+ thumbnailLoadTimeoutMs: 10,
+ }),
+ );
+ const hung = deferred<ThumbnailLoadedResult>();
+ const dispose = vi.fn();
+ let signal: AbortSignal | undefined;
+ const hungRequest = request(
+ "hung",
+ (activeSignal) => {
+ signal = activeSignal;
+ return hung.promise;
+ },
+ "visible",
+ { kind: "video" },
+ );
+ const nextLoad = vi.fn(async () => result("next"));
+ const nextRequest = request("next", nextLoad, "visible", { kind: "video" });
+ const hungLease = scheduler.acquire(hungRequest, vi.fn());
+ const nextLease = scheduler.acquire(nextRequest, vi.fn());
+
+ await vi.advanceTimersByTimeAsync(11);
+ await flush();
+ expect(signal?.aborted).toBe(true);
+ expect(nextLoad).toHaveBeenCalledTimes(1);
+ expect(scheduler.getSnapshot(hungRequest).status).toBe("error");
+
+ hung.resolve(result("late", 1, dispose));
+ await flush();
+ expect(dispose).toHaveBeenCalledTimes(1);
+ hungLease.release();
+ nextLease.release();
+ vi.useRealTimers();
+ });
+
+ it("isolates late results by session epoch", async () => {
+ const scheduler = new ThumbnailScheduler();
+ const old = deferred<ThumbnailLoadedResult>();
+ const oldRequest = request("poster", () => old.promise, "visible", { sessionEpoch: 1 });
+ const nextRequest = request("poster", async () => result("next"), "visible", {
+ sessionEpoch: 2,
+ });
+ scheduler.acquire(oldRequest, vi.fn());
+ scheduler.acquire(nextRequest, vi.fn());
+ await flush();
+ old.resolve(result("old"));
+ await flush();
+ expect(scheduler.getSnapshot(nextRequest)).toMatchObject({
+ status: "ready",
+ value: { url: "next" },
+ });
+ });
+
+ it("turns synchronous loader errors into bounded failure snapshots", async () => {
+ const scheduler = new ThumbnailScheduler();
+ const bad = request("throws", () => {
+ throw new Error("sync failure");
+ });
+ const lease = scheduler.acquire(bad, vi.fn());
+ await flush();
+ expect(scheduler.getSnapshot(bad)).toMatchObject({ status: "error" });
+ expect(scheduler.getDiagnostics().active).toBe(0);
+ lease.release();
+ });
+
+ it("disposes uncached results after the final lease and tolerates broken disposers", async () => {
+ const scheduler = new ThumbnailScheduler(
+ resolveTimelineViewportBudgets({ thumbnailCacheBytes: 1 }),
+ );
+ const dispose = vi.fn(() => {
+ throw new Error("cleanup failure");
+ });
+ const oversized = request("oversized", async () => result("large", 2, dispose));
+ const lease = scheduler.acquire(oversized, vi.fn());
+ await flush();
+ expect(scheduler.getSnapshot(oversized).status).toBe("ready");
+ expect(() => lease.release()).not.toThrow();
+ expect(dispose).toHaveBeenCalledTimes(1);
+ expect(scheduler.getSnapshot(oversized).status).toBe("idle");
+ });
+
+ it("evicts least-recently-used unleased values by bytes, count, and project count", async () => {
+ const scheduler = new ThumbnailScheduler(
+ resolveTimelineViewportBudgets({
+ thumbnailCacheBytes: 6,
+ thumbnailCacheEntries: 2,
+ thumbnailCacheEntriesPerProject: 2,
+ }),
+ );
+ const disposals = [vi.fn(), vi.fn(), vi.fn()];
+ for (let index = 0; index < 3; index++) {
+ const lease = scheduler.acquire(
+ request(`key-${index}`, async () => result(`url-${index}`, 3, disposals[index])),
+ vi.fn(),
+ );
+ await flush();
+ lease.release();
+ }
+
+ expect(scheduler.getDiagnostics()).toMatchObject({ cacheEntries: 2, cacheBytes: 6 });
+ expect(disposals[0]).toHaveBeenCalledTimes(1);
+ expect(disposals[1]).not.toHaveBeenCalled();
+ expect(disposals[2]).not.toHaveBeenCalled();
+ });
+
+ it("keeps failed requests quiet until the TTL expires", async () => {
+ vi.useFakeTimers();
+ const scheduler = new ThumbnailScheduler(
+ resolveTimelineViewportBudgets({ metadataFailureTtlMs: 100 }),
+ );
+ const load = vi.fn(async () => {
+ throw new Error("unsupported");
+ });
+
+ const first = scheduler.acquire(request("failed", load), vi.fn());
+ await flush();
+ first.release();
+ const second = scheduler.acquire(request("failed", load), vi.fn());
+ expect(load).toHaveBeenCalledTimes(1);
+ second.release();
+
+ vi.advanceTimersByTime(101);
+ scheduler.acquire(request("failed", load), vi.fn());
+ await flush();
+ expect(load).toHaveBeenCalledTimes(2);
+ vi.useRealTimers();
+ });
+});
+
+describe("createThumbnailKey", () => {
+ it("normalizes field order and preserves sentinel zero values", () => {
+ expect(createThumbnailKey({ source: "clip a", time: 0, missing: undefined })).toBe(
+ createThumbnailKey({ time: 0, source: "clip a" }),
+ );
+ });
+
+ it("includes the work shape in request identity", () => {
+ const poster = request("shared", vi.fn(), "visible", { kind: "video" });
+ const strip = { ...poster, rich: true };
+ expect(createThumbnailRequestIdentity(poster)).not.toBe(createThumbnailRequestIdentity(strip));
+ });
+});
diff --git a/packages/studio/src/player/lib/thumbnailScheduler.ts b/packages/studio/src/player/lib/thumbnailScheduler.ts
new file mode 100644
index 0000000000..d3ca347f55
--- /dev/null
+++ b/packages/studio/src/player/lib/thumbnailScheduler.ts
@@ -0,0 +1,483 @@
+import { TIMELINE_VIEWPORT_BUDGETS, type TimelineViewportBudgets } from "./timelineViewportBudgets";
+
+export type ThumbnailPriority = "overscan" | "visible" | "interaction";
+export type ThumbnailJobKind = "video" | "image" | "composition" | "waveform";
+
+export type ThumbnailValue =
+ | { kind: "image"; url: string; aspect: number }
+ | { kind: "filmstrip"; urls: readonly string[]; aspect: number }
+ | { kind: "waveform"; peaks: readonly number[] };
+
+export interface ThumbnailLoadedResult {
+ value: ThumbnailValue;
+ /** Estimated decoded/object-URL bytes retained by this result. */
+ weight: number;
+ dispose?: () => void;
+}
+
+export interface ThumbnailRequest {
+ key: string;
+ projectId: string;
+ sessionEpoch: number;
+ kind: ThumbnailJobKind;
+ priority: ThumbnailPriority;
+ /** Rich work is paused while the timeline is fast-scrolling. */
+ rich?: boolean;
+ load: (signal: AbortSignal) => Promise<ThumbnailLoadedResult>;
+}
+
+export type ThumbnailSnapshot =
+ | { status: "idle" | "queued" | "loading" }
+ | { status: "ready"; value: ThumbnailValue }
+ | { status: "error"; error: Error };
+
+export interface ThumbnailLease {
+ updatePriority(priority: ThumbnailPriority): void;
+ release(): void;
+}
+
+export interface ThumbnailSchedulerDiagnostics {
+ queued: number;
+ active: number;
+ leases: number;
+ cacheEntries: number;
+ cacheBytes: number;
+ waveformCacheEntries: number;
+ waveformCacheBytes: number;
+ activeByKind: Readonly<Record<ThumbnailJobKind, number>>;
+}
+
+type EntryState = "queued" | "loading" | "ready" | "error";
+
+interface ThumbnailEntry {
+ request: ThumbnailRequest;
+ scopedKey: string;
+ state: EntryState;
+ leases: Map<number, ThumbnailPriority>;
+ listeners: Map<number, () => void>;
+ controller: AbortController | null;
+ value?: ThumbnailValue;
+ error?: Error;
+ failedAt?: number;
+ weight: number;
+ dispose?: () => void;
+ disposed: boolean;
+ cached: boolean;
+ lastAccess: number;
+ snapshot: ThumbnailSnapshot;
+}
+
+const PRIORITY_SCORE: Readonly<Record<ThumbnailPriority, number>> = {
+ overscan: 0,
+ visible: 1,
+ interaction: 2,
+};
+
+const EMPTY_SNAPSHOT: ThumbnailSnapshot = Object.freeze({ status: "idle" });
+
+function concurrencyBucket(kind: ThumbnailJobKind): "video" | "composition" | "general" {
+ if (kind === "video") return "video";
+ if (kind === "composition") return "composition";
+ return "general";
+}
+
+function errorFrom(reason: unknown): Error {
+ return reason instanceof Error ? reason : new Error(String(reason));
+}
+
+export function createThumbnailKey(parts: Readonly<Record<string, string | number | undefined>>) {
+ return Object.entries(parts)
+ .filter((entry): entry is [string, string | number] => entry[1] !== undefined)
+ .sort(([left], [right]) => left.localeCompare(right))
+ .map(([name, value]) => `${encodeURIComponent(name)}=${encodeURIComponent(String(value))}`)
+ .join("&");
+}
+
+export function createThumbnailRequestIdentity(
+ request: Pick<ThumbnailRequest, "key" | "projectId" | "sessionEpoch" | "kind" | "rich">,
+) {
+ return createThumbnailKey({
+ project: request.projectId,
+ session: request.sessionEpoch,
+ request: request.key,
+ kind: request.kind,
+ rich: request.rich ? 1 : 0,
+ });
+}
+
+/** Sole client owner for thumbnail work, cached resources, and cleanup. */
+export class ThumbnailScheduler {
+ private readonly entries = new Map<string, ThumbnailEntry>();
+ private readonly budgets: Readonly<TimelineViewportBudgets>;
+ private nextLeaseId = 1;
+ private nextSequence = 1;
+ private scrolling = false;
+ private cacheBytes = 0;
+ private waveformCacheBytes = 0;
+ private readonly activeByBucket = { video: 0, composition: 0, general: 0 };
+ private readonly activeByKind: Record<ThumbnailJobKind, number> = {
+ video: 0,
+ image: 0,
+ composition: 0,
+ waveform: 0,
+ };
+ private readonly now: () => number;
+
+ constructor(
+ budgets: Readonly<TimelineViewportBudgets> = TIMELINE_VIEWPORT_BUDGETS,
+ now: () => number = Date.now,
+ ) {
+ this.budgets = budgets;
+ this.now = now;
+ }
+
+ acquire(request: ThumbnailRequest, listener: () => void): ThumbnailLease {
+ const scopedKey = createThumbnailRequestIdentity(request);
+ let entry = this.entries.get(scopedKey);
+ if (
+ entry?.state === "error" &&
+ entry.failedAt !== undefined &&
+ this.now() - entry.failedAt >= this.budgets.metadataFailureTtlMs
+ ) {
+ this.deleteEntry(scopedKey, entry);
+ entry = this.entries.get(scopedKey);
+ }
+ if (!entry) {
+ entry = {
+ request,
+ scopedKey,
+ state: "queued",
+ leases: new Map(),
+ listeners: new Map(),
+ controller: null,
+ weight: 0,
+ disposed: false,
+ cached: false,
+ lastAccess: this.nextSequence++,
+ snapshot: Object.freeze({ status: "queued" }),
+ };
+ this.entries.set(scopedKey, entry);
+ }
+
+ const leaseId = this.nextLeaseId++;
+ entry.leases.set(leaseId, request.priority);
+ entry.listeners.set(leaseId, listener);
+ entry.lastAccess = this.nextSequence++;
+ this.pump();
+
+ let released = false;
+ return {
+ updatePriority: (priority) => {
+ const current = this.entries.get(scopedKey);
+ if (!current || !current.leases.has(leaseId)) return;
+ current.leases.set(leaseId, priority);
+ current.lastAccess = this.nextSequence++;
+ this.pump();
+ },
+ release: () => {
+ if (released) return;
+ released = true;
+ const current = this.entries.get(scopedKey);
+ if (!current) return;
+ current.leases.delete(leaseId);
+ current.listeners.delete(leaseId);
+ if (current.leases.size === 0) {
+ if (current.state === "queued") {
+ this.deleteEntry(scopedKey, current);
+ } else if (current.state === "loading") {
+ current.controller?.abort();
+ this.deleteEntry(scopedKey, current);
+ } else if (current.state === "ready" && !current.cached) {
+ this.deleteEntry(scopedKey, current);
+ }
+ }
+ this.evict();
+ },
+ };
+ }
+
+ getSnapshot(
+ request: Pick<ThumbnailRequest, "key" | "projectId" | "sessionEpoch" | "kind" | "rich">,
+ ): ThumbnailSnapshot {
+ const entry = this.entries.get(createThumbnailRequestIdentity(request));
+ if (!entry) return EMPTY_SNAPSHOT;
+ return entry.snapshot;
+ }
+
+ setScrolling(scrolling: boolean): void {
+ if (this.scrolling === scrolling) return;
+ this.scrolling = scrolling;
+ if (!scrolling) this.pump();
+ }
+
+ /** Evict project cache entries that are no longer owned by mounted consumers. */
+ invalidateProject(projectId: string): void {
+ for (const [key, entry] of this.entries) {
+ if (entry.request.projectId !== projectId) continue;
+ if (entry.leases.size > 0) continue;
+ entry.controller?.abort();
+ this.deleteEntry(key, entry);
+ }
+ }
+
+ getDiagnostics(): ThumbnailSchedulerDiagnostics {
+ let queued = 0;
+ let active = 0;
+ let leases = 0;
+ let cacheEntries = 0;
+ let waveformCacheEntries = 0;
+ for (const entry of this.entries.values()) {
+ if (entry.state === "queued") queued++;
+ if (entry.state === "loading") active++;
+ if (entry.cached) {
+ if (entry.request.kind === "waveform") waveformCacheEntries++;
+ else cacheEntries++;
+ }
+ leases += entry.leases.size;
+ }
+ return {
+ queued,
+ active,
+ leases,
+ cacheEntries,
+ cacheBytes: this.cacheBytes,
+ waveformCacheEntries,
+ waveformCacheBytes: this.waveformCacheBytes,
+ activeByKind: { ...this.activeByKind },
+ };
+ }
+
+ private pump(): void {
+ const queued = Array.from(this.entries.values())
+ .filter((entry) => entry.state === "queued" && entry.leases.size > 0)
+ .sort((left, right) => {
+ const priorityDelta = this.entryPriority(right) - this.entryPriority(left);
+ return priorityDelta || left.lastAccess - right.lastAccess;
+ });
+
+ for (const entry of queued) {
+ if (this.scrolling && entry.request.rich) continue;
+ const bucket = concurrencyBucket(entry.request.kind);
+ if (this.activeByBucket[bucket] >= this.bucketLimit(bucket)) continue;
+ this.start(entry, bucket);
+ }
+ }
+
+ private start(entry: ThumbnailEntry, bucket: "video" | "composition" | "general"): void {
+ entry.state = "loading";
+ entry.snapshot = Object.freeze({ status: "loading" });
+ const controller = new AbortController();
+ entry.controller = controller;
+ this.activeByBucket[bucket]++;
+ this.activeByKind[entry.request.kind]++;
+ this.notify(entry);
+
+ const pending = this.loadWithTimeout(entry, controller);
+ void pending
+ .then((result) => this.acceptResult(entry, controller, result))
+ .catch((reason: unknown) => {
+ if (this.entries.get(entry.scopedKey) !== entry) return;
+ if (controller.signal.aborted && entry.leases.size === 0) {
+ this.deleteEntry(entry.scopedKey, entry);
+ return;
+ }
+ entry.state = "error";
+ entry.error = errorFrom(reason);
+ entry.failedAt = this.now();
+ entry.snapshot = Object.freeze({ status: "error", error: entry.error });
+ this.notify(entry);
+ this.evictFailures();
+ })
+ .finally(() => {
+ if (entry.controller === controller) entry.controller = null;
+ this.activeByBucket[bucket]--;
+ this.activeByKind[entry.request.kind]--;
+ this.pump();
+ });
+ }
+
+ private acceptResult(
+ entry: ThumbnailEntry,
+ controller: AbortController,
+ result: ThumbnailLoadedResult,
+ ): void {
+ if (controller.signal.aborted || this.entries.get(entry.scopedKey) !== entry) {
+ this.safeDispose(result.dispose);
+ return;
+ }
+ this.validateResult(result);
+ entry.state = "ready";
+ entry.value = result.value;
+ entry.weight = result.weight;
+ entry.dispose = result.dispose;
+ this.cacheResult(entry);
+ entry.snapshot = Object.freeze({ status: "ready", value: result.value });
+ this.notify(entry);
+ this.evict();
+ if (!entry.cached && entry.leases.size === 0) this.deleteEntry(entry.scopedKey, entry);
+ }
+
+ private validateResult(result: ThumbnailLoadedResult): void {
+ if (Number.isFinite(result.weight) && result.weight >= 0) return;
+ this.safeDispose(result.dispose);
+ throw new RangeError("Thumbnail result weight must be finite and non-negative");
+ }
+
+ private cacheResult(entry: ThumbnailEntry): void {
+ const isWaveform = entry.request.kind === "waveform";
+ const byteBudget = isWaveform
+ ? this.budgets.waveformCacheBytes
+ : this.budgets.thumbnailCacheBytes;
+ entry.cached = entry.weight <= byteBudget;
+ if (!entry.cached) return;
+ if (isWaveform) this.waveformCacheBytes += entry.weight;
+ else this.cacheBytes += entry.weight;
+ }
+
+ private entryPriority(entry: ThumbnailEntry): number {
+ let score = -1;
+ for (const priority of entry.leases.values()) {
+ score = Math.max(score, PRIORITY_SCORE[priority]);
+ }
+ return score;
+ }
+
+ private bucketLimit(bucket: "video" | "composition" | "general"): number {
+ if (bucket === "video") return this.budgets.concurrentVideoDecodes;
+ if (bucket === "composition") return this.budgets.concurrentCompositionFetches;
+ return this.budgets.concurrentMetadataJobs;
+ }
+
+ private evict(): void {
+ this.evictPartition(false);
+ this.evictPartition(true);
+ }
+
+ private evictPartition(waveform: boolean): void {
+ const cached = Array.from(this.entries.values()).filter(
+ (entry) => entry.cached && (entry.request.kind === "waveform") === waveform,
+ );
+ const perProject = new Map<string, number>();
+ for (const entry of cached) {
+ perProject.set(entry.request.projectId, (perProject.get(entry.request.projectId) ?? 0) + 1);
+ }
+ cached.sort((left, right) => left.lastAccess - right.lastAccess);
+
+ let cacheEntries = cached.length;
+ for (const entry of cached) {
+ const projectEntries = perProject.get(entry.request.projectId) ?? 0;
+ if (!this.isCacheOverBudget(waveform, cacheEntries, projectEntries)) continue;
+ this.uncache(entry);
+ cacheEntries--;
+ perProject.set(entry.request.projectId, projectEntries - 1);
+ if (entry.leases.size === 0) this.deleteEntry(entry.scopedKey, entry);
+ }
+ }
+
+ private isCacheOverBudget(
+ waveform: boolean,
+ cacheEntries: number,
+ projectEntries: number,
+ ): boolean {
+ const entryBudget = waveform
+ ? this.budgets.waveformCacheEntries
+ : this.budgets.thumbnailCacheEntries;
+ const byteBudget = waveform
+ ? this.budgets.waveformCacheBytes
+ : this.budgets.thumbnailCacheBytes;
+ const cacheBytes = waveform ? this.waveformCacheBytes : this.cacheBytes;
+ const projectOverBudget =
+ !waveform && projectEntries > this.budgets.thumbnailCacheEntriesPerProject;
+ return cacheEntries > entryBudget || cacheBytes > byteBudget || projectOverBudget;
+ }
+
+ private uncache(entry: ThumbnailEntry): void {
+ entry.cached = false;
+ if (entry.request.kind === "waveform") this.waveformCacheBytes -= entry.weight;
+ else this.cacheBytes -= entry.weight;
+ }
+
+ private notify(entry: ThumbnailEntry): void {
+ for (const listener of new Set(entry.listeners.values())) listener();
+ }
+
+ private loadWithTimeout(
+ entry: ThumbnailEntry,
+ controller: AbortController,
+ ): Promise<ThumbnailLoadedResult> {
+ let load: Promise<ThumbnailLoadedResult>;
+ try {
+ load = entry.request.load(controller.signal);
+ } catch (reason) {
+ load = Promise.reject(reason);
+ }
+
+ return new Promise((resolve, reject) => {
+ let settled = false;
+ const timeout = setTimeout(() => {
+ if (settled) return;
+ settled = true;
+ controller.abort();
+ reject(
+ new Error(`Thumbnail load timed out after ${this.budgets.thumbnailLoadTimeoutMs}ms`),
+ );
+ }, this.budgets.thumbnailLoadTimeoutMs);
+
+ load.then(
+ (result) => {
+ if (settled) {
+ this.safeDispose(result.dispose);
+ return;
+ }
+ settled = true;
+ clearTimeout(timeout);
+ resolve(result);
+ },
+ (reason: unknown) => {
+ if (settled) return;
+ settled = true;
+ clearTimeout(timeout);
+ reject(reason);
+ },
+ );
+ });
+ }
+
+ private deleteEntry(key: string, entry: ThumbnailEntry): void {
+ if (this.entries.get(key) !== entry) return;
+ this.entries.delete(key);
+ entry.snapshot = EMPTY_SNAPSHOT;
+ this.notify(entry);
+ if (entry.cached) {
+ entry.cached = false;
+ if (entry.request.kind === "waveform") this.waveformCacheBytes -= entry.weight;
+ else this.cacheBytes -= entry.weight;
+ }
+ if (!entry.disposed) {
+ entry.disposed = true;
+ this.safeDispose(entry.dispose);
+ }
+ entry.listeners.clear();
+ entry.leases.clear();
+ }
+
+ private evictFailures(): void {
+ const failed = Array.from(this.entries.values())
+ .filter((entry) => entry.state === "error" && entry.leases.size === 0)
+ .sort((left, right) => left.lastAccess - right.lastAccess);
+ const overflow = failed.length - this.budgets.thumbnailCacheEntries;
+ for (const entry of failed.slice(0, Math.max(0, overflow))) {
+ this.deleteEntry(entry.scopedKey, entry);
+ }
+ }
+
+ private safeDispose(dispose: (() => void) | undefined): void {
+ try {
+ dispose?.();
+ } catch {
+ // Cleanup is best-effort; one broken resource must not block the remaining cleanup.
+ }
+ }
+}
+
+export const thumbnailScheduler = new ThumbnailScheduler();
diff --git a/packages/studio/src/player/lib/thumbnailVideoDecoder.test.ts b/packages/studio/src/player/lib/thumbnailVideoDecoder.test.ts
new file mode 100644
index 0000000000..39e5859276
--- /dev/null
+++ b/packages/studio/src/player/lib/thumbnailVideoDecoder.test.ts
@@ -0,0 +1,127 @@
+// @vitest-environment happy-dom
+
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { decodeVideoThumbnail, videoThumbnailTimestamps } from "./thumbnailVideoDecoder";
+
+const dispose = vi.fn();
+const canvasesAtTimestamps = vi.fn();
+const input = {
+ getPrimaryVideoTrack: vi.fn(),
+ dispose,
+};
+
+vi.mock("mediabunny", () => ({
+ ALL_FORMATS: {},
+ UrlSource: class {
+ constructor(readonly url: string) {}
+ },
+ Input: class {
+ getPrimaryVideoTrack = input.getPrimaryVideoTrack;
+ dispose = input.dispose;
+ },
+ CanvasSink: class {
+ canvasesAtTimestamps = canvasesAtTimestamps;
+ },
+}));
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ vi.spyOn(URL, "createObjectURL").mockReturnValueOnce("blob:one").mockReturnValueOnce("blob:two");
+ vi.spyOn(URL, "revokeObjectURL").mockImplementation(() => {});
+ HTMLCanvasElement.prototype.toBlob = function toBlob(callback) {
+ callback(new Blob(["frame"], { type: "image/jpeg" }));
+ };
+ input.getPrimaryVideoTrack.mockResolvedValue({
+ getDisplayWidth: vi.fn(async () => 1080),
+ getDisplayHeight: vi.fn(async () => 1920),
+ getDurationFromMetadata: vi.fn(async () => 10),
+ });
+});
+
+describe("videoThumbnailTimestamps", () => {
+ it("uses the midpoint for a poster and sorted sparse points for a strip", () => {
+ expect(videoThumbnailTimestamps(2, 6, 1)).toEqual([5]);
+ expect(videoThumbnailTimestamps(2, 6, 4)).toEqual([2, 4, 6, 8]);
+ });
+
+ it("clamps invalid source ranges", () => {
+ expect(videoThumbnailTimestamps(-2, Number.NaN, 0)).toEqual([0]);
+ expect(videoThumbnailTimestamps(2, 8, Number.NaN)).toEqual([6]);
+ });
+});
+
+describe("decodeVideoThumbnail", () => {
+ it("extracts sparse frames, returns object URLs, and disposes once", async () => {
+ const canvas = document.createElement("canvas");
+ canvasesAtTimestamps.mockImplementation(async function* (timestamps: number[]) {
+ expect(timestamps).toEqual([2, 8]);
+ yield { canvas, timestamp: 2, duration: 1 };
+ yield { canvas, timestamp: 8, duration: 1 };
+ });
+ const result = await decodeVideoThumbnail(
+ { source: "/clip.mp4", sourceStart: 2, sourceRangeDuration: 6, frameCount: 2 },
+ new AbortController().signal,
+ );
+
+ expect(result.value).toEqual({
+ kind: "filmstrip",
+ urls: ["blob:one", "blob:two"],
+ aspect: 9 / 16,
+ });
+ result.dispose?.();
+ result.dispose?.();
+ expect(URL.revokeObjectURL).toHaveBeenCalledTimes(2);
+ expect(dispose).toHaveBeenCalledTimes(1);
+ });
+
+ it("releases input and degrades when the source has no video track", async () => {
+ input.getPrimaryVideoTrack.mockResolvedValue(null);
+ await expect(
+ decodeVideoThumbnail({ source: "/audio.mp3", frameCount: 1 }, new AbortController().signal),
+ ).rejects.toThrow("no decodable video track");
+ expect(dispose).toHaveBeenCalledTimes(1);
+ });
+
+ it("revokes partial results when cancellation lands during extraction", async () => {
+ const controller = new AbortController();
+ const canvas = document.createElement("canvas");
+ canvasesAtTimestamps.mockImplementation(async function* () {
+ yield { canvas, timestamp: 1, duration: 1 };
+ controller.abort();
+ yield { canvas, timestamp: 2, duration: 1 };
+ });
+ await expect(
+ decodeVideoThumbnail({ source: "/clip.mp4", frameCount: 2 }, controller.signal),
+ ).rejects.toMatchObject({ name: "AbortError" });
+ expect(URL.revokeObjectURL).toHaveBeenCalledTimes(1);
+ expect(dispose).toHaveBeenCalledTimes(1);
+ });
+
+ it("stops after metadata cancellation before occupying the decoder", async () => {
+ const controller = new AbortController();
+ let resolveWidth!: (width: number) => void;
+ const width = new Promise<number>((resolve) => {
+ resolveWidth = resolve;
+ });
+ const getDisplayWidth = vi.fn(() => width);
+ const getDurationFromMetadata = vi.fn(async () => 10);
+ input.getPrimaryVideoTrack.mockResolvedValue({
+ getDisplayWidth,
+ getDisplayHeight: vi.fn(async () => 1920),
+ getDurationFromMetadata,
+ });
+
+ const decoding = decodeVideoThumbnail(
+ { source: "/clip.mp4", frameCount: 1 },
+ controller.signal,
+ );
+ await vi.waitFor(() => expect(getDisplayWidth).toHaveBeenCalledOnce());
+ controller.abort();
+ resolveWidth(1080);
+
+ await expect(decoding).rejects.toMatchObject({ name: "AbortError" });
+ expect(getDurationFromMetadata).not.toHaveBeenCalled();
+ expect(canvasesAtTimestamps).not.toHaveBeenCalled();
+ expect(dispose).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/packages/studio/src/player/lib/thumbnailVideoDecoder.ts b/packages/studio/src/player/lib/thumbnailVideoDecoder.ts
new file mode 100644
index 0000000000..75634621f9
--- /dev/null
+++ b/packages/studio/src/player/lib/thumbnailVideoDecoder.ts
@@ -0,0 +1,170 @@
+import { TIMELINE_VIEWPORT_BUDGETS, type TimelineViewportBudgets } from "./timelineViewportBudgets";
+import type { ThumbnailLoadedResult, ThumbnailValue } from "./thumbnailScheduler";
+
+export interface VideoThumbnailDecodeRequest {
+ source: string;
+ sourceStart?: number;
+ sourceRangeDuration?: number;
+ frameCount: number;
+ fit?: "contain" | "cover";
+}
+
+export function videoThumbnailTimestamps(
+ start: number,
+ duration: number,
+ frameCount: number,
+): number[] {
+ const safeStart = Math.max(0, Number.isFinite(start) ? start : 0);
+ const safeDuration = Math.max(0, Number.isFinite(duration) ? duration : 0);
+ const count = Math.max(1, Number.isFinite(frameCount) ? Math.floor(frameCount) : 1);
+ if (count === 1) return [safeStart + safeDuration / 2];
+ return Array.from(
+ { length: count },
+ (_, index) => safeStart + (safeDuration * index) / (count - 1),
+ );
+}
+
+async function canvasToBlob(canvas: HTMLCanvasElement | OffscreenCanvas): Promise<Blob> {
+ if (canvas instanceof HTMLCanvasElement) {
+ return new Promise((resolve, reject) => {
+ canvas.toBlob(
+ (blob) => (blob ? resolve(blob) : reject(new Error("Video thumbnail encode failed"))),
+ "image/jpeg",
+ 0.72,
+ );
+ });
+ }
+ return canvas.convertToBlob({ type: "image/jpeg", quality: 0.72 });
+}
+
+interface DecodedResources {
+ urls: string[];
+ canvases: Set<HTMLCanvasElement | OffscreenCanvas>;
+}
+
+interface ThumbnailCanvasSink {
+ canvasesAtTimestamps(
+ timestamps: number[],
+ ): AsyncIterable<{ canvas: HTMLCanvasElement | OffscreenCanvas } | null>;
+}
+
+function throwIfAborted(signal: AbortSignal): void {
+ if (signal.aborted) throw new DOMException("Aborted", "AbortError");
+}
+
+function releaseDecodedResources(resources: DecodedResources): void {
+ for (const url of resources.urls.splice(0)) URL.revokeObjectURL(url);
+ for (const canvas of resources.canvases) {
+ canvas.width = 0;
+ canvas.height = 0;
+ }
+ resources.canvases.clear();
+}
+
+function targetDimensions(
+ aspect: number,
+ budgets: Readonly<TimelineViewportBudgets>,
+): { width: number; height: number } {
+ const width = Math.max(
+ 1,
+ Math.min(budgets.posterMaxPhysicalWidth, Math.round(budgets.posterMaxPhysicalHeight * aspect)),
+ );
+ return {
+ width,
+ height: Math.max(1, Math.min(budgets.posterMaxPhysicalHeight, Math.round(width / aspect))),
+ };
+}
+
+async function decodeFrames(
+ sink: ThumbnailCanvasSink,
+ timestamps: number[],
+ signal: AbortSignal,
+ resources: DecodedResources,
+): Promise<void> {
+ for await (const wrapped of sink.canvasesAtTimestamps(timestamps)) {
+ throwIfAborted(signal);
+ if (!wrapped) continue;
+ resources.canvases.add(wrapped.canvas);
+ const blob = await canvasToBlob(wrapped.canvas);
+ throwIfAborted(signal);
+ resources.urls.push(URL.createObjectURL(blob));
+ }
+}
+
+function loadedResult(
+ resources: DecodedResources,
+ aspect: number,
+ width: number,
+ height: number,
+): ThumbnailLoadedResult {
+ const firstUrl = resources.urls[0];
+ if (!firstUrl) throw new Error("Video source returned no thumbnail frames");
+ const value: ThumbnailValue =
+ resources.urls.length === 1
+ ? { kind: "image", url: firstUrl, aspect }
+ : { kind: "filmstrip", urls: [...resources.urls], aspect };
+ return {
+ value,
+ weight: width * height * 4 * resources.urls.length,
+ dispose: () => releaseDecodedResources(resources),
+ };
+}
+
+/** Sparse Mediabunny extraction with one pooled canvas and one cleanup owner. */
+export async function decodeVideoThumbnail(
+ request: VideoThumbnailDecodeRequest,
+ signal: AbortSignal,
+ budgets: Readonly<TimelineViewportBudgets> = TIMELINE_VIEWPORT_BUDGETS,
+): Promise<ThumbnailLoadedResult> {
+ const mediabunny = await import("mediabunny");
+ throwIfAborted(signal);
+
+ const input = new mediabunny.Input({
+ source: new mediabunny.UrlSource(request.source),
+ formats: mediabunny.ALL_FORMATS,
+ });
+ const resources: DecodedResources = { urls: [], canvases: new Set() };
+ try {
+ const track = await input.getPrimaryVideoTrack();
+ throwIfAborted(signal);
+ if (!track) throw new Error("Video source has no decodable video track");
+ const [displayWidth, displayHeight] = await Promise.all([
+ track.getDisplayWidth(),
+ track.getDisplayHeight(),
+ ]);
+ throwIfAborted(signal);
+ if (!(displayWidth > 0 && displayHeight > 0)) {
+ throw new Error("Video source has invalid dimensions");
+ }
+ const metadataDuration = await track.getDurationFromMetadata({ skipLiveWait: true });
+ throwIfAborted(signal);
+ const sourceDuration = Math.max(0, metadataDuration ?? request.sourceRangeDuration ?? 0);
+ const sourceStart = Math.min(Math.max(0, request.sourceStart ?? 0), sourceDuration);
+ const requestedDuration =
+ request.sourceRangeDuration ?? Math.max(0, sourceDuration - sourceStart);
+ const duration = Math.min(
+ Math.max(0, requestedDuration),
+ Math.max(0, sourceDuration - sourceStart),
+ );
+ const timestamps = videoThumbnailTimestamps(
+ sourceStart,
+ duration,
+ Math.min(request.frameCount, budgets.richPreviewFrameCount),
+ );
+ const aspect = displayWidth / displayHeight;
+ const target = targetDimensions(aspect, budgets);
+ const sink = new mediabunny.CanvasSink(track, {
+ width: target.width,
+ height: target.height,
+ fit: request.fit ?? "cover",
+ poolSize: 1,
+ });
+ await decodeFrames(sink, timestamps, signal, resources);
+ return loadedResult(resources, aspect, target.width, target.height);
+ } catch (error) {
+ releaseDecodedResources(resources);
+ throw error;
+ } finally {
+ input.dispose();
+ }
+}
diff --git a/packages/studio/src/player/lib/timelineViewportBudgets.ts b/packages/studio/src/player/lib/timelineViewportBudgets.ts
index 483a936b5d..cead6fd8a4 100644
--- a/packages/studio/src/player/lib/timelineViewportBudgets.ts
+++ b/packages/studio/src/player/lib/timelineViewportBudgets.ts
@@ -14,6 +14,7 @@ export interface TimelineViewportBudgets {
concurrentMetadataJobs: number;
concurrentCompositionFetches: number;
concurrentServerPages: number;
+ thumbnailLoadTimeoutMs: number;
thumbnailCacheBytes: number;
thumbnailCacheEntries: number;
thumbnailCacheEntriesPerProject: number;
@@ -70,6 +71,7 @@ export const TIMELINE_VIEWPORT_BUDGETS: Readonly<TimelineViewportBudgets> = Obje
concurrentMetadataJobs: 4,
concurrentCompositionFetches: 2,
concurrentServerPages: 1,
+ thumbnailLoadTimeoutMs: 30_000,
thumbnailCacheBytes: 64 * MEBIBYTE,
thumbnailCacheEntries: 256,
thumbnailCacheEntriesPerProject: 96,
diff --git a/packages/studio/src/player/store/playerStore.ts b/packages/studio/src/player/store/playerStore.ts
index 349f9a445c..f373b3b8a4 100644
--- a/packages/studio/src/player/store/playerStore.ts
+++ b/packages/studio/src/player/store/playerStore.ts
@@ -11,6 +11,7 @@ import {
import { clampTimelineZoomPercent, computePinnedZoomPercent } from "../components/timelineZoom";
import { createKeyframeSlice, type KeyframeCacheEntry, type KeyframeSlice } from "./keyframeSlice";
import { createTimelineFocusRequest, type TimelineFocusRequest } from "./timelineFocusState";
+import { createThumbnailSlice, type ThumbnailSlice } from "./thumbnailSlice";
export type { KeyframeCacheEntry } from "./keyframeSlice";
export { liveTime } from "./liveTime";
@@ -103,7 +104,7 @@ function resolveElementSelection(
};
}
-interface PlayerState extends KeyframeSlice {
+interface PlayerState extends KeyframeSlice, ThumbnailSlice {
isPlaying: boolean;
currentTime: number;
duration: number;
@@ -340,6 +341,7 @@ export const usePlayerStore = create<PlayerState>((set, get) => ({
timelineProjectId: get().timelineProjectId,
timelineSessionEpoch: get().timelineSessionEpoch,
})),
+ ...createThumbnailSlice(set),
activeKeyframePct: null,
setActiveKeyframePct: (pct) => set({ activeKeyframePct: pct }),
diff --git a/packages/studio/src/player/store/thumbnailSlice.ts b/packages/studio/src/player/store/thumbnailSlice.ts
new file mode 100644
index 0000000000..26aa469839
--- /dev/null
+++ b/packages/studio/src/player/store/thumbnailSlice.ts
@@ -0,0 +1,18 @@
+import type { StoreApi } from "zustand";
+import { readStudioUiPreferences, writeStudioUiPreferences } from "../../utils/studioUiPreferences";
+import { defaultThumbnailMode, type ThumbnailMode } from "../lib/thumbnailPolicy";
+
+export interface ThumbnailSlice {
+ thumbnailMode: ThumbnailMode;
+ setThumbnailMode: (mode: ThumbnailMode) => void;
+}
+
+export function createThumbnailSlice(set: StoreApi<ThumbnailSlice>["setState"]): ThumbnailSlice {
+ return {
+ thumbnailMode: defaultThumbnailMode(readStudioUiPreferences().thumbnailMode),
+ setThumbnailMode: (mode) => {
+ writeStudioUiPreferences({ thumbnailMode: mode });
+ set({ thumbnailMode: mode });
+ },
+ };
+}
diff --git a/packages/studio/src/utils/frameCapture.test.ts b/packages/studio/src/utils/frameCapture.test.ts
index b4dc4193cd..e48ac79b0c 100644
--- a/packages/studio/src/utils/frameCapture.test.ts
+++ b/packages/studio/src/utils/frameCapture.test.ts
@@ -14,7 +14,7 @@ describe("frame capture utilities", () => {
origin: "http://localhost:5194",
}),
).toBe(
- "http://localhost:5194/api/projects/demo%20project/thumbnail/index.html?t=1.235&format=png&v=1777464000000",
+ "http://localhost:5194/api/projects/demo%20project/thumbnail/index.html?t=1.235&format=png&output=source&v=1777464000000",
);
vi.useRealTimers();
diff --git a/packages/studio/src/utils/frameCapture.ts b/packages/studio/src/utils/frameCapture.ts
index bd513b4676..bba31ad3fa 100644
--- a/packages/studio/src/utils/frameCapture.ts
+++ b/packages/studio/src/utils/frameCapture.ts
@@ -24,6 +24,7 @@ export function buildFrameCaptureUrl({
);
url.searchParams.set("t", Math.max(0, currentTime).toFixed(3));
url.searchParams.set("format", "png");
+ url.searchParams.set("output", "source");
url.searchParams.set("v", String(Date.now()));
return url.toString();
}
diff --git a/packages/studio/src/utils/projectRouting.test.ts b/packages/studio/src/utils/projectRouting.test.ts
index 95b1580e51..1f1e0badc3 100644
--- a/packages/studio/src/utils/projectRouting.test.ts
+++ b/packages/studio/src/utils/projectRouting.test.ts
@@ -24,7 +24,7 @@ describe("project routing utilities", () => {
origin: "http://localhost:3002",
}),
).toBe(
- "http://localhost:3002/api/projects/Notion%20Showcase/thumbnail/index.html?t=1.809&format=png&v=1777636800000",
+ "http://localhost:3002/api/projects/Notion%20Showcase/thumbnail/index.html?t=1.809&format=png&output=source&v=1777636800000",
);
vi.useRealTimers();
diff --git a/packages/studio/src/utils/studioSelectionSnapshot.test.ts b/packages/studio/src/utils/studioSelectionSnapshot.test.ts
index 0175d3096f..fb645ba83a 100644
--- a/packages/studio/src/utils/studioSelectionSnapshot.test.ts
+++ b/packages/studio/src/utils/studioSelectionSnapshot.test.ts
@@ -39,7 +39,7 @@ describe("buildStudioSelectionSnapshot", () => {
currentTime: 1.25,
target: { hfId: "hero-title", selector: ".title", selectorIndex: 0 },
thumbnailUrl:
- "/api/projects/demo/thumbnail/index.html?t=1.25&format=png&selector=.title&selectorIndex=0",
+ "/api/projects/demo/thumbnail/index.html?t=1.25&format=png&output=source&selector=.title&selectorIndex=0",
});
expect(JSON.stringify(snapshot)).not.toContain("HTMLElement");
expect(snapshot).not.toHaveProperty("element");
diff --git a/packages/studio/src/utils/studioSelectionSnapshot.ts b/packages/studio/src/utils/studioSelectionSnapshot.ts
index 594dd47e17..b5499de57c 100644
--- a/packages/studio/src/utils/studioSelectionSnapshot.ts
+++ b/packages/studio/src/utils/studioSelectionSnapshot.ts
@@ -20,6 +20,7 @@ function thumbnailUrl({
const params = new URLSearchParams({
t: String(round3(currentTime)),
format: "png",
+ output: "source",
});
if (selection.selector) params.set("selector", selection.selector);
if (selection.selectorIndex != null) params.set("selectorIndex", String(selection.selectorIndex));
diff --git a/packages/studio/src/utils/studioUiPreferences.test.ts b/packages/studio/src/utils/studioUiPreferences.test.ts
index 982a10bc61..39b4c5ec3d 100644
--- a/packages/studio/src/utils/studioUiPreferences.test.ts
+++ b/packages/studio/src/utils/studioUiPreferences.test.ts
@@ -70,6 +70,20 @@ describe("timelineSnapEnabled preference", () => {
});
});
+describe("thumbnailMode preference", () => {
+ it("round-trips the adaptive mode", () => {
+ const storage = createStorage();
+ writeStudioUiPreferences({ thumbnailMode: "adaptive" }, storage);
+ expect(readStudioUiPreferences(storage).thumbnailMode).toBe("adaptive");
+ });
+
+ it("migrates the legacy boolean without retaining two owners", () => {
+ const storage = createStorage();
+ storage.setItem("hf-studio-ui-preferences", JSON.stringify({ thumbnailsEnabled: false }));
+ expect(readStudioUiPreferences(storage).thumbnailMode).toBe("hidden");
+ });
+});
+
describe("timeline zoom pin persistence", () => {
it("round-trips a pinned manual zoom (survives the post-edit reload)", () => {
const storage = createStorage();
diff --git a/packages/studio/src/utils/studioUiPreferences.ts b/packages/studio/src/utils/studioUiPreferences.ts
index 02677bc42c..7994fe7b73 100644
--- a/packages/studio/src/utils/studioUiPreferences.ts
+++ b/packages/studio/src/utils/studioUiPreferences.ts
@@ -14,6 +14,7 @@ export interface StudioUiPreferences {
timelineHeight?: number;
playbackRate?: number;
audioMuted?: boolean;
+ thumbnailMode?: "adaptive" | "hidden";
previewZoom?: StoredPreviewZoomState;
recentBlocks?: string[];
snapEnabled?: boolean;
@@ -80,6 +81,11 @@ function readStorage(storage: Storage | null): StudioUiPreferences {
if (typeof parsed.audioMuted === "boolean") {
preferences.audioMuted = parsed.audioMuted;
}
+ if (parsed.thumbnailMode === "adaptive" || parsed.thumbnailMode === "hidden") {
+ preferences.thumbnailMode = parsed.thumbnailMode;
+ } else if (typeof parsed.thumbnailsEnabled === "boolean") {
+ preferences.thumbnailMode = parsed.thumbnailsEnabled ? "adaptive" : "hidden";
+ }
if (isRecord(parsed.previewZoom)) {
const { zoomPercent, panX, panY } = parsed.previewZoom;
if (
diff --git a/packages/studio/vite.browser.test.ts b/packages/studio/vite.browser.test.ts
index b7f6288a16..6c5b3b866f 100644
--- a/packages/studio/vite.browser.test.ts
+++ b/packages/studio/vite.browser.test.ts
@@ -1,49 +1,114 @@
-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
+
+const browserMocks = vi.hoisted(() => {
+ const page = {
+ setViewport: vi.fn(async () => {}),
+ goto: vi.fn(async () => {}),
+ evaluate: vi.fn(async () => undefined),
+ waitForFunction: vi.fn(async () => undefined),
+ addScriptTag: vi.fn(async () => undefined),
+ screenshot: vi.fn(async () => Buffer.from("thumbnail")),
+ close: vi.fn(async () => {}),
+ };
+ const newPage = vi.fn(async () => page);
+ const sharedBrowser = { connected: true, newPage };
+ const launch = vi.fn(async () => sharedBrowser);
+ return { launch, newPage, page, sharedBrowser };
+});
+
+vi.mock("puppeteer-core", () => ({ default: { launch: browserMocks.launch } }));
+
+import { findSystemChrome, generateThumbnail, type GenerateThumbnailOptions } from "./vite.browser";
-const launch = vi.fn();
const originalBrowserPath = process.env["HYPERFRAMES_BROWSER_PATH"];
-vi.mock("puppeteer-core", () => ({
- default: { launch },
-}));
+function options(signal = new AbortController().signal): GenerateThumbnailOptions {
+ return {
+ project: { dir: process.cwd() },
+ compPath: "index.html",
+ seekTime: 1,
+ previewUrl: "http://localhost/preview",
+ width: 1920,
+ height: 1080,
+ outputWidth: 240,
+ outputHeight: 135,
+ format: "jpeg",
+ signal,
+ };
+}
describe("generateThumbnail", () => {
- beforeEach(() => {
+ beforeAll(() => {
process.env["HYPERFRAMES_BROWSER_PATH"] = process.execPath;
- launch.mockReset();
- launch.mockRejectedValue(new Error("browser launch failed"));
});
- afterEach(() => {
- if (originalBrowserPath === undefined) {
- delete process.env["HYPERFRAMES_BROWSER_PATH"];
- } else {
- process.env["HYPERFRAMES_BROWSER_PATH"] = originalBrowserPath;
- }
+ beforeEach(() => {
+ browserMocks.launch.mockReset().mockResolvedValue(browserMocks.sharedBrowser);
+ browserMocks.newPage.mockClear();
+ for (const mock of Object.values(browserMocks.page)) mock.mockClear();
+ });
+
+ afterAll(() => {
+ if (originalBrowserPath === undefined) delete process.env["HYPERFRAMES_BROWSER_PATH"];
+ else process.env["HYPERFRAMES_BROWSER_PATH"] = originalBrowserPath;
});
- it("contains browser launch failures and retries them on the next request", async () => {
- const { generateThumbnail } = await import("./vite.browser");
- const options = {
- project: { dir: "/tmp/hyperframes-thumbnail-test" },
- compPath: "index.html",
- seekTime: 0.5,
- previewUrl: "http://localhost/preview",
+ it("contains a transient browser launch failure and retries the next request", async () => {
+ browserMocks.launch.mockRejectedValueOnce(new Error("launch failed"));
+
+ await expect(generateThumbnail(options())).resolves.toBeNull();
+ await expect(generateThumbnail(options())).resolves.toEqual(Buffer.from("thumbnail"));
+ expect(browserMocks.launch).toHaveBeenCalledTimes(2);
+ });
+
+ it("captures at the route-provided physical output size", async () => {
+ await expect(generateThumbnail(options())).resolves.toEqual(Buffer.from("thumbnail"));
+
+ expect(browserMocks.page.setViewport).toHaveBeenCalledWith({
width: 1920,
height: 1080,
- format: "jpeg" as const,
- };
+ deviceScaleFactor: 0.125,
+ });
+ expect(browserMocks.page.close).toHaveBeenCalledTimes(1);
+ });
+
+ it("lets the route own dedupe and closes browser work on cancellation", async () => {
+ const controller = new AbortController();
+ const cancelled = generateThumbnail(options(controller.signal));
+ await vi.waitFor(() => expect(browserMocks.newPage).toHaveBeenCalledTimes(1));
+ controller.abort();
+ await expect(cancelled).resolves.toBeNull();
+ expect(browserMocks.page.close).toHaveBeenCalled();
+
+ browserMocks.newPage.mockClear();
+ await Promise.all([generateThumbnail(options()), generateThumbnail(options())]);
+ expect(browserMocks.newPage).toHaveBeenCalledTimes(2);
+ });
+
+ it("contains a canceled screenshot without crashing the dev server", async () => {
+ const controller = new AbortController();
+ let rejectScreenshot: ((reason: Error) => void) | undefined;
+ browserMocks.page.screenshot.mockImplementationOnce(
+ () =>
+ new Promise<Buffer>((_resolve, reject) => {
+ rejectScreenshot = reject;
+ }),
+ );
+ browserMocks.page.close.mockImplementationOnce(async () => {
+ rejectScreenshot?.(new Error("Target closed"));
+ });
- await expect(generateThumbnail(options)).resolves.toBeNull();
- await expect(generateThumbnail({ ...options, seekTime: 1 })).resolves.toBeNull();
+ const thumbnail = generateThumbnail(options(controller.signal));
+ const result = expect(thumbnail).resolves.toBeNull();
+ await vi.waitFor(() => expect(browserMocks.page.screenshot).toHaveBeenCalledTimes(1));
+ controller.abort();
- expect(launch).toHaveBeenCalledTimes(2);
+ await result;
});
});
describe("findSystemChrome", () => {
- it("uses the CLI browser override before legacy producer and system paths", async () => {
- const { findSystemChrome } = await import("./vite.browser");
+ it("uses the CLI browser override before legacy producer and system paths", () => {
const pathExists = vi.fn(() => true);
expect(
@@ -58,8 +123,7 @@ describe("findSystemChrome", () => {
expect(pathExists).toHaveBeenCalledTimes(1);
});
- it("finds a standard Windows Chrome installation", async () => {
- const { findSystemChrome } = await import("./vite.browser");
+ it("finds a standard Windows Chrome installation", () => {
const chromePath = "C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe";
const pathExists = vi.fn((path: string) => path === chromePath);
diff --git a/packages/studio/vite.browser.ts b/packages/studio/vite.browser.ts
index b46b54ea2c..d2c06a9873 100644
--- a/packages/studio/vite.browser.ts
+++ b/packages/studio/vite.browser.ts
@@ -1,19 +1,14 @@
// Shared Puppeteer browser management and thumbnail generation for Studio dev server.
-import { existsSync } from "node:fs";
-import { createHash } from "node:crypto";
-import { win32 as pathWin32 } from "node:path";
-import {
- createStudioDevRenderBodyScripts,
- readStudioDevManualEditManifestContent,
- readStudioDevMotionManifestContent,
-} from "./vite.studioMotion";
+import { existsSync, readdirSync } from "node:fs";
+import { homedir } from "node:os";
+import { join, win32 as pathWin32 } from "node:path";
+import { thumbnailDeviceScaleFactor } from "@hyperframes/studio-server";
+import { createStudioDevRenderBodyScripts } from "./vite.studioMotion";
import { seekThumbnailPreview } from "./vite.thumbnail";
-// ── Shared Puppeteer browser ─────────────────────────────────────────────────
-
-let _browser: import("puppeteer-core").Browser | null = null;
-let _browserLaunchPromise: Promise<import("puppeteer-core").Browser> | null = null;
+let browser: import("puppeteer-core").Browser | null = null;
+let browserLaunch: Promise<import("puppeteer-core").Browser | null> | null = null;
function systemChromePaths(env: NodeJS.ProcessEnv, platform: NodeJS.Platform): string[] {
if (platform === "win32") {
@@ -29,30 +24,84 @@ function systemChromePaths(env: NodeJS.ProcessEnv, platform: NodeJS.Platform): s
];
}
if (platform === "darwin") {
- return ["/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"];
+ return [
+ "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
+ "/Applications/Google Chrome Canary.app/Contents/MacOS/Google Chrome Canary",
+ "/Applications/Chromium.app/Contents/MacOS/Chromium",
+ "/Applications/Brave Browser.app/Contents/MacOS/Brave Browser",
+ "/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge",
+ ];
+ }
+ return [
+ "/usr/bin/google-chrome",
+ "/usr/bin/google-chrome-stable",
+ "/usr/bin/chromium",
+ "/usr/bin/chromium-browser",
+ ];
+}
+
+function findPuppeteerCacheChrome(
+ env: NodeJS.ProcessEnv,
+ pathExists: (path: string) => boolean,
+): string | undefined {
+ const chromeRoot = join(
+ env["PUPPETEER_CACHE_DIR"] ?? join(homedir(), ".cache", "puppeteer"),
+ "chrome",
+ );
+ let versionDirs: string[];
+ try {
+ versionDirs = readdirSync(chromeRoot);
+ } catch {
+ return undefined;
}
- return ["/usr/bin/google-chrome", "/usr/bin/chromium-browser"];
+ const buildOrder = (directory: string): number =>
+ (directory.split("-").pop() ?? "")
+ .split(".")
+ .map((part) => Number.parseInt(part, 10) || 0)
+ .reduce((order, part) => order * 100000 + part, 0);
+ const relativeCandidates = [
+ "chrome-mac-arm64/Google Chrome for Testing.app/Contents/MacOS/Google Chrome for Testing",
+ "chrome-mac-x64/Google Chrome for Testing.app/Contents/MacOS/Google Chrome for Testing",
+ "chrome-linux64/chrome",
+ "chrome-win64/chrome.exe",
+ ];
+ for (const directory of versionDirs.sort((left, right) => buildOrder(right) - buildOrder(left))) {
+ for (const relativePath of relativeCandidates) {
+ const executable = join(chromeRoot, directory, relativePath);
+ if (pathExists(executable)) return executable;
+ }
+ }
+ return undefined;
}
-/** Resolve the same explicit browser overrides used by the CLI before system paths. */
+/** Resolve explicit CLI overrides before system installs and Puppeteer's cache. */
export function findSystemChrome(
env: NodeJS.ProcessEnv = process.env,
pathExists: (path: string) => boolean = existsSync,
platform: NodeJS.Platform = process.platform,
): string | undefined {
- const override = env["HYPERFRAMES_BROWSER_PATH"] ?? env["PRODUCER_HEADLESS_SHELL_PATH"];
- if (override && pathExists(override)) return override;
- return systemChromePaths(env, platform).find((path) => pathExists(path));
+ const override = [
+ env["HYPERFRAMES_BROWSER_PATH"],
+ env["PRODUCER_HEADLESS_SHELL_PATH"],
+ env["PUPPETEER_EXECUTABLE_PATH"],
+ env["CHROME_PATH"],
+ env["CHROME_BIN"],
+ ].find((candidate): candidate is string => Boolean(candidate) && pathExists(candidate));
+ return (
+ override ??
+ systemChromePaths(env, platform).find(pathExists) ??
+ findPuppeteerCacheChrome(env, pathExists)
+ );
}
async function getSharedBrowser(): Promise<import("puppeteer-core").Browser | null> {
- if (_browser?.connected) return _browser;
- if (_browserLaunchPromise) return _browserLaunchPromise;
- const launchPromise = (async () => {
+ if (browser?.connected) return browser;
+ if (browserLaunch) return browserLaunch;
+ const launch = (async () => {
const puppeteer = await import("puppeteer-core");
const executablePath = findSystemChrome();
if (!executablePath) return null;
- _browser = await puppeteer.default.launch({
+ browser = await puppeteer.default.launch({
headless: true,
executablePath,
args: [
@@ -65,20 +114,16 @@ async function getSharedBrowser(): Promise<import("puppeteer-core").Browser | nu
"--enable-unsafe-swiftshader",
],
});
- return _browser;
+ return browser;
})();
- _browserLaunchPromise = launchPromise;
+ browserLaunch = launch;
try {
- return await launchPromise;
+ return await launch;
} finally {
- if (_browserLaunchPromise === launchPromise) _browserLaunchPromise = null;
+ if (browserLaunch === launch) browserLaunch = null;
}
}
-// In-flight thumbnail dedup
-const _thumbnailInflight = new Map<string, Promise<Buffer>>();
-const THUMBNAIL_CACHE_VERSION = "v4";
-
interface ScreenshotClip {
x: number;
y: number;
@@ -91,12 +136,8 @@ async function applyStudioRenderBodyScriptsToThumbnailPage(
projectDir: string,
activeCompositionPath: string,
): Promise<void> {
- const scripts = createStudioDevRenderBodyScripts(projectDir, {
- activeCompositionPath,
- });
- for (const script of scripts) {
- await page.addScriptTag({ content: script });
- }
+ const scripts = createStudioDevRenderBodyScripts(projectDir, { activeCompositionPath });
+ for (const script of scripts) await page.addScriptTag({ content: script });
}
async function reapplyStudioRenderBodyScriptsToThumbnailPage(
@@ -107,12 +148,8 @@ async function reapplyStudioRenderBodyScriptsToThumbnailPage(
__hfStudioManualEditsApply?: () => number;
__hfStudioMotionApply?: () => number;
};
- if (typeof runtimeWindow.__hfStudioManualEditsApply === "function") {
- runtimeWindow.__hfStudioManualEditsApply();
- }
- if (typeof runtimeWindow.__hfStudioMotionApply === "function") {
- runtimeWindow.__hfStudioMotionApply();
- }
+ runtimeWindow.__hfStudioManualEditsApply?.();
+ runtimeWindow.__hfStudioMotionApply?.();
});
}
@@ -123,105 +160,111 @@ export interface GenerateThumbnailOptions {
previewUrl: string;
width: number;
height: number;
- format: "jpeg" | "png";
+ outputWidth: number;
+ outputHeight: number;
+ format?: "jpeg" | "png";
selector?: string;
selectorIndex?: number;
+ signal: AbortSignal;
}
-export async function generateThumbnail(opts: GenerateThumbnailOptions): Promise<Buffer | null> {
- const selectorKey = opts.selector
- ? `_${opts.selector.replace(/[^a-zA-Z0-9_-]+/g, "_").slice(0, 80)}_${opts.selectorIndex ?? 0}`
- : "";
- const manualManifestContent = readStudioDevManualEditManifestContent(opts.project.dir);
- const manualManifestKey = manualManifestContent.trim()
- ? `_${createHash("sha1").update(manualManifestContent).digest("hex").slice(0, 16)}`
- : "";
- const motionManifestContent = readStudioDevMotionManifestContent(opts.project.dir);
- const motionManifestKey = motionManifestContent.trim()
- ? `_${createHash("sha1").update(motionManifestContent).digest("hex").slice(0, 16)}`
- : "";
- const cacheKey = `${THUMBNAIL_CACHE_VERSION}${manualManifestKey}${motionManifestKey}_${opts.compPath.replace(/\//g, "_")}_${opts.seekTime.toFixed(2)}${selectorKey}.${opts.format === "png" ? "png" : "jpg"}`;
+async function prepareThumbnailPage(
+ page: import("puppeteer-core").Page,
+ opts: GenerateThumbnailOptions,
+): Promise<void> {
+ await page.setViewport({
+ width: opts.width,
+ height: opts.height,
+ deviceScaleFactor: thumbnailDeviceScaleFactor(opts),
+ });
+ await page.goto(opts.previewUrl, { waitUntil: "domcontentloaded", timeout: 10000 });
+ await page.evaluate(() => {
+ document.documentElement.style.background = "#1c2028";
+ document.body.style.background = "#1c2028";
+ document.body.style.margin = "0";
+ document.body.style.overflow = "hidden";
+ });
+ await page
+ .waitForFunction(`!!(window.__timelines && Object.keys(window.__timelines).length > 0)`, {
+ timeout: 5000,
+ })
+ .catch(() => {});
+ await seekThumbnailPreview(page, opts.seekTime);
+ await applyStudioRenderBodyScriptsToThumbnailPage(page, opts.project.dir, opts.compPath);
+ await page.evaluate("document.fonts?.ready");
+ await new Promise((resolve) => setTimeout(resolve, 200));
+ await reapplyStudioRenderBodyScriptsToThumbnailPage(page);
+}
+
+async function resolveScreenshotClip(
+ page: import("puppeteer-core").Page,
+ selector: string | undefined,
+ selectorIndex: number | undefined,
+): Promise<ScreenshotClip | undefined> {
+ if (!selector) return undefined;
+ return page.evaluate(
+ (targetSelector: string, targetIndex: number | undefined) => {
+ const matches = Array.from(document.querySelectorAll(targetSelector)).filter(
+ (element): element is HTMLElement => element instanceof HTMLElement,
+ );
+ const safeIndex = Math.max(0, Math.min(matches.length - 1, Math.floor(targetIndex ?? 0)));
+ const element = matches[safeIndex] ?? null;
+ if (!(element instanceof HTMLElement)) return undefined;
+ const rect = element.getBoundingClientRect();
+ if (rect.width < 4 || rect.height < 4) return undefined;
+ const padding = 8;
+ const x = Math.max(0, rect.left - padding);
+ const y = Math.max(0, rect.top - padding);
+ return {
+ x,
+ y,
+ width: Math.max(1, Math.min(rect.width + padding * 2, window.innerWidth - x)),
+ height: Math.max(1, Math.min(rect.height + padding * 2, window.innerHeight - y)),
+ };
+ },
+ selector,
+ selectorIndex,
+ );
+}
+
+async function captureThumbnail(
+ page: import("puppeteer-core").Page,
+ format: GenerateThumbnailOptions["format"],
+ clip: ScreenshotClip | undefined,
+): Promise<Buffer> {
+ const clipOption = clip ? { clip } : {};
+ const screenshot = await page.screenshot(
+ format === "png"
+ ? { type: "png", ...clipOption }
+ : { type: "jpeg", quality: 75, ...clipOption },
+ );
+ return Buffer.from(screenshot);
+}
- let bufferPromise = _thumbnailInflight.get(cacheKey);
- if (!bufferPromise) {
- bufferPromise = (async () => {
- let page: Awaited<ReturnType<import("puppeteer-core").Browser["newPage"]>> | null = null;
- try {
- const browser = await getSharedBrowser();
- if (!browser) return null;
- page = await browser.newPage();
- await page.setViewport({
- width: opts.width,
- height: opts.height,
- deviceScaleFactor: opts.format === "png" ? 1 : 0.5,
- });
- await page.goto(opts.previewUrl, { waitUntil: "domcontentloaded", timeout: 10000 });
- await page.evaluate(() => {
- document.documentElement.style.background = "#1c2028";
- document.body.style.background = "#1c2028";
- document.body.style.margin = "0";
- document.body.style.overflow = "hidden";
- });
- await page
- .waitForFunction(`!!(window.__timelines && Object.keys(window.__timelines).length > 0)`, {
- timeout: 5000,
- })
- .catch(() => {});
- await seekThumbnailPreview(page, opts.seekTime);
- await applyStudioRenderBodyScriptsToThumbnailPage(page, opts.project.dir, opts.compPath);
- await page.evaluate("document.fonts?.ready");
- await new Promise((r) => setTimeout(r, 200));
- await reapplyStudioRenderBodyScriptsToThumbnailPage(page);
- let clip: ScreenshotClip | undefined;
- if (opts.selector) {
- clip = await page.evaluate(
- (selector: string, selectorIndex: number | undefined) => {
- const matches = Array.from(document.querySelectorAll(selector)).filter(
- (el): el is HTMLElement => el instanceof HTMLElement,
- );
- const safeIndex = Math.max(
- 0,
- Math.min(matches.length - 1, Math.floor(selectorIndex ?? 0)),
- );
- const el = matches[safeIndex] ?? null;
- if (!(el instanceof HTMLElement)) return undefined;
- const rect = el.getBoundingClientRect();
- if (rect.width < 4 || rect.height < 4) return undefined;
- const pad = 8;
- const x = Math.max(0, rect.left - pad);
- const y = Math.max(0, rect.top - pad);
- const maxWidth = window.innerWidth - x;
- const maxHeight = window.innerHeight - y;
- return {
- x,
- y,
- width: Math.max(1, Math.min(rect.width + pad * 2, maxWidth)),
- height: Math.max(1, Math.min(rect.height + pad * 2, maxHeight)),
- };
- },
- opts.selector,
- opts.selectorIndex,
- );
- }
- const buf = await page.screenshot(
- opts.format === "png"
- ? { type: "png", ...(clip ? { clip } : {}) }
- : { type: "jpeg", quality: 75, ...(clip ? { clip } : {}) },
- );
- await page.close();
- return buf as Buffer;
- } catch (err) {
- if (page) await page.close().catch(() => {});
- console.warn(
- "[Studio] Thumbnail generation failed:",
- err instanceof Error ? err.message : err,
- );
- return null;
- }
- })();
- _thumbnailInflight.set(cacheKey, bufferPromise);
- const clearInflight = () => _thumbnailInflight.delete(cacheKey);
- bufferPromise.then(clearInflight, clearInflight);
+export async function generateThumbnail(opts: GenerateThumbnailOptions): Promise<Buffer | null> {
+ if (opts.signal.aborted) return null;
+ let page: import("puppeteer-core").Page | null = null;
+ const closePage = () => void page?.close().catch(() => {});
+ opts.signal.addEventListener("abort", closePage, { once: true });
+ try {
+ const sharedBrowser = await getSharedBrowser();
+ if (!sharedBrowser || opts.signal.aborted) return null;
+ page = await sharedBrowser.newPage();
+ if (opts.signal.aborted) return null;
+ await prepareThumbnailPage(page, opts);
+ const clip = await resolveScreenshotClip(page, opts.selector, opts.selectorIndex);
+ if (opts.signal.aborted) return null;
+ return await captureThumbnail(page, opts.format, clip);
+ } catch (error) {
+ if (!opts.signal.aborted) {
+ console.warn(
+ "[Studio] Thumbnail generation failed:",
+ error instanceof Error ? error.message : error,
+ );
+ }
+ return null;
+ } finally {
+ opts.signal.removeEventListener("abort", closePage);
+ await page?.close().catch(() => {});
}
- return bufferPromise;
}
diff --git a/packages/studio/vite.thumbnail.ts b/packages/studio/vite.thumbnail.ts
index 3fc7227aa6..3c9eb9a6e9 100644
--- a/packages/studio/vite.thumbnail.ts
+++ b/packages/studio/vite.thumbnail.ts
@@ -1,9 +1,4 @@
-interface ThumbnailPreviewPage {
- evaluate<TArg, TResult>(
- fn: (arg: TArg) => TResult | Promise<TResult>,
- arg: TArg,
- ): Promise<TResult>;
-}
+type ThumbnailPreviewPage = Pick<import("puppeteer-core").Page, "evaluate">;
type SeekResult = "player" | "timelines" | "none";