diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json index 76cbc26054..29f6672b35 100644 --- a/.claude-plugin/plugin.json +++ b/.claude-plugin/plugin.json @@ -1,7 +1,7 @@ { "name": "hyperframes", "description": "HyperFrames by HeyGen. Write HTML, render video. Compositions, GSAP and runtime adapter animations, captions, voiceovers, audio-reactive visuals, and website-to-video capture for HyperFrames.", - "version": "0.7.29", + "version": "0.7.36", "author": { "name": "HeyGen", "email": "hyperframes@heygen.com", diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.json index 086c62772d..bddad34091 100644 --- a/.codex-plugin/plugin.json +++ b/.codex-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "hyperframes", - "version": "0.7.29", + "version": "0.7.36", "description": "Write HTML, render video. Compositions, Tailwind v4 styles, GSAP and runtime adapter animations, captions, voiceovers, audio-reactive visuals, and website-to-video capture for HyperFrames.", "author": { "name": "HeyGen", diff --git a/.cursor-plugin/plugin.json b/.cursor-plugin/plugin.json index 5efdc215fb..e363cbe1d4 100644 --- a/.cursor-plugin/plugin.json +++ b/.cursor-plugin/plugin.json @@ -2,7 +2,7 @@ "$schema": "https://cursor.com/schemas/cursor-plugin/plugin.json", "name": "hyperframes", "displayName": "HyperFrames by HeyGen", - "version": "0.7.29", + "version": "0.7.36", "description": "Write HTML, render video. Compositions, Tailwind v4 styles, GSAP and runtime adapter animations, captions, voiceovers, audio-reactive visuals, and website-to-video capture for HyperFrames.", "author": { "name": "HeyGen", diff --git a/README.md b/README.md index 3a49feefcb..14606e8eb9 100644 --- a/README.md +++ b/README.md @@ -38,7 +38,7 @@ HyperFrames is an open-source framework for turning HTML, CSS, media, and seekab Install the HyperFrames skills, then describe the video you want: ```bash -npx skills add heygen-com/hyperframes +npx skills add heygen-com/hyperframes --yes ``` Try a prompt like: diff --git a/docs/changelog.mdx b/docs/changelog.mdx index 07d3a3ab07..f7c51a34dc 100644 --- a/docs/changelog.mdx +++ b/docs/changelog.mdx @@ -8,6 +8,126 @@ Recent HyperFrames releases, including user-facing features, fixes, and migratio {/* New release entries are prepended by `bun run changelog:draft --write`. */} + +This release closes the remaining Windows FFmpeg path gap by making CLI preflight +choose real `ffmpeg.exe`/`ffprobe.exe` binaries over shell shims. `hyperframes +render` now avoids exporting `ffmpeg.cmd` as `HYPERFRAMES_FFMPEG_PATH`, keeping +the engine on the hardened executable-resolution path. + +## Fixes + +- **CLI:** Prefer real ffmpeg exe over cmd shim ([98b539df](https://github.com/heygen-com/hyperframes/commit/98b539df728f221de677e7ede3e9e3eb4cad2bca), [#1958](https://github.com/heygen-com/hyperframes/pull/1958)) + +[View the full commit range](https://github.com/heygen-com/hyperframes/compare/v0.7.35...v0.7.36). + + + +This release fixes three feedback-driven reliability issues: Lambda render bundles now provide CommonJS path globals for inlined dependencies, Windows FFmpeg lookup prefers real executables over command shims, and offline SFX resolution no longer records missing bundled files as usable audio. + +## Fixes + +- **Lambda:** Define `__dirname` and `__filename` in handler bundles ([f999b40d](https://github.com/heygen-com/hyperframes/commit/f999b40d73aa8e0cbe082c199a566f544fbf6f96)) +- **Engine:** Prefer real FFmpeg executables over Windows command shims ([b7dcb9e2](https://github.com/heygen-com/hyperframes/commit/b7dcb9e2a3bd220c889be0ac8ff31b0ea5c62a36)) +- **Hyperframes Media:** Skip and report offline SFX entries whose bundled file is missing ([b34e623b](https://github.com/heygen-com/hyperframes/commit/b34e623bf8c5fb2ae9608edf1908c466584d627e)) + +[View the full commit range](https://github.com/heygen-com/hyperframes/compare/v0.7.34...v0.7.35). + + + +This release hardens DOM layer masking in the engine so temporary screenshot +visibility changes restore the exact prior inline state. It adds another guard +around layered HDR captures, reducing the chance that masking one frame affects +later captures. + +## Fixes + +- **Engine:** Preserve DOM mask visibility state ([56d4a7032](https://github.com/heygen-com/hyperframes/commit/56d4a7032b64ecc3f46eeb7ed17e62a11af1c07b), [#1953](https://github.com/heygen-com/hyperframes/pull/1953)) + +[View the full commit range](https://github.com/heygen-com/hyperframes/compare/v0.7.33...v0.7.34). + + + +This release fixes an HDR compositing regression where hidden or future timed DOM +descendants could be revived during per-layer screenshots and bleed into HDR +frames. DOM-layer masking now preserves those hidden descendants while capturing +the active layer, keeping HDR output aligned with preview timing. + +## Fixes + +- **Producer:** Avoid reviving hidden DOM in HDR layers ([bb066077b](https://github.com/heygen-com/hyperframes/commit/bb066077b4ecbf4efc021779e37da6475c6f80dd), [#1935](https://github.com/heygen-com/hyperframes/pull/1935)) + +[View the full commit range](https://github.com/heygen-com/hyperframes/compare/v0.7.32...v0.7.33). + + + +This release hardens the CLI validation and browser-install paths: validate now seeks through the runtime player, honors the configured timeout more consistently, and browser installs recover from stale or partial downloads without racing concurrent forced reinstalls. It also closes Windows media setup gaps, scopes `window.__hyperframes` correctly inside sub-compositions, pads transition-tail frame durations, and moves large audio filter graphs out of the command line. + +## Fixes + +- **Hyperframes Media:** Install MusicGen deps via python3 -m pip, not bare pip ([942080fa8](https://github.com/heygen-com/hyperframes/commit/942080fa8e8e77de93ef6546690b5b5421d80e88), [#1894](https://github.com/heygen-com/hyperframes/pull/1894)) +- **Hyperframes Media:** Resolve python3 -\> python/py on Windows ([3388635f1](https://github.com/heygen-com/hyperframes/commit/3388635f1d1431de0b2a2e7d132f834f7614557c), [#1922](https://github.com/heygen-com/hyperframes/pull/1922)) +- **CLI:** Validate seeks the runtime player directly, not raw timelines ([3f49f107e](https://github.com/heygen-com/hyperframes/commit/3f49f107eb8fb64b34f621bfcd076391ff06e167), [#1895](https://github.com/heygen-com/hyperframes/pull/1895)) +- **CLI:** Validate navigation timeout honors --timeout, hints on CDN scripts ([0338be97f](https://github.com/heygen-com/hyperframes/commit/0338be97fdc548fd4a179561810c0c9320b61388), [#1929](https://github.com/heygen-com/hyperframes/pull/1929)) +- **Video Workflows:** Pad the frame's own duration to match the transition tail ([8bc1e5d60](https://github.com/heygen-com/hyperframes/commit/8bc1e5d603bd828511bdc6dddaa96a64ea7a43d3), [#1889](https://github.com/heygen-com/hyperframes/pull/1889)) +- **Engine:** Write the audio mix filter graph to a file, not the command line ([8a3227f54](https://github.com/heygen-com/hyperframes/commit/8a3227f5482320907edcb47972c3d7f6e25c6d62), [#1890](https://github.com/heygen-com/hyperframes/pull/1890)) +- **CLI:** Purge stale/partial browser installs instead of wedging retries ([78069da14](https://github.com/heygen-com/hyperframes/commit/78069da1403669cb3f68a475da128d0b0ce14a97), [#1913](https://github.com/heygen-com/hyperframes/pull/1913)) +- **Core:** Route window.__hyperframes to the scoped variant in sub-comps ([f7c9c35d8](https://github.com/heygen-com/hyperframes/commit/f7c9c35d8b1095037402cc55539084d514691b28), [#1931](https://github.com/heygen-com/hyperframes/pull/1931)) + +[View the full commit range](https://github.com/heygen-com/hyperframes/compare/v0.7.31...v0.7.32). + + + +This release makes Figma imports first-class citizens of the shared media inventory: every `hyperframes figma asset` import now regenerates `.media/index.md` (byte-identical with media-use's format), carries `--description`/`--entity` metadata into the manifest, index, and alt text, and the reuse path correctly upserts metadata and dedupes against any prior format/scale/version tuple. media-use's entity lookups now match figma-imported brand marks across the icon/image boundary. + +## Features + +- **Core,cli:** Media-use interop — shared index.md regen + description/entity on figma imports ([3900caaaa](https://github.com/heygen-com/hyperframes/commit/3900caaaa94443efb01597dac26df1533f8add35), [#1927](https://github.com/heygen-com/hyperframes/pull/1927)) + +[View the full commit range](https://github.com/heygen-com/hyperframes/compare/v0.7.30...v0.7.31). + + + +This release adds a low-volume attempt counter to the resolver-shadow tripwire, giving the SDK-cutover soak gate a real `divergences / attempts` denominator instead of a bare divergence count. It also fixes `moveElement` losing its offset when the target element is under a running GSAP animation. + +## Features + +- **Studio:** Add resolver-shadow attempt counter for soak-gate denominator ([fe821ff8b](https://github.com/heygen-com/hyperframes/commit/fe821ff8bc9acbb840b4a42153db66790b9419a1), [#1926](https://github.com/heygen-com/hyperframes/pull/1926)) + +## Fixes + +- **Sdk:** MoveElement survives GSAP animation per-axis via runtime delta translate ([74faa4b2a](https://github.com/heygen-com/hyperframes/commit/74faa4b2a42c60c77d1550e7288bf3333c15e25d), [#1875](https://github.com/heygen-com/hyperframes/pull/1875)) + +[View the full commit range](https://github.com/heygen-com/hyperframes/compare/v0.7.29...v0.7.30). + + { The draft loop keeps the model clean during a drag. The SDK is **not** in the 60fps path — you call `preview.applyDraft` on every `pointermove` and `preview.commitPreview` once on `pointerup`. The model sees exactly one `moveElement` op per drag, rather than hundreds. -`applyDraft` writes CSS custom properties (`--hf-studio-dx`, `--hf-studio-dy`) directly onto the target element inside the iframe. The composition's CSS uses these vars to translate the element visually. Nothing in the SDK model changes. +`applyDraft` sets the element's CSS `translate` directly inside the iframe — the pre-drag value composed with the accumulated delta — so the drag is visible in any composition without composition-side CSS, and works on GSAP-animated elements (a `translate` set after GSAP's first parse composes with the animated transform instead of being overwritten). Nothing in the SDK model changes. `cancelPreview` restores the pre-drag translate; `commitPreview` derives one `moveElement` op and mirrors the committed position onto the live element. ```typescript let dragging = false; diff --git a/docs/sdk/reference/adapters.mdx b/docs/sdk/reference/adapters.mdx index 8a8666dc8c..87e149e71c 100644 --- a/docs/sdk/reference/adapters.mdx +++ b/docs/sdk/reference/adapters.mdx @@ -100,15 +100,15 @@ interface PreviewAdapter { - Applies draft CSS markers to the preview element at 60fps during a drag. Writes CSS custom properties (`--hf-studio-dx`, `--hf-studio-dy`) onto the element so the composition's CSS can visually translate it without touching the model. The **SDK is not called here** — this is a direct write to the preview surface by your pointer-move handler. + Visually translates the preview element at 60fps during a drag: sets the element's CSS `translate` to its pre-drag value composed with the accumulated delta. Works on GSAP-animated elements (a `translate` set after GSAP's first parse composes with the animated transform). The **SDK is not called here** — this is a direct write to the preview surface by your pointer-move handler. Switching `id` mid-drag reverts the previous element's draft first. - Called once on pointer-up. Reads the accumulated draft markers, derives a `moveElement` op from them, dispatches it into the SDK, emits a patch event, and clears the markers. This is the only moment the SDK becomes aware of a drag. + Called once on pointer-up. Reads the accumulated draft delta, derives a `moveElement` op from it, dispatches it into the SDK, emits a patch event, and mirrors the committed position onto the live element (so it holds without a reload). This is the only moment the SDK becomes aware of a drag. If dispatch throws, the draft translate is reverted and the error propagates. - Reverts the draft CSS markers without dispatching any op. The model is never changed. Call this on `Escape` keydown or when a drag is aborted. + Restores the element's pre-drag `translate` without dispatching any op. The model is never changed. Call this on `Escape` keydown or when a drag is aborted. diff --git a/packages/aws-lambda/package.json b/packages/aws-lambda/package.json index 6aa5c15339..6718091c49 100644 --- a/packages/aws-lambda/package.json +++ b/packages/aws-lambda/package.json @@ -1,6 +1,6 @@ { "name": "@hyperframes/aws-lambda", - "version": "0.7.29", + "version": "0.7.36", "description": "AWS Lambda adapter for HyperFrames distributed rendering — handler, client-side SDK, and CDK construct.", "repository": { "type": "git", diff --git a/packages/aws-lambda/scripts/build-zip.test.ts b/packages/aws-lambda/scripts/build-zip.test.ts new file mode 100644 index 0000000000..f2c5c3a94b --- /dev/null +++ b/packages/aws-lambda/scripts/build-zip.test.ts @@ -0,0 +1,14 @@ +import { describe, expect, it } from "bun:test"; +import { readFileSync } from "node:fs"; +import { fileURLToPath } from "node:url"; + +describe("build-zip handler banner", () => { + it("defines CommonJS path globals for inlined CJS dependencies", () => { + const source = readFileSync(fileURLToPath(new URL("./build-zip.ts", import.meta.url)), "utf8"); + + expect(source).toContain('import { fileURLToPath as __hf_fileURLToPath } from "url";'); + expect(source).toContain('import { dirname as __hf_dirname } from "path";'); + expect(source).toContain("const __filename = __hf_fileURLToPath(import.meta.url);"); + expect(source).toContain("const __dirname = __hf_dirname(__filename);"); + }); +}); diff --git a/packages/aws-lambda/scripts/build-zip.ts b/packages/aws-lambda/scripts/build-zip.ts index 0586c3ca63..09db81dbfe 100644 --- a/packages/aws-lambda/scripts/build-zip.ts +++ b/packages/aws-lambda/scripts/build-zip.ts @@ -252,6 +252,10 @@ async function bundleHandler(stagingDir: string): Promise { "// hyperframes-aws-lambda handler bundle", 'import { createRequire as __hf_createRequire } from "module";', "const require = __hf_createRequire(import.meta.url);", + 'import { fileURLToPath as __hf_fileURLToPath } from "url";', + 'import { dirname as __hf_dirname } from "path";', + "const __filename = __hf_fileURLToPath(import.meta.url);", + "const __dirname = __hf_dirname(__filename);", ].join("\n"), }, }); diff --git a/packages/cli/package.json b/packages/cli/package.json index 4d8bd40f5b..6d0a987faf 100644 --- a/packages/cli/package.json +++ b/packages/cli/package.json @@ -1,6 +1,6 @@ { "name": "@hyperframes/cli", - "version": "0.7.29", + "version": "0.7.36", "description": "HyperFrames CLI — create, preview, and render HTML video compositions", "repository": { "type": "git", diff --git a/packages/cli/src/browser/ffmpeg.test.ts b/packages/cli/src/browser/ffmpeg.test.ts index 1088d22adf..f541e6d40f 100644 --- a/packages/cli/src/browser/ffmpeg.test.ts +++ b/packages/cli/src/browser/ffmpeg.test.ts @@ -1,5 +1,6 @@ import { execSync } from "node:child_process"; import { existsSync } from "node:fs"; +import { resolve } from "node:path"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; vi.mock("node:child_process", () => ({ execSync: vi.fn() })); @@ -23,6 +24,14 @@ afterEach(() => { }); describe("findFFmpeg", () => { + it("prefers the real Windows exe when where lists a cmd shim first", async () => { + Object.defineProperty(process, "platform", { value: "win32", configurable: true }); + mockExec.mockReturnValue("C:\\tools\\ffmpeg.cmd\r\nC:\\tools\\ffmpeg.exe\r\n"); + + const { findFFmpeg } = await import("./ffmpeg.js"); + expect(findFFmpeg()).toBe(resolve("C:\\tools\\ffmpeg.exe")); + }); + it("falls back to a common install dir when `which` fails (GUI-launched PATH)", async () => { // Simulate a process whose PATH lacks /opt/homebrew/bin: `which ffmpeg` throws. mockExec.mockImplementation(() => { diff --git a/packages/cli/src/browser/ffmpeg.ts b/packages/cli/src/browser/ffmpeg.ts index 9c0670ca14..e5f77cf62c 100644 --- a/packages/cli/src/browser/ffmpeg.ts +++ b/packages/cli/src/browser/ffmpeg.ts @@ -7,6 +7,26 @@ import { detectLinuxDistro, ffmpegInstallCommand } from "./linuxDeps.js"; export const FFMPEG_PATH_ENV = "HYPERFRAMES_FFMPEG_PATH"; export const FFPROBE_PATH_ENV = "HYPERFRAMES_FFPROBE_PATH"; +function chooseBestPathCandidate( + name: "ffmpeg" | "ffprobe", + candidates: string[], +): string | undefined { + const normalized = candidates.map((s) => s.trim()).filter(Boolean); + if (normalized.length === 0) return undefined; + const lowerName = name.toLowerCase(); + const preferredExe = normalized.find((candidate) => + candidate.toLowerCase().endsWith(`${lowerName}.exe`), + ); + if (preferredExe) return preferredExe; + const exact = normalized.find((candidate) => candidate.toLowerCase().endsWith(lowerName)); + if (exact) return exact; + const nonShellShim = normalized.find((candidate) => { + const lower = candidate.toLowerCase(); + return !lower.endsWith(".cmd") && !lower.endsWith(".bat"); + }); + return nonShellShim ?? normalized[0]; +} + function findOnPath(name: "ffmpeg" | "ffprobe"): string | undefined { try { const cmd = process.platform === "win32" ? `where ${name}` : `which ${name}`; @@ -15,11 +35,8 @@ function findOnPath(name: "ffmpeg" | "ffprobe"): string | undefined { stdio: ["pipe", "pipe", "pipe"], timeout: 5000, }); - const first = output - .split(/\r?\n/) - .map((s) => s.trim()) - .find(Boolean); - return first ? resolve(first) : undefined; + const candidate = chooseBestPathCandidate(name, output.split(/\r?\n/)); + return candidate ? resolve(candidate) : undefined; } catch { return undefined; } diff --git a/packages/cli/src/browser/manager.test.ts b/packages/cli/src/browser/manager.test.ts index f19d1993bd..7f166efb9b 100644 --- a/packages/cli/src/browser/manager.test.ts +++ b/packages/cli/src/browser/manager.test.ts @@ -21,7 +21,7 @@ * `background-removal/manager.test.ts`) so we don't touch the real * `HOME` cache. */ -import { join } from "node:path"; +import { join, sep } from "node:path"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; // Use `path.join` so the fake paths line up with whatever separator Node's @@ -30,7 +30,10 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; // `/fake/home/...` literals would fail on Windows because the set lookup // would never match the `\\`-joined real paths. const FAKE_HOME = join("/", "fake", "home"); +const CACHE_ROOT = join(FAKE_HOME, ".cache", "hyperframes"); const HF_CACHE = join(FAKE_HOME, ".cache", "hyperframes", "chrome"); +const HF_LOCK = join(CACHE_ROOT, ".chrome.install.lock"); +const HF_RECLAIM_LOCK = join(CACHE_ROOT, ".chrome.install.reclaim.lock"); const PUPPETEER_CACHE = join(FAKE_HOME, ".cache", "puppeteer", "chrome-headless-shell"); const PUPPETEER_BINARY = join( PUPPETEER_CACHE, @@ -75,8 +78,15 @@ function installFsMocks({ existing, dirs }: FsMockOptions) { mtimes.set(p, Date.now()); }, rmSync: (p: string) => { - paths.delete(p); - mtimes.delete(p); + // Real rmSync({recursive:true}) removes the target AND everything under + // it; the mock's flat path Set has no real tree structure, so simulate + // that by also dropping any tracked path nested under `p`. + for (const existingPath of [...paths]) { + if (existingPath === p || existingPath.startsWith(p + sep)) { + paths.delete(existingPath); + mtimes.delete(existingPath); + } + } }, statSync: (p: string) => { if (!paths.has(p)) { @@ -97,9 +107,10 @@ function installFsMocks({ existing, dirs }: FsMockOptions) { function installPuppeteerBrowsersMock( opts: { - installedInHfCache?: Array<{ browser: string; executablePath: string }>; + installedInHfCache?: Array<{ browser: string; executablePath: string; path?: string }>; installedInHfCacheError?: Error; installResult?: { executablePath: string }; + installImpl?: () => Promise<{ executablePath: string }>; } = {}, ) { vi.doMock("@puppeteer/browsers", () => ({ @@ -108,7 +119,11 @@ function installPuppeteerBrowsersMock( getInstalledBrowsers: opts.installedInHfCacheError ? vi.fn().mockRejectedValue(opts.installedInHfCacheError) : vi.fn().mockResolvedValue(opts.installedInHfCache ?? []), - install: vi.fn().mockResolvedValue(opts.installResult ?? { executablePath: HF_BINARY }), + install: vi + .fn() + .mockImplementation( + opts.installImpl ?? (async () => opts.installResult ?? { executablePath: HF_BINARY }), + ), })); } @@ -169,9 +184,15 @@ describe("findBrowser — cache resolution", () => { "chrome-headless-shell-linux64", "redownloaded-chrome-headless-shell", ); - installFsMocks({ existing: new Set([HF_CACHE]) }); + const staleInstallDir = join(HF_CACHE, "chrome-headless-shell", "linux-131.0.6778.85"); + // The stale install DIR is present (extraction got partway through, e.g. an + // ABOUT/LICENSE-only extract) even though the exe itself is missing — + // exercises the purge-before-redownload fix, not just the redownload path. + const paths = installFsMocks({ existing: new Set([HF_CACHE, staleInstallDir]) }); installPuppeteerBrowsersMock({ - installedInHfCache: [{ browser: "chrome-headless-shell", executablePath: HF_BINARY }], + installedInHfCache: [ + { browser: "chrome-headless-shell", executablePath: HF_BINARY, path: staleInstallDir }, + ], installResult: { executablePath: redownloadedBinary }, }); const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {}); @@ -181,6 +202,67 @@ describe("findBrowser — cache resolution", () => { expect(result).toEqual({ executablePath: redownloadedBinary, source: "download" }); expect(warnSpy).toHaveBeenCalledWith(expect.stringContaining("Cached binary missing")); + // The stale directory must be gone before @puppeteer/browsers' install() + // sees it — otherwise install() throws "folder exists but exe missing" + // instead of re-extracting (the exact bug both feedback reports hit). + expect(paths.has(staleInstallDir)).toBe(false); + }); + + it("ensureBrowser({force: true}) purges the whole cache before downloading, bypassing any cache/system shortcut", async () => { + const staleInstallDir = join(HF_CACHE, "chrome-headless-shell", "linux-131.0.6778.85"); + const downloadedBinary = join(HF_CACHE, "chrome-headless-shell", "force-downloaded"); + // A HEALTHY cached binary AND system Chrome are both present — force must + // ignore both shortcuts and always re-download, which is the whole point + // of the flag (the reported bug: --force did nothing, a stale dir kept + // winning over every retry). + const paths = installFsMocks({ + existing: new Set([HF_CACHE, HF_BINARY, staleInstallDir, SYSTEM_CHROME]), + }); + installPuppeteerBrowsersMock({ + installedInHfCache: [ + { browser: "chrome-headless-shell", executablePath: HF_BINARY, path: staleInstallDir }, + ], + installResult: { executablePath: downloadedBinary }, + }); + + const { ensureBrowser } = await import("./manager.js"); + const result = await ensureBrowser({ force: true }); + + expect(result).toEqual({ executablePath: downloadedBinary, source: "download" }); + // clearBrowser() wipes prior contents; withInstallLock uses a sibling lock + // outside CACHE_DIR, so assert the purge on what was actually INSIDE it, + // not the directory's own existence. + expect(paths.has(staleInstallDir)).toBe(false); + expect(paths.has(HF_BINARY)).toBe(false); + }); + + it("serializes concurrent force downloads so one purge cannot delete another installer's lock", async () => { + const downloadedBinary = join(HF_CACHE, "chrome-headless-shell", "force-downloaded"); + const paths = installFsMocks({ existing: new Set([CACHE_ROOT, HF_CACHE, HF_BINARY]) }); + let activeInstalls = 0; + let maxActiveInstalls = 0; + installPuppeteerBrowsersMock({ + installedInHfCache: [{ browser: "chrome-headless-shell", executablePath: HF_BINARY }], + installImpl: async () => { + activeInstalls += 1; + maxActiveInstalls = Math.max(maxActiveInstalls, activeInstalls); + expect(paths.has(HF_LOCK)).toBe(true); + await new Promise((resolve) => setTimeout(resolve, 20)); + activeInstalls -= 1; + return { executablePath: downloadedBinary }; + }, + }); + + const { ensureBrowser } = await import("./manager.js"); + + await expect( + Promise.all([ensureBrowser({ force: true }), ensureBrowser({ force: true })]), + ).resolves.toEqual([ + { executablePath: downloadedBinary, source: "download" }, + { executablePath: downloadedBinary, source: "download" }, + ]); + expect(maxActiveInstalls).toBe(1); + expect(paths.has(HF_LOCK)).toBe(false); }); it("ensureBrowser does not leak the install lock directory after a successful download", async () => { @@ -191,7 +273,6 @@ describe("findBrowser — cache resolution", () => { // same extract target. mkdirSync as an atomic mutex closes that race; // this asserts the lock is actually released afterward (a leaked lock // would permanently wedge every future render on this machine). - const HF_LOCK = join(HF_CACHE, ".install.lock"); const downloadedBinary = join(HF_CACHE, "chrome-headless-shell", "downloaded"); // Cache dir exists but is empty (no manifest entries) — distinct from the // ENOTDIR "cache unreadable" case, which falls back to system instead. @@ -216,8 +297,7 @@ describe("findBrowser — cache resolution", () => { // withInstallLock directly with tiny real timeouts (it takes an // injectable timeoutMs/pollMs for exactly this) rather than mocking // Date.now()/setTimeout through the full ensureBrowser call graph. - const HF_LOCK = join(HF_CACHE, ".install.lock"); - const paths = installFsMocks({ existing: new Set([HF_CACHE, HF_LOCK]) }); + const paths = installFsMocks({ existing: new Set([CACHE_ROOT, HF_LOCK]) }); const { withInstallLock } = await import("./manager.js"); const result = await withInstallLock(async () => "done", 10, 5); @@ -231,9 +311,7 @@ describe("findBrowser — cache resolution", () => { // the stale-lock deadline together, waiter A can reclaim the stale lock and // acquire a fresh one. Waiter B's old deadline is still expired, but it must // not delete A's fresh lock. - const HF_LOCK = join(HF_CACHE, ".install.lock"); - const RECLAIM_LOCK = join(HF_CACHE, ".install.reclaim.lock"); - const paths = installFsMocks({ existing: new Set([HF_CACHE, HF_LOCK]) }); + const paths = installFsMocks({ existing: new Set([CACHE_ROOT, HF_LOCK]) }); const { withInstallLock } = await import("./manager.js"); const first = withInstallLock( @@ -248,7 +326,7 @@ describe("findBrowser — cache resolution", () => { await expect(Promise.all([first, second])).resolves.toEqual(["first", "second"]); expect(paths.has(HF_LOCK)).toBe(false); - expect(paths.has(RECLAIM_LOCK)).toBe(false); + expect(paths.has(HF_RECLAIM_LOCK)).toBe(false); }); it("warns and falls through when the hyperframes cache cannot be read", async () => { diff --git a/packages/cli/src/browser/manager.ts b/packages/cli/src/browser/manager.ts index a7c6ea14fc..a2a345eb4e 100644 --- a/packages/cli/src/browser/manager.ts +++ b/packages/cli/src/browser/manager.ts @@ -21,6 +21,7 @@ async function loadPuppeteerBrowsers(): Promise { } const CHROME_VERSION = "131.0.6778.85"; +const CACHE_ROOT_DIR = join(homedir(), ".cache", "hyperframes"); const CACHE_DIR = join(homedir(), ".cache", "hyperframes", "chrome"); // Puppeteer's managed cache — where `@puppeteer/browsers install // chrome-headless-shell` (and `puppeteer install`) drop binaries. The engine's @@ -39,8 +40,8 @@ const PUPPETEER_CACHE_DIR = join(homedir(), ".cache", "puppeteer", "chrome-headl // // mkdirSync is atomic (EEXIST if another process already holds it), so it // doubles as a zero-dependency cross-process mutex — no lockfile library needed. -const INSTALL_LOCK_DIR = join(CACHE_DIR, ".install.lock"); -const INSTALL_RECLAIM_LOCK_DIR = join(CACHE_DIR, ".install.reclaim.lock"); +const INSTALL_LOCK_DIR = join(CACHE_ROOT_DIR, ".chrome.install.lock"); +const INSTALL_RECLAIM_LOCK_DIR = join(CACHE_ROOT_DIR, ".chrome.install.reclaim.lock"); const INSTALL_LOCK_TIMEOUT_MS = 120_000; // generous: a real download+extract can take a while const INSTALL_LOCK_POLL_MS = 200; @@ -88,7 +89,9 @@ export async function withInstallLock( pollMs = INSTALL_LOCK_POLL_MS, ): Promise { // recursive:false below needs the parent to already exist (unlike `mkdir -p`). - if (!existsSync(CACHE_DIR)) mkdirSync(CACHE_DIR, { recursive: true }); + // Keep lock dirs outside CACHE_DIR so force-clearing the Chrome cache cannot + // delete another installer's in-flight lock. + if (!existsSync(CACHE_ROOT_DIR)) mkdirSync(CACHE_ROOT_DIR, { recursive: true }); let deadline = Date.now() + timeoutMs; for (;;) { if (existsSync(INSTALL_RECLAIM_LOCK_DIR)) { @@ -127,11 +130,31 @@ export interface BrowserResult { export interface EnsureBrowserOptions { onProgress?: (downloadedBytes: number, totalBytes: number) => void; + // Purge any cached HF-managed download before resolving, so a stale or + // partially-extracted install can't make the retry look like a no-op. + force?: boolean; } interface CacheLookupResult { result?: BrowserResult; staleHyperframesCachePath?: string; + // Root install-folder path for the stale entry (InstalledBrowser#path), NOT + // the missing executablePath above — this is what actually needs deleting. + staleInstallPath?: string; +} + +/** + * Remove one browser version's install directory (not the whole CACHE_DIR). + * @puppeteer/browsers' install() treats an existing-but-incomplete directory + * as already installed and throws "folder exists but executable is missing" + * rather than re-extracting — so an extraction interrupted by a Windows AV + * lock, a sleep/wake cycle, or ctrl-C (left with only alphabetically-early + * files like ABOUT/LICENSE, no exe) wedges every subsequent ensure/render + * with the same error until someone manually deletes the directory. Purging + * it first makes the retry actually retry. + */ +function purgeStaleInstall(installPath: string): void { + rmSync(installPath, { recursive: true, force: true }); } // --- Internal helpers ------------------------------------------------------- @@ -215,7 +238,7 @@ async function findFromCache(): Promise { return { result: { executablePath: match.executablePath, source: "cache" } }; } if (match) { - return { staleHyperframesCachePath: match.executablePath }; + return { staleHyperframesCachePath: match.executablePath, staleInstallPath: match.path }; } } @@ -371,7 +394,10 @@ export async function findBrowser(): Promise { `[browser] Cached binary missing at ${fromCache.staleHyperframesCachePath} — re-downloading...`, ); try { - return await withInstallLock(() => downloadBrowser()); + return await withInstallLock(async () => { + if (fromCache.staleInstallPath) purgeStaleInstall(fromCache.staleInstallPath); + return downloadBrowser(); + }); } catch (err) { const cause = normalizeErrorMessage(err); throw new Error( @@ -445,27 +471,44 @@ export async function ensureBrowser(options?: EnsureBrowserOptions): Promise downloadBrowser(options)); - } + if (!options?.force) { + const fromCache = await findFromCache(); + if (fromCache.result) return fromCache.result; + if (fromCache.staleHyperframesCachePath) { + console.warn( + `[browser] Cached binary missing at ${fromCache.staleHyperframesCachePath} — re-downloading...`, + ); + return withInstallLock(async () => { + if (fromCache.staleInstallPath) purgeStaleInstall(fromCache.staleInstallPath); + return downloadBrowser(options); + }); + } - const fromSystem = findFromSystem(); - if (fromSystem) { - warnSystemFallbackOnce(fromSystem.executablePath); - return fromSystem; + const fromSystem = findFromSystem(); + if (fromSystem) { + warnSystemFallbackOnce(fromSystem.executablePath); + return fromSystem; + } } return withInstallLock(async () => { + if (options?.force) { + // `--force` means "always get a fresh managed download" — purging the + // whole HF-managed cache after acquiring the install lock keeps two + // concurrent force retries from deleting each other's in-flight lock or + // partially extracted install. + clearBrowser(); + } + // Re-check after acquiring the lock: a concurrent invocation may have // finished installing while we were waiting, in which case reuse its - // result instead of downloading and extracting a second time. - const afterLock = await findFromCache(); - if (afterLock.result) return afterLock.result; + // result instead of downloading and extracting a second time. Skipped + // under --force, which already purged and always wants a fresh download. + if (!options?.force) { + const afterLock = await findFromCache(); + if (afterLock.result) return afterLock.result; + if (afterLock.staleInstallPath) purgeStaleInstall(afterLock.staleInstallPath); + } return downloadBrowser(options); }); } diff --git a/packages/cli/src/commands/browser.ts b/packages/cli/src/commands/browser.ts index 20e9ea6c95..d9391cc108 100644 --- a/packages/cli/src/commands/browser.ts +++ b/packages/cli/src/commands/browser.ts @@ -5,6 +5,7 @@ import { c } from "../ui/colors.js"; export const examples: Example[] = [ ["Find or download Chrome for rendering", "hyperframes browser ensure"], + ["Purge a stale/partial download and re-download", "hyperframes browser ensure --force"], ["Print the Chrome executable path", "hyperframes browser path"], ["Remove cached Chrome download", "hyperframes browser clear"], ]; @@ -19,11 +20,11 @@ import { } from "../browser/manager.js"; import { trackBrowserInstall, trackCommandFailure } from "../telemetry/events.js"; -async function runEnsure(): Promise { +async function runEnsure(options?: { force?: boolean }): Promise { clack.intro(c.bold("hyperframes browser ensure")); - // ARM64 Linux: Chrome headless shell is not available. - // Try to find system Chromium first, then attempt auto-install via apt. + // ARM64 Linux: Chrome headless shell is not available (apt-get/system-only + // install flow, no download cache to force a purge of) — --force is a no-op here. if (isLinuxArm()) { const s = clack.spinner(); s.start("Linux ARM64 detected — looking for system Chromium..."); @@ -61,26 +62,31 @@ async function runEnsure(): Promise { } const s = clack.spinner(); - s.start("Looking for an existing browser..."); + if (!options?.force) { + s.start("Looking for an existing browser..."); - const existing = await findBrowser(); - if (existing) { - s.stop(c.success("Browser found")); - console.log(); - console.log(` ${c.dim("Source:")} ${c.bold(existing.source)}`); - console.log(` ${c.dim("Path:")} ${c.bold(existing.executablePath)}`); - console.log(); - clack.outro(c.success("Ready to render.")); - return; + const existing = await findBrowser(); + if (existing) { + s.stop(c.success("Browser found")); + console.log(); + console.log(` ${c.dim("Source:")} ${c.bold(existing.source)}`); + console.log(` ${c.dim("Path:")} ${c.bold(existing.executablePath)}`); + console.log(); + clack.outro(c.success("Ready to render.")); + return; + } + + s.stop("No browser found — downloading"); + } else { + s.start("Purging cached download and re-downloading..."); } - s.stop("No browser found — downloading"); - const downloadSpinner = clack.spinner(); downloadSpinner.start(`Downloading Chrome Headless Shell ${c.dim("v" + CHROME_VERSION)}...`); let lastPct = -1; const result = await ensureBrowser({ + force: options?.force, onProgress: (downloaded, total) => { if (total <= 0) return; const pct = Math.floor((downloaded / total) * 100); @@ -141,6 +147,12 @@ export default defineCommand({ "ensure = find or download Chrome, path = print executable path, clear = remove cached download", required: false, }, + force: { + type: "boolean", + description: + "ensure only: purge any cached download (including a stale/partial one) and re-download from scratch", + default: false, + }, }, async run({ args }) { const subcommand = args.subcommand; @@ -157,16 +169,17 @@ ${c.bold("SUBCOMMANDS:")} ${c.accent("clear")} ${c.dim("Remove cached Chrome download")} ${c.bold("EXAMPLES:")} - ${c.accent("npx hyperframes browser ensure")} ${c.dim("Download Chrome if needed")} - ${c.accent("npx hyperframes browser path")} ${c.dim("Print path for scripts")} - ${c.accent("npx hyperframes browser clear")} ${c.dim("Remove cached browser")} + ${c.accent("npx hyperframes browser ensure")} ${c.dim("Download Chrome if needed")} + ${c.accent("npx hyperframes browser ensure --force")} ${c.dim("Purge a stale/partial download and re-download")} + ${c.accent("npx hyperframes browser path")} ${c.dim("Print path for scripts")} + ${c.accent("npx hyperframes browser clear")} ${c.dim("Remove cached browser")} `); return; } switch (subcommand) { case "ensure": - return runEnsure(); + return runEnsure({ force: args.force }); case "path": return runPath(); case "clear": diff --git a/packages/cli/src/commands/figma/asset.test.ts b/packages/cli/src/commands/figma/asset.test.ts index 680866673d..c3e25a340b 100644 --- a/packages/cli/src/commands/figma/asset.test.ts +++ b/packages/cli/src/commands/figma/asset.test.ts @@ -101,4 +101,56 @@ describe("runAssetImport", () => { /node/i, ); }); + + it("records description + entity and regenerates .media/index.md", async () => { + const dir = scratch(); + const out = await runAssetImport( + "KEY:1-2", + { format: "png", description: "hero illustration", entity: "Acme hero" }, + deps(dir), + ); + expect(out.record.description).toBe("hero illustration"); + expect(out.record.entity).toBe("Acme hero"); + expect(out.snippet.html).toContain('alt="hero illustration"'); + const index = readFileSync(join(dir, ".media", "index.md"), "utf8"); + expect(index).toContain("hero illustration"); + expect(index).toContain(out.record.id); + }); + + it("applies --description/--entity on a reuse hit instead of dropping them", async () => { + const dir = scratch(); + const first = await runAssetImport("KEY:1-2", { format: "png" }, deps(dir)); + expect(first.record.description).toBeUndefined(); + const again = await runAssetImport( + "KEY:1-2", + { format: "png", description: "Acme logo", entity: "Acme logo" }, + deps(dir), + ); + expect(again.reused).toBe(true); + expect(again.record.description).toBe("Acme logo"); + expect(again.snippet.html).toContain('alt="Acme logo"'); + const index = readFileSync(join(dir, ".media", "index.md"), "utf8"); + expect(index).toContain("Acme logo"); + expect(index).not.toContain("image_002"); + }); + + it("reuses against ANY matching tuple, not just the oldest row", async () => { + const dir = scratch(); + await runAssetImport("KEY:1-2", { format: "svg" }, deps(dir)); // image_001 (svg) + const png = await runAssetImport("KEY:1-2", { format: "png" }, deps(dir)); // image_002 + expect(png.reused).toBe(false); + const pngAgain = await runAssetImport("KEY:1-2", { format: "png" }, deps(dir)); + expect(pngAgain.reused).toBe(true); + expect(pngAgain.record.id).toBe(png.record.id); + }); + + it("flattens whitespace in descriptions so index.md rows stay single-line", async () => { + const dir = scratch(); + const out = await runAssetImport( + "KEY:1-2", + { format: "png", description: "line one\nline two" }, + deps(dir), + ); + expect(out.record.description).toBe("line one line two"); + }); }); diff --git a/packages/cli/src/commands/figma/asset.ts b/packages/cli/src/commands/figma/asset.ts index 4508682494..79252c0305 100644 --- a/packages/cli/src/commands/figma/asset.ts +++ b/packages/cli/src/commands/figma/asset.ts @@ -9,12 +9,14 @@ import { appendRecord, buildAssetSnippet, createFigmaClient, - findByFigmaNode, + findAllByFigmaNode, freezeBytes, nextId, parseFigmaRef, + regenerateIndex, sanitizeSvg, typeDirPath, + updateRecord, type AssetSnippet, type FigmaAssetFormat, type FigmaClient, @@ -28,6 +30,10 @@ import { withFigmaErrors } from "./cliError.js"; export interface AssetImportOptions { format: FigmaAssetFormat; scale?: number; + /** human description — lands in the manifest + index.md + */ + description?: string; + /** media-use interop: entity name for `resolve --entity` cache hits */ + entity?: string; } export interface AssetImportDeps { @@ -55,21 +61,39 @@ export async function runAssetImport( ); const { version } = await deps.client.fileVersion(ref.fileKey); + const description = normalizeMeta(opts.description); + const entity = normalizeMeta(opts.entity); // Cache key per spec §5: fileKey:nodeId:format:scale:version → reuse. - // Unspecified scale is canonically 1 on both sides (figma's default), so - // `--scale 1` and no flag dedupe to the same record. Reuse also requires - // the frozen file to still exist — a deleted file falls through to - // re-import instead of returning a snippet that points at nothing. - const existing = findByFigmaNode(deps.projectDir, ref.fileKey, ref.nodeId); - if ( - existing && - existing.provenance.format === opts.format && - (existing.provenance.scale ?? 1) === (opts.scale ?? 1) && - existing.provenance.version === version && - existsSync(join(deps.projectDir, existing.path)) - ) { - return { record: existing, snippet: buildAssetSnippet(existing), reused: true }; + // Check EVERY row for the node (a node can legitimately have several + // format/scale/version tuples — the oldest-row shortcut minted duplicates + // forever once a second tuple existed). Unspecified scale is canonically 1 + // on both sides (figma's default). Reuse also requires the frozen file to + // still exist — a deleted file falls through to re-import. + const existing = findAllByFigmaNode(deps.projectDir, ref.fileKey, ref.nodeId).find( + (r) => + r.provenance.format === opts.format && + (r.provenance.scale ?? 1) === (opts.scale ?? 1) && + r.provenance.version === version && + existsSync(join(deps.projectDir, r.path)), + ); + if (existing) { + // Metadata supplied on a re-import still lands: upsert the row instead + // of silently discarding the flags. + let record = existing; + if ( + (description !== undefined && description !== existing.description) || + (entity !== undefined && entity !== existing.entity) + ) { + record = { + ...existing, + ...(description !== undefined && { description }), + ...(entity !== undefined && { entity }), + }; + updateRecord(deps.projectDir, record); + } + safeRegenerateIndex(deps.projectDir); + return { record, snippet: buildAssetSnippet(record), reused: true }; } const rendered = await deps.client.renderNode(ref, opts); @@ -92,6 +116,8 @@ export async function runAssetImport( type: "image", path: relative(deps.projectDir, destAbs), source: `figma:${ref.fileKey}/${ref.nodeId}`, + ...(description !== undefined && { description }), + ...(entity !== undefined && { entity }), provenance: { source: "figma", fileKey: ref.fileKey, @@ -102,9 +128,29 @@ export async function runAssetImport( }, }; appendRecord(deps.projectDir, record); + safeRegenerateIndex(deps.projectDir); return { record, snippet: buildAssetSnippet(record), reused: false }; } +/** index.md is a single table row per record — newlines/tabs in a + * description would corrupt the whole table. */ +function normalizeMeta(value: string | undefined): string | undefined { + if (value === undefined) return undefined; + const cleaned = value.replace(/\s+/g, " ").trim(); + return cleaned.length > 0 ? cleaned : undefined; +} + +/** Keep the agent-readable inventory in step with the manifest (media-use + * regenerates the same file after its writes). Best-effort: the import is + * already durable, so an index write failure must not fail the command. */ +function safeRegenerateIndex(projectDir: string): void { + try { + regenerateIndex(projectDir); + } catch (err) { + console.warn(`index.md regeneration failed: ${err instanceof Error ? err.message : err}`); + } +} + const FORMATS: readonly FigmaAssetFormat[] = ["png", "svg", "jpg", "pdf"]; function parseFormat(raw: string): FigmaAssetFormat { @@ -122,6 +168,14 @@ export default defineCommand({ }, format: { type: "string", description: "png | svg | jpg | pdf", default: "svg" }, scale: { type: "string", description: "export scale (e.g. 2)" }, + description: { + type: "string", + description: "what this asset is (index.md + ); e.g. the layer's purpose", + }, + entity: { + type: "string", + description: 'entity name for media-use cache lookups (e.g. "Acme logo")', + }, dir: { type: "string", description: "project directory", default: "." }, }, async run({ args }) { @@ -133,6 +187,8 @@ export default defineCommand({ { format: parseFormat(args.format), scale: args.scale !== undefined ? Number(args.scale) : undefined, + description: args.description, + entity: args.entity, }, { projectDir: args.dir, client, download: downloadRender }, ); diff --git a/packages/cli/src/commands/figma/component.ts b/packages/cli/src/commands/figma/component.ts index 5c6f6bf4e0..b80a2f9f0b 100644 --- a/packages/cli/src/commands/figma/component.ts +++ b/packages/cli/src/commands/figma/component.ts @@ -67,12 +67,14 @@ export async function runComponentImport( // The search key must match the EMITTED (html-escaped) node id, and // replaceAll covers the same node appearing twice in the tree. let html = mapped.html; + const frozenAssets: string[] = []; for (const req of mapped.rasterize) { const asset = await runAssetImport( `${ref.fileKey}:${req.nodeId}`, - { format: "svg" }, + { format: "svg", description: req.name }, { projectDir: deps.projectDir, client: deps.client, download: deps.download }, ); + frozenAssets.push(asset.record.path); // src is a URL — always forward slashes, even when relative() yields // windows separators. const srcRel = relative(componentDir, join(deps.projectDir, asset.record.path)).replaceAll( @@ -99,9 +101,11 @@ export async function runComponentImport( target: `compositions/components/${name}/${name}.html`, type: "hyperframes:snippet", }, - ...mapped.rasterize.map((r) => ({ - path: `${r.slug}.svg`, - target: `.media/images/${r.slug}.svg`, + // The paths the frozen files ACTUALLY landed at (image_NNN.svg), which + // is also what the emitted HTML references — not the slug names. + ...frozenAssets.map((p) => ({ + path: p.split("/").pop() ?? p, + target: p.replaceAll("\\", "/"), type: "hyperframes:asset", })), ], diff --git a/packages/cli/src/commands/validate.test.ts b/packages/cli/src/commands/validate.test.ts index 1030612c5d..1cc7ce36d8 100644 --- a/packages/cli/src/commands/validate.test.ts +++ b/packages/cli/src/commands/validate.test.ts @@ -1,8 +1,11 @@ -import { describe, expect, it } from "vitest"; +import { describe, expect, it, vi } from "vitest"; import { extractCompositionErrorsFromLint, + navigationTimeoutHint, raceMediaReady, + resolveNavigationTimeoutMs, shouldIgnoreRequestFailure, + waitForPreferredSeekTarget, } from "./validate.js"; import type { ProjectLintResult } from "../utils/lintProject.js"; @@ -89,6 +92,28 @@ describe("shouldIgnoreRequestFailure", () => { }); }); +describe("waitForPreferredSeekTarget", () => { + it("waits for the runtime player/bridge target before falling back to raw timelines", async () => { + const page = { + waitForFunction: vi.fn(async () => undefined), + }; + + await waitForPreferredSeekTarget(page, 123); + + expect(page.waitForFunction).toHaveBeenCalledWith(expect.any(Function), { timeout: 123 }); + }); + + it("does not fail validation when only the legacy raw timeline fallback is available", async () => { + const page = { + waitForFunction: vi.fn(async () => { + throw new Error("waiting failed: timeout"); + }), + }; + + await expect(waitForPreferredSeekTarget(page, 1)).resolves.toBeUndefined(); + }); +}); + describe("extractCompositionErrorsFromLint", () => { // `bundleToSingleHtml` (the inliner validate.ts bundles through) is // intentionally tolerant of missing/empty/unparsable data-composition-src @@ -192,3 +217,39 @@ describe("extractCompositionErrorsFromLint", () => { expect(errors.map((e) => e.text)).toEqual(["scene-a is empty", "scene-b is empty"]); }); }); + +// Regression: `validate` used a hardcoded 10s page-navigation timeout that +// ignored --timeout, so a composition loading GSAP from a CDN + + +`; + + const browser = await puppeteer.launch({ + headless: true, + args: ["--no-sandbox", "--disable-setuid-sandbox"], + }); + + try { + const page = await browser.newPage(); + await page.setContent(html, { waitUntil: "networkidle0", timeout: 10000 }); + + // The runtime applies position edits after it binds the timeline — wait + // for the translate to land on a marked element. String form: tsx/esbuild + // injects a __name helper into serialized closures that the page lacks. + await page.waitForFunction( + `(function () { + var el = document.getElementById("ax"); + return el !== null && getComputedStyle(el).translate !== "none"; + })()`, + { timeout: 10000 }, + ); + + const sampleScript = `(function (time) { + if (window.__player && typeof window.__player.renderSeek === "function") { + window.__player.renderSeek(time); + } else if (window.__hf && typeof window.__hf.seek === "function") { + window.__hf.seek(time); + } else { + throw new Error("no runtime seek surface (__player.renderSeek / __hf.seek)"); + } + function read(id) { + var el = document.getElementById(id); + if (!el) throw new Error("missing #" + id); + var cs = getComputedStyle(el); + var m = new DOMMatrix(cs.transform === "none" ? "" : cs.transform); + var parts = cs.translate === "none" ? [] : cs.translate.split(" "); + var tx = parts.length > 0 ? parseFloat(parts[0]) : 0; + var ty = parts.length > 1 ? parseFloat(parts[1]) : 0; + return { x: m.m41 + tx, y: m.m42 + ty }; + } + return { + t: time, + ax: read("ax"), + ay: read("ay"), + axy: read("axy"), + ts: read("ts"), + st: read("st"), + }; + })`; + + const samples: Sample[] = []; + for (const t of [0, 1, 2.5, 4]) { + const sample = (await page.evaluate(`(${sampleScript})(${t})`)) as Sample; + samples.push(sample); + } + + const close = (actual: number, expected: number): boolean => Math.abs(actual - expected) <= 0.5; + + for (const s of samples) { + // X-animated: x = animation (100·t) + edit (50); y = edit (−70). + assert( + close(s.ax.x, 100 * s.t + 50), + `t=${s.t}: X-animated element x should be ${100 * s.t + 50}, got ${s.ax.x}`, + ); + assert(close(s.ax.y, -70), `t=${s.t}: X-animated element y should keep -70, got ${s.ax.y}`); + // Y-animated: y = animation (75·t) + edit (−70); x = edit (50). + assert(close(s.ay.x, 50), `t=${s.t}: Y-animated element x should keep 50, got ${s.ay.x}`); + assert( + close(s.ay.y, 75 * s.t - 70), + `t=${s.t}: Y-animated element y should be ${75 * s.t - 70}, got ${s.ay.y}`, + ); + // Both-axis-animated: both axes = animation + edit (the shape that + // originated the per-axis loss bug). + assert( + close(s.axy.x, 100 * s.t + 50), + `t=${s.t}: XY-animated element x should be ${100 * s.t + 50}, got ${s.axy.x}`, + ); + assert( + close(s.axy.y, 75 * s.t - 70), + `t=${s.t}: XY-animated element y should be ${75 * s.t - 70}, got ${s.axy.y}`, + ); + // tl.set at t=1.0: before it fires, position = edit only; after, set + edit. + const setX = s.t >= 1.0 ? 200 : 0; + const setY = s.t >= 1.0 ? 100 : 0; + assert( + close(s.ts.x, setX + 50), + `t=${s.t}: tl.set element x should be ${setX + 50}, got ${s.ts.x}`, + ); + assert( + close(s.ts.y, setY - 70), + `t=${s.t}: tl.set element y should be ${setY - 70}, got ${s.ts.y}`, + ); + // Static: both axes hold the edit. + assert(close(s.st.x, 50), `t=${s.t}: static element x should be 50, got ${s.st.x}`); + assert(close(s.st.y, -70), `t=${s.t}: static element y should be -70, got ${s.st.y}`); + } + + // GSAP-free composition: no window.gsap, no timelines — the edit must + // still render (applied at runtime init, not only at timeline bind). + const gsapFreeHtml = ` + +
+
+
+ +`; + + const page2 = await browser.newPage(); + await page2.setContent(gsapFreeHtml, { waitUntil: "networkidle0", timeout: 10000 }); + await page2.waitForFunction( + `(function () { + var el = document.getElementById("st"); + return el !== null && getComputedStyle(el).translate !== "none"; + })()`, + { timeout: 10000 }, + ); + const gsapFree = (await page2.evaluate( + `(function () { + var cs = getComputedStyle(document.getElementById("st")); + return { translate: cs.translate }; + })()`, + )) as { translate: string }; + assert( + gsapFree.translate === "50px -70px", + `GSAP-free composition should render the edit as translate 50px -70px, got ${gsapFree.translate}`, + ); + + console.log( + JSON.stringify({ + event: "runtime_position_edits_browser_test_passed", + samples, + gsapFree, + }), + ); + } finally { + await browser.close(); + } +} + +main().catch((err) => { + console.error(err.message); + process.exit(1); +}); diff --git a/packages/engine/src/services/audioMixer.test.ts b/packages/engine/src/services/audioMixer.test.ts index 6f6eb4756a..0533688807 100644 --- a/packages/engine/src/services/audioMixer.test.ts +++ b/packages/engine/src/services/audioMixer.test.ts @@ -3,14 +3,29 @@ import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; import { join } from "node:path"; import { tmpdir } from "node:os"; -const { runFfmpegMock } = vi.hoisted(() => ({ - runFfmpegMock: vi.fn(async () => ({ - success: true, - durationMs: 1, - stderr: "", - exitCode: 0, - })), -})); +// The mix filter graph is written to a temp file and passed via +// -filter_complex_script (not inlined via -filter_complex) so the command +// line doesn't scale with track count — production code deletes that file +// the moment the (real) ffmpeg process exits. The mock captures each call's +// filter content synchronously, while the file still exists, into an +// index-aligned side array (rather than re-reading it from disk after +// processCompositionAudio resolves, by which point it's already gone). +const { runFfmpegMock, capturedFilterScripts } = vi.hoisted(() => { + const capturedFilterScripts: string[] = []; + return { + capturedFilterScripts, + runFfmpegMock: vi.fn(async (args: string[]) => { + const idx = args.indexOf("-filter_complex_script"); + if (idx >= 0) { + const { readFileSync } = await import("node:fs"); + capturedFilterScripts.push(readFileSync(args[idx + 1], "utf8")); + } else { + capturedFilterScripts.push(""); + } + return { success: true, durationMs: 1, stderr: "", exitCode: 0 }; + }), + }; +}); vi.mock("../utils/runFfmpeg.js", () => ({ runFfmpeg: runFfmpegMock, @@ -23,6 +38,7 @@ describe("processCompositionAudio", () => { afterEach(() => { runFfmpegMock.mockClear(); + capturedFilterScripts.length = 0; for (const dir of tempDirs.splice(0)) { rmSync(dir, { recursive: true, force: true }); } @@ -57,9 +73,7 @@ describe("processCompositionAudio", () => { expect(result.success).toBe(true); expect(runFfmpegMock).toHaveBeenCalledTimes(2); - const mixArgs = runFfmpegMock.mock.calls[1]?.[0]; - const filterIndex = mixArgs.indexOf("-filter_complex"); - const filter = mixArgs[filterIndex + 1]; + const filter = capturedFilterScripts[1]; expect(filter).toContain("volume=0"); expect(filter).toContain("[mixed]volume=1[out]"); @@ -119,8 +133,7 @@ describe("processCompositionAudio", () => { // 3 prepare calls (one per track via Promise.all) precede the mix call, // so the mix is at index 3, not index 1. expect(runFfmpegMock).toHaveBeenCalledTimes(4); - const mixArgs = runFfmpegMock.mock.calls[3]?.[0]; - const filter = mixArgs[mixArgs.indexOf("-filter_complex") + 1]; + const filter = capturedFilterScripts[3]; expect(filter).toContain("amix=inputs=3"); expect(filter).not.toContain("normalize="); @@ -161,9 +174,7 @@ describe("processCompositionAudio", () => { expect(result.success).toBe(true); - const mixArgs = runFfmpegMock.mock.calls[1]?.[0]; - const filterIndex = mixArgs.indexOf("-filter_complex"); - const filter = mixArgs[filterIndex + 1]; + const filter = capturedFilterScripts[1]; expect(filter).toContain("volume="); expect(filter).toContain(":eval=frame"); @@ -211,9 +222,7 @@ describe("processCompositionAudio", () => { expect(result.success).toBe(true); - const mixArgs = runFfmpegMock.mock.calls[1]?.[0]; - const filterIndex = mixArgs.indexOf("-filter_complex"); - const filter = mixArgs[filterIndex + 1]; + const filter = capturedFilterScripts[1]; // One nested `if(lt(...))` is emitted per segment; cap it well under the // FFmpeg evaluator's nesting limit (MAX_VOLUME_SEGMENTS = 32). @@ -235,20 +244,24 @@ describe("processCompositionAudio", () => { // Simulate an ffmpeg build that rejects the automation expression: the // first mix attempt fails, the static-volume retry succeeds. (prepare = - // call 0, automated mix = call 1, fallback mix = call 2.) + // call 0, automated mix = call 1, fallback mix = call 2.) These two + // one-time overrides bypass the default mock's capturedFilterScripts + // push, so they push an empty placeholder themselves to keep the array + // index-aligned with call order for the fallback mix's assertion below. runFfmpegMock - .mockImplementationOnce(async () => ({ - success: true, - durationMs: 1, - stderr: "", - exitCode: 0, - })) - .mockImplementationOnce(async () => ({ - success: false, - durationMs: 1, - stderr: "Error initializing filters", - exitCode: 234, - })); + .mockImplementationOnce(async () => { + capturedFilterScripts.push(""); + return { success: true, durationMs: 1, stderr: "", exitCode: 0 }; + }) + .mockImplementationOnce(async () => { + capturedFilterScripts.push(""); + return { + success: false, + durationMs: 1, + stderr: "Error initializing filters", + exitCode: 234, + }; + }); const result = await processCompositionAudio( [ @@ -280,12 +293,61 @@ describe("processCompositionAudio", () => { expect(result.error).toMatch(/base volume/i); // The fallback mix omits the automation expression (base volume only). - const fallbackArgs = runFfmpegMock.mock.calls[2]?.[0]; - const fallbackFilter = fallbackArgs[fallbackArgs.indexOf("-filter_complex") + 1]; + const fallbackFilter = capturedFilterScripts[2]; expect(fallbackFilter).not.toContain(":eval=frame"); expect(fallbackFilter).toContain("volume=0.8"); }); + it("keeps the ffmpeg command line short with a large track count (regression for spawn ENAMETOOLONG)", async () => { + const baseDir = mkdtempSync(join(tmpdir(), "hf-audio-base-")); + const workDir = mkdtempSync(join(tmpdir(), "hf-audio-work-")); + tempDirs.push(baseDir, workDir); + + // Reported in the wild at 146 timed audio clips: the old inline + // -filter_complex string scaled with track count and blew past the OS + // command-line length limit. 150 tracks reproduces the same shape. + const trackCount = 150; + const elements = Array.from({ length: trackCount }, (_, i) => { + const filename = `clip-${i}.wav`; + writeFileSync(join(baseDir, filename), "stub"); + return { + id: `clip-${i}`, + src: filename, + start: i * 0.1, + end: i * 0.1 + 0.5, + mediaStart: 0, + layer: i, + volume: 1, + type: "audio" as const, + }; + }); + + const result = await processCompositionAudio( + elements, + baseDir, + workDir, + join(baseDir, "out.m4a"), + trackCount * 0.1 + 0.5, + ); + + expect(result.success).toBe(true); + expect(result.tracksProcessed).toBe(trackCount); + + const mixArgs = runFfmpegMock.mock.calls.at(-1)?.[0] as string[]; + expect(mixArgs).toContain("-filter_complex_script"); + expect(mixArgs).not.toContain("-filter_complex"); + + // The only things that scale with track count are the -i pairs (short, + // fixed-size each) and the filter SCRIPT FILE's content (off the command + // line entirely) — not the args array's own total character length. + const argsLength = mixArgs.join(" ").length; + expect(argsLength).toBeLessThan(20_000); + + const filter = capturedFilterScripts.at(-1); + expect(filter).toContain(`amix=inputs=${trackCount}`); + expect((filter?.match(/atrim=/g) ?? []).length).toBe(trackCount); + }); + it("prepares percent-encoded non-Latin audio srcs from decoded filesystem paths", async () => { const baseDir = mkdtempSync(join(tmpdir(), "hf-audio-base-")); const workDir = mkdtempSync(join(tmpdir(), "hf-audio-work-")); diff --git a/packages/engine/src/services/audioMixer.ts b/packages/engine/src/services/audioMixer.ts index b47d6171cb..eb3ad47c55 100644 --- a/packages/engine/src/services/audioMixer.ts +++ b/packages/engine/src/services/audioMixer.ts @@ -4,7 +4,7 @@ * Processes and mixes audio tracks using FFmpeg. */ -import { existsSync, mkdirSync, rmSync } from "fs"; +import { closeSync, existsSync, mkdirSync, mkdtempSync, openSync, rmSync, writeFileSync } from "fs"; import { isAbsolute, join, dirname } from "path"; import { parseHTML } from "linkedom"; import { extractAudioMetadata } from "../utils/ffprobe.js"; @@ -384,11 +384,9 @@ async function mixAudioTracks( const outputDir = dirname(outputPath); if (!existsSync(outputDir)) mkdirSync(outputDir, { recursive: true }); - const buildArgs = (ignoreAutomation: boolean): string[] => { - const inputs: string[] = []; + const buildFilterComplex = (ignoreAutomation: boolean): string => { const filterParts: string[] = []; tracks.forEach((track, i) => { - inputs.push("-i", track.srcPath); const delayMs = Math.round(track.start * 1000); const trimDuration = track.end - track.start; const volumeFilter = buildVolumeExpression(track, ignoreAutomation); @@ -403,12 +401,31 @@ async function mixAudioTracks( // gain by track count so per-track volumes authored in data-volume are preserved. const compensatedGain = masterOutputGain * tracks.length; const postMixGainFilter = `[mixed]volume=${formatFilterNumber(compensatedGain)}[out]`; - const fullFilter = [...filterParts, mixFilter, postMixGainFilter].join(";"); + return [...filterParts, mixFilter, postMixGainFilter].join(";"); + }; - return [ + // A large track count (100+) makes the inline `-filter_complex ` + // argument scale linearly with track count until it exceeds the OS + // command-line length limit — spawn ENAMETOOLONG, seen in practice at 146 + // tracks — even though every individual filter segment is short. FFmpeg's + // own `-filter_complex_script ` reads the same graph from disk + // instead, sidestepping the argv limit for the one component of this + // command line that actually grows with the composition. + const runMix = (ignoreAutomation: boolean) => { + const inputs: string[] = []; + tracks.forEach((track) => inputs.push("-i", track.srcPath)); + const scriptDir = mkdtempSync(join(outputDir, ".filter-complex-")); + const scriptPath = join(scriptDir, "graph.txt"); + const fd = openSync(scriptPath, "wx", 0o600); + try { + writeFileSync(fd, buildFilterComplex(ignoreAutomation)); + } finally { + closeSync(fd); + } + const args = [ ...inputs, - "-filter_complex", - fullFilter, + "-filter_complex_script", + scriptPath, "-map", "[out]", "-acodec", @@ -420,9 +437,12 @@ async function mixAudioTracks( "-y", outputPath, ]; + return runFfmpeg(args, { signal, timeout: ffmpegProcessTimeout }).finally(() => + rmSync(scriptDir, { recursive: true, force: true }), + ); }; - let result = await runFfmpeg(buildArgs(false), { signal, timeout: ffmpegProcessTimeout }); + let result = await runMix(false); // Defense in depth: volume automation is folded into an FFmpeg `volume` // expression whose evaluator limits are build-dependent (see @@ -432,7 +452,7 @@ async function mixAudioTracks( let degradedAutomation = false; const hasAutomation = tracks.some((track) => (track.volumeKeyframes?.length ?? 0) > 0); if (!result.success && !signal?.aborted && hasAutomation) { - const retry = await runFfmpeg(buildArgs(true), { signal, timeout: ffmpegProcessTimeout }); + const retry = await runMix(true); if (retry.success) { result = retry; degradedAutomation = true; diff --git a/packages/engine/src/services/screenshotService.test.ts b/packages/engine/src/services/screenshotService.test.ts index b60b5c54cf..348a0221b0 100644 --- a/packages/engine/src/services/screenshotService.test.ts +++ b/packages/engine/src/services/screenshotService.test.ts @@ -8,6 +8,8 @@ import { injectVideoFramesBatch, syncVideoFrameVisibility, shouldDefaultCaptureBeyondViewport, + applyDomLayerMask, + removeDomLayerMask, } from "./screenshotService.js"; // Stub a Page + CDPSession just enough that pageScreenshotCapture can call @@ -361,6 +363,29 @@ describe("video-frame injection respects ancestor visibility", () => { } as unknown as Page; } + function installDomMaskGlobals(setup: { window: Window; document: Document }): () => void { + const globals = globalThis as unknown as { + window?: Window; + document?: Document; + HTMLElement?: typeof HTMLElement; + CSS?: typeof CSS; + }; + const previousWindow = globals.window; + const previousDocument = globals.document; + const previousHTMLElement = globals.HTMLElement; + const previousCSS = globals.CSS; + globals.window = setup.window; + globals.document = setup.document; + globals.HTMLElement = setup.window.HTMLElement; + globals.CSS = { escape: (value: string) => value.replace(/[^a-zA-Z0-9_-]/g, "\\$&") } as CSS; + return () => { + globals.window = previousWindow; + globals.document = previousDocument; + globals.HTMLElement = previousHTMLElement; + globals.CSS = previousCSS; + }; + } + it("skips replacement-frame creation when the video's host has visibility:hidden", async () => { const { teardown, setup } = withGlobals(setupHostHiddenScenario({ visibility: "hidden" })); try { @@ -546,4 +571,105 @@ describe("video-frame injection respects ancestor visibility", () => { expect(seededImg.style.visibility).toBe("hidden"); expect(setPropertySpy).toHaveBeenCalledWith("visibility", "hidden", "important"); }); + + it("applyDomLayerMask does not revive hidden idless timed descendants of a shown layer", async () => { + const { window, document } = parseHTML( + ` +
+
late label
+
+ `, + ); + const scene = document.getElementById("scene") as HTMLElement; + const label = document.querySelector(".label") as HTMLElement; + label.style.visibility = "hidden"; + + Object.defineProperty(window, "getComputedStyle", { + configurable: true, + value: (el: Element) => ({ + display: (el as HTMLElement).style.display || "block", + visibility: (el as HTMLElement).style.visibility || "visible", + }), + }); + + const teardown = installDomMaskGlobals({ window, document }); + try { + await applyDomLayerMask(passthroughPage(), ["scene"], []); + expect(scene.style.visibility || "").toBe(""); + expect(label.style.visibility).toBe("hidden"); + + await removeDomLayerMask(passthroughPage(), []); + expect(label.style.visibility).toBe("hidden"); + expect(label.hasAttribute("data-hf-dom-layer-mask-hidden")).toBe(false); + } finally { + teardown(); + } + }); + + it("removeDomLayerMask keeps hidden timed descendants hidden when they are also extraHideIds", async () => { + const { window, document } = parseHTML( + ` +
+
late label
+
+ `, + ); + const caption = document.getElementById("caption") as HTMLElement; + caption.style.visibility = "hidden"; + + Object.defineProperty(window, "getComputedStyle", { + configurable: true, + value: (el: Element) => ({ + display: (el as HTMLElement).style.display || "block", + visibility: (el as HTMLElement).style.visibility || "visible", + }), + }); + + const teardown = installDomMaskGlobals({ window, document }); + try { + await applyDomLayerMask(passthroughPage(), ["scene"], ["caption"]); + await removeDomLayerMask(passthroughPage(), ["caption"]); + + expect(caption.style.visibility).toBe("hidden"); + expect(caption.hasAttribute("data-hf-dom-layer-mask-hidden")).toBe(false); + } finally { + teardown(); + } + }); + + it("removeDomLayerMask restores extraHideIds and render frames to previous visibility", async () => { + const { window, document } = parseHTML( + ` +
current
+ + + `, + ); + const visibleCaption = document.getElementById("visible-caption") as HTMLElement; + const clip = document.getElementById("clip") as HTMLElement; + const renderFrame = document.getElementById("__render_frame_clip__") as HTMLElement; + visibleCaption.style.visibility = "visible"; + clip.style.visibility = "hidden"; + renderFrame.style.setProperty("visibility", "hidden", "important"); + + Object.defineProperty(window, "getComputedStyle", { + configurable: true, + value: (el: Element) => ({ + display: (el as HTMLElement).style.display || "block", + visibility: (el as HTMLElement).style.visibility || "visible", + }), + }); + + const teardown = installDomMaskGlobals({ window, document }); + try { + await applyDomLayerMask(passthroughPage(), [], ["visible-caption", "clip"]); + await removeDomLayerMask(passthroughPage(), ["visible-caption", "clip"]); + + expect(visibleCaption.style.visibility).toBe("visible"); + expect(clip.style.visibility).toBe("hidden"); + expect(renderFrame.style.visibility).toBe("hidden"); + } finally { + teardown(); + } + }); }); diff --git a/packages/engine/src/services/screenshotService.ts b/packages/engine/src/services/screenshotService.ts index 5957b60484..0a197005cd 100644 --- a/packages/engine/src/services/screenshotService.ts +++ b/packages/engine/src/services/screenshotService.ts @@ -261,6 +261,9 @@ export async function captureAlphaPng(page: Page, width: number, height: number) * tests can assert presence/absence of the mask between captures. */ export const DOM_LAYER_MASK_STYLE_ID = "__hf_dom_layer_mask__"; +const DOM_LAYER_MASK_HIDDEN_ATTR = "data-hf-dom-layer-mask-hidden"; +const DOM_LAYER_MASK_PREV_VISIBILITY_ATTR = "data-hf-dom-layer-mask-prev-visibility"; +const DOM_LAYER_MASK_PREV_PRIORITY_ATTR = "data-hf-dom-layer-mask-prev-priority"; /** * Mask the DOM so a single layer screenshot captures ONLY the layer's pixels. @@ -282,12 +285,15 @@ export const DOM_LAYER_MASK_STYLE_ID = "__hf_dom_layer_mask__"; * layer elements remain visible even though intermediate parents are * hidden by the mass-hide rule. * 2. Inline-hide each `extraHideId` (and its `__render_frame_*` sibling) with - * `visibility: hidden !important`. Inline `!important` beats stylesheet - * `!important`, so this overrides the show rule for elements that fall - * under a show selector but should NOT paint — typically other-layer - * elements that are descendants of a container layer (for example HDR - * videos and other-layer SDR videos are descendants of `#root` when we - * capture the root DOM layer). + * `visibility: hidden !important`, while first recording its previous + * inline visibility. Inline `!important` beats stylesheet `!important`, + * so this overrides the show rule for elements that fall under a show + * selector but should NOT paint — typically other-layer elements that are + * descendants of a container layer (for example HDR videos and other-layer + * SDR videos are descendants of `#root` when we capture the root DOM layer). + * 3. Inline-hide timed descendants of shown elements that were hidden before + * the mask was installed. This covers idless child clips and same-layer + * descendants that the `extraHideIds` id list cannot represent. * * Only `visibility` is set on extraHideIds — never `opacity`. CSS opacity is * multiplicative through the descendant chain and a descendant cannot escape @@ -315,12 +321,71 @@ export async function applyDomLayerMask( extraHideIds: string[], ): Promise { await page.evaluate( - (args: { show: string[]; hide: string[]; styleId: string }) => { + (args: { + show: string[]; + hide: string[]; + styleId: string; + hiddenAttr: string; + prevVisibilityAttr: string; + prevPriorityAttr: string; + }) => { const existing = document.getElementById(args.styleId); if (existing) existing.remove(); + const restoreMaskedElements = () => { + const masked = document.querySelectorAll(`[${args.hiddenAttr}="1"]`); + for (const node of masked) { + if (!(node instanceof HTMLElement)) continue; + const prevVisibility = node.getAttribute(args.prevVisibilityAttr); + const prevPriority = node.getAttribute(args.prevPriorityAttr); + if (prevVisibility === null) { + node.style.removeProperty("visibility"); + } else { + node.style.setProperty("visibility", prevVisibility, prevPriority ?? ""); + } + node.removeAttribute(args.hiddenAttr); + node.removeAttribute(args.prevVisibilityAttr); + node.removeAttribute(args.prevPriorityAttr); + } + }; + restoreMaskedElements(); + + const rememberAndHideElement = (el: HTMLElement) => { + if (el.getAttribute(args.hiddenAttr) !== "1") { + const prevVisibility = el.style.getPropertyValue("visibility"); + const prevPriority = + typeof el.style.getPropertyPriority === "function" + ? el.style.getPropertyPriority("visibility") + : ""; + if (prevVisibility) { + el.setAttribute(args.prevVisibilityAttr, prevVisibility); + } else { + el.removeAttribute(args.prevVisibilityAttr); + } + if (prevPriority) { + el.setAttribute(args.prevPriorityAttr, prevPriority); + } else { + el.removeAttribute(args.prevPriorityAttr); + } + el.setAttribute(args.hiddenAttr, "1"); + } + el.style.setProperty("visibility", "hidden", "important"); + }; + + const hiddenTimedDescendants: HTMLElement[] = []; + const rememberHiddenTimedDescendants = (root: Element) => { + for (const node of root.querySelectorAll("[data-start]")) { + if (!(node instanceof HTMLElement)) continue; + const computed = window.getComputedStyle(node); + if (computed.visibility !== "hidden" && computed.display !== "none") continue; + hiddenTimedDescendants.push(node); + } + }; + const showSelectors: string[] = []; for (const id of args.show) { + const el = document.getElementById(id); + if (el) rememberHiddenTimedDescendants(el); const escaped = CSS.escape(id); showSelectors.push(`#${escaped}`, `#${escaped} *`); const renderEscaped = CSS.escape(`__render_frame_${id}__`); @@ -338,26 +403,38 @@ export async function applyDomLayerMask( style.textContent = `${massHideRule}\n${showRule}`; document.head.appendChild(style); + for (const el of hiddenTimedDescendants) { + rememberAndHideElement(el); + } + for (const id of args.hide) { const el = document.getElementById(id); if (el) { - el.style.setProperty("visibility", "hidden", "important"); + rememberAndHideElement(el); } const img = document.getElementById(`__render_frame_${id}__`); if (img) { - img.style.setProperty("visibility", "hidden", "important"); + rememberAndHideElement(img); } } }, - { show: showIds, hide: extraHideIds, styleId: DOM_LAYER_MASK_STYLE_ID }, + { + show: showIds, + hide: extraHideIds, + styleId: DOM_LAYER_MASK_STYLE_ID, + hiddenAttr: DOM_LAYER_MASK_HIDDEN_ATTR, + prevVisibilityAttr: DOM_LAYER_MASK_PREV_VISIBILITY_ATTR, + prevPriorityAttr: DOM_LAYER_MASK_PREV_PRIORITY_ATTR, + }, ); } /** * Tear down the mask installed by applyDomLayerMask. * - * Removes the mask stylesheet and clears the inline `visibility` properties - * set on `extraHideIds` (and their `__render_frame_*` siblings). + * Removes the mask stylesheet and restores the inline `visibility` values + * temporarily overwritten for hidden timed descendants, `extraHideIds`, and + * their `__render_frame_*` siblings. * * IMPORTANT: We do NOT strip inline `opacity` here. applyDomLayerMask only * ever sets `visibility` (never `opacity`), so any inline opacity present on @@ -367,21 +444,37 @@ export async function applyDomLayerMask( * we strip opacity here and then seek to the same time for the next layer, * GSAP won't put it back and the wrapper will render fully opaque. */ -export async function removeDomLayerMask(page: Page, extraHideIds: string[]): Promise { +export async function removeDomLayerMask(page: Page, _extraHideIds: string[]): Promise { await page.evaluate( - (args: { hide: string[]; styleId: string }) => { + (args: { + styleId: string; + hiddenAttr: string; + prevVisibilityAttr: string; + prevPriorityAttr: string; + }) => { const style = document.getElementById(args.styleId); if (style) style.remove(); - for (const id of args.hide) { - const el = document.getElementById(id); - if (el) { - el.style.removeProperty("visibility"); + const masked = document.querySelectorAll(`[${args.hiddenAttr}="1"]`); + for (const node of masked) { + if (!(node instanceof HTMLElement)) continue; + const prevVisibility = node.getAttribute(args.prevVisibilityAttr); + const prevPriority = node.getAttribute(args.prevPriorityAttr); + if (prevVisibility === null) { + node.style.removeProperty("visibility"); + } else { + node.style.setProperty("visibility", prevVisibility, prevPriority ?? ""); } - const img = document.getElementById(`__render_frame_${id}__`); - if (img) img.style.removeProperty("visibility"); + node.removeAttribute(args.hiddenAttr); + node.removeAttribute(args.prevVisibilityAttr); + node.removeAttribute(args.prevPriorityAttr); } }, - { hide: extraHideIds, styleId: DOM_LAYER_MASK_STYLE_ID }, + { + styleId: DOM_LAYER_MASK_STYLE_ID, + hiddenAttr: DOM_LAYER_MASK_HIDDEN_ATTR, + prevVisibilityAttr: DOM_LAYER_MASK_PREV_VISIBILITY_ATTR, + prevPriorityAttr: DOM_LAYER_MASK_PREV_PRIORITY_ATTR, + }, ); } diff --git a/packages/engine/src/services/streamingEncoder.test.ts b/packages/engine/src/services/streamingEncoder.test.ts index f917860783..4623af1d14 100644 --- a/packages/engine/src/services/streamingEncoder.test.ts +++ b/packages/engine/src/services/streamingEncoder.test.ts @@ -13,7 +13,7 @@ import { EventEmitter } from "events"; import { mkdtempSync } from "fs"; import { tmpdir } from "os"; import { join } from "path"; -import { afterEach, describe, expect, it, vi } from "vitest"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { buildStreamingArgs, @@ -475,9 +475,17 @@ async function resolveWithin(promise: Promise, ms = 100): Promise { + const originalPath = process.env.PATH; + + beforeEach(() => { + process.env.PATH = ""; + }); + afterEach(() => { vi.resetModules(); vi.doUnmock("child_process"); + if (originalPath === undefined) delete process.env.PATH; + else process.env.PATH = originalPath; }); it("returns a success result when ffmpeg exits cleanly after close()", async () => { diff --git a/packages/engine/src/services/videoFrameInjector.ts b/packages/engine/src/services/videoFrameInjector.ts index 8ee8318aa6..8644c31602 100644 --- a/packages/engine/src/services/videoFrameInjector.ts +++ b/packages/engine/src/services/videoFrameInjector.ts @@ -371,6 +371,13 @@ export interface ElementStackingInfo { layoutHeight: number; opacity: number; visible: boolean; + /** + * True when the SDR video replacement image injected beside this element is + * currently paintable. Native videos are hidden during capture, so this lets + * the layered HDR compositor keep their replacement frames in the right DOM + * layer without reviving unrelated hidden elements. + */ + renderFrameVisible: boolean; isHdr: boolean; transform: string; // CSS transform matrix string, e.g. "matrix(1,0,0,1,0,0)" or "none" borderRadius: [number, number, number, number]; // [tl, tr, br, bl] in CSS px from nearest clipping ancestor @@ -635,6 +642,17 @@ export async function queryElementStacking( return Number.isFinite(n) ? n : 0; } + function isElementPaintable(node: Element): boolean { + const rect = node.getBoundingClientRect(); + const style = window.getComputedStyle(node); + return ( + style.visibility !== "hidden" && + style.display !== "none" && + rect.width > 0 && + rect.height > 0 + ); + } + for (const el of elements) { const id = el.id; if (!id) continue; @@ -647,11 +665,9 @@ export async function queryElementStacking( // remains the GSAP-controlled value. Walk from the element itself to // multiply through any ancestor opacity stacks. const opacity = getEffectiveOpacity(el); - const visible = - style.visibility !== "hidden" && - style.display !== "none" && - rect.width > 0 && - rect.height > 0; + const visible = isElementPaintable(el); + const renderFrame = document.getElementById(`__render_frame_${id}__`); + const renderFrameVisible = renderFrame ? isElementPaintable(renderFrame) : false; // offsetWidth/offsetHeight only exist on HTMLElement (not on // SVGElement, MathMLElement, etc.). Fall back to the bounding rect // dimensions for non-HTML elements so callers always get sensible @@ -668,6 +684,7 @@ export async function queryElementStacking( layoutHeight: htmlEl?.offsetHeight || Math.round(rect.height), opacity, visible, + renderFrameVisible, isHdr: hdrSet.has(id), // For HDR elements, use the full accumulated viewport matrix so the // affine blit can apply rotation/scale/translate properly. For DOM diff --git a/packages/engine/src/utils/ffmpegBinaries.test.ts b/packages/engine/src/utils/ffmpegBinaries.test.ts index e026e7fdfb..d55730d69e 100644 --- a/packages/engine/src/utils/ffmpegBinaries.test.ts +++ b/packages/engine/src/utils/ffmpegBinaries.test.ts @@ -1,6 +1,8 @@ // fallow-ignore-file code-duplication -import { resolve } from "node:path"; -import { afterEach, describe, expect, it } from "vitest"; +import { chmodSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join, resolve } from "node:path"; +import { afterEach, describe, expect, it, vi } from "vitest"; import { assertConfiguredFfmpegBinariesExist, getFfmpegBinary, @@ -10,12 +12,17 @@ import { describe("ffmpeg binary env resolution", () => { const originalFfmpegPath = process.env.HYPERFRAMES_FFMPEG_PATH; const originalFfprobePath = process.env.HYPERFRAMES_FFPROBE_PATH; + const originalPath = process.env.PATH; afterEach(() => { + vi.resetModules(); + vi.doUnmock("child_process"); if (originalFfmpegPath === undefined) delete process.env.HYPERFRAMES_FFMPEG_PATH; else process.env.HYPERFRAMES_FFMPEG_PATH = originalFfmpegPath; if (originalFfprobePath === undefined) delete process.env.HYPERFRAMES_FFPROBE_PATH; else process.env.HYPERFRAMES_FFPROBE_PATH = originalFfprobePath; + if (originalPath === undefined) delete process.env.PATH; + else process.env.PATH = originalPath; }); it("uses configured absolute paths when env vars are set", () => { @@ -40,4 +47,43 @@ describe("ffmpeg binary env resolution", () => { expect(() => assertConfiguredFfmpegBinariesExist()).not.toThrow(); }); + + it("prefers the real Windows exe when PATH lookup lists a cmd shim first", async () => { + vi.resetModules(); + vi.doMock("child_process", () => ({ + execFileSync: () => "C:\\tools\\ffmpeg.cmd\r\nC:\\tools\\ffmpeg.exe\r\n", + })); + + const { getFfmpegBinary: getMockedFfmpegBinary } = await import("./ffmpegBinaries.js"); + + expect(getMockedFfmpegBinary()).toBe(resolve("C:\\tools\\ffmpeg.exe")); + }); + + it("falls back to scanning PATH when which/where fails", async () => { + const binDir = mkdtempSync(join(tmpdir(), "hyperframes-ffmpeg-path-")); + const ffmpegPath = join(binDir, process.platform === "win32" ? "ffmpeg.exe" : "ffmpeg"); + const execFileSync = vi.fn(() => { + throw new Error("lookup command failed"); + }); + writeFileSync(ffmpegPath, "#!/bin/sh\n"); + chmodSync(ffmpegPath, 0o755); + process.env.PATH = binDir; + vi.resetModules(); + vi.doMock("child_process", () => ({ execFileSync })); + + try { + const { getFfmpegBinary: getMockedFfmpegBinary } = await import("./ffmpegBinaries.js"); + + expect(getMockedFfmpegBinary()).toBe(resolve(ffmpegPath)); + expect(execFileSync).toHaveBeenCalledOnce(); + } finally { + rmSync(binDir, { force: true, recursive: true }); + } + }); + + it("calls out a mangled replacement character in configured binary paths", () => { + process.env.HYPERFRAMES_FFMPEG_PATH = "/missing/ffmpeg�.exe"; + + expect(() => assertConfiguredFfmpegBinariesExist()).toThrow(/replacement character|mangled/i); + }); }); diff --git a/packages/engine/src/utils/ffmpegBinaries.ts b/packages/engine/src/utils/ffmpegBinaries.ts index 89df65830f..46c470bcf8 100644 --- a/packages/engine/src/utils/ffmpegBinaries.ts +++ b/packages/engine/src/utils/ffmpegBinaries.ts @@ -1,15 +1,71 @@ // fallow-ignore-file code-duplication import { execFileSync } from "child_process"; -import { existsSync } from "fs"; -import { resolve } from "path"; +import { accessSync, constants, existsSync } from "fs"; +import { delimiter, join, resolve } from "path"; export const FFMPEG_PATH_ENV = "HYPERFRAMES_FFMPEG_PATH"; export const FFPROBE_PATH_ENV = "HYPERFRAMES_FFPROBE_PATH"; const pathCache = new Map(); +function candidateFileName(candidate: string): string { + return candidate.split(/[\\/]/).at(-1)?.toLowerCase() ?? candidate.toLowerCase(); +} + +function chooseBestPathCandidate( + name: "ffmpeg" | "ffprobe", + candidates: readonly string[], +): string | undefined { + const normalized = candidates.map((candidate) => candidate.trim()).filter(Boolean); + return ( + normalized.find((candidate) => candidateFileName(candidate) === `${name}.exe`) ?? + normalized.find((candidate) => candidateFileName(candidate) === name) ?? + normalized.find((candidate) => !candidateFileName(candidate).match(/\.(cmd|bat)$/i)) ?? + normalized[0] + ); +} + +function scanPath(name: "ffmpeg" | "ffprobe"): string | undefined { + const pathValue = process.env.PATH; + if (!pathValue) return undefined; + + const extensions = + process.platform === "win32" + ? [ + ".exe", + ...new Set( + (process.env.PATHEXT ?? ".COM;.EXE;.BAT;.CMD") + .split(";") + .map((ext) => ext.trim().toLowerCase()) + .filter(Boolean), + ), + "", + ] + : [""]; + const candidates: string[] = []; + for (const dir of pathValue.split(delimiter)) { + if (!dir) continue; + for (const ext of extensions) { + const candidate = join(dir, `${name}${ext}`); + if (isExecutablePathCandidate(candidate)) candidates.push(candidate); + } + } + return chooseBestPathCandidate(name, candidates); +} + +function isExecutablePathCandidate(candidate: string): boolean { + if (process.platform === "win32") return existsSync(candidate); + try { + accessSync(candidate, constants.X_OK); + return true; + } catch { + return false; + } +} + function findOnPath(name: "ffmpeg" | "ffprobe"): string | undefined { if (pathCache.has(name)) return pathCache.get(name); + let found: string | undefined; try { const command = process.platform === "win32" ? "where" : "which"; const output = execFileSync(command, [name], { @@ -17,17 +73,13 @@ function findOnPath(name: "ffmpeg" | "ffprobe"): string | undefined { stdio: ["pipe", "pipe", "pipe"], timeout: 5000, }); - const first = output - .split(/\r?\n/) - .map((s) => s.trim()) - .find(Boolean); - const resolved = first ? resolve(first) : undefined; - pathCache.set(name, resolved); - return resolved; + found = chooseBestPathCandidate(name, output.split(/\r?\n/)); } catch { - pathCache.set(name, undefined); - return undefined; + found = scanPath(name); } + const resolved = found ? resolve(found) : undefined; + pathCache.set(name, resolved); + return resolved; } function getConfiguredBinary(envName: string, binaryName: "ffmpeg" | "ffprobe"): string { @@ -49,7 +101,7 @@ export function assertConfiguredFfmpegBinariesExist(): void { if (ffmpegPath && !existsSync(ffmpegPath)) { throw new Error( `[FFmpeg] FFmpeg binary not found at ${FFMPEG_PATH_ENV}="${ffmpegPath}". ` + - "Install FFmpeg or unset the override.", + `Install FFmpeg or unset the override.${pathEncodingHint(ffmpegPath)}`, ); } @@ -57,7 +109,12 @@ export function assertConfiguredFfmpegBinariesExist(): void { if (ffprobePath && !existsSync(ffprobePath)) { throw new Error( `[FFmpeg] FFprobe binary not found at ${FFPROBE_PATH_ENV}="${ffprobePath}". ` + - "Install FFmpeg or unset the override.", + `Install FFmpeg or unset the override.${pathEncodingHint(ffprobePath)}`, ); } } + +function pathEncodingHint(configuredPath: string): string { + if (!configuredPath.includes("\uFFFD")) return ""; + return " The path contains a Unicode replacement character, which usually means it was mangled while being copied or decoded."; +} diff --git a/packages/engine/src/utils/ffprobe.test.ts b/packages/engine/src/utils/ffprobe.test.ts index 5a51503848..c545190b59 100644 --- a/packages/engine/src/utils/ffprobe.test.ts +++ b/packages/engine/src/utils/ffprobe.test.ts @@ -166,12 +166,19 @@ function createSpawnSpy(outcomes: SpawnOutcome[]): { describe("ffprobe missing-binary fallback", () => { const originalFfprobePath = process.env.HYPERFRAMES_FFPROBE_PATH; + const originalPath = process.env.PATH; + + function hidePathBinaries(): void { + process.env.PATH = ""; + } afterEach(() => { vi.resetModules(); vi.doUnmock("child_process"); if (originalFfprobePath === undefined) delete process.env.HYPERFRAMES_FFPROBE_PATH; else process.env.HYPERFRAMES_FFPROBE_PATH = originalFfprobePath; + if (originalPath === undefined) delete process.env.PATH; + else process.env.PATH = originalPath; }); it("spawns the configured absolute FFprobe path when HYPERFRAMES_FFPROBE_PATH is set", async () => { @@ -198,6 +205,7 @@ describe("ffprobe missing-binary fallback", () => { it("extractMediaMetadata falls back to PNG cICP metadata when ffprobe is missing", async () => { const { spawn, calls } = createSpawnSpy([{ kind: "missing" }]); + hidePathBinaries(); vi.resetModules(); vi.doMock("child_process", () => ({ spawn })); @@ -294,6 +302,7 @@ describe("ffprobe missing-binary fallback", () => { it("extractMediaMetadata rethrows ffprobe-missing error for non-image files without fallback", async () => { const { spawn } = createSpawnSpy([{ kind: "missing" }]); + hidePathBinaries(); vi.resetModules(); vi.doMock("child_process", () => ({ spawn })); @@ -304,6 +313,7 @@ describe("ffprobe missing-binary fallback", () => { it("extractAudioMetadata surfaces a ffprobe-missing error verbatim", async () => { const { spawn, calls } = createSpawnSpy([{ kind: "missing" }]); + hidePathBinaries(); vi.resetModules(); vi.doMock("child_process", () => ({ spawn })); @@ -318,6 +328,7 @@ describe("ffprobe missing-binary fallback", () => { it("analyzeKeyframeIntervals surfaces a ffprobe-missing error verbatim", async () => { const { spawn, calls } = createSpawnSpy([{ kind: "missing" }]); + hidePathBinaries(); vi.resetModules(); vi.doMock("child_process", () => ({ spawn })); @@ -332,6 +343,7 @@ describe("ffprobe missing-binary fallback", () => { it("ffprobe-missing error message includes install hint", async () => { const { spawn } = createSpawnSpy([{ kind: "missing" }]); + hidePathBinaries(); vi.resetModules(); vi.doMock("child_process", () => ({ spawn })); diff --git a/packages/gcp-cloud-run/package.json b/packages/gcp-cloud-run/package.json index 95aadeba4e..26ddae3cd1 100644 --- a/packages/gcp-cloud-run/package.json +++ b/packages/gcp-cloud-run/package.json @@ -1,6 +1,6 @@ { "name": "@hyperframes/gcp-cloud-run", - "version": "0.7.29", + "version": "0.7.36", "description": "Google Cloud Run + Workflows adapter for HyperFrames distributed rendering — request handler, client-side SDK, and Terraform module.", "repository": { "type": "git", diff --git a/packages/lint/package.json b/packages/lint/package.json index eb559fb078..7268738605 100644 --- a/packages/lint/package.json +++ b/packages/lint/package.json @@ -1,6 +1,6 @@ { "name": "@hyperframes/lint", - "version": "0.7.29", + "version": "0.7.36", "repository": { "type": "git", "url": "https://github.com/heygen-com/hyperframes", diff --git a/packages/parsers/package.json b/packages/parsers/package.json index 228a72ba00..9630404703 100644 --- a/packages/parsers/package.json +++ b/packages/parsers/package.json @@ -1,6 +1,6 @@ { "name": "@hyperframes/parsers", - "version": "0.7.29", + "version": "0.7.36", "repository": { "type": "git", "url": "https://github.com/heygen-com/hyperframes", diff --git a/packages/player/package.json b/packages/player/package.json index e010a98431..99295e4828 100644 --- a/packages/player/package.json +++ b/packages/player/package.json @@ -1,6 +1,6 @@ { "name": "@hyperframes/player", - "version": "0.7.29", + "version": "0.7.36", "description": "Embeddable web component for HyperFrames compositions", "repository": { "type": "git", diff --git a/packages/producer/package.json b/packages/producer/package.json index 8576dca7c0..cd2eb75c15 100644 --- a/packages/producer/package.json +++ b/packages/producer/package.json @@ -1,6 +1,6 @@ { "name": "@hyperframes/producer", - "version": "0.7.29", + "version": "0.7.36", "description": "HTML-to-video rendering engine using Chrome's BeginFrame API", "repository": { "type": "git", diff --git a/packages/producer/src/services/hdrCompositor.test.ts b/packages/producer/src/services/hdrCompositor.test.ts new file mode 100644 index 0000000000..774301c9cb --- /dev/null +++ b/packages/producer/src/services/hdrCompositor.test.ts @@ -0,0 +1,64 @@ +import { describe, expect, it } from "vitest"; +import type { ElementStackingInfo } from "@hyperframes/engine"; +import { selectDomLayerShowIds } from "./hdrCompositor.js"; + +function makeEl(id: string, overrides?: Partial): ElementStackingInfo { + return { + id, + zIndex: 0, + x: 0, + y: 0, + width: 1920, + height: 1080, + layoutWidth: 1920, + layoutHeight: 1080, + opacity: 1, + visible: true, + renderFrameVisible: false, + isHdr: false, + transform: "none", + borderRadius: [0, 0, 0, 0], + objectFit: "fill", + objectPosition: "50% 50%", + clipRect: null, + ...overrides, + }; +} + +describe("selectDomLayerShowIds", () => { + it("does not re-show hidden DOM elements while preserving visible injected video frames", () => { + expect( + selectDomLayerShowIds( + ["visible-overlay", "hidden-later-scene", "hidden-sdr-video"], + [ + makeEl("visible-overlay"), + makeEl("hidden-later-scene", { visible: false }), + makeEl("hidden-sdr-video", { + visible: false, + renderFrameVisible: true, + }), + ], + ), + ).toEqual(["visible-overlay", "hidden-sdr-video"]); + }); + + it("does not re-show opacity-zero scene members or their injected frames", () => { + expect( + selectDomLayerShowIds( + ["active-overlay", "inactive-scene-video", "inactive-scene-label"], + [ + makeEl("active-overlay"), + makeEl("inactive-scene-video", { + opacity: 0, + visible: false, + renderFrameVisible: true, + }), + makeEl("inactive-scene-label", { + opacity: 0, + visible: true, + }), + ], + ), + ).toEqual(["active-overlay"]); + }); +}); diff --git a/packages/producer/src/services/hdrCompositor.ts b/packages/producer/src/services/hdrCompositor.ts index f188bd8cd5..970cba39d8 100644 --- a/packages/producer/src/services/hdrCompositor.ts +++ b/packages/producer/src/services/hdrCompositor.ts @@ -416,6 +416,17 @@ export function resolveCompositeTransfer( return hasHdrContent && effectiveHdr ? effectiveHdr.transfer : "srgb"; } +export function selectDomLayerShowIds( + layerElementIds: string[], + fullStacking: ElementStackingInfo[], +): string[] { + const byId = new Map(fullStacking.map((el) => [el.id, el])); + return layerElementIds.filter((id) => { + const el = byId.get(id); + return !!el && el.opacity > 0 && (el.visible || el.renderFrameVisible === true); + }); +} + export interface HdrCompositeContext { log: ProducerLogger; domSession: CaptureSession; @@ -607,10 +618,10 @@ export async function compositeHdrFrame( // // The mask: // - mass-hides every body descendant via stylesheet - // - re-shows the layer's elements (and their descendants and - // their injected `__render_frame_*` siblings) so deep-nested - // content stays visible even though intermediate ancestors - // are hidden + // - re-shows the layer's currently paintable elements (and their + // descendants and injected `__render_frame_*` siblings) so + // deep-nested content stays visible even though intermediate + // ancestors are hidden // - inline-hides every other data-start element so they don't // paint when they happen to be descendants of a layer element // (most importantly: HDR videos and other-layer SDR videos @@ -621,6 +632,17 @@ export async function compositeHdrFrame( // border/box-shadow of cards, etc.) and the resulting opaque // pixels overwrite previously composited HDR content beneath. const layerIds = new Set(layer.elementIds); + const showIds = selectDomLayerShowIds(layer.elementIds, fullStacking); + if (showIds.length === 0) { + if (shouldLog) { + log.info("[diag] dom layer skipped, all elements not paintable", { + frame: debugFrameIndex, + layerIdx, + layerIds: layer.elementIds, + }); + } + continue; + } const hideIds = allElementIds.filter((id) => !layerIds.has(id)); if (hdrPerf) hdrPerf.domLayerCaptures += 1; @@ -640,7 +662,7 @@ export async function compositeHdrFrame( // 3. Install the mask (mass-hide stylesheet + inline-hide non-layer ids) await timeHdrPhaseAsync(hdrPerf, "domMaskApplyMs", () => - applyDomLayerMask(domSession.page, layer.elementIds, hideIds), + applyDomLayerMask(domSession.page, showIds, hideIds), ); // 4. Screenshot @@ -669,6 +691,7 @@ export async function compositeHdrFrame( frame: debugFrameIndex, layerIdx, layerIds: layer.elementIds, + showIds, hideCount: hideIds.length, pngBytes: domPng.length, alphaPixels, diff --git a/packages/producer/src/services/render/stages/captureHdrFrameShared.dom-mask.test.ts b/packages/producer/src/services/render/stages/captureHdrFrameShared.dom-mask.test.ts new file mode 100644 index 0000000000..0e1dd0c382 --- /dev/null +++ b/packages/producer/src/services/render/stages/captureHdrFrameShared.dom-mask.test.ts @@ -0,0 +1,121 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; +import type { ElementStackingInfo } from "@hyperframes/engine"; +import { + applyDomLayerMask, + blitRgba8OverRgb48le, + captureAlphaPng, + decodePng, + removeDomLayerMask, +} from "@hyperframes/engine"; +import type { ProducerLogger } from "../../../logger.js"; +import type { HdrCompositeContext } from "../../hdrCompositor.js"; +import { captureSceneIntoBuffer } from "./captureHdrFrameShared.js"; + +vi.mock("@hyperframes/engine", async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + applyDomLayerMask: vi.fn(async () => undefined), + captureAlphaPng: vi.fn(async () => Buffer.from("png")), + decodePng: vi.fn(() => ({ data: Buffer.alloc(4), width: 1, height: 1 })), + removeDomLayerMask: vi.fn(async () => undefined), + blitRgba8OverRgb48le: vi.fn(), + }; +}); + +function makeEl(id: string, overrides?: Partial): ElementStackingInfo { + return { + id, + zIndex: 0, + x: 0, + y: 0, + width: 1, + height: 1, + layoutWidth: 1, + layoutHeight: 1, + opacity: 1, + visible: true, + renderFrameVisible: false, + isHdr: false, + transform: "none", + borderRadius: [0, 0, 0, 0], + objectFit: "fill", + objectPosition: "50% 50%", + clipRect: null, + ...overrides, + }; +} + +function makeContext(): HdrCompositeContext { + return { + log: makeLogger(), + domSession: { page: { evaluate: vi.fn() } } as never, + beforeCaptureHook: null, + width: 1, + height: 1, + fps: 30, + compositeTransfer: "srgb", + nativeHdrImageIds: new Set(), + hdrImageBuffers: new Map(), + hdrImageTransferCache: new Map(), + hdrVideoFrameSources: new Map(), + hdrVideoStartTimes: new Map(), + imageTransfers: new Map(), + videoTransfers: new Map(), + debugDumpEnabled: false, + debugDumpDir: null, + }; +} + +function makeLogger(): ProducerLogger { + return { + debug: vi.fn(), + info: vi.fn(), + warn: vi.fn(), + error: vi.fn(), + } as unknown as ProducerLogger; +} + +describe("captureSceneIntoBuffer", () => { + beforeEach(() => { + vi.mocked(applyDomLayerMask).mockClear(); + vi.mocked(captureAlphaPng).mockClear(); + vi.mocked(decodePng).mockClear(); + vi.mocked(removeDomLayerMask).mockClear(); + vi.mocked(blitRgba8OverRgb48le).mockClear(); + }); + + it("does not re-show hidden transition-scene members in the DOM mask", async () => { + const page = { evaluate: vi.fn(async () => undefined) }; + + await captureSceneIntoBuffer({ + session: { page, onBeforeCapture: null } as never, + sceneBuf: Buffer.alloc(6), + sceneIds: new Set(["visible-overlay", "hidden-inner", "hidden-sdr-video"]), + stackingInfo: [ + makeEl("visible-overlay"), + makeEl("hidden-inner", { visible: false }), + makeEl("hidden-sdr-video", { visible: false, renderFrameVisible: true }), + makeEl("outside-scene"), + ], + time: 0.5, + width: 1, + height: 1, + nativeHdrIds: new Set(), + nativeHdrImageIds: new Set(), + beforeCaptureHook: null, + hdrCompositeCtx: makeContext(), + compositeTransfer: "srgb", + hdrTargetTransfer: undefined, + hdrPerf: undefined, + log: makeLogger(), + frameIdx: 15, + }); + + expect(applyDomLayerMask).toHaveBeenCalledWith( + page, + ["visible-overlay", "hidden-sdr-video"], + ["outside-scene"], + ); + }); +}); diff --git a/packages/producer/src/services/render/stages/captureHdrFrameShared.ts b/packages/producer/src/services/render/stages/captureHdrFrameShared.ts index 975627101f..2e25a64055 100644 --- a/packages/producer/src/services/render/stages/captureHdrFrameShared.ts +++ b/packages/producer/src/services/render/stages/captureHdrFrameShared.ts @@ -29,6 +29,7 @@ import { blitHdrImageLayer, blitHdrVideoLayer, closeHdrVideoFrameSource, + selectDomLayerShowIds, } from "../../hdrCompositor.js"; import { type HdrPerfCollector, @@ -234,10 +235,11 @@ export async function captureSceneIntoBuffer(a: CaptureSceneArgs): Promise ); } } - const showIds = Array.from(sceneIds); + const showIds = selectDomLayerShowIds(Array.from(sceneIds), stackingInfo); const hideIds = stackingInfo .map((e) => e.id) .filter((id) => !sceneIds.has(id) || nativeHdrIds.has(id)); + if (showIds.length === 0) return; if (hdrPerf) hdrPerf.domLayerCaptures += 1; await timeHdrPhaseAsync(hdrPerf, "domMaskApplyMs", () => applyDomLayerMask(session.page, showIds, hideIds), diff --git a/packages/producer/tests/hdr-regression/output/compiled.html b/packages/producer/tests/hdr-regression/output/compiled.html index 3a33c22145..a6c419e64e 100644 --- a/packages/producer/tests/hdr-regression/output/compiled.html +++ b/packages/producer/tests/hdr-regression/output/compiled.html @@ -1,6 +1,534 @@ +} HDR PQ Regression Suite