Skip to content

Write HTML. Render video. Built for agents.

perf(engine): faster shader transitions via page-side WebGL compositing (#832)

Vance Ingallsf84cc492deac
diff --git a/packages/cli/src/browser/manager.test.ts b/packages/cli/src/browser/manager.test.ts
index ae826e691a..118d233777 100644
--- a/packages/cli/src/browser/manager.test.ts
+++ b/packages/cli/src/browser/manager.test.ts
@@ -102,7 +102,10 @@ describe("findBrowser — cache resolution", () => {
vi.doUnmock("@puppeteer/browsers");
});
- it("resolves to the hyperframes-managed cache when present", async () => {
+ it("resolves to the hyperframes-managed cache when puppeteer cache is empty", async () => {
+ // Only HF cache populated. Puppeteer cache is the higher-priority path
+ // (see "prefers puppeteer cache" test below), so this exercises the
+ // last-resort fallback.
installFsMocks({ existing: new Set([HF_CACHE, HF_BINARY]) });
installPuppeteerBrowsersMock({
installedInHfCache: [{ browser: "chrome-headless-shell", executablePath: HF_BINARY }],
@@ -129,8 +132,35 @@ describe("findBrowser — cache resolution", () => {
expect(result).toEqual({ executablePath: PUPPETEER_BINARY, source: "cache" });
});
+ it("prefers the puppeteer cache over the hyperframes cache when BOTH are populated", async () => {
+ // The HF cache is pinned to `CHROME_VERSION` (131-era) which lags upstream
+ // by many releases. The engine's `resolveHeadlessShellPath` scans the
+ // puppeteer cache and selects newest-version-first; if the CLI handed
+ // engine the older HF-cache binary while a newer puppeteer-cache binary
+ // exists, the two would silently disagree on which binary to use.
+ // This test pins the priority: puppeteer cache wins when both are populated.
+ installFsMocks({
+ existing: new Set([HF_CACHE, HF_BINARY, PUPPETEER_CACHE, PUPPETEER_BINARY]),
+ dirs: { [PUPPETEER_CACHE]: ["linux-148.0.7778.97"] },
+ });
+ installPuppeteerBrowsersMock({
+ installedInHfCache: [{ browser: "chrome-headless-shell", executablePath: HF_BINARY }],
+ });
+
+ const { findBrowser } = await import("./manager.js");
+ const result = await findBrowser();
+
+ expect(result?.executablePath).toBe(PUPPETEER_BINARY);
+ expect(result?.source).toBe("cache");
+ });
+
it("picks the newest version when multiple chrome-headless-shell builds are cached", async () => {
- const olderBinary = `${PUPPETEER_CACHE}/linux-131.0.6778.85/chrome-headless-shell-linux64/chrome-headless-shell`;
+ const olderBinary = join(
+ PUPPETEER_CACHE,
+ "linux-131.0.6778.85",
+ "chrome-headless-shell-linux64",
+ "chrome-headless-shell",
+ );
installFsMocks({
existing: new Set([PUPPETEER_CACHE, PUPPETEER_BINARY, olderBinary]),
dirs: { [PUPPETEER_CACHE]: ["linux-131.0.6778.85", "linux-148.0.7778.97"] },
@@ -143,6 +173,32 @@ describe("findBrowser — cache resolution", () => {
expect(result?.executablePath).toBe(PUPPETEER_BINARY);
});
+ it("uses numeric (not lexicographic) version ordering — linux-148 beats linux-99", async () => {
+ // Regression guard for the lexicographic-sort bug: `"linux-99..."` sorts
+ // after `"linux-148..."` character-by-character (because `'9' > '1'`),
+ // which would have caused the CLI to hand engine an ancient 99-era binary
+ // when a fresh 148 was sitting right next to it. Numeric semver-style
+ // ordering is the only correct semantic.
+ const linux99Binary = join(
+ PUPPETEER_CACHE,
+ "linux-99.0.6533.123",
+ "chrome-headless-shell-linux64",
+ "chrome-headless-shell",
+ );
+ installFsMocks({
+ existing: new Set([PUPPETEER_CACHE, PUPPETEER_BINARY, linux99Binary]),
+ // Intentionally list the entries in an order that would expose the bug
+ // under naive `.sort().reverse()` (which puts `linux-99...` first).
+ dirs: { [PUPPETEER_CACHE]: ["linux-99.0.6533.123", "linux-148.0.7778.97"] },
+ });
+ installPuppeteerBrowsersMock();
+
+ const { findBrowser } = await import("./manager.js");
+ const result = await findBrowser();
+
+ expect(result?.executablePath).toBe(PUPPETEER_BINARY);
+ });
+
it("falls back to system Chrome and warns on Linux when no cache has headless-shell", async () => {
installFsMocks({ existing: new Set([SYSTEM_CHROME]) });
installPuppeteerBrowsersMock();
diff --git a/packages/cli/src/browser/manager.ts b/packages/cli/src/browser/manager.ts
index cffc099aff..fc1c9999a7 100644
--- a/packages/cli/src/browser/manager.ts
+++ b/packages/cli/src/browser/manager.ts
@@ -73,7 +73,26 @@ function findFromEnv(): BrowserResult | undefined {
}
async function findFromCache(): Promise<BrowserResult | undefined> {
- // 1) Hyperframes-managed cache (populated by `clearBrowser` + `install` below).
+ // 1) Puppeteer's managed cache — where `npx @puppeteer/browsers install
+ // chrome-headless-shell` lands, and where `puppeteer install` from a project
+ // depending on full `puppeteer` (not `puppeteer-core`) lands. The engine's
+ // `resolveHeadlessShellPath` reads from here and selects newest-version-
+ // first; the CLI must match that semantic or it will silently hand the
+ // engine an older binary than the engine itself would pick.
+ //
+ // We intentionally check puppeteer BEFORE the hyperframes-managed cache:
+ // the HF cache is pinned to `CHROME_VERSION` (above) which lags behind
+ // upstream Chrome by many releases. If a user installed chrome-headless-shell
+ // separately (via `@puppeteer/browsers install`) we want to use that
+ // newer binary, not the pinned-stale fallback.
+ const fromPuppeteer = findFromPuppeteerCache();
+ if (fromPuppeteer) {
+ return fromPuppeteer;
+ }
+
+ // 2) Hyperframes-managed cache (populated by `ensureBrowser` below as a
+ // download-of-last-resort). This is the fallback path: only reached when
+ // no puppeteer-cache binary exists.
if (existsSync(CACHE_DIR)) {
const installed = await getInstalledBrowsers({ cacheDir: CACHE_DIR });
const match = installed.find((b) => b.browser === Browser.CHROMEHEADLESSSHELL);
@@ -82,27 +101,61 @@ async function findFromCache(): Promise<BrowserResult | undefined> {
}
}
- // 2) Puppeteer's managed cache — where `npx @puppeteer/browsers install
- // chrome-headless-shell` lands, and where `puppeteer install` from a project
- // that depends on full `puppeteer` (not `puppeteer-core`) lands. The engine
- // already reads from here (`resolveHeadlessShellPath`); without this branch
- // the CLI would skip past a perfectly good chrome-headless-shell and fall
- // through to `findFromSystem()`, picking regular Chrome which has dropped
- // `HeadlessExperimental.enable` and disables the perf-optimized capture
- // path.
- const fromPuppeteer = findFromPuppeteerCache();
- if (fromPuppeteer) {
- return fromPuppeteer;
+ return undefined;
+}
+
+/**
+ * Parse a puppeteer-cache version directory name (`linux-148.0.7778.97`,
+ * `mac_arm-131.0.6778.85`, etc.) into a numeric tuple for ordering.
+ *
+ * Lexicographic sort on these strings is buggy because `"99"` > `"148"` (the
+ * `9` outranks the `1` character-wise), so a 99-era binary would beat a
+ * 148-era binary in `.sort().reverse()`. We split on `-` to drop the platform
+ * prefix, then on `.` to get integer segments. Returns `undefined` for names
+ * that don't have at least one parseable numeric segment so they sort last.
+ */
+function parseVersionSegments(versionDir: string): number[] | undefined {
+ const dashIdx = versionDir.indexOf("-");
+ const versionPart = dashIdx >= 0 ? versionDir.slice(dashIdx + 1) : versionDir;
+ const segments = versionPart.split(".");
+ const parsed: number[] = [];
+ for (const seg of segments) {
+ const n = parseInt(seg, 10);
+ if (!Number.isFinite(n)) {
+ // Stop at the first non-numeric segment but keep what we've collected.
+ break;
+ }
+ parsed.push(n);
}
+ return parsed.length > 0 ? parsed : undefined;
+}
- return undefined;
+/** Numeric semver-style descending comparator for puppeteer cache dirs. */
+function compareVersionDirsDescending(a: string, b: string): number {
+ const pa = parseVersionSegments(a);
+ const pb = parseVersionSegments(b);
+ // Unparseable names sort after parseable ones (so we still try them, just last).
+ if (!pa && !pb) return 0;
+ if (!pa) return 1;
+ if (!pb) return -1;
+ const len = Math.max(pa.length, pb.length);
+ for (let i = 0; i < len; i += 1) {
+ const av = pa[i] ?? 0;
+ const bv = pb[i] ?? 0;
+ if (av !== bv) return bv - av; // descending (newest first)
+ }
+ return 0;
}
function findFromPuppeteerCache(): BrowserResult | undefined {
if (!existsSync(PUPPETEER_CACHE_DIR)) return undefined;
let versions: string[];
try {
- versions = readdirSync(PUPPETEER_CACHE_DIR).sort().reverse(); // newest first
+ // Numeric semver-style sort, newest first. Lexicographic `.sort().reverse()`
+ // (the previous implementation, still in engine `resolveHeadlessShellPath`)
+ // mis-orders `linux-99...` ahead of `linux-148...` because character `'9'`
+ // outranks `'1'`. See `parseVersionSegments` above.
+ versions = [...readdirSync(PUPPETEER_CACHE_DIR)].sort(compareVersionDirsDescending);
} catch {
return undefined;
}
@@ -159,7 +212,7 @@ function warnSystemFallbackOnce(executablePath: string): void {
if (isHeadlessShellBinary(executablePath)) return;
_warnedSystemFallback = true;
console.warn(
- `[hyperframes] Using system Chrome at ${executablePath}; HeadlessExperimental.beginFrame is unavailable in regular Chrome builds, so the perf-optimized capture path falls back to screenshot mode. Install chrome-headless-shell for the optimized path:\n npx @puppeteer/browsers install chrome-headless-shell`,
+ `[hyperframes] Using system Chrome at ${executablePath}; HeadlessExperimental.beginFrame is unavailable in regular Chrome builds, so the perf-optimized capture path falls back to screenshot mode. Install chrome-headless-shell for the optimized path:\n npx @puppeteer/browsers install chrome-headless-shell\n(Or set HYPERFRAMES_BROWSER_PATH to point at an existing chrome-headless-shell binary.)`,
);
}
diff --git a/packages/cli/src/commands/render.ts b/packages/cli/src/commands/render.ts
index 183d5a4fdd..015559674e 100644
--- a/packages/cli/src/commands/render.ts
+++ b/packages/cli/src/commands/render.ts
@@ -222,6 +222,15 @@ export default defineCommand({
description:
"Output resolution preset: landscape (1920x1080), portrait (1080x1920), landscape-4k (3840x2160), portrait-4k (2160x3840), square (1080x1080), square-4k (2160x2160). Aliases: 1080p, 4k, uhd, 1080p-square, square-1080p, 4k-square. The composition is unchanged — Chrome renders at higher DPR (deviceScaleFactor) so the captured screenshot lands at the requested dimensions. Aspect ratio must match the composition; the scale must be an integer multiple. Not yet supported with --hdr.",
},
+ "page-side-compositing": {
+ type: "boolean",
+ description:
+ "Run shader transitions on a page-side WebGL canvas inside Chrome " +
+ "instead of the Node-side layered blend. ~6× faster for SDR " +
+ "shader-transition renders. HDR/alpha/video content auto-disables. " +
+ "Use --no-page-side-compositing to force the layered path.",
+ default: true,
+ },
},
async run({ args }) {
// ── Resolve project ────────────────────────────────────────────────────
@@ -293,6 +302,11 @@ export default defineCommand({
workers = parsed;
}
+ // ── Wire opt-in: page-side compositing ───────────────────────────────
+ if (args["page-side-compositing"] === false) {
+ process.env.HF_PAGE_SIDE_COMPOSITING = "false";
+ }
+
// ── Validate max-concurrent-renders ─────────────────────────────────
if (args["max-concurrent-renders"] != null) {
const parsed = parseInt(args["max-concurrent-renders"], 10);
@@ -538,6 +552,7 @@ export default defineCommand({
variables,
entryFile,
outputResolution,
+ pageSideCompositing: args["page-side-compositing"] !== false,
exitAfterComplete: true,
});
} else {
@@ -584,6 +599,7 @@ interface RenderOptions {
exitAfterComplete?: boolean;
/** Output resolution preset; see `resolveDeviceScaleFactor` for constraints. */
outputResolution?: CanvasResolution;
+ pageSideCompositing?: boolean;
}
export type VariablesParseError =
@@ -878,6 +894,7 @@ async function renderDocker(
variables: options.variables,
entryFile: options.entryFile,
outputResolution: options.outputResolution,
+ pageSideCompositing: options.pageSideCompositing,
},
});
diff --git a/packages/cli/src/utils/dockerRunArgs.test.ts b/packages/cli/src/utils/dockerRunArgs.test.ts
index 8b8e09e9d8..7409bdb851 100644
--- a/packages/cli/src/utils/dockerRunArgs.test.ts
+++ b/packages/cli/src/utils/dockerRunArgs.test.ts
@@ -277,4 +277,17 @@ describe("buildDockerRunArgs", () => {
const args = buildDockerRunArgs({ ...FIXED_INPUT, options: BASE });
expect(args).not.toContain("--resolution");
});
+
+ it("forwards --no-page-side-compositing when pageSideCompositing is false", () => {
+ const args = buildDockerRunArgs({
+ ...FIXED_INPUT,
+ options: { ...BASE, pageSideCompositing: false },
+ });
+ expect(args).toContain("--no-page-side-compositing");
+ });
+
+ it("omits --no-page-side-compositing when pageSideCompositing is not explicitly false", () => {
+ const args = buildDockerRunArgs({ ...FIXED_INPUT, options: BASE });
+ expect(args).not.toContain("--no-page-side-compositing");
+ });
});
diff --git a/packages/cli/src/utils/dockerRunArgs.ts b/packages/cli/src/utils/dockerRunArgs.ts
index 986a750345..5237036c88 100644
--- a/packages/cli/src/utils/dockerRunArgs.ts
+++ b/packages/cli/src/utils/dockerRunArgs.ts
@@ -41,6 +41,7 @@ export interface DockerRenderOptions {
entryFile?: string;
/** Output resolution preset (e.g. "landscape-4k"). Forwarded as `--resolution`. */
outputResolution?: string;
+ pageSideCompositing?: boolean;
}
export function buildDockerRunArgs(input: DockerRunArgsInput): string[] {
@@ -80,5 +81,6 @@ export function buildDockerRunArgs(input: DockerRunArgsInput): string[] {
: []),
...(options.entryFile ? ["--composition", options.entryFile] : []),
...(options.outputResolution ? ["--resolution", options.outputResolution] : []),
+ ...(options.pageSideCompositing === false ? ["--no-page-side-compositing"] : []),
];
}
diff --git a/packages/core/src/compiler/timingCompiler.test.ts b/packages/core/src/compiler/timingCompiler.test.ts
index 1dfafea835..b7dcf044c3 100644
--- a/packages/core/src/compiler/timingCompiler.test.ts
+++ b/packages/core/src/compiler/timingCompiler.test.ts
@@ -55,6 +55,32 @@ describe("compileTimingAttrs", () => {
expect(unresolved[0].start).toBe(1);
});
+ it("auto-injects data-start='0' when missing so video is discoverable", () => {
+ const html = '<video src="clip.mp4" muted>';
+ const { html: compiled, unresolved } = compileTimingAttrs(html);
+
+ expect(compiled).toContain('data-start="0"');
+ expect(compiled).toContain('id="hf-video-0"');
+ expect(unresolved).toHaveLength(1);
+ expect(unresolved[0].start).toBe(0);
+ });
+
+ it("marks auto-injected data-start with data-hf-auto-start sentinel", () => {
+ const html = '<video src="clip.mp4" muted>';
+ const { html: compiled } = compileTimingAttrs(html);
+
+ expect(compiled).toContain('data-start="0"');
+ expect(compiled).toContain("data-hf-auto-start");
+ });
+
+ it("does not add data-hf-auto-start when author provides data-start", () => {
+ const html = '<video id="v1" src="clip.mp4" data-start="5" muted>';
+ const { html: compiled } = compileTimingAttrs(html);
+
+ expect(compiled).toContain('data-start="5"');
+ expect(compiled).not.toContain("data-hf-auto-start");
+ });
+
it("compiles audio tags the same as video (minus data-has-audio)", () => {
const html = '<audio id="a1" src="music.mp3" data-start="0" data-duration="10">';
const { html: compiled } = compileTimingAttrs(html);
diff --git a/packages/core/src/compiler/timingCompiler.ts b/packages/core/src/compiler/timingCompiler.ts
index 835bc1882f..169c37b298 100644
--- a/packages/core/src/compiler/timingCompiler.ts
+++ b/packages/core/src/compiler/timingCompiler.ts
@@ -85,8 +85,13 @@ function compileTag(
id = `${isVideo ? "hf-video" : "hf-audio"}-${generateId()}`;
result = injectAttr(result, "id", id);
}
- const startStr = getAttr(result, "data-start");
- const start = startStr !== null ? parseFloat(startStr) : 0;
+ let startStr = getAttr(result, "data-start");
+ if (startStr === null) {
+ result = injectAttr(result, "data-start", "0");
+ result = injectAttr(result, "data-hf-auto-start", "");
+ startStr = "0";
+ }
+ const start = parseFloat(startStr);
const mediaStartStr = getAttr(result, "data-media-start");
const mediaStart = mediaStartStr ? parseFloat(mediaStartStr) : 0;
diff --git a/packages/engine/src/config.test.ts b/packages/engine/src/config.test.ts
index 0e29345b73..5573637285 100644
--- a/packages/engine/src/config.test.ts
+++ b/packages/engine/src/config.test.ts
@@ -138,4 +138,23 @@ describe("resolveConfig", () => {
const config = resolveConfig();
expect(config.frameDataUriCacheLimit).toBe(32);
});
+
+ describe("enablePageSideCompositing (HF_PAGE_SIDE_COMPOSITING)", () => {
+ it("defaults to true", () => {
+ const config = resolveConfig();
+ expect(config.enablePageSideCompositing).toBe(true);
+ });
+
+ it("disabled when HF_PAGE_SIDE_COMPOSITING=false", () => {
+ setEnv("HF_PAGE_SIDE_COMPOSITING", "false");
+ const config = resolveConfig();
+ expect(config.enablePageSideCompositing).toBe(false);
+ });
+
+ it("explicit override wins over the env var", () => {
+ setEnv("HF_PAGE_SIDE_COMPOSITING", "true");
+ const config = resolveConfig({ enablePageSideCompositing: false });
+ expect(config.enablePageSideCompositing).toBe(false);
+ });
+ });
});
diff --git a/packages/engine/src/config.ts b/packages/engine/src/config.ts
index c2738ee945..de4d6dd9be 100644
--- a/packages/engine/src/config.ts
+++ b/packages/engine/src/config.ts
@@ -48,6 +48,35 @@ export interface EngineConfig {
expectedChromiumMajor?: number;
/** Force screenshot capture mode (skip BeginFrame even on Linux). */
forceScreenshot: boolean;
+ /**
+ * Opt-in: page-side shader-transition compositing.
+ *
+ * When `true`, shader transitions for SDR compositions run their blend
+ * inside Chrome via WebGL on a page-side compositor canvas instead of
+ * Node-side per-pixel blending (the hf#677 layered pipeline). The engine
+ * then captures ONE opaque RGB frame per output frame via the streaming
+ * capture path, skipping per-scene transparent screenshots and the
+ * Node-side shader-blend worker pool entirely.
+ *
+ * The feature stacks on top of the hf#677 chain — it does not undo it.
+ * When this flag is OFF (the default), behaviour is byte-identical to the
+ * current path. When ON and the composition has no shader transitions or
+ * has HDR content (which forces the layered path regardless), this flag
+ * is a no-op.
+ *
+ * Mac viability: Chrome on Mac accelerates page-side WebGL canvases via
+ * Metal/CoreAnimation natively. This is the lever for Mac users who
+ * cannot use `--enable-begin-frame-control` (Chromium structural limit,
+ * crbug.com/40656275).
+ *
+ * Determinism: page-side WebGL is f32, not f64. Byte-equality fixture
+ * pins are NOT compatible with this path; the new path's correctness
+ * pin is PSNR-based. Default OFF preserves the existing pins for the
+ * hf#677 chain.
+ *
+ * Env fallback: `HF_PAGE_SIDE_COMPOSITING=true`.
+ */
+ enablePageSideCompositing: boolean;
// ── Encoding ─────────────────────────────────────────────────────────
enableChunkedEncode: boolean;
@@ -148,6 +177,7 @@ export const DEFAULT_CONFIG: EngineConfig = {
browserTimeout: 120_000,
protocolTimeout: 300_000,
forceScreenshot: false,
+ enablePageSideCompositing: true,
enableChunkedEncode: false,
chunkSizeFrames: 360,
@@ -221,6 +251,10 @@ export function resolveConfig(overrides?: Partial<EngineConfig>): EngineConfig {
: undefined,
forceScreenshot: envBool("PRODUCER_FORCE_SCREENSHOT", DEFAULT_CONFIG.forceScreenshot),
+ enablePageSideCompositing: envBool(
+ "HF_PAGE_SIDE_COMPOSITING",
+ DEFAULT_CONFIG.enablePageSideCompositing,
+ ),
enableChunkedEncode: envBool(
"PRODUCER_ENABLE_CHUNKED_ENCODE",
diff --git a/packages/engine/src/services/frameCapture.ts b/packages/engine/src/services/frameCapture.ts
index dadc0bd91a..e945063a25 100644
--- a/packages/engine/src/services/frameCapture.ts
+++ b/packages/engine/src/services/frameCapture.ts
@@ -713,20 +713,51 @@ async function prepareFrameForCapture(
const seekStart = Date.now();
// Seek via the __hf protocol. The page's seek() implementation handles
// all framework-specific logic (GSAP stepping, CSS animation sync, etc.)
- await page.evaluate((t: number) => {
+ // Seek + check page-side composite pending flag in one round-trip.
+ const hasPendingComposite = await page.evaluate((t: number) => {
if (window.__hf && typeof window.__hf.seek === "function") {
window.__hf.seek(t);
}
+ return !!(window as unknown as { __hf_page_composite_pending?: boolean })
+ .__hf_page_composite_pending;
}, quantizedTime);
+
const seekMs = Date.now() - seekStart;
- // Before-capture hook (e.g. video frame injection)
+ // Before-capture hook (e.g. video frame injection) — runs before
+ // page-side compositor clones so cloneNode picks up injected <img>
+ // replacements for <video> elements.
const beforeCaptureStart = Date.now();
if (session.onBeforeCapture) {
await session.onBeforeCapture(page, quantizedTime);
}
const beforeCaptureMs = Date.now() - beforeCaptureStart;
+ // Page-side compositing three-phase protocol:
+ // 1. prepare — clone scenes (now containing injected video <img>s)
+ // 2. micro-screenshot — force browser to paint cloned elements
+ // 3. resolve — drawElementImage reads paint records, shader composites
+ if (hasPendingComposite && session.captureMode !== "beginframe") {
+ await page.evaluate(async () => {
+ const w = window as unknown as { __hf_page_composite_prepare?: () => Promise<boolean> };
+ if (typeof w.__hf_page_composite_prepare === "function") {
+ await w.__hf_page_composite_prepare();
+ }
+ });
+ const cdp = await getCdpSession(page);
+ await cdp.send("Page.captureScreenshot", {
+ format: "jpeg",
+ quality: 1,
+ clip: { x: 0, y: 0, width: 1, height: 1, scale: 1 },
+ });
+ await page.evaluate(() => {
+ const w = window as unknown as { __hf_page_composite_resolve?: () => boolean };
+ if (typeof w.__hf_page_composite_resolve === "function") {
+ w.__hf_page_composite_resolve();
+ }
+ });
+ }
+
return { quantizedTime, seekMs, beforeCaptureMs };
}
diff --git a/packages/producer/src/services/fileServer.ts b/packages/producer/src/services/fileServer.ts
index b79482ab24..8362f52c6b 100644
--- a/packages/producer/src/services/fileServer.ts
+++ b/packages/producer/src/services/fileServer.ts
@@ -428,6 +428,29 @@ const HF_EARLY_STUB = `(function() {
if (!window.__hf) window.__hf = {};
})();`;
+/**
+ * Page-side compositing opt-in flag stub.
+ *
+ * When the engine is launched with `enablePageSideCompositing: true`, the
+ * orchestrator injects this stub into the very top of every served HTML
+ * page. The flag is read by `@hyperframes/shader-transitions`' engine-mode
+ * `init()` to switch from the default opacity-flip mode (which leaves
+ * shader blending to the Node side via the hf#677 layered pipeline) to a
+ * page-side WebGL compositor that runs the shader inside Chrome and
+ * exposes a single opaque RGB frame for the engine to capture.
+ *
+ * Sentinel ONLY — no logic here. The compositor itself ships inside
+ * `@hyperframes/shader-transitions` and is loaded by the composition's
+ * regular script bundle.
+ *
+ * Default OFF: when the flag is not set, behavior is byte-identical to
+ * the existing layered path.
+ */
+export const HF_PAGE_SIDE_COMPOSITING_STUB = `(function() {
+ if (typeof window === "undefined") return;
+ window.__HF_PAGE_SIDE_COMPOSITING__ = true;
+})();`;
+
/**
* Bridge script: maps window.__player (Hyperframe runtime) → window.__hf (engine protocol).
* Injected after RENDER_MODE_SCRIPT so the engine's frameCapture can find window.__hf.
@@ -525,6 +548,7 @@ export interface FileServerHandle {
url: string;
port: number;
close: () => void;
+ addPreHeadScript: (script: string) => void;
}
export function createFileServer(options: FileServerOptions): Promise<FileServerHandle> {
@@ -631,6 +655,9 @@ export function createFileServer(options: FileServerOptions): Promise<FileServer
resolve({
url: `http://localhost:${info.port}`,
port: info.port,
+ addPreHeadScript: (script: string) => {
+ preHeadScripts.push(script);
+ },
close: () => {
for (const socket of connections) socket.destroy();
connections.clear();
diff --git a/packages/producer/src/services/htmlCompiler.ts b/packages/producer/src/services/htmlCompiler.ts
index fd20f5a35b..ca5dec6a39 100644
--- a/packages/producer/src/services/htmlCompiler.ts
+++ b/packages/producer/src/services/htmlCompiler.ts
@@ -1151,6 +1151,109 @@ export async function discoverMediaFromBrowser(page: Page): Promise<BrowserMedia
return elements as BrowserMediaElement[];
}
+export interface VideoVisibilityWindow {
+ videoId: string;
+ visibleStart: number;
+ visibleEnd: number;
+}
+
+/**
+ * Seek the GSAP timeline to discover when each video's parent scene is visible.
+ * Only processes videos with the data-hf-auto-start sentinel (auto-injected timing).
+ */
+export async function discoverVideoVisibilityFromTimeline(
+ page: Page,
+ compositionDuration: number,
+): Promise<VideoVisibilityWindow[]> {
+ if (compositionDuration <= 0) return [];
+
+ return page.evaluate((duration: number) => {
+ const results: { videoId: string; visibleStart: number; visibleEnd: number }[] = [];
+ const videos = document.querySelectorAll("video[data-hf-auto-start]");
+ if (videos.length === 0) return results;
+
+ const timelines = (window as unknown as { __timelines?: Record<string, unknown> }).__timelines;
+ if (!timelines) return results;
+
+ const rootEl = document.querySelector("[data-composition-id]");
+ const compId = rootEl?.getAttribute("data-composition-id");
+ if (!compId) return results;
+
+ const tl = timelines[compId] as
+ | {
+ totalTime?: (t: number, suppressEvents?: boolean) => unknown;
+ seek?: (t: number, suppressEvents?: boolean) => unknown;
+ }
+ | undefined;
+ if (!tl) return results;
+
+ const seekTl = (t: number) => {
+ if (typeof tl.totalTime === "function") {
+ tl.totalTime(t, true);
+ } else if (typeof tl.seek === "function") {
+ tl.seek(t, true);
+ }
+ };
+
+ const SAMPLE_STEP = 0.1;
+ const BINARY_PRECISION = 1 / 60;
+
+ for (const videoEl of videos) {
+ const id = videoEl.id;
+ if (!id) continue;
+
+ const sceneEl = videoEl.closest(".scene") || videoEl;
+
+ let firstVisible: number | null = null;
+ let lastVisible: number | null = null;
+
+ for (let t = 0; t <= duration; t += SAMPLE_STEP) {
+ seekTl(t);
+ const opacity = parseFloat(window.getComputedStyle(sceneEl).opacity);
+ if (opacity > 0) {
+ if (firstVisible === null) firstVisible = t;
+ lastVisible = t;
+ }
+ }
+
+ if (firstVisible === null || lastVisible === null) continue;
+
+ // Binary search left boundary
+ let lo = Math.max(0, firstVisible - SAMPLE_STEP);
+ let hi = firstVisible;
+ while (hi - lo > BINARY_PRECISION) {
+ const mid = (lo + hi) / 2;
+ seekTl(mid);
+ const opacity = parseFloat(window.getComputedStyle(sceneEl).opacity);
+ if (opacity > 0) hi = mid;
+ else lo = mid;
+ }
+ const exactStart = hi;
+
+ // Binary search right boundary
+ lo = lastVisible;
+ hi = Math.min(duration, lastVisible + SAMPLE_STEP);
+ while (hi - lo > BINARY_PRECISION) {
+ const mid = (lo + hi) / 2;
+ seekTl(mid);
+ const opacity = parseFloat(window.getComputedStyle(sceneEl).opacity);
+ if (opacity > 0) lo = mid;
+ else hi = mid;
+ }
+ const exactEnd = lo;
+
+ results.push({
+ videoId: id,
+ visibleStart: Math.max(0, exactStart),
+ visibleEnd: Math.min(duration, exactEnd),
+ });
+ }
+
+ seekTl(0);
+ return results;
+ }, compositionDuration);
+}
+
/**
* Resolve composition durations via Puppeteer by querying window.__timelines.
* The page must already have the interceptor loaded and timelines registered.
diff --git a/packages/producer/src/services/render/stages/probeStage.ts b/packages/producer/src/services/render/stages/probeStage.ts
index 22b3df73df..478f5428e8 100644
--- a/packages/producer/src/services/render/stages/probeStage.ts
+++ b/packages/producer/src/services/render/stages/probeStage.ts
@@ -38,6 +38,7 @@ import { fpsToNumber } from "@hyperframes/core";
import type { CompiledComposition } from "../../htmlCompiler.js";
import {
discoverMediaFromBrowser,
+ discoverVideoVisibilityFromTimeline,
recompileWithResolutions,
resolveCompositionDurations,
} from "../../htmlCompiler.js";
@@ -104,7 +105,9 @@ export async function runProbeStage(input: ProbeStageInput): Promise<ProbeStageR
let lastBrowserConsole: string[] = [];
const probeStart = Date.now();
- const needsBrowser = composition.duration <= 0 || compiled.unresolvedCompositions.length > 0;
+ const hasAutoStartVideos = compiled.html.includes("data-hf-auto-start");
+ const needsBrowser =
+ composition.duration <= 0 || compiled.unresolvedCompositions.length > 0 || hasAutoStartVideos;
if (needsBrowser) {
const reasons = [];
@@ -287,6 +290,28 @@ export async function runProbeStage(input: ProbeStageInput): Promise<ProbeStageR
}
}
}
+
+ // Runtime video discovery: for videos with auto-injected timing (data-hf-auto-start),
+ // seek the GSAP timeline to find actual scene visibility windows and override start/end.
+ if (composition.videos.length > 0) {
+ const visibilityWindows = await discoverVideoVisibilityFromTimeline(
+ probeSession.page,
+ composition.duration,
+ );
+ assertNotAborted();
+
+ for (const win of visibilityWindows) {
+ const video = composition.videos.find((v) => v.id === win.videoId);
+ if (!video) continue;
+ if (win.visibleStart >= 0 && win.visibleEnd > win.visibleStart) {
+ video.start = win.visibleStart;
+ video.end = win.visibleEnd;
+ log.info(
+ `[Probe] Runtime video discovery: ${video.id} visible ${win.visibleStart.toFixed(2)}s–${win.visibleEnd.toFixed(2)}s`,
+ );
+ }
+ }
+ }
}
const browserProbeMs = Date.now() - probeStart;
diff --git a/packages/producer/src/services/renderOrchestrator.ts b/packages/producer/src/services/renderOrchestrator.ts
index 915defc687..3a8ee69f14 100644
--- a/packages/producer/src/services/renderOrchestrator.ts
+++ b/packages/producer/src/services/renderOrchestrator.ts
@@ -78,7 +78,12 @@ import {
import { join, dirname, resolve } from "path";
import { randomUUID } from "crypto";
import { fileURLToPath } from "url";
-import { createFileServer, type FileServerHandle, VIRTUAL_TIME_SHIM } from "./fileServer.js";
+import {
+ createFileServer,
+ type FileServerHandle,
+ HF_PAGE_SIDE_COMPOSITING_STUB,
+ VIRTUAL_TIME_SHIM,
+} from "./fileServer.js";
import { defaultLogger, type ProducerLogger } from "../logger.js";
import { type HdrImageTransferCache } from "./hdrImageTransferCache.js";
import {
@@ -1618,7 +1623,9 @@ export async function executeRenderJob(
const stage4Start = Date.now();
updateJobStatus(job, "rendering", "Starting frame capture", 25, onProgress);
- // Start file server (may already be running from duration discovery)
+ // Start file server (may already be running from duration discovery).
+ // The page-side compositing stub is injected later (after hasHdrContent
+ // is known) via addPreHeadScript — see usePageSideCompositingForTransitions.
if (!fileServer) {
fileServer = await createFileServer({
projectDir,
@@ -1742,11 +1749,34 @@ export async function executeRenderJob(
// issues (orange shift) with no quality benefit.
const nativeHdrIds = new Set([...nativeHdrVideoIds, ...nativeHdrImageIds]);
const hasHdrContent = Boolean(effectiveHdr && nativeHdrIds.size > 0);
- const useLayeredComposite = shouldUseLayeredComposite({
- hasHdrContent,
- hasShaderTransitions: compiled.hasShaderTransitions,
- isPngSequence,
- });
+ // Page-side compositing opt-in: when the engine is configured to run the
+ // shader blend inside Chrome via a page-side WebGL canvas, the layered
+ // Node-side composite path is unnecessary for SDR shader transitions.
+ // The streaming path takes ONE opaque RGB screenshot per output frame —
+ // exactly the single capture the page-side compositor produces. HDR
+ // content still forces the layered path (HDR layers need per-layer
+ // alpha + native HDR raw frame compositing in Node; that's out of scope
+ // for this opt-in).
+ const usePageSideCompositingForTransitions =
+ cfg.enablePageSideCompositing &&
+ compiled.hasShaderTransitions &&
+ !hasHdrContent &&
+ !isPngSequence &&
+ !needsAlpha;
+ if (usePageSideCompositingForTransitions) {
+ fileServer.addPreHeadScript(HF_PAGE_SIDE_COMPOSITING_STUB);
+ log.info(
+ "[Render] Page-side compositing enabled — bypassing Node-side layered " +
+ "shader-blend path. Engine will capture one opaque RGB frame per output frame.",
+ );
+ }
+ const useLayeredComposite =
+ !usePageSideCompositingForTransitions &&
+ shouldUseLayeredComposite({
+ hasHdrContent,
+ hasShaderTransitions: compiled.hasShaderTransitions,
+ isPngSequence,
+ });
const encoderHdr = hasHdrContent ? effectiveHdr : undefined;
// png-sequence has no encoder, but the rest of the orchestrator still
// reads `preset.quality` for `effectiveQuality` and `preset.codec` for
diff --git a/packages/shader-transitions/src/capture.ts b/packages/shader-transitions/src/capture.ts
index 08aa82caff..8ae834c997 100644
--- a/packages/shader-transitions/src/capture.ts
+++ b/packages/shader-transitions/src/capture.ts
@@ -61,7 +61,7 @@ function forceSceneVisibleInClone(source: HTMLElement, cloneDoc: Document): void
});
}
-function stabilizeTransformedBoxShadows(root: HTMLElement): void {
+export function stabilizeTransformedBoxShadows(root: HTMLElement): void {
const view = root.ownerDocument.defaultView;
if (!view) return;
diff --git a/packages/shader-transitions/src/engineModePageComposite.test.ts b/packages/shader-transitions/src/engineModePageComposite.test.ts
new file mode 100644
index 0000000000..f812db7422
--- /dev/null
+++ b/packages/shader-transitions/src/engineModePageComposite.test.ts
@@ -0,0 +1,80 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+import {
+ isPageSideCompositingSupported,
+ PAGE_COMPOSITOR_BUILD_CANARY,
+ PAGE_COMPOSITOR_CANVAS_ID,
+} from "./engineModePageComposite.js";
+
+describe("isPageSideCompositingSupported", () => {
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ });
+
+ it("returns false outside the browser (no window)", () => {
+ vi.stubGlobal("window", undefined);
+ expect(isPageSideCompositingSupported()).toBe(false);
+ });
+
+ it("returns false outside the browser (no document)", () => {
+ vi.stubGlobal("window", {});
+ vi.stubGlobal("document", undefined);
+ expect(isPageSideCompositingSupported()).toBe(false);
+ });
+
+ it("returns true when drawElementImage and WebGL are both available", () => {
+ vi.stubGlobal("window", {});
+ vi.stubGlobal("document", {
+ createElement: (tag: string) => {
+ if (tag === "canvas") {
+ return {
+ setAttribute: () => undefined,
+ layoutSubtree: true,
+ getContext: (type: string) => {
+ if (type === "2d") return { drawElementImage: () => undefined };
+ if (type === "webgl")
+ return { getExtension: () => ({ loseContext: () => undefined }) };
+ return null;
+ },
+ };
+ }
+ return {};
+ },
+ });
+ expect(isPageSideCompositingSupported()).toBe(true);
+ });
+
+ it("returns false when drawElementImage is missing", () => {
+ vi.stubGlobal("window", {});
+ vi.stubGlobal("document", {
+ createElement: () => ({
+ setAttribute: () => undefined,
+ getContext: (type: string) =>
+ type === "webgl" ? { getExtension: () => ({ loseContext: () => undefined }) } : {},
+ }),
+ });
+ expect(isPageSideCompositingSupported()).toBe(false);
+ });
+
+ it("returns false when WebGL is unavailable", () => {
+ vi.stubGlobal("window", {});
+ vi.stubGlobal("document", {
+ createElement: () => ({
+ setAttribute: () => undefined,
+ layoutSubtree: true,
+ getContext: (type: string) =>
+ type === "2d" ? { drawElementImage: () => undefined } : null,
+ }),
+ });
+ expect(isPageSideCompositingSupported()).toBe(false);
+ });
+});
+
+describe("page-side compositor exported constants", () => {
+ it("exports a stable canary string used by the bundled-CLI smoke", () => {
+ expect(PAGE_COMPOSITOR_BUILD_CANARY).toBe("__hf_page_compositor_v1__");
+ });
+
+ it("exports a stable canvas id", () => {
+ expect(PAGE_COMPOSITOR_CANVAS_ID).toBe("__hf-page-side-compositor");
+ });
+});
diff --git a/packages/shader-transitions/src/engineModePageComposite.ts b/packages/shader-transitions/src/engineModePageComposite.ts
new file mode 100644
index 0000000000..ea806a9020
--- /dev/null
+++ b/packages/shader-transitions/src/engineModePageComposite.ts
@@ -0,0 +1,344 @@
+/**
+ * engineModePageComposite — page-side WebGL compositor for engine render mode.
+ *
+ * Opt-in via `window.__HF_PAGE_SIDE_COMPOSITING__ = true` (set by the producer
+ * when `EngineConfig.enablePageSideCompositing` is true). When the flag is
+ * off, hyper-shader's engine-mode path stays on the opacity-flip-only timeline
+ * and the producer's hf#677 Node-side layered pipeline runs the shader blend.
+ *
+ * Two-phase capture protocol:
+ *
+ * Phase 1 (seek wrapper, runs inside page.evaluate):
+ * - Runs original GSAP seek to position the timeline
+ * - If inside a transition window, clones FROM/TO scene elements into
+ * layoutsubtree staging canvases
+ * - Sets window.__hf_page_composite_pending with transition metadata
+ * - Returns immediately (seek resolves)
+ *
+ * Paint force (engine-side, frameCapture.ts):
+ * - Engine detects the pending flag and fires a micro Page.captureScreenshot
+ * to force the browser compositor to paint the staging canvas clones
+ *
+ * Phase 2 (engine calls window.__hf_page_composite_resolve):
+ * - drawElementImage reads the now-valid paint records from the clones
+ * - Uploads textures to WebGL, runs the shader, shows the GL overlay
+ * - Cleans up staging canvases
+ *
+ * This gives native-fidelity capture (identical to preview-path
+ * drawElementImage) without depending on requestAnimationFrame for paint.
+ */
+
+import {
+ createContext,
+ setupQuad,
+ createProgram,
+ createTexture,
+ uploadTextureSource,
+ renderShader,
+ type AccentColors,
+} from "./webgl.js";
+import { getFragSource, type ShaderName } from "./shaders/registry.js";
+import { isHtmlInCanvasCaptureSupported } from "./capture.js";
+
+interface PageCompositeTransitionConfig {
+ time: number;
+ shader: ShaderName;
+ duration?: number;
+}
+
+export interface PageCompositorInstallOptions {
+ scenes: string[];
+ transitions: PageCompositeTransitionConfig[];
+ bgColor: string;
+ accentColors: AccentColors;
+ width: number;
+ height: number;
+ defaultDuration: number;
+}
+
+interface ResolvedTransition {
+ time: number;
+ duration: number;
+ shader: string;
+ fromSceneId: string;
+ toSceneId: string;
+ prog: WebGLProgram;
+}
+
+export const PAGE_COMPOSITOR_CANVAS_ID = "__hf-page-side-compositor";
+export const PAGE_COMPOSITOR_BUILD_CANARY = "__hf_page_compositor_v1__";
+
+export function isPageSideCompositingSupported(): boolean {
+ if (typeof window === "undefined" || typeof document === "undefined") return false;
+ if (!isHtmlInCanvasCaptureSupported()) return false;
+ const probe = document.createElement("canvas");
+ const gl = probe.getContext("webgl") || probe.getContext("experimental-webgl");
+ if (!gl) return false;
+ (gl as WebGLRenderingContext).getExtension("WEBGL_lose_context")?.loseContext();
+ return true;
+}
+
+export function installPageSideCompositor(options: PageCompositorInstallOptions): boolean {
+ if (typeof window === "undefined") return false;
+ (window as unknown as { __HF_PAGE_COMPOSITOR_CANARY__?: string }).__HF_PAGE_COMPOSITOR_CANARY__ =
+ PAGE_COMPOSITOR_BUILD_CANARY;
+ if (!isPageSideCompositingSupported()) {
+ // eslint-disable-next-line no-console
+ console.warn(
+ "[HyperShader] page-side compositing requested but drawElementImage/WebGL is not " +
+ "available; falling back to opacity-flip mode " +
+ "(Node-side layered pipeline will handle the blend).",
+ );
+ return false;
+ }
+ if (document.getElementById(PAGE_COMPOSITOR_CANVAS_ID)) return true;
+
+ const { scenes, transitions, accentColors, width, height, defaultDuration } = options;
+
+ const glCanvas = document.createElement("canvas");
+ glCanvas.id = PAGE_COMPOSITOR_CANVAS_ID;
+ glCanvas.width = width;
+ glCanvas.height = height;
+ glCanvas.style.cssText =
+ "position:fixed;top:0;left:0;width:100%;height:100%;z-index:2147483646;pointer-events:none;display:none;";
+ document.body.appendChild(glCanvas);
+
+ const gl = createContext(glCanvas, width, height);
+ if (!gl) {
+ // eslint-disable-next-line no-console
+ console.warn("[HyperShader] page-side compositor: WebGL context unavailable.");
+ glCanvas.remove();
+ return false;
+ }
+ const quadBuf = setupQuad(gl);
+
+ const programs = new Map<string, WebGLProgram>();
+ for (const t of transitions) {
+ if (programs.has(t.shader)) continue;
+ try {
+ programs.set(t.shader, createProgram(gl, getFragSource(t.shader)));
+ } catch (err) {
+ // eslint-disable-next-line no-console
+ console.warn(`[HyperShader] page-side compositor: failed to compile "${t.shader}":`, err);
+ }
+ }
+
+ const resolved: ResolvedTransition[] = [];
+ for (let i = 0; i < transitions.length; i++) {
+ const t = transitions[i];
+ if (!t) continue;
+ const fromSceneId = scenes[i];
+ const toSceneId = scenes[i + 1];
+ const prog = programs.get(t.shader);
+ if (!fromSceneId || !toSceneId || !prog) continue;
+ resolved.push({
+ time: t.time,
+ duration: t.duration ?? defaultDuration,
+ shader: t.shader,
+ fromSceneId,
+ toSceneId,
+ prog,
+ });
+ }
+ if (resolved.length === 0) {
+ glCanvas.remove();
+ return false;
+ }
+
+ const fromTex = createTexture(gl);
+ const toTex = createTexture(gl);
+
+ type DrawElementImageCtx = CanvasRenderingContext2D & {
+ drawElementImage: (el: Element, x: number, y: number, w: number, h: number) => void;
+ };
+
+ interface StagingCanvas extends HTMLCanvasElement {
+ layoutSubtree?: boolean;
+ }
+
+ // Persistent staging canvases — children are swapped per transition frame.
+ // Kept in the DOM so the compositor paints them on the next frame.
+ const fromStaging = document.createElement("canvas") as StagingCanvas;
+ const toStaging = document.createElement("canvas") as StagingCanvas;
+ for (const s of [fromStaging, toStaging]) {
+ s.width = width;
+ s.height = height;
+ s.setAttribute("layoutsubtree", "");
+ s.style.cssText =
+ "position:fixed;top:0;left:0;width:" +
+ width +
+ "px;height:" +
+ height +
+ "px;z-index:-9998;pointer-events:none;";
+ document.body.appendChild(s);
+ }
+
+ function findActive(time: number): ResolvedTransition | null {
+ for (const t of resolved) {
+ if (time >= t.time && time <= t.time + t.duration) return t;
+ }
+ return null;
+ }
+
+ let currentActive: ResolvedTransition | null = null;
+ let currentProgress = 0;
+
+ type PendingWindow = Window & {
+ __hf_page_composite_pending?: boolean;
+ __hf_page_composite_resolve?: () => boolean;
+ };
+ const pWin = window as PendingWindow;
+
+ // Phase 2a: clone scenes into staging canvases. Called after video frame
+ // injection so cloneNode picks up <img> replacements for <video> elements.
+ // Awaits decode on cloned data-URI images so drawElementImage reads
+ // the current frame, not a stale paint cache entry.
+ async function prepareComposite(): Promise<boolean> {
+ const active = currentActive;
+ if (!active) {
+ pWin.__hf_page_composite_pending = false;
+ return false;
+ }
+
+ const fromEl = document.getElementById(active.fromSceneId);
+ const toEl = document.getElementById(active.toSceneId);
+ if (!(fromEl instanceof HTMLElement) || !(toEl instanceof HTMLElement)) {
+ pWin.__hf_page_composite_pending = false;
+ return false;
+ }
+ while (fromStaging.firstChild) fromStaging.removeChild(fromStaging.firstChild);
+ while (toStaging.firstChild) toStaging.removeChild(toStaging.firstChild);
+ fromStaging.appendChild(fromEl.cloneNode(true));
+ toStaging.appendChild(toEl.cloneNode(true));
+
+ // Decode any data-URI images in clones so the browser has current
+ // bitmaps before the micro-screenshot forces a paint pass.
+ const decodes: Promise<void>[] = [];
+ for (const staging of [fromStaging, toStaging]) {
+ for (const img of staging.querySelectorAll("img")) {
+ if (img.src && img.src.startsWith("data:") && typeof img.decode === "function") {
+ decodes.push(img.decode().catch(() => {}));
+ }
+ }
+ }
+ if (decodes.length > 0) await Promise.all(decodes);
+
+ return true;
+ }
+
+ // Phase 2b: drawElementImage from painted clones + shader composite.
+ // Called after micro-screenshot forces the browser to paint the clones.
+ function resolveComposite(): boolean {
+ const active = currentActive;
+ if (!active) {
+ pWin.__hf_page_composite_pending = false;
+ return false;
+ }
+
+ const fromChild = fromStaging.firstElementChild;
+ const toChild = toStaging.firstElementChild;
+ if (!fromChild || !toChild) {
+ pWin.__hf_page_composite_pending = false;
+ return false;
+ }
+
+ const fromCtx = fromStaging.getContext("2d") as DrawElementImageCtx | null;
+ const toCtx = toStaging.getContext("2d") as DrawElementImageCtx | null;
+ if (!fromCtx?.drawElementImage || !toCtx?.drawElementImage) {
+ pWin.__hf_page_composite_pending = false;
+ return false;
+ }
+
+ try {
+ fromCtx.fillStyle = options.bgColor;
+ fromCtx.fillRect(0, 0, width, height);
+ fromCtx.drawElementImage(fromChild, 0, 0, width, height);
+
+ toCtx.fillStyle = options.bgColor;
+ toCtx.fillRect(0, 0, width, height);
+ toCtx.drawElementImage(toChild, 0, 0, width, height);
+ } catch (err) {
+ // eslint-disable-next-line no-console
+ console.warn("[HyperShader] page-side compositor: drawElementImage failed:", err);
+ pWin.__hf_page_composite_pending = false;
+ return false;
+ }
+
+ uploadTextureSource(gl as WebGLRenderingContext, fromTex, fromStaging);
+ uploadTextureSource(gl as WebGLRenderingContext, toTex, toStaging);
+
+ try {
+ renderShader(
+ gl as WebGLRenderingContext,
+ quadBuf,
+ active.prog,
+ fromTex,
+ toTex,
+ currentProgress,
+ accentColors,
+ width,
+ height,
+ );
+ glCanvas.style.display = "block";
+ } catch (err) {
+ // eslint-disable-next-line no-console
+ console.warn("[HyperShader] page-side compositor: renderShader failed:", err);
+ glCanvas.style.display = "none";
+ }
+ pWin.__hf_page_composite_pending = false;
+ return true;
+ }
+
+ pWin.__hf_page_composite_resolve = resolveComposite;
+ (
+ pWin as unknown as { __hf_page_composite_prepare?: () => Promise<boolean> }
+ ).__hf_page_composite_prepare = prepareComposite;
+
+ type HfWindow = Window & {
+ __hf?: { seek?: (t: number) => unknown };
+ };
+ const hfWin = window as HfWindow;
+ const wrapSeek = (): void => {
+ if (!hfWin.__hf) return;
+ const originalSeek = hfWin.__hf.seek;
+ if (typeof originalSeek !== "function") return;
+ const wrapped = (time: number): unknown => {
+ const result = originalSeek.call(hfWin.__hf, time);
+ const active = findActive(time);
+ if (!active) {
+ glCanvas.style.display = "none";
+ pWin.__hf_page_composite_pending = false;
+ while (fromStaging.firstChild) fromStaging.removeChild(fromStaging.firstChild);
+ while (toStaging.firstChild) toStaging.removeChild(toStaging.firstChild);
+ return result;
+ }
+ currentActive = active;
+ currentProgress =
+ active.duration === 0
+ ? 1
+ : Math.min(1, Math.max(0, (time - active.time) / active.duration));
+ pWin.__hf_page_composite_pending = true;
+
+ return result;
+ };
+ hfWin.__hf.seek = wrapped;
+ };
+
+ let attempts = 0;
+ const ivHandle = window.setInterval(() => {
+ attempts += 1;
+ if (hfWin.__hf?.seek) {
+ wrapSeek();
+ window.clearInterval(ivHandle);
+ } else if (attempts > 200) {
+ window.clearInterval(ivHandle);
+ // eslint-disable-next-line no-console
+ console.warn(
+ "[HyperShader] page-side compositor: window.__hf.seek never appeared after 10s; " +
+ "the engine bridge did not initialize. Falling back to opacity-flip mode.",
+ );
+ }
+ }, 50);
+
+ return true;
+}
diff --git a/packages/shader-transitions/src/hyper-shader.ts b/packages/shader-transitions/src/hyper-shader.ts
index 8bb3171d83..2ee750b415 100644
--- a/packages/shader-transitions/src/hyper-shader.ts
+++ b/packages/shader-transitions/src/hyper-shader.ts
@@ -12,9 +12,11 @@ import {
} from "./webgl.js";
import { getFragSource, type ShaderName } from "./shaders/registry.js";
import { initCapture, captureScene } from "./capture.js";
+import { installPageSideCompositor } from "./engineModePageComposite.js";
declare const gsap: {
timeline: (opts: Record<string, unknown>) => GsapTimeline;
+ set: (target: HTMLElement | string, vars: Record<string, unknown>) => unknown;
to: (target: HTMLElement | string, vars: Record<string, unknown>) => unknown;
fromTo: (
target: HTMLElement | string,
@@ -2216,6 +2218,41 @@ function initEngineMode(
tl.set(`#${fromId}`, { opacity: 0 }, T + dur);
}
+ // Page-side compositing opt-in (default OFF). When the producer launches
+ // with `EngineConfig.enablePageSideCompositing: true`, it sets the
+ // sentinel `window.__HF_PAGE_SIDE_COMPOSITING__` via an early stub. We
+ // detect it here and install the WebGL-on-page composite path on top of
+ // the opacity-flip timeline. The opacity timeline still runs (the
+ // installer wraps `window.__hf.seek` AFTER the timeline runs, so DOM
+ // state at the sampled time is correct before texture capture) but the
+ // installed compositor overrides the seek's final visible state during
+ // each transition window with a single shader-composited overlay canvas.
+ const pageCompositingFlag =
+ typeof window !== "undefined" &&
+ Boolean(
+ (window as unknown as { __HF_PAGE_SIDE_COMPOSITING__?: boolean })
+ .__HF_PAGE_SIDE_COMPOSITING__,
+ );
+ if (pageCompositingFlag) {
+ const bgColor = config.bgColor ?? "#000";
+ const accentColors: AccentColors = config.accentColor
+ ? deriveAccentColors(config.accentColor)
+ : { accent: [1, 0.6, 0.2], dark: [0.4, 0.15, 0], bright: [1, 0.85, 0.5] };
+ const rawW = Number(root?.getAttribute("data-width"));
+ const rawH = Number(root?.getAttribute("data-height"));
+ const compWidth = Number.isFinite(rawW) && rawW > 0 ? rawW : 1920;
+ const compHeight = Number.isFinite(rawH) && rawH > 0 ? rawH : 1080;
+ installPageSideCompositor({
+ scenes,
+ transitions,
+ bgColor,
+ accentColors,
+ width: compWidth,
+ height: compHeight,
+ defaultDuration: DEFAULT_DURATION,
+ });
+ }
+
registerTimeline(compId, tl, config.timeline);
return tl;
}
diff --git a/packages/shader-transitions/src/index.ts b/packages/shader-transitions/src/index.ts
index f7d57f6c44..265427f700 100644
--- a/packages/shader-transitions/src/index.ts
+++ b/packages/shader-transitions/src/index.ts
@@ -1,3 +1,9 @@
export { init, type HyperShaderConfig, type TransitionConfig } from "./hyper-shader.js";
export { isHtmlInCanvasCaptureSupported } from "./capture.js";
export { SHADER_NAMES, type ShaderName } from "./shaders/registry.js";
+export {
+ installPageSideCompositor,
+ isPageSideCompositingSupported,
+ PAGE_COMPOSITOR_BUILD_CANARY,
+ PAGE_COMPOSITOR_CANVAS_ID,
+} from "./engineModePageComposite.js";
diff --git a/scripts/page-side-compositing-smoke/fixture/index.html b/scripts/page-side-compositing-smoke/fixture/index.html
new file mode 100644
index 0000000000..4bb40813ec
--- /dev/null
+++ b/scripts/page-side-compositing-smoke/fixture/index.html
@@ -0,0 +1,82 @@
+<!doctype html>
+<html lang="en">
+ <head>
+ <meta charset="UTF-8" />
+ <title>page-side-compositing-smoke</title>
+ <!--
+ Loaded at smoke time: copy ../packages/shader-transitions/dist/index.global.js
+ into the fixture's working directory so the composition uses the LOCAL build
+ (containing the page-side compositor canary) instead of a CDN release.
+ -->
+ <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/gsap.min.js"></script>
+ <script src="./shader-transitions.global.js"></script>
+ <style>
+ html,
+ body {
+ margin: 0;
+ padding: 0;
+ background: #000;
+ }
+ #main {
+ position: relative;
+ width: 1280px;
+ height: 720px;
+ overflow: hidden;
+ background: #000;
+ font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
+ }
+ .scene {
+ position: absolute;
+ inset: 0;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ font-size: 200px;
+ font-weight: 800;
+ color: #fff;
+ letter-spacing: 0.08em;
+ }
+ /* Visually distinctive so a Mac viewer can eyeball parity between
+ the two paths: scene A is warm orange, scene B is cool blue,
+ the transition shader morphs UV space — the result should look
+ clearly intermediate at the midpoint. */
+ #scene-a {
+ background: linear-gradient(135deg, #e85d04, #f48c06);
+ opacity: 1;
+ }
+ #scene-b {
+ background: linear-gradient(135deg, #03045e, #0077b6);
+ opacity: 0;
+ }
+ </style>
+ </head>
+ <body>
+ <div
+ id="main"
+ data-composition-id="page-side-compositing-smoke"
+ data-start="0"
+ data-duration="2"
+ data-width="1280"
+ data-height="720"
+ >
+ <div id="scene-a" class="scene">A</div>
+ <div id="scene-b" class="scene">B</div>
+ </div>
+
+ <script>
+ window.__timelines = window.__timelines || {};
+ const tl = gsap.timeline({ paused: true });
+ // 2s composition; shader fires at t=1.0s, runs 0.5s.
+ // `cross-warp-morph` is FBM-warp + noise-mask — visually distinctive at
+ // the midpoint, exercises NQ noise helpers in the fragment shader.
+ HyperShader.init({
+ bgColor: "#000000",
+ accentColor: "#ffb703",
+ scenes: ["scene-a", "scene-b"],
+ transitions: [{ time: 1.0, shader: "cross-warp-morph", duration: 0.5 }],
+ timeline: tl,
+ });
+ window.__timelines["page-side-compositing-smoke"] = tl;
+ </script>
+ </body>
+</html>
diff --git a/scripts/page-side-compositing-smoke/run.mjs b/scripts/page-side-compositing-smoke/run.mjs
new file mode 100644
index 0000000000..4e46ec9ae6
--- /dev/null
+++ b/scripts/page-side-compositing-smoke/run.mjs
@@ -0,0 +1,176 @@
+#!/usr/bin/env node
+/**
+ * Bundled-CLI smoke for `--page-side-compositing` (opt-in spike).
+ *
+ * Validates that:
+ * 1. The bundled CLI accepts the new flag.
+ * 2. The local `@hyperframes/shader-transitions` IIFE bundle carries the
+ * page-side compositor canary string (build is wired correctly).
+ * 3. Rendering the fixture WITH and WITHOUT the flag both produce valid
+ * MP4s with the same duration. (Pixel-equality is NOT a correctness
+ * property here — see the determinism note in the PR body.)
+ * 4. Wall-time pair is captured for the PR body.
+ *
+ * Per `feedback_validate_bundled_cli_not_dev_path.md`: the canonical
+ * execution path is the BUNDLED CLI at `packages/cli/dist/cli.js`, never
+ * `bun run` against raw TS sources. Do not "improve" this script to use
+ * `bun run` — bundle-specific bugs (path resolvers, env bootstrap, lazy
+ * modules) are invisible to the dev path.
+ *
+ * Usage from the repo root:
+ *
+ * node scripts/page-side-compositing-smoke/run.mjs
+ *
+ * Outputs:
+ *
+ * <tmpdir>/raw.mp4 (baseline path, flag off)
+ * <tmpdir>/page-side.mp4 (page-side path, flag on)
+ * <tmpdir>/wall-times.json (wall-time pair for the PR)
+ */
+
+import { execFileSync, spawnSync } from "node:child_process";
+import {
+ copyFileSync,
+ existsSync,
+ mkdirSync,
+ mkdtempSync,
+ rmSync,
+ statSync,
+ writeFileSync,
+} from "node:fs";
+import { dirname, join, resolve } from "node:path";
+import { tmpdir } from "node:os";
+import { fileURLToPath } from "node:url";
+
+const HERE = dirname(fileURLToPath(import.meta.url));
+const REPO_ROOT = resolve(HERE, "..", "..");
+const FIXTURE_SRC = join(HERE, "fixture");
+const WORK_DIR = mkdtempSync(join(tmpdir(), "hf-page-side-smoke-"));
+const FIXTURE_RUN_DIR = join(WORK_DIR, "fixture");
+const CLI_PATH = join(REPO_ROOT, "packages", "cli", "dist", "cli.js");
+const SHADER_BUNDLE = join(REPO_ROOT, "packages", "shader-transitions", "dist", "index.global.js");
+// Canary string defined in
+// `packages/shader-transitions/src/engineModePageComposite.ts` —
+// kept identical here on purpose. Test broken → engineModePageComposite.test
+// fails first.
+const PAGE_COMPOSITOR_CANARY = "__hf_page_compositor_v1__";
+
+function note(line) {
+ process.stdout.write("[smoke] " + line + "\n");
+}
+
+function fail(msg) {
+ process.stderr.write("[smoke] FAIL: " + msg + "\n");
+ process.exit(1);
+}
+
+function assertExists(path, label) {
+ if (!existsSync(path)) fail(label + " missing at " + path);
+}
+
+function assertCanary() {
+ assertExists(SHADER_BUNDLE, "shader-transitions IIFE bundle");
+ const buf = execFileSync("grep", ["-c", PAGE_COMPOSITOR_CANARY, SHADER_BUNDLE]);
+ const count = Number(buf.toString().trim());
+ if (count < 1) {
+ fail(
+ "shader-transitions bundle is missing the page-side compositor canary " +
+ `("${PAGE_COMPOSITOR_CANARY}"). Rebuild @hyperframes/shader-transitions and re-run.`,
+ );
+ }
+ note(`canary present in ${SHADER_BUNDLE} (${count}× hit)`);
+}
+
+function assertCliCanary() {
+ assertExists(CLI_PATH, "bundled CLI");
+ // The CLI bundle should carry the env-var key for HF_PAGE_SIDE_COMPOSITING
+ // and the page-side flag name. Either confirms the engine + producer +
+ // CLI side of the change is wired through tsup.
+ const cliCanaries = ["HF_PAGE_SIDE_COMPOSITING", "page-side-compositing"];
+ for (const needle of cliCanaries) {
+ const buf = execFileSync("grep", ["-c", needle, CLI_PATH]);
+ const count = Number(buf.toString().trim());
+ if (count < 1) {
+ fail(`bundled CLI is missing canary "${needle}". Rebuild @hyperframes/cli and re-run.`);
+ }
+ note(`CLI bundle carries "${needle}" (${count}× hit)`);
+ }
+}
+
+function setupFixture() {
+ if (existsSync(WORK_DIR)) rmSync(WORK_DIR, { recursive: true, force: true });
+ mkdirSync(FIXTURE_RUN_DIR, { recursive: true });
+ copyFileSync(join(FIXTURE_SRC, "index.html"), join(FIXTURE_RUN_DIR, "index.html"));
+ copyFileSync(SHADER_BUNDLE, join(FIXTURE_RUN_DIR, "shader-transitions.global.js"));
+ note("fixture staged at " + FIXTURE_RUN_DIR);
+}
+
+function runRender(label, outputPath, extraArgs) {
+ note(`render: ${label} → ${outputPath}`);
+ const argv = [
+ CLI_PATH,
+ "render",
+ FIXTURE_RUN_DIR,
+ "-o",
+ outputPath,
+ "--fps",
+ "30",
+ "--workers",
+ "1",
+ "--quality",
+ "draft",
+ "--quiet",
+ ...extraArgs,
+ ];
+ const t0 = Date.now();
+ const res = spawnSync("node", argv, { stdio: "inherit", cwd: REPO_ROOT });
+ const wallMs = Date.now() - t0;
+ if (res.status !== 0) {
+ fail(`render "${label}" exited with status ${res.status}`);
+ }
+ if (!existsSync(outputPath)) {
+ fail(`render "${label}" did not produce ${outputPath}`);
+ }
+ const size = statSync(outputPath).size;
+ if (size < 1024) {
+ fail(`render "${label}" produced suspiciously small output (${size} bytes)`);
+ }
+ note(` wall=${(wallMs / 1000).toFixed(2)}s size=${(size / 1024).toFixed(1)}KB`);
+ return { label, wallMs, sizeBytes: size, outputPath };
+}
+
+function main() {
+ note(`repo root: ${REPO_ROOT}`);
+ assertExists(CLI_PATH, "bundled CLI (packages/cli/dist/cli.js)");
+ assertExists(SHADER_BUNDLE, "shader-transitions IIFE bundle");
+ assertCliCanary();
+ assertCanary();
+ setupFixture();
+
+ const baseline = runRender("baseline (flag OFF)", join(WORK_DIR, "raw.mp4"), []);
+ const pageSide = runRender("page-side (flag ON)", join(WORK_DIR, "page-side.mp4"), [
+ "--page-side-compositing",
+ ]);
+
+ const summary = {
+ baseline: { wallMs: baseline.wallMs, sizeBytes: baseline.sizeBytes },
+ pageSide: { wallMs: pageSide.wallMs, sizeBytes: pageSide.sizeBytes },
+ walltimeRatio: baseline.wallMs / Math.max(1, pageSide.wallMs),
+ notes:
+ "fixture: 2s @ 30fps, 1280x720, single cross-warp-morph transition. " +
+ "Wall times include CLI startup + browser launch — for a perf signal, " +
+ "amortize over a longer fixture on the target host (Vance's Mac).",
+ };
+ writeFileSync(join(WORK_DIR, "wall-times.json"), JSON.stringify(summary, null, 2));
+ note("wrote " + join(WORK_DIR, "wall-times.json"));
+ note("baseline: " + (baseline.wallMs / 1000).toFixed(2) + "s");
+ note("page-side: " + (pageSide.wallMs / 1000).toFixed(2) + "s");
+ note(
+ `ratio (baseline/page-side): ${summary.walltimeRatio.toFixed(2)}× ` +
+ "(>1 means page-side faster, <1 means slower — sandbox is software " +
+ "WebGL, so a ratio near 1 here is expected and NOT predictive of Mac).",
+ );
+ note("OK");
+}
+
+main();