Files
hyperframes/packages/studio/vite.browser.test.ts
T
James RussoandClaude Opus 5.5 80cda85d76 fix(studio-server): run thumbnail captures in an opaque origin (#7528)
* fix(studio-server): run thumbnail captures in an opaque origin

The thumbnail renderer loads each composition as a top-level page, so its
scripts ran on the Studio's origin. The capture document (`?hf-capture`) now
carries `Content-Security-Policy: sandbox allow-scripts`, so those scripts get
an opaque origin.

An opaque page's CORS-mode loads fail without a CORS header. The renderer that
opened the page is trusted, so it adds `Access-Control-Allow-Origin: null`
itself, over that page's own DevTools session, to the loads a frame needs:
- fonts, module scripts and images;
- the `.html` scenes, `.json` and `.cube` files the runtime fetches.
Only GETs of the project's preview files qualify, matched by file type. Both
thumbnail renderers do this: the CLI's and the Vite dev server's.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(studio-server): let an opaque capture wait for a video's preview copy

A video the browser cannot decode is drawn from its `?hf-proxy=` copy. The
runtime waits for that copy with a ranged fetch, preflighted when it carries
the priority header. In the opaque capture page both failed, so each such
thumbnail fell back to a still after about five seconds of retries.

The renderer now answers that preflight itself. It also exposes the copy's
status headers to the wait, for video files under the preview path only.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* refactor(studio-server): keep capture-load comments within the package share

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(studio-server): keep video pixels and project fetches in opaque thumbnail captures

- Media loads: the renderer now grants them, and a capture document loads the
  project's own videos with `crossorigin="anonymous"`. Color grading and shader
  textures can then read their pixels.
- Fetches: every GET of the project's preview files is granted, except a dotfile
  or dot-folder path such as `.env` or `.git/`. This covers the models and fonts
  that registry blocks fetch at runtime.
- Opt-in: the capture sandbox is now a `createStudioApi` option,
  `sandboxThumbnailCaptures`, off by default. The CLI Studio server and the Vite
  dev server turn it on, because their thumbnail renderers install the grant.
  Another app keeps its current capture documents until its renderer does the
  same.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(shader-transitions): prepare transitions when IndexedDB is denied

An opaque-origin document, such as a sandboxed preview or thumbnail capture,
has no IndexedDB, and opening it throws. The snapshot cache now treats that
as no cache, so the transitions still prepare and draw.

Thumbnail captures also grant a CORS read of a missing preview file, so a
fetch() sees its status as a same-origin page would.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(studio-server): leave a video with another host's <source> out of capture CORS

A video whose <source> child points to another host now keeps its plain
load in a thumbnail capture. Adding crossorigin to it would make a CDN
that sends no CORS headers refuse the video, leaving the clip blank.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 07:50:59 +00:00

253 lines
8.8 KiB
TypeScript

import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
import { join } from "node:path";
const browserMocks = vi.hoisted(() => {
const cdp = { send: vi.fn(async (_method: string) => undefined), on: vi.fn() };
const page = {
createCDPSession: vi.fn(async () => cdp),
setViewport: vi.fn(async () => {}),
goto: vi.fn(async () => {}),
evaluate: vi.fn(async () => undefined),
waitForFunction: vi.fn(async () => undefined),
addScriptTag: vi.fn(async () => undefined),
screenshot: vi.fn(async () => Buffer.from("thumbnail")),
close: vi.fn(async () => {}),
};
const newPage = vi.fn(async () => page);
const sharedBrowser = { connected: true as boolean, newPage };
const launch = vi.fn(async () => sharedBrowser);
const versionProbe = vi.fn(() => "150.0.0.0");
return { cdp, launch, newPage, page, sharedBrowser, versionProbe };
});
vi.mock("puppeteer-core", () => ({ default: { launch: browserMocks.launch } }));
vi.mock("node:child_process", async (original) => ({
...(await original<typeof import("node:child_process")>()),
execFileSync: browserMocks.versionProbe,
}));
import { findSystemChrome, generateThumbnail, type GenerateThumbnailOptions } from "./vite.browser";
const originalBrowserPath = process.env["HYPERFRAMES_BROWSER_PATH"];
const controllers: AbortController[] = [];
function options(signal = trackedSignal()): GenerateThumbnailOptions {
return {
project: { dir: process.cwd() },
compPath: "index.html",
seekTime: 1,
previewUrl: "http://localhost/preview",
width: 1920,
height: 1080,
outputWidth: 240,
outputHeight: 135,
format: "jpeg",
signal,
};
}
function trackedSignal(): AbortSignal {
const controller = new AbortController();
controllers.push(controller);
return controller.signal;
}
describe("generateThumbnail", () => {
beforeAll(async () => {
process.env["HYPERFRAMES_BROWSER_PATH"] = process.execPath;
// generateThumbnail loads puppeteer lazily; the first load is slow on a cold Windows runner.
await import("puppeteer-core");
}, 60_000);
beforeEach(() => {
browserMocks.launch.mockReset().mockResolvedValue(browserMocks.sharedBrowser);
browserMocks.newPage.mockClear();
browserMocks.versionProbe.mockClear();
for (const mock of Object.values(browserMocks.page)) mock.mockClear();
browserMocks.cdp.send.mockClear();
});
afterEach(() => {
// Cancel any request a timed-out test left running, so it cannot close pages in the next test.
for (const controller of controllers.splice(0)) controller.abort();
});
afterAll(() => {
if (originalBrowserPath === undefined) delete process.env["HYPERFRAMES_BROWSER_PATH"];
else process.env["HYPERFRAMES_BROWSER_PATH"] = originalBrowserPath;
});
it("contains a transient browser launch failure and retries the next request", async () => {
browserMocks.launch.mockRejectedValueOnce(new Error("launch failed"));
await expect(generateThumbnail(options())).resolves.toBeNull();
await expect(generateThumbnail(options())).resolves.toEqual(Buffer.from("thumbnail"));
expect(browserMocks.launch).toHaveBeenCalledTimes(2);
});
it("blocks on the browser's version only to word a failure, and only once", async () => {
const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
// An earlier test's browser would skip the launch.
browserMocks.sharedBrowser.connected = false;
browserMocks.launch.mockImplementationOnce(async () => {
browserMocks.sharedBrowser.connected = true;
return browserMocks.sharedBrowser;
});
await expect(generateThumbnail(options())).resolves.toEqual(Buffer.from("thumbnail"));
expect(browserMocks.launch).toHaveBeenCalledTimes(1);
expect(browserMocks.versionProbe).not.toHaveBeenCalled();
browserMocks.page.goto.mockRejectedValueOnce(new Error("page failed"));
browserMocks.page.goto.mockRejectedValueOnce(new Error("page failed again"));
await generateThumbnail(options());
await generateThumbnail(options());
expect(warn).toHaveBeenCalledWith(expect.stringContaining("150.0.0.0"), "page failed again");
expect(browserMocks.versionProbe).toHaveBeenCalledTimes(1);
warn.mockRestore();
});
it("grants the capture page's loads on its own session before it navigates", async () => {
const previewUrl = "http://127.0.0.1:5190/api/projects/demo/preview?hf-capture=1";
await expect(generateThumbnail({ ...options(), previewUrl })).resolves.toEqual(
Buffer.from("thumbnail"),
);
const enable = browserMocks.cdp.send.mock.calls.findIndex(
([method]) => method === "Fetch.enable",
);
expect(enable).toBeGreaterThanOrEqual(0);
expect(browserMocks.cdp.send.mock.invocationCallOrder[enable]).toBeLessThan(
browserMocks.page.goto.mock.invocationCallOrder[0]!,
);
expect(browserMocks.page.goto).toHaveBeenCalledWith(previewUrl, expect.anything());
});
it("captures at the route-provided physical output size", async () => {
await expect(generateThumbnail(options())).resolves.toEqual(Buffer.from("thumbnail"));
expect(browserMocks.page.setViewport).toHaveBeenCalledWith({
width: 1920,
height: 1080,
deviceScaleFactor: 0.125,
});
expect(browserMocks.page.close).toHaveBeenCalledTimes(1);
});
it("lets the route own dedupe and closes browser work on cancellation", async () => {
const controller = new AbortController();
const cancelled = generateThumbnail(options(controller.signal));
await vi.waitFor(() => expect(browserMocks.newPage).toHaveBeenCalledTimes(1));
controller.abort();
await expect(cancelled).resolves.toBeNull();
expect(browserMocks.page.close).toHaveBeenCalled();
browserMocks.newPage.mockClear();
await Promise.all([generateThumbnail(options()), generateThumbnail(options())]);
expect(browserMocks.newPage).toHaveBeenCalledTimes(2);
});
it("contains a canceled screenshot without crashing the dev server", async () => {
const controller = new AbortController();
let rejectScreenshot: ((reason: Error) => void) | undefined;
browserMocks.page.screenshot.mockImplementationOnce(
() =>
new Promise<Buffer>((_resolve, reject) => {
rejectScreenshot = reject;
}),
);
browserMocks.page.close.mockImplementationOnce(async () => {
rejectScreenshot?.(new Error("Target closed"));
});
const thumbnail = generateThumbnail(options(controller.signal));
const result = expect(thumbnail).resolves.toBeNull();
await vi.waitFor(() => expect(browserMocks.page.screenshot).toHaveBeenCalledTimes(1));
controller.abort();
await result;
});
});
describe("findSystemChrome", () => {
it("uses the CLI browser override before legacy producer and system paths", () => {
const pathExists = vi.fn(() => true);
expect(
findSystemChrome(
{
HYPERFRAMES_BROWSER_PATH: "/custom/browser",
PRODUCER_HEADLESS_SHELL_PATH: "/legacy/browser",
},
pathExists,
),
).toBe("/custom/browser");
expect(pathExists).toHaveBeenCalledTimes(1);
});
it("finds a standard Windows Chrome installation", () => {
const chromePath = "C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe";
const pathExists = vi.fn((path: string) => path === chromePath);
expect(findSystemChrome({}, pathExists, "win32", () => "Chrome/140.0.1")).toBe(chromePath);
});
it("prefers the newest Puppeteer cache entry over a compatible system Chrome", () => {
const cachePath = join(
"/tmp/puppeteer",
"chrome",
"chrome-152.0.1",
"chrome-linux64",
"chrome",
);
const systemPath = "/usr/bin/google-chrome";
const pathExists = vi.fn((path: string) => path === cachePath || path === systemPath);
expect(
findSystemChrome(
{ PUPPETEER_CACHE_DIR: "/tmp/puppeteer" },
pathExists,
"linux",
() => "Chrome/113.0.1",
() => ["chrome-152.0.1"],
),
).toBe(cachePath);
});
it("uses Puppeteer's Windows cache executable layout", () => {
const cachePath = join(
"C:\\puppeteer",
"chrome",
"chrome-152.0.1",
"chrome-win64",
"chrome.exe",
);
const pathExists = vi.fn((path: string) => path === cachePath);
expect(
findSystemChrome(
{ PUPPETEER_CACHE_DIR: "C:\\puppeteer" },
pathExists,
"win32",
() => "Chrome/113.0.1",
() => ["chrome-152.0.1"],
),
).toBe(cachePath);
});
it("rejects a system Chrome older than the Puppeteer-supported major", () => {
const systemPath = "/usr/bin/google-chrome";
const pathExists = vi.fn((path: string) => path === systemPath);
expect(
findSystemChrome(
{},
pathExists,
"linux",
() => "Google Chrome 113.0.1",
() => [],
),
).toBe(undefined);
});
});