fix(studio): thumbnails of compositions with no code of their own load in under a second (#8316)

* fix(studio): thumbnails of compositions with no code of their own load in under a second

Both thumbnail paths (the CLI's preview server and Studio's dev server) waited up to 5 s for
a GSAP timeline before shooting a card. A composition with no script never registers one, so
each of its cards took the full 5 s, and the route shoots one card at a time, so the third
card came at about 16 s.

The wait cannot simply go: a composition may register its timeline late, in a timer or a
load handler, after the runtime is ready, and shooting it then shows the wrong moment.

So the preview route now marks the page a thumbnail loads when nothing on it can register a
timeline: no script but Studio's own (the runtime, GSAP core, an import map, the registry
line), no inline event handler, frame, template or child composition loaded at run time, and
no Studio motion. A marked page is shot once the runtime is ready. Every other page is held
for its timeline exactly as before.

The rule lives once, in studio-server, and both thumbnail paths wait on it.

fails without the fix: "is skipped for a composition with no code of its own" and "holds for
a composition whose script registers its timeline late"
(packages/studio-server/src/routes/preview.thumbnailMark.test.ts), "thumbnailSeekReadyInBrowser"
(packages/studio-server/src/helpers/screenshotClip.test.ts), "hasAuthoredCode"
(packages/studio-server/src/helpers/authoredCode.test.ts), and "holds a thumbnail's shot on
the thumbnail readiness rule" (packages/cli/src/server/studioServer.test.ts and
packages/studio/vite.browser.test.ts).

* test(studio-server): the thumbnail mark test builds its page from elements, not parsed text

The test read the served page back through DOMParser and innerHTML to hand its metas to the
readiness rule, which code scanning reports as DOM text reinterpreted as HTML. It now finds
the served page's meta tags with the compiler's own tag scanner and creates each one as an
element, so no text is parsed as markup.

Also adds a row to the code check's table: a script inside an inline SVG counts as code.

fails without the fix: "is skipped for a composition with no code of its own"
(packages/studio-server/src/routes/preview.thumbnailMark.test.ts) still fails when the route
writes no mark.
This commit is contained in:
Miguel Ángel
2026-11-20 21:19:26 +00:00
committed by GitHub
parent 8d5863cfb2
commit 5f024e34e2
13 changed files with 261 additions and 22 deletions
+18 -2
View File
@@ -23,6 +23,7 @@ import {
HistoryBusyError,
HistoryClosedError,
} from "@hyperframes/studio-server";
import { thumbnailSeekReadyInBrowser } from "@hyperframes/studio-server/screenshot-clip";
import { loadHyperframeRuntimeSource } from "@hyperframes/core";
import { loadRuntimeSource } from "./runtimeSource.js";
import { findFFmpeg, findFFprobe } from "../browser/ffmpeg.js";
@@ -719,11 +720,14 @@ describe("Studio thumbnail capture", () => {
afterEach(async () => {
await server?.shutdown();
});
function fakePageBrowser(onEvaluate = () => {}) {
function fakePageBrowser(
onEvaluate = () => {},
waitForFunction = async (_ready: () => boolean) => {},
) {
const screenshot = vi.fn(async () => Buffer.from("jpeg"));
const evaluate = vi.fn(async () => onEvaluate());
const page = new Proxy(
{ screenshot, evaluate },
{ screenshot, evaluate, waitForFunction },
{
get: (target, key) =>
key === "then"
@@ -751,6 +755,18 @@ describe("Studio thumbnail capture", () => {
signal,
});
it("holds a thumbnail's shot on the thumbnail readiness rule", async () => {
const waits: unknown[] = [];
const { screenshot } = fakePageBrowser(undefined, async (ready) => {
expect(screenshot).not.toHaveBeenCalled();
waits.push(ready);
});
const dir = tmpProject();
server = createStudioServer({ projectDir: dir });
await expect(server.adapter.generateThumbnail?.(opts(dir))).resolves.toBeInstanceOf(Buffer);
expect(waits[0]).toBe(thumbnailSeekReadyInBrowser);
});
it("stops a thumbnail whose request is aborted before its screenshot", async () => {
let abortOnEvaluate: AbortController | undefined;
const { screenshot } = fakePageBrowser(() => abortOnEvaluate?.abort());
+3 -10
View File
@@ -97,8 +97,9 @@ import { resolveAutoProxy } from "../utils/projectConfig.js";
import {
clearElementScreenshotIsolation,
getElementScreenshotClip,
type ScreenshotClip,
thumbnailSeekReadyInBrowser,
} from "@hyperframes/studio-server/screenshot-clip";
import type { ScreenshotClip } from "@hyperframes/studio-server/screenshot-clip";
import type { RenderJob } from "@hyperframes/producer";
import { isWithinProjectRoot } from "@hyperframes/parsers/asset-resolution";
import { seekCompositionTimeline } from "../capture/captureCompositionFrame.js";
@@ -890,15 +891,7 @@ export function createStudioServer(options: StudioServerOptions): StudioServer {
requiresWebGpu && session.softwareWebGpu,
);
await page
.waitForFunction(
() => {
const w = window as Window & {
__timelines?: Record<string, unknown>;
};
return !!(w.__timelines && Object.keys(w.__timelines).length > 0);
},
{ timeout: 5000 },
)
.waitForFunction(thumbnailSeekReadyInBrowser, { timeout: 5000 })
.catch(() => {});
},
async (page) => {
@@ -0,0 +1,45 @@
import { describe, expect, it } from "vitest";
import { hasAuthoredCode, TIMELINE_REGISTRY_SCRIPT } from "./authoredCode";
const page = (head: string, body: string) =>
`<!DOCTYPE html><html><head>${head}</head><body>${body}</body></html>`;
const runtime = '<script data-hyperframes-preview-runtime="1" src="/api/runtime.js"></script>';
const gsap = '<script src="/api/vendor/npm/gsap@3.15.0/dist/gsap.min.js"></script>';
const still = '<div data-composition-id="card"><h1 style="animation:fade 1s">Hi</h1></div>';
describe("hasAuthoredCode", () => {
it.each([
["a still or CSS-animated composition", page("<style>h1{color:red}</style>", still)],
[
"Studio's runtime, GSAP core and registry line",
page(runtime + gsap, TIMELINE_REGISTRY_SCRIPT + still),
],
["an import map", page('<script type="importmap">{"imports":{}}</script>', still)],
])("finds none in %s", (_name, html) => {
expect(hasAuthoredCode(html)).toBe(false);
});
it.each([
["an inline script", page("", `${still}<script>setTimeout(register, 400)</script>`)],
["an upper-case script tag", page("", `${still}<SCRIPT>setTimeout(register, 400)</SCRIPT>`)],
["a script inside an inline SVG", page("", `${still}<svg><script>register()</script></svg>`)],
[
"a script held until fonts load",
page("", `${still}<script type="text/hf-after-fonts">go()</script>`),
],
["a script file of the project", page('<script src="./main.js"></script>', still)],
[
"a GSAP plugin file",
page('<script src="/gsap@3/dist/ScrollTrigger.min.js"></script>', still),
],
["an inline event handler", page("", `<img src="a.png" onload="register()">${still}`)],
["a frame", page("", `${still}<iframe src="./inner.html"></iframe>`)],
["a template", page("", `<template><script>go()</script></template>${still}`)],
[
"a child composition loaded at run time",
page("", '<div data-composition-src="./child.html"></div>'),
],
])("finds %s", (_name, html) => {
expect(hasAuthoredCode(html)).toBe(true);
});
});
@@ -0,0 +1,25 @@
import { RUNTIME_BOOTSTRAP_ATTR } from "@hyperframes/core/compiler";
import { findStartTags } from "@hyperframes/core/compiler/html-document";
import { isGsapCoreUrl } from "./gsapCoreScript.js";
import { IMPORT_MAP_TYPE } from "./rootImportMap.js";
export const TIMELINE_REGISTRY_SCRIPT =
"<script>window.__timelines=window.__timelines||{};</script>";
const HANDLER_FRAME_TEMPLATE_OR_CHILD_COMPOSITION =
/\son[a-z]+\s*=|<(iframe|frame|object|embed|template)\b|\sdata-composition-src\s*=/i;
const SCRIPT_SRC = /\ssrc\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))/i;
function isStudioOwnScript(html: string, start: number): boolean {
if (html.startsWith(TIMELINE_REGISTRY_SCRIPT, start)) return true;
const tag = html.slice(start, html.indexOf(">", start) + 1);
if (tag.includes(RUNTIME_BOOTSTRAP_ATTR) || IMPORT_MAP_TYPE.test(tag)) return true;
const src = SCRIPT_SRC.exec(tag);
return src !== null && isGsapCoreUrl((src[1] ?? src[2] ?? src[3] ?? "").replace(/&amp;/gi, "&"));
}
// Code that could still register a timeline. Whatever is not known to be Studio's own counts, so unsure means held.
export function hasAuthoredCode(html: string): boolean {
if (HANDLER_FRAME_TEMPLATE_OR_CHILD_COMPOSITION.test(html)) return true;
return findStartTags(html, "script").some((start) => !isStudioOwnScript(html, start));
}
@@ -4,7 +4,7 @@ import { underBase } from "./rootPaths.js";
type Entries = Record<string, string>;
type ImportMap = { imports?: Entries; scopes?: Record<string, Entries> };
const IMPORT_MAP_TYPE = /\btype\s*=\s*["']?importmap["']?(?=[\s/>])/i;
export const IMPORT_MAP_TYPE = /\btype\s*=\s*["']?importmap["']?(?=[\s/>])/i;
/** The first import map's JSON and where it sits; templates, comments and raw text are skipped. */
function findImportMap(html: string): { start: number; end: number; json: string } | null {
@@ -1,5 +1,10 @@
import { afterEach, describe, expect, it } from "vitest";
import { clearElementScreenshotIsolation, getElementScreenshotClip } from "./screenshotClip";
import {
clearElementScreenshotIsolation,
getElementScreenshotClip,
THUMBNAIL_NO_AUTHORED_CODE_META,
thumbnailSeekReadyInBrowser,
} from "./screenshotClip";
afterEach(() => {
document.body.innerHTML = "";
@@ -83,3 +88,32 @@ describe("getElementScreenshotClip", () => {
expect(document.getElementById("outside")!.style.getPropertyValue("opacity")).toBe(outside);
});
});
describe("thumbnailSeekReadyInBrowser", () => {
const mark = `<meta name="${THUMBNAIL_NO_AUTHORED_CODE_META}">`;
afterEach(() => {
for (const key of ["__timelines", "__renderReady"]) Reflect.deleteProperty(window, key);
});
it.each([
["a registered timeline, before the runtime is ready", { __timelines: { main: {} } }, "", true],
[
"a page marked as having no code, once the runtime is ready",
{ __renderReady: true },
mark,
true,
],
["a page whose code may still register a timeline", { __renderReady: true }, "", false],
[
"an empty timeline registry on such a page",
{ __renderReady: true, __timelines: {} },
"",
false,
],
["a marked page whose runtime is not ready yet", {}, mark, false],
])("%s", (_page, state, head, ready) => {
document.head.innerHTML = head;
for (const [key, value] of Object.entries(state)) Reflect.set(window, key, value);
expect(thumbnailSeekReadyInBrowser()).toBe(ready);
});
});
@@ -60,3 +60,17 @@ export function clearElementScreenshotIsolation(): void {
}
page.__hfThumbnailFaded = [];
}
export const THUMBNAIL_NO_AUTHORED_CODE_META = "hyperframes-thumbnail-no-authored-code";
// Serialised into the page, so the meta name is spelled out. A timeline may register late: only a marked page skips it.
export function thumbnailSeekReadyInBrowser(): boolean {
const timelines: unknown = Reflect.get(window, "__timelines");
if (typeof timelines === "object" && timelines !== null && Object.keys(timelines).length > 0) {
return true;
}
return (
Boolean(Reflect.get(window, "__renderReady")) &&
document.querySelector('meta[name="hyperframes-thumbnail-no-authored-code"]') !== null
);
}
@@ -15,6 +15,7 @@ import {
import { findStartTags, isFullHtmlDocument } from "@hyperframes/core/compiler/html-document";
import { gsapCdnDist } from "@hyperframes/core/gsap-cdn";
import { resolveWithinProject } from "@hyperframes/core/safe-path";
import { TIMELINE_REGISTRY_SCRIPT } from "./authoredCode.js";
import { htmlHasGsapCore, insertGsapCoreBeforeHeadPlugin } from "./gsapCoreScript.js";
import { withRootPathsRelative } from "./rootPaths.js";
@@ -418,7 +419,7 @@ ${htmlOpen}
${headContent}
</head>
${bodyOpen}
<script>window.__timelines=window.__timelines||{};</script>
${TIMELINE_REGISTRY_SCRIPT}
${rewrittenContent}
</body>
</html>`;
+1
View File
@@ -71,6 +71,7 @@ export {
clearElementScreenshotIsolation,
getElementScreenshotClip,
type ScreenshotClip,
thumbnailSeekReadyInBrowser,
} from "./helpers/screenshotClip.js";
export {
thumbnailDeviceScaleFactor,
@@ -0,0 +1,96 @@
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { findStartTags } from "@hyperframes/core/compiler/html-document";
import { afterEach, describe, expect, it, onTestFinished } from "vitest";
import {
THUMBNAIL_NO_AUTHORED_CODE_META,
thumbnailSeekReadyInBrowser,
} from "../helpers/screenshotClip";
import { buildSubCompositionHtml } from "../helpers/subComposition";
import { injectStudioPreviewAugmentations, withPreviewRuntime } from "./preview";
const STILL = '<div data-composition-id="card" data-duration="2"><h1 id="title">Hi</h1></div>';
const LATE = `${STILL}<script>setTimeout(function () {
window.__timelines.card = gsap.timeline({ paused: true });
}, 400);</script>`;
const MOTION = JSON.stringify({
version: 1,
motions: [
{
kind: "gsap-motion",
target: { sourceFile: "card.html", id: "title" },
start: 0,
duration: 1,
ease: "none",
from: { x: 0 },
to: { x: 10 },
},
],
});
function project(files: Record<string, string>): string {
const dir = mkdtempSync(join(tmpdir(), "hf-thumbnail-mark-"));
onTestFinished(() => rmSync(dir, { recursive: true, force: true }));
for (const [rel, content] of Object.entries(files)) {
mkdirSync(join(dir, rel, ".."), { recursive: true });
writeFileSync(join(dir, rel), content, "utf-8");
}
return dir;
}
/** The page a thumbnail loads for card.html, as the preview route assembles it. */
function servedPage(files: Record<string, string>, capture = true): string {
const dir = project({
"index.html": "<!doctype html><html><head></head><body></body></html>",
...files,
});
const built = buildSubCompositionHtml(dir, "card.html", "/api/runtime.js") ?? "";
return injectStudioPreviewAugmentations(
withPreviewRuntime(built, "/api/runtime.js"),
"/api/runtime.js",
"signature",
dir,
"card.html",
{ capture, gsapBaseUrl: "https://cdn.jsdelivr.net/npm", sandboxedCapture: false },
);
}
/** Opens the served page far enough for the rule: its named metas, the runtime ready, no timeline registered. */
function readyWithoutTimeline(html: string): boolean {
for (const start of findStartTags(html, "meta")) {
const name = /\sname="([^"]*)"/.exec(html.slice(start, html.indexOf(">", start)))?.[1];
if (name === undefined) continue;
const meta = document.createElement("meta");
meta.name = name;
document.head.append(meta);
}
Reflect.set(window, "__renderReady", true);
return thumbnailSeekReadyInBrowser();
}
afterEach(() => {
document.head.replaceChildren();
Reflect.deleteProperty(window, "__renderReady");
});
describe("a thumbnail's wait for a timeline", () => {
it("is skipped for a composition with no code of its own", () => {
expect(readyWithoutTimeline(servedPage({ "card.html": STILL }))).toBe(true);
});
it("holds for a composition whose script registers its timeline late", () => {
expect(readyWithoutTimeline(servedPage({ "card.html": LATE }))).toBe(false);
});
it("holds for a still composition that Studio motion animates", () => {
const files = { "card.html": STILL, ".hyperframes/studio-motion.json": MOTION };
expect(readyWithoutTimeline(servedPage(files))).toBe(false);
});
it("marks only the page a thumbnail loads, not the preview a person sees", () => {
expect(servedPage({ "card.html": STILL }, false)).not.toContain(
THUMBNAIL_NO_AUTHORED_CODE_META,
);
});
});
+8 -2
View File
@@ -37,6 +37,8 @@ import {
normalizeGsapLocalRoot,
} from "@hyperframes/core/gsap-cdn";
import { findStartTags, injectTagsAtHeadStart } from "@hyperframes/core/compiler/html-document";
import { hasAuthoredCode } from "../helpers/authoredCode.js";
import { THUMBNAIL_NO_AUTHORED_CODE_META } from "../helpers/screenshotClip.js";
import { isWithinProjectRoot } from "@hyperframes/parsers/asset-resolution";
import type { ResolvedProject, StudioApiAdapter } from "../types.js";
import {
@@ -386,10 +388,15 @@ export function injectStudioPreviewAugmentations(
activeCompositionPath: string,
options: { capture: boolean; gsapBaseUrl: string; sandboxedCapture: boolean },
): string {
const studioMotion = readStudioMotion(projectDir, activeCompositionPath);
const noTimelineToCome =
options.capture && !studioMotion && !hasAuthoredCode(html)
? `<meta name="${THUMBNAIL_NO_AUTHORED_CODE_META}">`
: "";
const marked = options.capture
? injectTagsAtHeadStart(
options.sandboxedCapture ? corsProjectVideos(html) : html,
`<meta name="${STUDIO_PREVIEW_MARK_META}" content="${STUDIO_PREVIEW_CAPTURE_MODE}">`,
`<meta name="${STUDIO_PREVIEW_MARK_META}" content="${STUDIO_PREVIEW_CAPTURE_MODE}">${noTimelineToCome}`,
)
: injectTagsAtHeadStart(
lazyPreviewImages(html),
@@ -405,7 +412,6 @@ export function injectStudioPreviewAugmentations(
),
options.gsapBaseUrl,
);
const studioMotion = readStudioMotion(projectDir, activeCompositionPath);
// Studio motion's GSAP core goes in first, so a MotionPathPlugin injected next lands after it.
const withMotionDependencies = studioMotion
? injectStudioMotionDependencies(
+11
View File
@@ -26,6 +26,7 @@ vi.mock("node:child_process", async (original) => ({
execFileSync: browserMocks.versionProbe,
}));
import { thumbnailSeekReadyInBrowser } from "@hyperframes/studio-server";
import { findSystemChrome, generateThumbnail, type GenerateThumbnailOptions } from "./vite.browser";
const originalBrowserPath = process.env["HYPERFRAMES_BROWSER_PATH"];
@@ -123,6 +124,16 @@ describe("generateThumbnail", () => {
expect(browserMocks.page.goto).toHaveBeenCalledWith(previewUrl, expect.anything());
});
it("holds a thumbnail's shot on the thumbnail readiness rule", async () => {
await expect(generateThumbnail(options())).resolves.toEqual(Buffer.from("thumbnail"));
const { waitForFunction, screenshot } = browserMocks.page;
expect(waitForFunction).toHaveBeenCalledWith(thumbnailSeekReadyInBrowser, { timeout: 5000 });
expect(waitForFunction.mock.invocationCallOrder[0]).toBeLessThan(
screenshot.mock.invocationCallOrder[0] ?? 0,
);
});
it("captures at the route-provided physical output size", async () => {
await expect(generateThumbnail(options())).resolves.toEqual(Buffer.from("thumbnail"));
+2 -5
View File
@@ -8,6 +8,7 @@ import {
getElementScreenshotClip,
grantCaptureLoads,
thumbnailDeviceScaleFactor,
thumbnailSeekReadyInBrowser,
type ScreenshotClip,
} from "@hyperframes/studio-server";
import { createStudioDevRenderBodyScripts } from "./vite.studioMotion";
@@ -236,11 +237,7 @@ async function prepareThumbnailPage(
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 page.waitForFunction(thumbnailSeekReadyInBrowser, { timeout: 5000 }).catch(() => {});
await seekThumbnailPreview(page, opts.seekTime);
await page.evaluate("window.__hfWaitForSeekCompletion?.()");
await applyStudioRenderBodyScriptsToThumbnailPage(page, opts.project.dir, opts.compPath);