mirror of
https://github.com/heygen-com/hyperframes.git
synced 2026-11-18 16:08:56 +00:00
* 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>
1314 lines
52 KiB
TypeScript
1314 lines
52 KiB
TypeScript
import {
|
|
waitForRenderCancellation,
|
|
cancelAndVerifyArtifacts,
|
|
} from "../../../../test-utils/renderCancellation";
|
|
import { EventEmitter } from "node:events";
|
|
import { afterEach, describe, expect, it, vi } from "vitest";
|
|
import {
|
|
existsSync,
|
|
mkdirSync,
|
|
mkdtempSync,
|
|
readdirSync,
|
|
readFileSync,
|
|
renameSync,
|
|
rmSync,
|
|
symlinkSync,
|
|
writeFileSync,
|
|
} from "node:fs";
|
|
import { tmpdir } from "node:os";
|
|
import { basename, join } from "node:path";
|
|
import {
|
|
createProjectSignature,
|
|
fileContentVersion,
|
|
HistoryBusyError,
|
|
HistoryClosedError,
|
|
} from "@hyperframes/studio-server";
|
|
import { loadHyperframeRuntimeSource } from "@hyperframes/core";
|
|
import { loadRuntimeSource } from "./runtimeSource.js";
|
|
import { findFFmpeg, findFFprobe } from "../browser/ffmpeg.js";
|
|
import { createStudioServer, type StudioServer } from "./studioServer.js";
|
|
|
|
// Forces loadStudioProducer() down its production import branch (real
|
|
// isDevMode() is true for a .ts test file, which instead throws a
|
|
// "requires bun" error before ever reaching executeRenderJob — see
|
|
// studioServer.ts's loadStudioProducer). Only startRender reads this.
|
|
vi.mock("../utils/env.js", () => ({ isDevMode: () => false }));
|
|
|
|
const producerState = vi.hoisted(() => ({
|
|
// Set per-test to control when the render "finishes" so a shutdown that
|
|
// races an in-flight render is observable instead of vacuous.
|
|
executeRenderJob: (
|
|
_job: unknown,
|
|
_dir: string,
|
|
_outputPath: string,
|
|
_onProgress: unknown,
|
|
_signal: AbortSignal,
|
|
): Promise<void> => Promise.resolve(),
|
|
}));
|
|
vi.mock("@hyperframes/producer", () => ({
|
|
createRenderJob: (opts: Record<string, unknown>) => ({ ...opts, perfSummary: undefined }),
|
|
executeRenderJob: (...args: Parameters<typeof producerState.executeRenderJob>) =>
|
|
producerState.executeRenderJob(...args),
|
|
}));
|
|
// Stand-ins for the HEIF and GIF steps: each writes a converted file where a real conversion would.
|
|
const imagePrep = vi.hoisted(() => ({
|
|
convert: async (html: string, options: { outputDir: string }) => {
|
|
const { mkdirSync, writeFileSync } = await import("node:fs");
|
|
mkdirSync(options.outputDir, { recursive: true });
|
|
writeFileSync(`${options.outputDir}/converted`, "image");
|
|
return { html, preparedAssets: new Map<string, string>() };
|
|
},
|
|
}));
|
|
vi.mock("../../../producer/src/services/heifImagePrep.js", () => ({
|
|
prepareHeifImageInputs: async (html: string, options: { outputDir: string }) => ({
|
|
...(await imagePrep.convert(html, options)),
|
|
preparedImages: [],
|
|
}),
|
|
}));
|
|
vi.mock("../../../producer/src/services/animatedGifPrep.js", () => ({
|
|
prepareAnimatedGifInputs: async (html: string, options: { outputDir: string }) => ({
|
|
...(await imagePrep.convert(html, options)),
|
|
preparedGifs: [],
|
|
}),
|
|
}));
|
|
const engineState = vi.hoisted(() => ({
|
|
acquireBrowser: async (..._args: unknown[]): Promise<unknown> => {
|
|
throw new Error("acquireBrowser called without a test double");
|
|
},
|
|
closeBrowserPool: async (): Promise<void> => {},
|
|
}));
|
|
vi.mock("@hyperframes/engine", () => ({
|
|
acquireBrowser: (...args: unknown[]) => engineState.acquireBrowser(...args),
|
|
buildChromeArgs: () => [],
|
|
killTrackedProcesses: () => {},
|
|
closeBrowserPool: () => engineState.closeBrowserPool(),
|
|
getSystemTotalMb: () => 0,
|
|
}));
|
|
vi.mock("../browser/gpuPolicy.js", () => ({
|
|
resolveCaptureBrowserGpuMode: async () => "software",
|
|
resolveLocalBrowserGpuMode: () => "software",
|
|
compositionRequiresWebGpu: () => false,
|
|
assertWebGpuAdapterAvailable: async () => {},
|
|
resolveLocalWebGpu: (browserGpuMode: string) => ({
|
|
gpuConfig: { browserGpuMode, allowSoftwareWebGpu: false },
|
|
softwareWebGpu: false,
|
|
}),
|
|
}));
|
|
vi.mock("../browser/preflight.js", async (importOriginal) => ({
|
|
...(await importOriginal<typeof import("../browser/preflight.js")>()),
|
|
resolveRenderBrowser: async () => ({ executablePath: "/fake/chrome", source: "system" }),
|
|
}));
|
|
vi.mock("../browser/manager.js", () => ({
|
|
ensureBrowser: async () => ({ executablePath: undefined, source: "system" }),
|
|
}));
|
|
|
|
const cpuSamplerState = vi.hoisted(() => ({
|
|
samplers: [] as { requesterOptedIn: boolean; stopped: boolean }[],
|
|
}));
|
|
vi.mock("../telemetry/renderCpu.js", () => ({
|
|
startRenderCpuSampler: (requesterOptedIn = true) => {
|
|
const sampler = { requesterOptedIn, stopped: false };
|
|
cpuSamplerState.samplers.push(sampler);
|
|
return {
|
|
stop: () => {
|
|
sampler.stopped = true;
|
|
return { cpuBusyAvgPct: 57, cpuBusyPeakPct: 90 };
|
|
},
|
|
};
|
|
},
|
|
}));
|
|
|
|
// Lets one test hold the project history in its opening; every other test opens the real one.
|
|
const historyState = vi.hoisted(() => ({
|
|
open: null as null | ((...args: unknown[]) => Promise<unknown>),
|
|
}));
|
|
vi.mock("@hyperframes/studio-server", async (importOriginal) => {
|
|
const original = await importOriginal<typeof import("@hyperframes/studio-server")>();
|
|
return {
|
|
...original,
|
|
createProjectSignature: vi.fn(original.createProjectSignature),
|
|
openProjectHistory: (...args: Parameters<typeof original.openProjectHistory>) =>
|
|
historyState.open ? historyState.open(...args) : original.openProjectHistory(...args),
|
|
};
|
|
});
|
|
|
|
// Only `fs.watch` is replaced, so the SSE describe below can fire a file-change
|
|
// on demand; every other server test keeps reading and writing real files.
|
|
const mockWatcher = new EventEmitter() as EventEmitter & { close: () => void };
|
|
mockWatcher.close = vi.fn();
|
|
|
|
vi.mock("node:fs", async (importOriginal) => {
|
|
const original = await importOriginal<typeof import("node:fs")>();
|
|
const watch = vi.fn(
|
|
(_path: string, _options: unknown, onChange: (event: string, filename: string) => void) => {
|
|
mockWatcher.on("change", onChange);
|
|
return mockWatcher;
|
|
},
|
|
);
|
|
return { ...original, default: { ...original, watch }, watch };
|
|
});
|
|
|
|
// Every server-backed describe below wants the same two things: a throwaway
|
|
// project directory, and a server whose watcher is closed afterwards. Three
|
|
// copies of that got out of step, so it lives here once.
|
|
const dirs: string[] = [];
|
|
let server: StudioServer | undefined;
|
|
|
|
function tmpProject(): string {
|
|
const dir = mkdtempSync(join(tmpdir(), "hf-studio-server-test-"));
|
|
dirs.push(dir);
|
|
return dir;
|
|
}
|
|
|
|
const openReaders: ReadableStreamDefaultReader<Uint8Array>[] = [];
|
|
|
|
afterEach(async () => {
|
|
await Promise.all(openReaders.splice(0).map((reader) => reader.cancel().catch(() => {})));
|
|
mockWatcher.removeAllListeners();
|
|
server?.watcher.close();
|
|
server = undefined;
|
|
delete process.env.HYPERFRAMES_FFMPEG_PATH;
|
|
delete process.env.HYPERFRAMES_FFPROBE_PATH;
|
|
for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true });
|
|
});
|
|
|
|
describe("loadRuntimeSource", () => {
|
|
it("loads runtime source from the published core entrypoint", async () => {
|
|
await expect(loadRuntimeSource()).resolves.toBe(loadHyperframeRuntimeSource());
|
|
});
|
|
});
|
|
|
|
describe("Studio thumbnail GPU capture plumbing", () => {
|
|
it("uses the shared auto probe, resolved launch mode, requirement guard, and completion-aware seek", () => {
|
|
const source = readFileSync(new URL("./studioServer.ts", import.meta.url), "utf8");
|
|
expect(source).toContain("resolveCaptureBrowserGpuMode");
|
|
expect(source).toContain("resolveLocalWebGpu(resolvedGpuMode, true)");
|
|
expect(source).toContain("requiresWebGpu && session.softwareWebGpu");
|
|
expect(source).toContain("await seekCompositionTimeline(page, opts.seekTime");
|
|
});
|
|
});
|
|
|
|
describe("createStudioServer project history (D-491)", () => {
|
|
it("serves the project's history, and a change the watcher sees becomes an entry", async () => {
|
|
const projectDir = tmpProject();
|
|
writeFileSync(join(projectDir, "index.html"), "<html>before</html>");
|
|
server = createStudioServer({ projectDir, historyRoot: tmpProject() });
|
|
const historyUrl = `/api/projects/${encodeURIComponent(basename(projectDir))}/history`;
|
|
const list = async () =>
|
|
(await (await server!.app.request(historyUrl)).json()) as {
|
|
entries: Array<{ who: { kind: string } }>;
|
|
back: { label: string } | null;
|
|
};
|
|
expect(await list()).toMatchObject({ entries: [], back: null });
|
|
|
|
writeFileSync(join(projectDir, "index.html"), "<html>agent</html>");
|
|
mockWatcher.emit("change", "change", "index.html");
|
|
|
|
// Writes with no window open group until 2 s of quiet.
|
|
await vi.waitFor(async () => expect((await list()).entries).toHaveLength(1), {
|
|
timeout: 5_000,
|
|
interval: 200,
|
|
});
|
|
expect((await list()).entries[0]!.who.kind).toBe("outside");
|
|
await server.shutdown();
|
|
});
|
|
|
|
it.each([
|
|
["another process was holding", new HistoryBusyError(1)],
|
|
["whose folder changed while it opened", new HistoryClosedError("now another project")],
|
|
])(
|
|
"tries a history %s again on the next request, instead of turning it off",
|
|
async (_, refusal) => {
|
|
historyState.open = async () => {
|
|
historyState.open = null;
|
|
throw refusal;
|
|
};
|
|
const projectDir = tmpProject();
|
|
server = createStudioServer({ projectDir, historyRoot: tmpProject() });
|
|
const historyUrl = `/api/projects/${encodeURIComponent(basename(projectDir))}/history`;
|
|
expect((await server.app.request(historyUrl)).status).toBe(404);
|
|
expect((await server.app.request(historyUrl)).status).toBe(200);
|
|
await server.shutdown();
|
|
},
|
|
);
|
|
|
|
// A preview an agent starts inside a host app's run can outlive it; holding the lock, it refused every later run.
|
|
it("never opens the history inside a host app's run, which owns it", async () => {
|
|
const opens: unknown[] = [];
|
|
historyState.open = async (options) => {
|
|
opens.push(options);
|
|
throw new Error("the history was opened");
|
|
};
|
|
vi.stubEnv("HYPERFRAMES_DESKTOP_PROJECT", "/a/project");
|
|
try {
|
|
const projectDir = tmpProject();
|
|
server = createStudioServer({ projectDir, historyRoot: tmpProject() });
|
|
const historyUrl = `/api/projects/${encodeURIComponent(basename(projectDir))}/history`;
|
|
expect((await server.app.request(historyUrl)).status).toBe(404);
|
|
expect(opens).toEqual([]);
|
|
await server.shutdown();
|
|
} finally {
|
|
vi.unstubAllEnvs();
|
|
historyState.open = null;
|
|
}
|
|
});
|
|
|
|
it("never makes a request wait on another process's history lock again once it was busy", async () => {
|
|
const waits: unknown[] = [];
|
|
historyState.open = async (options) => {
|
|
waits.push((options as { ownerWaitMs?: number }).ownerWaitMs);
|
|
throw new HistoryBusyError(1);
|
|
};
|
|
const projectDir = tmpProject();
|
|
server = createStudioServer({ projectDir, historyRoot: tmpProject() });
|
|
const historyUrl = `/api/projects/${encodeURIComponent(basename(projectDir))}/history`;
|
|
await server.app.request(historyUrl);
|
|
await server.app.request(historyUrl);
|
|
historyState.open = null;
|
|
expect(waits).toEqual([undefined, 0]);
|
|
await server.shutdown();
|
|
});
|
|
|
|
it("waits for the history lock again once a history opened after a busy one", async () => {
|
|
const waits: unknown[] = [];
|
|
const reopenable = { replacedAtPath: () => true, close: async () => {} };
|
|
let opens = 0;
|
|
historyState.open = async (options) => {
|
|
waits.push((options as { ownerWaitMs?: number }).ownerWaitMs);
|
|
opens += 1;
|
|
if (opens === 1) throw new HistoryBusyError(1);
|
|
if (opens === 2) return reopenable;
|
|
historyState.open = null;
|
|
throw new HistoryBusyError(1);
|
|
};
|
|
const projectDir = tmpProject();
|
|
server = createStudioServer({ projectDir, historyRoot: tmpProject() });
|
|
const historyUrl = `/api/projects/${encodeURIComponent(basename(projectDir))}/history`;
|
|
await server.app.request(historyUrl);
|
|
await server.app.request(historyUrl);
|
|
historyState.open = null;
|
|
expect(waits).toEqual([undefined, 0, undefined]);
|
|
await server.shutdown();
|
|
});
|
|
|
|
it("opens a new project's own history once it takes the folder's path", async () => {
|
|
const projectDir = tmpProject();
|
|
writeFileSync(join(projectDir, "index.html"), "<html>before</html>");
|
|
server = createStudioServer({ projectDir, historyRoot: tmpProject() });
|
|
const historyUrl = `/api/projects/${encodeURIComponent(basename(projectDir))}/history`;
|
|
expect((await server.app.request(historyUrl)).status).toBe(200);
|
|
renameSync(projectDir, `${projectDir}-moved`);
|
|
dirs.push(`${projectDir}-moved`);
|
|
mkdirSync(projectDir);
|
|
writeFileSync(join(projectDir, "index.html"), "<html>new</html>");
|
|
|
|
expect((await server.app.request(historyUrl)).status).toBe(200);
|
|
expect(existsSync(join(projectDir, ".hyperframes", "history-id"))).toBe(true);
|
|
await server.shutdown();
|
|
});
|
|
|
|
it("shutdown returns within preview's exit watchdog while the history is still opening", async () => {
|
|
historyState.open = () => new Promise(() => {});
|
|
try {
|
|
const projectDir = tmpProject();
|
|
server = createStudioServer({ projectDir, historyRoot: tmpProject() });
|
|
void server.app.request(`/api/projects/${encodeURIComponent(basename(projectDir))}/history`);
|
|
await new Promise((resolve) => setTimeout(resolve, 50));
|
|
const started = Date.now();
|
|
await server.shutdown();
|
|
expect(Date.now() - started).toBeLessThan(2_900);
|
|
} finally {
|
|
historyState.open = null;
|
|
}
|
|
});
|
|
});
|
|
|
|
describe("createStudioServer autoProxy plumbing", () => {
|
|
it("hyperframes.json media.autoProxy=false flows through to the adapter", () => {
|
|
const projectDir = tmpProject();
|
|
writeFileSync(
|
|
join(projectDir, "hyperframes.json"),
|
|
JSON.stringify({ media: { autoProxy: false } }),
|
|
);
|
|
|
|
server = createStudioServer({ projectDir });
|
|
|
|
expect(server.adapter.autoProxy).toBe(false);
|
|
});
|
|
|
|
it("defaults the adapter to autoProxy=true when neither option nor config disables it", () => {
|
|
server = createStudioServer({ projectDir: tmpProject() });
|
|
expect(server.adapter.autoProxy).toBe(true);
|
|
});
|
|
|
|
it("an explicit option (the preview command's resolved --proxy flag) wins over config", () => {
|
|
const projectDir = tmpProject();
|
|
writeFileSync(
|
|
join(projectDir, "hyperframes.json"),
|
|
JSON.stringify({ media: { autoProxy: false } }),
|
|
);
|
|
|
|
server = createStudioServer({ projectDir, autoProxy: true });
|
|
|
|
expect(server.adapter.autoProxy).toBe(true);
|
|
});
|
|
|
|
it("advertises the GPU policy used for thumbnail capture", async () => {
|
|
const projectDir = tmpProject();
|
|
server = createStudioServer({ projectDir, browserGpuMode: "software" });
|
|
|
|
const response = await server.app.request("/__hyperframes_config");
|
|
|
|
expect(response.status).toBe(200);
|
|
await expect(response.json()).resolves.toMatchObject({ browserGpuMode: "software" });
|
|
});
|
|
});
|
|
|
|
// A render that never reaches the executor (browser check refused, import failed) must fail with
|
|
// its reason, not hang until the suite timeout.
|
|
async function untilStarted(started: Promise<void>, state: { status: string; error?: string }) {
|
|
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
const never = new Promise<never>((_, reject) => {
|
|
timer = setTimeout(
|
|
() =>
|
|
reject(
|
|
new Error(
|
|
`render never reached executeRenderJob: status=${state.status} error=${state.error}`,
|
|
),
|
|
),
|
|
5_000,
|
|
);
|
|
});
|
|
try {
|
|
await Promise.race([started, never]);
|
|
} finally {
|
|
clearTimeout(timer);
|
|
}
|
|
}
|
|
|
|
describe("createStudioServer shutdown", () => {
|
|
function startRenderOpts(jobId: string, outputPath: string) {
|
|
return {
|
|
project: { id: "demo", dir: tmpProject(), title: "demo" },
|
|
outputPath,
|
|
format: "mp4" as const,
|
|
fps: { num: 30, den: 1 },
|
|
quality: "draft",
|
|
jobId,
|
|
};
|
|
}
|
|
|
|
it("hands the limiter's audioLoweredDb to the job state and the render sidecar", async () => {
|
|
producerState.executeRenderJob = async (job) => {
|
|
if (typeof job === "object" && job !== null) Reflect.set(job, "audioLoweredDb", 1.44);
|
|
};
|
|
const outputPath = join(mkdtempSync(join(tmpdir(), "hf-lowered-")), "out.mp4");
|
|
server = createStudioServer({ projectDir: tmpProject() });
|
|
const state = server.adapter.startRender(startRenderOpts("job-lowered", outputPath));
|
|
await vi.waitFor(() => expect(state.status, state.error).toBe("complete"), { timeout: 5_000 });
|
|
expect(state.audioLoweredDb).toBe(1.44);
|
|
const meta = JSON.parse(readFileSync(outputPath.replace(/\.mp4$/, ".meta.json"), "utf8"));
|
|
expect(meta.audioLoweredDb).toBe(1.44);
|
|
});
|
|
|
|
it("stops measuring CPU however a render ends, and never for an opted-out requester", async () => {
|
|
cpuSamplerState.samplers = [];
|
|
const outDir = mkdtempSync(join(tmpdir(), "hf-render-cpu-"));
|
|
server = createStudioServer({ projectDir: tmpProject() });
|
|
|
|
producerState.executeRenderJob = async () => {};
|
|
const done = server.adapter.startRender(startRenderOpts("job-done", join(outDir, "a.mp4")));
|
|
await vi.waitFor(() => expect(done.status, done.error).toBe("complete"), { timeout: 5_000 });
|
|
|
|
producerState.executeRenderJob = async () => {
|
|
throw new Error("boom");
|
|
};
|
|
const failed = server.adapter.startRender({
|
|
...startRenderOpts("job-failed", join(outDir, "b.mp4")),
|
|
telemetryOptOut: true,
|
|
});
|
|
await vi.waitFor(() => expect(failed.status).toBe("failed"), { timeout: 5_000 });
|
|
|
|
let started!: () => void;
|
|
const startedPromise = new Promise<void>((resolve) => {
|
|
started = resolve;
|
|
});
|
|
producerState.executeRenderJob = (_job, _dir, _outputPath, _onProgress, signal) => {
|
|
started();
|
|
return new Promise((_resolve, reject) => {
|
|
const onAbort = () => reject(Object.assign(new Error("cancelled"), { name: "AbortError" }));
|
|
if (signal.aborted) onAbort();
|
|
else signal.addEventListener("abort", onAbort);
|
|
});
|
|
};
|
|
const cancelled = server.adapter.startRender(
|
|
startRenderOpts("job-cancelled", join(outDir, "c.mp4")),
|
|
);
|
|
await untilStarted(startedPromise, cancelled);
|
|
cancelled.cancel?.();
|
|
await vi.waitFor(() => expect(cancelled.status).toBe("cancelled"), { timeout: 5_000 });
|
|
|
|
expect(cpuSamplerState.samplers).toEqual([
|
|
{ requesterOptedIn: true, stopped: true },
|
|
{ requesterOptedIn: false, stopped: true },
|
|
{ requesterOptedIn: true, stopped: true },
|
|
]);
|
|
rmSync(outDir, { recursive: true, force: true });
|
|
});
|
|
|
|
it("forwards GIF loop count and writes a metadata sidecar without overwriting output", async () => {
|
|
producerState.executeRenderJob = async (job, _dir, outputPath) => {
|
|
expect(job).toMatchObject({ format: "gif", gifLoop: 3 });
|
|
writeFileSync(outputPath, "GIF89a");
|
|
};
|
|
const projectDir = tmpProject();
|
|
const outputPath = join(projectDir, "out.gif");
|
|
server = createStudioServer({ projectDir });
|
|
const state = server.adapter.startRender({
|
|
...startRenderOpts("gif-job", outputPath),
|
|
format: "gif",
|
|
gifLoop: 3,
|
|
});
|
|
await vi.waitFor(() => expect(state.status, state.error).toBe("complete"));
|
|
expect(readFileSync(outputPath, "utf8")).toBe("GIF89a");
|
|
expect(JSON.parse(readFileSync(join(projectDir, "out.meta.json"), "utf8"))).toMatchObject({
|
|
status: "complete",
|
|
});
|
|
});
|
|
|
|
it.each([false, true])(
|
|
"removes cancelled GIF output and sidecar (late completion: %s)",
|
|
async (lateCompletion) => {
|
|
const projectDir = tmpProject();
|
|
const outputPath = join(projectDir, "out.gif");
|
|
const metaPath = join(projectDir, "out.meta.json");
|
|
producerState.executeRenderJob = async (_job, _dir, output, _progress, signal) => {
|
|
writeFileSync(output, "partial-gif");
|
|
writeFileSync(metaPath, "{}");
|
|
await waitForRenderCancellation(signal, lateCompletion);
|
|
};
|
|
server = createStudioServer({ projectDir });
|
|
const state = server.adapter.startRender({
|
|
...startRenderOpts("gif-job", outputPath),
|
|
format: "gif",
|
|
});
|
|
await cancelAndVerifyArtifacts(state, outputPath, metaPath);
|
|
},
|
|
);
|
|
|
|
it("cancels an in-flight render's signal and waits for it before draining the browser pool", async () => {
|
|
const events: string[] = [];
|
|
let started!: () => void;
|
|
const startedPromise = new Promise<void>((resolve) => {
|
|
started = resolve;
|
|
});
|
|
producerState.executeRenderJob = (_job, _dir, _outputPath, _onProgress, signal) => {
|
|
started();
|
|
return new Promise((_resolve, reject) => {
|
|
const onAbort = () =>
|
|
setTimeout(() => {
|
|
events.push("render-settled");
|
|
reject(Object.assign(new Error("cancelled"), { name: "AbortError" }));
|
|
}, 20);
|
|
// A signal aborted before this executor ran would never fire a later
|
|
// "abort" listener (edge-triggered, not level-triggered) — check the
|
|
// already-aborted case too, same as real capture code must.
|
|
if (signal.aborted) onAbort();
|
|
else signal.addEventListener("abort", onAbort);
|
|
});
|
|
};
|
|
|
|
server = createStudioServer({ projectDir: tmpProject() });
|
|
const outputPath = join(tmpdir(), "shutdown-render.mp4");
|
|
const state = server.adapter.startRender(startRenderOpts("job-1", outputPath));
|
|
expect(state.status).toBe("rendering");
|
|
|
|
// Wait until the render has actually reached executeRenderJob (several
|
|
// microtask hops through loadStudioProducer/ensureBrowser) before racing
|
|
// it against shutdown, or shutdown could abort a signal nothing is
|
|
// listening on yet — a race in this test, not in the fix under test.
|
|
await untilStarted(startedPromise, state);
|
|
|
|
await server.shutdown();
|
|
events.push("drain-and-shutdown-returned");
|
|
|
|
expect(events).toEqual(["render-settled", "drain-and-shutdown-returned"]);
|
|
});
|
|
|
|
it("refuses a render started after shutdown has begun instead of launching a fresh browser", async () => {
|
|
let releaseFirstRender: () => void = () => {};
|
|
let started!: () => void;
|
|
const startedPromise = new Promise<void>((resolve) => {
|
|
started = resolve;
|
|
});
|
|
producerState.executeRenderJob = () => {
|
|
started();
|
|
return new Promise<void>((resolve) => {
|
|
releaseFirstRender = resolve;
|
|
});
|
|
};
|
|
|
|
server = createStudioServer({ projectDir: tmpProject() });
|
|
const first = server.adapter.startRender(startRenderOpts("job-1", join(tmpdir(), "a.mp4")));
|
|
await untilStarted(startedPromise, first);
|
|
|
|
const shutdownPromise = server.shutdown();
|
|
// shuttingDown is set synchronously as shutdown()'s first statement, so a
|
|
// render request arriving anywhere after that call has been made (even
|
|
// before it resolves) must already see it.
|
|
const late = server.adapter.startRender(startRenderOpts("job-2", join(tmpdir(), "b.mp4")));
|
|
|
|
expect(late.status).toBe("failed");
|
|
expect(late.error).toMatch(/shutting down/i);
|
|
|
|
releaseFirstRender();
|
|
await shutdownPromise;
|
|
});
|
|
|
|
const thumbnailOpts = () => ({
|
|
project: { id: "demo", dir: tmpProject(), title: "demo" },
|
|
compPath: "index.html",
|
|
seekTime: 0.5,
|
|
width: 640,
|
|
height: 360,
|
|
outputWidth: 640,
|
|
outputHeight: 360,
|
|
previewUrl: "http://localhost/preview",
|
|
signal: new AbortController().signal,
|
|
});
|
|
|
|
it("does not launch a browser for a thumbnail request after shutdown has begun", async () => {
|
|
const acquire = vi.fn();
|
|
engineState.acquireBrowser = acquire;
|
|
server = createStudioServer({ projectDir: tmpProject() });
|
|
await server.shutdown();
|
|
|
|
await expect(server.adapter.generateThumbnail?.(thumbnailOpts())).resolves.toBeNull();
|
|
expect(acquire).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("releases a thumbnail browser that finished launching after shutdown began", async () => {
|
|
const release = vi.fn(async () => {});
|
|
let launched!: () => void;
|
|
const launchedPromise = new Promise<void>((resolve) => (launched = resolve));
|
|
let finishLaunch: () => void = () => {};
|
|
engineState.acquireBrowser = async () => {
|
|
launched();
|
|
await new Promise<void>((resolve) => (finishLaunch = resolve));
|
|
return { browser: new EventEmitter(), release };
|
|
};
|
|
let reachedBrowserClose!: () => void;
|
|
const reachedBrowserClosePromise = new Promise<void>(
|
|
(resolve) => (reachedBrowserClose = resolve),
|
|
);
|
|
engineState.closeBrowserPool = async () => reachedBrowserClose();
|
|
server = createStudioServer({ projectDir: tmpProject() });
|
|
const thumbnail = server.adapter.generateThumbnail?.(thumbnailOpts());
|
|
await launchedPromise;
|
|
|
|
const shutdown = server.shutdown();
|
|
// shutdown() starts the pool close alongside the thumbnail-browser close,
|
|
// before it waits on renders: closing is the signal the close has begun
|
|
// while the launch is still pending, without racing a fixed sleep.
|
|
await reachedBrowserClosePromise;
|
|
finishLaunch();
|
|
await shutdown;
|
|
|
|
await expect(thumbnail).resolves.toBeNull();
|
|
expect(release).toHaveBeenCalledTimes(1);
|
|
});
|
|
|
|
it("closes browsers within a bounded timeout even when a render's done promise never settles", async () => {
|
|
const closeBrowserPool = vi.fn(async () => {});
|
|
engineState.closeBrowserPool = closeBrowserPool;
|
|
const release = vi.fn(async () => {});
|
|
let launched!: () => void;
|
|
const launchedPromise = new Promise<void>((resolve) => (launched = resolve));
|
|
let finishLaunch: () => void = () => {};
|
|
engineState.acquireBrowser = async () => {
|
|
launched();
|
|
await new Promise<void>((resolve) => (finishLaunch = resolve));
|
|
return { browser: new EventEmitter(), release };
|
|
};
|
|
|
|
let started!: () => void;
|
|
const startedPromise = new Promise<void>((resolve) => {
|
|
started = resolve;
|
|
});
|
|
producerState.executeRenderJob = () => {
|
|
started();
|
|
// Never settles, even once aborted -- the pathological case the CLI's
|
|
// 3s exit watchdog exists to survive.
|
|
return new Promise<void>(() => {});
|
|
};
|
|
|
|
server = createStudioServer({ projectDir: tmpProject() });
|
|
const state = server.adapter.startRender(startRenderOpts("job-1", join(tmpdir(), "hang.mp4")));
|
|
await untilStarted(startedPromise, state);
|
|
|
|
const thumbnail = server.adapter.generateThumbnail?.(thumbnailOpts());
|
|
await launchedPromise;
|
|
finishLaunch();
|
|
|
|
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
const never = new Promise<never>((_, reject) => {
|
|
timer = setTimeout(
|
|
() => reject(new Error("shutdown() did not resolve within its bound")),
|
|
3_000,
|
|
);
|
|
});
|
|
try {
|
|
await Promise.race([server.shutdown(), never]);
|
|
} finally {
|
|
clearTimeout(timer);
|
|
}
|
|
|
|
expect(release).toHaveBeenCalledTimes(1);
|
|
expect(closeBrowserPool).toHaveBeenCalledTimes(1);
|
|
await expect(thumbnail).resolves.toBeNull();
|
|
});
|
|
|
|
it("does not hand an already-leased browser to a new caller once shutdown has begun", async () => {
|
|
const release = vi.fn(async () => {});
|
|
const newPage = vi.fn(async () => {
|
|
throw new Error("no real page in this test double");
|
|
});
|
|
engineState.acquireBrowser = async () => ({
|
|
browser: { connected: true, newPage, on: () => {} },
|
|
release,
|
|
});
|
|
|
|
server = createStudioServer({ projectDir: tmpProject() });
|
|
await server.adapter.generateThumbnail?.(thumbnailOpts());
|
|
expect(newPage).toHaveBeenCalledTimes(1);
|
|
|
|
const shutdownPromise = server.shutdown();
|
|
// shuttingDown flips true synchronously as shutdown()'s first statement,
|
|
// before its closeThumbnailBrowser() call runs -- this request lands in
|
|
// that window and must not reuse the still-connected lease.
|
|
const late = server.adapter.generateThumbnail?.(thumbnailOpts());
|
|
|
|
await expect(late).resolves.toBeNull();
|
|
expect(newPage).toHaveBeenCalledTimes(1);
|
|
await shutdownPromise;
|
|
});
|
|
});
|
|
|
|
describe("Studio thumbnail capture", () => {
|
|
// The thumbnail browser lease is module-wide; without a shutdown the next test inherits this one's fake.
|
|
afterEach(async () => {
|
|
await server?.shutdown();
|
|
});
|
|
function fakePageBrowser(onEvaluate = () => {}) {
|
|
const screenshot = vi.fn(async () => Buffer.from("jpeg"));
|
|
const evaluate = vi.fn(async () => onEvaluate());
|
|
const page = new Proxy(
|
|
{ screenshot, evaluate },
|
|
{
|
|
get: (target, key) =>
|
|
key === "then"
|
|
? undefined
|
|
: key in target
|
|
? target[key as keyof typeof target]
|
|
: async () => {},
|
|
},
|
|
);
|
|
engineState.acquireBrowser = async () => ({
|
|
browser: { connected: true, newPage: async () => page, on: () => {} },
|
|
release: async () => {},
|
|
});
|
|
return { screenshot, evaluate };
|
|
}
|
|
const opts = (dir: string, signal = new AbortController().signal) => ({
|
|
project: { id: "demo", dir, title: "demo" },
|
|
compPath: "index.html",
|
|
seekTime: 0.5,
|
|
width: 640,
|
|
height: 360,
|
|
outputWidth: 640,
|
|
outputHeight: 360,
|
|
previewUrl: "http://localhost/preview",
|
|
signal,
|
|
});
|
|
|
|
it("stops a thumbnail whose request is aborted before its screenshot", async () => {
|
|
let abortOnEvaluate: AbortController | undefined;
|
|
const { screenshot } = fakePageBrowser(() => abortOnEvaluate?.abort());
|
|
const dir = tmpProject();
|
|
server = createStudioServer({ projectDir: dir });
|
|
await expect(server.adapter.generateThumbnail?.(opts(dir))).resolves.toBeInstanceOf(Buffer);
|
|
expect(screenshot).toHaveBeenCalledTimes(1);
|
|
|
|
const aborting = new AbortController();
|
|
abortOnEvaluate = aborting;
|
|
await expect(
|
|
server.adapter.generateThumbnail?.(opts(dir, aborting.signal)),
|
|
).resolves.toBeNull();
|
|
expect(screenshot).toHaveBeenCalledTimes(1);
|
|
});
|
|
|
|
it("undoes a row's isolation after its screenshot, since the page is reused", async () => {
|
|
const { screenshot, evaluate } = fakePageBrowser();
|
|
const dir = tmpProject();
|
|
server = createStudioServer({ projectDir: dir });
|
|
await server.adapter.generateThumbnail?.({ ...opts(dir), selector: "#title" });
|
|
const clears = evaluate.mock.calls.flatMap((call, i) =>
|
|
((call as unknown[])[0] as { name?: string }).name === "clearElementScreenshotIsolation"
|
|
? [evaluate.mock.invocationCallOrder[i]!]
|
|
: [],
|
|
);
|
|
expect(clears).toHaveLength(1);
|
|
expect(clears[0]).toBeGreaterThan(screenshot.mock.invocationCallOrder[0]!);
|
|
});
|
|
|
|
it("serves thumbnail capture documents in an opaque origin", async () => {
|
|
const dir = tmpProject();
|
|
writeFileSync(join(dir, "index.html"), '<div data-composition-id="main"></div>');
|
|
server = createStudioServer({ projectDir: dir, projectName: "demo" });
|
|
const capture = await server.app.request(
|
|
"http://localhost/api/projects/demo/preview?hf-capture=1",
|
|
);
|
|
expect(capture.headers.get("content-security-policy")).toBe("sandbox allow-scripts");
|
|
const preview = await server.app.request("http://localhost/api/projects/demo/preview");
|
|
expect(preview.headers.get("content-security-policy")).toBeNull();
|
|
});
|
|
|
|
it("grants the capture page's loads on its own session before it navigates", async () => {
|
|
const calls: string[] = [];
|
|
const session = {
|
|
send: vi.fn(async (method: string) => void calls.push(method)),
|
|
on: vi.fn(),
|
|
};
|
|
const page = new Proxy(
|
|
{
|
|
createCDPSession: async () => session,
|
|
goto: async () => void calls.push("goto"),
|
|
screenshot: async () => Buffer.from("jpeg"),
|
|
},
|
|
{
|
|
get: (target, key) =>
|
|
key === "then"
|
|
? undefined
|
|
: key in target
|
|
? target[key as keyof typeof target]
|
|
: async () => {},
|
|
},
|
|
);
|
|
engineState.acquireBrowser = async () => ({
|
|
browser: { connected: true, newPage: async () => page, on: () => {} },
|
|
release: async () => {},
|
|
});
|
|
const dir = tmpProject();
|
|
server = createStudioServer({ projectDir: dir });
|
|
const previewUrl = "http://127.0.0.1:3002/api/projects/demo/preview?hf-capture=1";
|
|
await expect(
|
|
server.adapter.generateThumbnail?.({ ...opts(dir), previewUrl }),
|
|
).resolves.toBeInstanceOf(Buffer);
|
|
expect(calls.slice(0, 2)).toEqual(["Fetch.enable", "goto"]);
|
|
expect(session.on).toHaveBeenCalledWith("Fetch.requestPaused", expect.any(Function));
|
|
});
|
|
|
|
it("reuses the cached project signature instead of walking the project per thumbnail", async () => {
|
|
fakePageBrowser();
|
|
const dir = tmpProject();
|
|
server = createStudioServer({ projectDir: dir });
|
|
await server.adapter.generateThumbnail?.(opts(dir));
|
|
const walks = vi.mocked(createProjectSignature).mock.calls.length;
|
|
for (let i = 0; i < 3; i++) await server.adapter.generateThumbnail?.(opts(dir));
|
|
expect(vi.mocked(createProjectSignature).mock.calls.length).toBe(walks);
|
|
});
|
|
});
|
|
|
|
describe("Studio project lint endpoint", () => {
|
|
it("surfaces findings that require the complete project graph", async () => {
|
|
const projectDir = tmpProject();
|
|
mkdirSync(join(projectDir, "compositions"));
|
|
mkdirSync(join(projectDir, "scenes"));
|
|
writeFileSync(
|
|
join(projectDir, "index.html"),
|
|
`<html><body><div data-composition-id="main" data-width="1920" data-height="1080" data-start="0" data-duration="10"></div></body></html>`,
|
|
);
|
|
writeFileSync(
|
|
join(projectDir, "compositions", "index.html"),
|
|
`<html><body><div data-composition-id="authored" data-width="1920" data-height="1080" data-start="0" data-duration="5"><div class="clip" data-start="0" data-duration="5">Visible</div></div></body></html>`,
|
|
);
|
|
writeFileSync(join(projectDir, "scenes", "intro.html"), "<html><body>Intro</body></html>");
|
|
server = createStudioServer({ projectDir, projectName: "demo" });
|
|
|
|
const response = await server.app.request("http://localhost/api/projects/demo/lint");
|
|
const payload = (await response.json()) as {
|
|
findings?: Array<{ code?: string; file?: string }>;
|
|
};
|
|
|
|
expect(response.status).toBe(200);
|
|
expect(payload.findings).toContainEqual(
|
|
expect.objectContaining({ code: "blank_root_with_standalone_composition" }),
|
|
);
|
|
expect(payload.findings).toContainEqual(expect.objectContaining({ file: "scenes/intro.html" }));
|
|
expect(payload.findings?.every((finding) => !finding.file?.startsWith(projectDir))).toBe(true);
|
|
});
|
|
});
|
|
|
|
describe("host guarding on identity-bearing responses", () => {
|
|
// NOTE: the SPA-injection branch itself is covered in telemetryIdentity.test.ts
|
|
// via buildStudioHeadScriptsForHost. It cannot be asserted here: this route
|
|
// only reaches the injection branch when packages/studio/dist is built,
|
|
// which is true locally and false in the CI test lane, so a route-level
|
|
// assertion on the returned HTML passes on a dev box and fails in CI.
|
|
|
|
it("refuses the identity endpoint for a hostile Host", async () => {
|
|
server = createStudioServer({ projectDir: tmpProject() });
|
|
const res = await server.app.request("/api/telemetry-identity", {
|
|
headers: { host: "evil.example.com" },
|
|
});
|
|
expect(res.status).toBe(403);
|
|
expect(await res.text()).not.toContain('distinctId":"');
|
|
});
|
|
|
|
it("gives the thumbnail browser the origin it listens on, not the request's", async () => {
|
|
let listening: string | undefined;
|
|
server = createStudioServer({ projectDir: tmpProject(), origin: () => listening });
|
|
expect(server.adapter.serverOrigin?.()).toBeUndefined();
|
|
listening = "http://127.0.0.1:3002";
|
|
expect(server.adapter.serverOrigin?.()).toBe("http://127.0.0.1:3002");
|
|
});
|
|
|
|
it("serves the identity endpoint on a loopback Host", async () => {
|
|
server = createStudioServer({ projectDir: tmpProject() });
|
|
const res = await server.app.request("/api/telemetry-identity", {
|
|
headers: { host: "127.0.0.1:5173" },
|
|
});
|
|
expect(res.status).toBe(200);
|
|
// The seed is no longer served here at all — Studio gets decisions
|
|
// injected instead, so nothing needs it over HTTP.
|
|
expect(Object.keys((await res.json()) as object)).toEqual(["distinctId"]);
|
|
});
|
|
});
|
|
|
|
// Studio asks this before it offers Export, so a machine without an encoder
|
|
// gets an install command up front instead of a 503 after the work is done.
|
|
describe("FFmpeg environment endpoint", () => {
|
|
it("reports the cause and a pasteable command when FFmpeg is unusable", async () => {
|
|
// A configured-but-missing override is the one "no FFmpeg" state a test can
|
|
// force on a machine that does have FFmpeg installed.
|
|
process.env.HYPERFRAMES_FFMPEG_PATH = join(tmpdir(), "hf-missing-ffmpeg");
|
|
server = createStudioServer({ projectDir: tmpProject() });
|
|
|
|
const res = await server.app.request("/api/environment/ffmpeg");
|
|
expect(res.status).toBe(200);
|
|
const body = (await res.json()) as {
|
|
ok: boolean;
|
|
title?: string;
|
|
detail?: string;
|
|
command?: string;
|
|
};
|
|
|
|
expect(body.ok).toBe(false);
|
|
expect(body.title).toContain("not found");
|
|
expect(body.detail).toBeTruthy();
|
|
// Undefined only on platforms with no one-line install; CI runs none.
|
|
expect(body.command).toBeTruthy();
|
|
});
|
|
|
|
// Needs a real FFmpeg: the check runs `-version` on whatever it resolves, so
|
|
// a stand-in binary would only prove the stand-in works. Skipped rather than
|
|
// faked on machines without one.
|
|
it.skipIf(!findFFmpeg() || !findFFprobe())(
|
|
"answers a plain ok when both binaries resolve",
|
|
async () => {
|
|
server = createStudioServer({ projectDir: tmpProject() });
|
|
|
|
const res = await server.app.request("/api/environment/ffmpeg");
|
|
|
|
expect(await res.json()).toEqual({ ok: true });
|
|
},
|
|
);
|
|
});
|
|
|
|
describe("Studio file-change SSE", () => {
|
|
/** Opens `count` `/api/events` connections and waits for each to register its listener. */
|
|
async function subscribe(count: number): Promise<ReadableStreamDefaultReader<Uint8Array>[]> {
|
|
const responses = await Promise.all(
|
|
Array.from({ length: count }, () => server!.app.request("/api/events")),
|
|
);
|
|
const streams = responses.map((response) => {
|
|
const reader = response.body!.getReader();
|
|
openReaders.push(reader);
|
|
return reader;
|
|
});
|
|
// streamSSE runs its callback after the Response resolves, so the listener
|
|
// each connection adds has to exist before the watcher fires.
|
|
await new Promise((resolve) => setTimeout(resolve, 20));
|
|
return streams;
|
|
}
|
|
|
|
const nextEvent = async (reader: ReadableStreamDefaultReader<Uint8Array>): Promise<string> =>
|
|
new TextDecoder().decode((await reader.read()).value);
|
|
|
|
/** The version as it appears inside the JSON-encoded SSE data line. */
|
|
const encodedVersion = (content: string): string =>
|
|
fileContentVersion(content).replaceAll('"', '\\"');
|
|
|
|
/** A project whose preview has been loaded once, as an open Studio tab does on its first render. */
|
|
async function previewedProject(): Promise<{ projectDir: string; projectUrl: string }> {
|
|
const projectDir = tmpProject();
|
|
mkdirSync(join(projectDir, "assets"));
|
|
writeFileSync(join(projectDir, "assets", "logo.png"), "logo-v1");
|
|
writeFileSync(
|
|
join(projectDir, "index.html"),
|
|
'<html><body><div data-composition-id="root"><img src="assets/logo.png"></div></body></html>',
|
|
);
|
|
server = createStudioServer({ projectDir });
|
|
const projectUrl = `/api/projects/${encodeURIComponent(basename(projectDir))}`;
|
|
// An unread asset body keeps logo.png open, and Windows refuses to move a folder holding an open file.
|
|
for (const path of [`${projectUrl}/preview`, `${projectUrl}/preview/assets/logo.png`]) {
|
|
const response = await server.app.request(path);
|
|
expect(response.status).toBe(200);
|
|
await response.arrayBuffer();
|
|
}
|
|
return { projectDir, projectUrl };
|
|
}
|
|
|
|
it("leaves no timer behind once the tab disconnects, so a stopping CLI can exit", async () => {
|
|
server = createStudioServer({ projectDir: tmpProject() });
|
|
const timeouts = vi.spyOn(globalThis, "setTimeout");
|
|
const [stream] = await subscribe(1);
|
|
await stream!.cancel();
|
|
|
|
const keepAlive = timeouts.mock.calls.filter(([, ms]) => (ms ?? 0) >= 30_000);
|
|
timeouts.mockRestore();
|
|
expect(keepAlive).toEqual([]);
|
|
});
|
|
|
|
it("marks a notes write as not affecting the preview, so the tab does not reload", async () => {
|
|
const { projectDir } = await previewedProject();
|
|
const [stream] = await subscribe(1);
|
|
|
|
writeFileSync(join(projectDir, "notes.md"), "review notes");
|
|
mockWatcher.emit("change", "rename", "notes.md");
|
|
|
|
const payload = await nextEvent(stream!);
|
|
expect(payload).toContain('"path":"notes.md"');
|
|
expect(payload).toContain('"affectsPreview":false');
|
|
expect(payload).toContain('"affectedCompositions":[]');
|
|
});
|
|
|
|
it("marks a write to an asset the preview loaded as affecting it", async () => {
|
|
const { projectDir } = await previewedProject();
|
|
const [stream] = await subscribe(1);
|
|
|
|
writeFileSync(join(projectDir, "assets", "logo.png"), "logo-v2");
|
|
mockWatcher.emit("change", "change", "assets/logo.png");
|
|
|
|
expect(await nextEvent(stream!)).toContain('"affectsPreview":true');
|
|
});
|
|
|
|
it("reloads when a folder holding an asset the preview missed is moved in", async () => {
|
|
const { projectDir, projectUrl } = await previewedProject();
|
|
expect((await server!.app.request(`${projectUrl}/preview/media/clip.png`)).status).toBe(404);
|
|
const [stream] = await subscribe(1);
|
|
|
|
mkdirSync(join(projectDir, "media"));
|
|
writeFileSync(join(projectDir, "media", "clip.png"), "clip");
|
|
mockWatcher.emit("change", "rename", "media");
|
|
|
|
const payload = await nextEvent(stream!);
|
|
expect(payload).toContain('"path":"media"');
|
|
expect(payload).toContain('"affectsPreview":true');
|
|
});
|
|
|
|
it("reloads when a folder holding an asset the preview loaded is moved out", async () => {
|
|
const { projectDir } = await previewedProject();
|
|
const [stream] = await subscribe(1);
|
|
|
|
renameSync(join(projectDir, "assets"), join(tmpProject(), "assets"));
|
|
mockWatcher.emit("change", "rename", "assets");
|
|
|
|
expect(await nextEvent(stream!)).toContain('"affectsPreview":true');
|
|
});
|
|
|
|
it("still delivers a new file in a folder an old watchIgnore listed, for the file tree", async () => {
|
|
const { projectDir } = await previewedProject();
|
|
writeFileSync(
|
|
join(projectDir, "hyperframes.json"),
|
|
JSON.stringify({ preview: { watchIgnore: ["docs"] } }),
|
|
);
|
|
const [stream] = await subscribe(1);
|
|
|
|
mkdirSync(join(projectDir, "docs"));
|
|
writeFileSync(join(projectDir, "docs", "report.json"), "{}");
|
|
mockWatcher.emit("change", "rename", "docs/report.json");
|
|
|
|
const payload = await nextEvent(stream!);
|
|
expect(payload).toContain('"path":"docs/report.json"');
|
|
expect(payload).toContain('"affectsPreview":false');
|
|
});
|
|
|
|
it("counts every write as affecting the preview until the preview has loaded anything", async () => {
|
|
const projectDir = tmpProject();
|
|
writeFileSync(join(projectDir, "index.html"), "<html></html>");
|
|
server = createStudioServer({ projectDir });
|
|
const [stream] = await subscribe(1);
|
|
|
|
writeFileSync(join(projectDir, "notes.md"), "notes");
|
|
mockWatcher.emit("change", "rename", "notes.md");
|
|
|
|
expect(await nextEvent(stream!)).toContain('"affectsPreview":true');
|
|
});
|
|
|
|
it("labels a Studio write for every open subscriber, not just the first", async () => {
|
|
const projectDir = tmpProject();
|
|
writeFileSync(join(projectDir, "index.html"), "<html>before</html>");
|
|
server = createStudioServer({ projectDir });
|
|
const streams = await subscribe(2);
|
|
|
|
const written = "<html>after</html>";
|
|
const write = await server.app.request(
|
|
`/api/projects/${encodeURIComponent(basename(projectDir))}/files/index.html`,
|
|
{
|
|
method: "PUT",
|
|
headers: {
|
|
"If-Match": fileContentVersion("<html>before</html>"),
|
|
"X-Hyperframes-Write-Token": "studio-write-1",
|
|
},
|
|
body: written,
|
|
},
|
|
);
|
|
expect(write.status).toBe(200);
|
|
mockWatcher.emit("change", "change", "index.html");
|
|
|
|
for (const payload of await Promise.all(streams.map(nextEvent))) {
|
|
expect(payload).toContain("studio-write-1");
|
|
expect(payload).toContain(encodedVersion(written));
|
|
}
|
|
});
|
|
|
|
it("still reports an external write with a version so subscribers can dedupe it", async () => {
|
|
const projectDir = tmpProject();
|
|
writeFileSync(join(projectDir, "index.html"), "<html>before</html>");
|
|
server = createStudioServer({ projectDir });
|
|
const streams = await subscribe(2);
|
|
|
|
writeFileSync(join(projectDir, "index.html"), "<html>agent</html>");
|
|
mockWatcher.emit("change", "change", "index.html");
|
|
|
|
for (const payload of await Promise.all(streams.map(nextEvent))) {
|
|
expect(payload).not.toContain("writeToken");
|
|
expect(payload).toContain(encodedVersion("<html>agent</html>"));
|
|
}
|
|
});
|
|
|
|
it("labels the deletion an undo from Studio makes with Studio's write token", async () => {
|
|
const projectDir = tmpProject();
|
|
writeFileSync(join(projectDir, "index.html"), "<html>before</html>");
|
|
server = createStudioServer({ projectDir, historyRoot: tmpProject() });
|
|
const history = `/api/projects/${encodeURIComponent(basename(projectDir))}/history`;
|
|
const post = (path: string, body: object, headers: Record<string, string> = {}) =>
|
|
server!.app.request(`${history}${path}`, {
|
|
method: "POST",
|
|
headers: { "Content-Type": "application/json", ...headers },
|
|
body: JSON.stringify(body),
|
|
});
|
|
await server.app.request(history); // opens the history, as Studio's first load does
|
|
writeFileSync(join(projectDir, "extra.html"), "<html>added</html>");
|
|
await post("/claim", { label: "Added a section", paths: ["extra.html"] });
|
|
const streams = await subscribe(1);
|
|
|
|
await post("/step", { direction: "back" }, { "X-Hyperframes-Write-Token": "studio-undo-1" });
|
|
expect(existsSync(join(projectDir, "extra.html"))).toBe(false);
|
|
mockWatcher.emit("change", "rename", "extra.html");
|
|
|
|
const [payload] = await Promise.all(streams.map(nextEvent));
|
|
expect(payload).toContain("studio-undo-1");
|
|
});
|
|
|
|
// `/api/events` is one connection per SERVER, not per project: a tab left
|
|
// open from a `preview` run whose port was later reused by a DIFFERENT
|
|
// project shares this exact stream. Without `projectId` on the wire, that
|
|
// stale tab cannot tell "my project changed" from "the other project this
|
|
// server now serves changed" — see useExternalFileChangeCoordinator's
|
|
// cross-project filter, which reads this field.
|
|
it("labels every file-change with this server's project id", async () => {
|
|
const projectDir = tmpProject();
|
|
writeFileSync(join(projectDir, "index.html"), "<html>before</html>");
|
|
server = createStudioServer({ projectDir, projectName: "demo-project" });
|
|
const streams = await subscribe(1);
|
|
|
|
writeFileSync(join(projectDir, "index.html"), "<html>agent</html>");
|
|
mockWatcher.emit("change", "change", "index.html");
|
|
|
|
const [payload] = await Promise.all(streams.map(nextEvent));
|
|
expect(payload).toContain('"projectId":"demo-project"');
|
|
});
|
|
});
|
|
|
|
describe("createStudioServer /api write guard allowed hosts", () => {
|
|
const TUNNEL_HOST = "demo.tunnels.example";
|
|
|
|
async function tunnelWrite(projectDir: string): Promise<Response> {
|
|
// A write from the Studio page behind a tunnel, driven through the
|
|
// CLI's own /api/* forwarder, the way a browser save reaches the API.
|
|
return server!.app.request(
|
|
`http://${TUNNEL_HOST}/api/projects/${encodeURIComponent(basename(projectDir))}/files/planted.html`,
|
|
{
|
|
method: "POST",
|
|
headers: {
|
|
Host: TUNNEL_HOST,
|
|
Origin: `https://${TUNNEL_HOST}`,
|
|
"X-Forwarded-Proto": "https",
|
|
"Content-Type": "text/plain",
|
|
},
|
|
body: "<html>planted</html>",
|
|
},
|
|
);
|
|
}
|
|
|
|
it("refuses a tunnel write without the env var, naming the host and the var", async () => {
|
|
const projectDir = tmpProject();
|
|
writeFileSync(join(projectDir, "index.html"), "<html>before</html>");
|
|
delete process.env.HYPERFRAMES_PREVIEW_ALLOWED_HOSTS;
|
|
server = createStudioServer({ projectDir });
|
|
|
|
const res = await tunnelWrite(projectDir);
|
|
expect(res.status).toBe(403);
|
|
const body = (await res.json()) as { error: string };
|
|
expect(body.error).toContain(TUNNEL_HOST);
|
|
expect(body.error).toContain("HYPERFRAMES_PREVIEW_ALLOWED_HOSTS");
|
|
expect(existsSync(join(projectDir, "planted.html"))).toBe(false);
|
|
});
|
|
|
|
it("accepts a tunnel write when HYPERFRAMES_PREVIEW_ALLOWED_HOSTS names the host", async () => {
|
|
const projectDir = tmpProject();
|
|
writeFileSync(join(projectDir, "index.html"), "<html>before</html>");
|
|
process.env.HYPERFRAMES_PREVIEW_ALLOWED_HOSTS = `other.example, ${TUNNEL_HOST}`;
|
|
try {
|
|
server = createStudioServer({ projectDir });
|
|
const res = await tunnelWrite(projectDir);
|
|
expect(res.status).toBe(201);
|
|
expect(existsSync(join(projectDir, "planted.html"))).toBe(true);
|
|
} finally {
|
|
delete process.env.HYPERFRAMES_PREVIEW_ALLOWED_HOSTS;
|
|
}
|
|
});
|
|
});
|
|
|
|
describe("createStudioServer Host check on every route", () => {
|
|
const FOREIGN_HOST = "rebound.example:3002";
|
|
|
|
function read(path: string, host: string, extra: Record<string, string> = {}): Promise<Response> {
|
|
return Promise.resolve(
|
|
server!.app.request(`http://${host}${path}`, { headers: { Host: host, ...extra } }),
|
|
);
|
|
}
|
|
|
|
function routes(projectDir: string): string[] {
|
|
const id = encodeURIComponent(basename(projectDir));
|
|
return [
|
|
"/__hyperframes_config",
|
|
"/api/projects",
|
|
`/api/projects/${id}/files/index.html`,
|
|
"/api/events",
|
|
"/",
|
|
];
|
|
}
|
|
|
|
it("refuses reads on every route for a Host the server does not answer on", async () => {
|
|
const projectDir = tmpProject();
|
|
writeFileSync(join(projectDir, "index.html"), "<html>secret-body</html>");
|
|
delete process.env.HYPERFRAMES_PREVIEW_ALLOWED_HOSTS;
|
|
server = createStudioServer({ projectDir });
|
|
|
|
for (const path of routes(projectDir)) {
|
|
const res = await read(path, FOREIGN_HOST);
|
|
expect(res.status, path).toBe(403);
|
|
const text = await res.text();
|
|
expect(text, path).not.toContain("secret-body");
|
|
expect(text, path).not.toContain(projectDir);
|
|
expect(text, path).toContain("HYPERFRAMES_PREVIEW_ALLOWED_HOSTS");
|
|
}
|
|
});
|
|
|
|
it("does not let X-Forwarded-Host stand in for the Host header", async () => {
|
|
const projectDir = tmpProject();
|
|
writeFileSync(join(projectDir, "index.html"), "<html>secret-body</html>");
|
|
server = createStudioServer({ projectDir });
|
|
|
|
const res = await read("/__hyperframes_config", FOREIGN_HOST, {
|
|
"X-Forwarded-Host": "localhost:3002",
|
|
});
|
|
expect(res.status).toBe(403);
|
|
});
|
|
|
|
it("answers loopback names", async () => {
|
|
const projectDir = tmpProject();
|
|
writeFileSync(join(projectDir, "index.html"), "<html>secret-body</html>");
|
|
server = createStudioServer({ projectDir });
|
|
|
|
for (const host of ["localhost:3002", "127.0.0.1:3002", "[::1]:3002"]) {
|
|
const config = await read("/__hyperframes_config", host);
|
|
expect(config.status, host).toBe(200);
|
|
const file = await read(
|
|
`/api/projects/${encodeURIComponent(basename(projectDir))}/files/index.html`,
|
|
host,
|
|
);
|
|
expect(file.status, host).toBe(200);
|
|
expect(await file.text(), host).toContain("secret-body");
|
|
}
|
|
});
|
|
|
|
it("answers a host named in HYPERFRAMES_PREVIEW_ALLOWED_HOSTS", async () => {
|
|
const projectDir = tmpProject();
|
|
writeFileSync(join(projectDir, "index.html"), "<html>secret-body</html>");
|
|
process.env.HYPERFRAMES_PREVIEW_ALLOWED_HOSTS = "demo.tunnels.example";
|
|
try {
|
|
server = createStudioServer({ projectDir });
|
|
const res = await read("/__hyperframes_config", "demo.tunnels.example");
|
|
expect(res.status).toBe(200);
|
|
const other = await read("/__hyperframes_config", FOREIGN_HOST);
|
|
expect(other.status).toBe(403);
|
|
} finally {
|
|
delete process.env.HYPERFRAMES_PREVIEW_ALLOWED_HOSTS;
|
|
}
|
|
});
|
|
});
|
|
|
|
describe("createStudioServer preview image preparation", () => {
|
|
const html = '<div data-composition-id="main"><img src="photo.png"></div>';
|
|
const prepared = (projectDir: string) =>
|
|
["heif", "gif"].filter((kind) =>
|
|
existsSync(join(projectDir, ".hyperframes", "prepared-assets", kind, "converted")),
|
|
);
|
|
|
|
it("prepares HEIF and GIF images inside a project's own .hyperframes folder", async () => {
|
|
const projectDir = tmpProject();
|
|
server = createStudioServer({ projectDir });
|
|
|
|
await server.adapter.transformPreviewHtml?.({
|
|
html,
|
|
project: { id: "p", dir: projectDir },
|
|
activeCompositionPath: "index.html",
|
|
});
|
|
|
|
expect(prepared(projectDir)).toEqual(["heif", "gif"]);
|
|
});
|
|
|
|
it.skipIf(process.platform === "win32")(
|
|
"serves images unprepared when .hyperframes is a link, and writes nothing where it points",
|
|
async () => {
|
|
const projectDir = tmpProject();
|
|
const outside = tmpProject();
|
|
symlinkSync(outside, join(projectDir, ".hyperframes"));
|
|
server = createStudioServer({ projectDir });
|
|
|
|
const served = await server.adapter.transformPreviewHtml?.({
|
|
html,
|
|
project: { id: "p", dir: projectDir },
|
|
activeCompositionPath: "index.html",
|
|
});
|
|
|
|
expect(served).toContain('src="photo.png"');
|
|
expect(readdirSync(outside)).toEqual([]);
|
|
},
|
|
);
|
|
});
|