import { afterEach, describe, expect, it, vi } from "vitest"; import { Hono } from "hono"; import { mkdtempSync, mkdirSync, writeFileSync, symlinkSync, rmSync, existsSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { VALID_CANVAS_RESOLUTIONS } from "@hyperframes/parsers"; import { registerRenderRoutes } from "./render"; import type { StudioApiAdapter } from "../types"; function createAdapter( startRenderSpy: ReturnType, rendersDir = mkdtempSync(join(tmpdir(), "hf-render-test-")), ): { adapter: StudioApiAdapter; rendersDir: string } { const adapter: StudioApiAdapter = { listProjects: () => [], // Use a real, existing dir: isSafePath() canonicalizes the project dir with // realpath and fails closed if it doesn't exist (real projects always do). resolveProject: async (id: string) => ({ id, dir: tmpdir() }), bundle: async () => null, lint: async () => ({ findings: [] }), runtimeUrl: "/api/runtime.js", rendersDir: () => rendersDir, startRender: (opts) => { startRenderSpy(opts); return { id: opts.jobId, status: "rendering", progress: 0, outputPath: opts.outputPath, }; }, }; return { adapter, rendersDir }; } function buildApp(spy: ReturnType): { app: Hono; rendersDir: string; cleanup: () => void; } { const { adapter, rendersDir } = createAdapter(spy); const app = new Hono(); registerRenderRoutes(app, adapter); return { app, rendersDir, cleanup: () => rmSync(rendersDir, { recursive: true, force: true }) }; } describe("POST /projects/:id/render — job ids", () => { it("gives two exports started in the same second their own job and output file", async () => { vi.useFakeTimers({ toFake: ["Date"] }); vi.setSystemTime(new Date("2026-11-02T12:00:00Z")); const spy = vi.fn(); const { app, rendersDir, cleanup } = buildApp(spy); try { const start = () => app.request("http://localhost/projects/demo/render", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ fps: 30, quality: "standard", format: "mp4" }), }); const [first, second] = await Promise.all([start(), start()]); const ids = [ ((await first.json()) as { jobId: string }).jobId, ((await second.json()) as { jobId: string }).jobId, ]; expect(new Set(ids).size).toBe(2); expect(spy.mock.calls.map(([opts]) => opts.outputPath)).toEqual( ids.map((id) => join(rendersDir, `${id}.mp4`)), ); } finally { vi.useRealTimers(); cleanup(); } }); }); describe("GET /projects/:id/renders — stale sidecar status", () => { it("does not mark an existing output failed from stale metadata", async () => { const spy = vi.fn(); const { app, rendersDir, cleanup } = buildApp(spy); try { writeFileSync(join(rendersDir, "retry.mp4"), "valid-output"); writeFileSync( join(rendersDir, "retry.meta.json"), JSON.stringify({ status: "failed", error: "first attempt" }), ); const res = await app.request("http://localhost/projects/demo/renders"); expect(res.status).toBe(200); const body = await res.json(); expect(body.renders).toEqual([expect.objectContaining({ id: "retry", status: "complete" })]); } finally { cleanup(); } }); }); describe("POST /projects/:id/render — outputResolution forwarding", () => { it("forwards a valid resolution preset to the adapter", async () => { const spy = vi.fn(); const { app, cleanup } = buildApp(spy); try { const res = await app.request("http://localhost/projects/demo/render", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ fps: 30, quality: "high", format: "mp4", resolution: "landscape-4k", }), }); expect(res.status).toBe(200); expect(spy).toHaveBeenCalledOnce(); const opts = spy.mock.calls[0][0]; expect(opts.outputResolution).toBe("landscape-4k"); } finally { cleanup(); } }); it("omits outputResolution when the request does not specify one", async () => { const spy = vi.fn(); const { app, cleanup } = buildApp(spy); try { const res = await app.request("http://localhost/projects/demo/render", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ fps: 30, quality: "standard", format: "mp4" }), }); expect(res.status).toBe(200); const opts = spy.mock.calls[0][0]; expect(opts.outputResolution).toBeUndefined(); } finally { cleanup(); } }); it("drops an invalid resolution string (defense-in-depth, not a 400)", async () => { // The route is intentionally lenient on unknown enum values — the producer // is the source of truth for validation and emits a clear error message. // We just want to make sure garbage doesn't propagate as if it were valid. const spy = vi.fn(); const { app, cleanup } = buildApp(spy); try { const res = await app.request("http://localhost/projects/demo/render", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ fps: 30, quality: "standard", format: "mp4", resolution: "8k" }), }); expect(res.status).toBe(200); const opts = spy.mock.calls[0][0]; expect(opts.outputResolution).toBeUndefined(); } finally { cleanup(); } }); // Contract pin per PR #2529 R2 review: the HTTP route accepts canonical // presets only, not the CLI-side tier aliases (`1080p` / `hd` / `4k` / // `uhd`, `landscape-4k` is already canonical). Miga asked that Studio // Server's contract stay explicit here rather than silently extending it. // Aliases fall through to the same `undefined` sink as any unknown value, // which means the render falls back to composition dimensions — a safe, // deliberate no-op rather than a portrait-1080p failure mode. it.each(["1080p", "4k", "hd", "uhd"])( "does NOT accept the CLI-side tier alias %s (canonical-only contract)", async (alias) => { const spy = vi.fn(); const { app, cleanup } = buildApp(spy); try { const res = await app.request("http://localhost/projects/demo/render", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ fps: 30, quality: "standard", format: "mp4", resolution: alias, }), }); expect(res.status).toBe(200); // Alias falls through to undefined → render uses composition dims. // If Studio Server ever extends its contract to accept aliases, // it must also plumb `outputResolutionAspectAgnostic` alongside so // the compile stage can remap orientation; today the surface is // deliberately narrow. expect(spy.mock.calls[0][0].outputResolution).toBeUndefined(); } finally { cleanup(); } }, ); it("accepts each canonical preset value", async () => { for (const preset of VALID_CANVAS_RESOLUTIONS) { const spy = vi.fn(); const { app, cleanup } = buildApp(spy); try { await app.request("http://localhost/projects/demo/render", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ fps: 30, quality: "standard", format: "mp4", resolution: preset }), }); expect(spy.mock.calls[0][0].outputResolution).toBe(preset); } finally { cleanup(); } } }); }); describe("POST /projects/:id/render — composition forwarding", () => { it("forwards a valid composition path to the adapter", async () => { const spy = vi.fn(); const { app, cleanup } = buildApp(spy); try { const res = await app.request("http://localhost/projects/demo/render", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ fps: 30, quality: "standard", format: "mp4", composition: "compositions/intro.html", }), }); expect(res.status).toBe(200); expect(spy).toHaveBeenCalledOnce(); expect(spy.mock.calls[0][0].composition).toBe("compositions/intro.html"); } finally { cleanup(); } }); it("omits composition when not specified", async () => { const spy = vi.fn(); const { app, cleanup } = buildApp(spy); try { const res = await app.request("http://localhost/projects/demo/render", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ fps: 30, quality: "standard", format: "mp4" }), }); expect(res.status).toBe(200); expect(spy.mock.calls[0][0].composition).toBeUndefined(); } finally { cleanup(); } }); it("omits composition when empty string", async () => { const spy = vi.fn(); const { app, cleanup } = buildApp(spy); try { const res = await app.request("http://localhost/projects/demo/render", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ fps: 30, quality: "standard", format: "mp4", composition: "" }), }); expect(res.status).toBe(200); expect(spy.mock.calls[0][0].composition).toBeUndefined(); } finally { cleanup(); } }); it("rejects path-traversal attempts with 400", async () => { const spy = vi.fn(); const { app, cleanup } = buildApp(spy); try { const res = await app.request("http://localhost/projects/demo/render", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ fps: 30, quality: "standard", format: "mp4", composition: "../../../etc/passwd", }), }); expect(res.status).toBe(400); expect(spy).not.toHaveBeenCalled(); } finally { cleanup(); } }); }); describe("POST /projects/:id/render — fps wire format", () => { // The fps fraction-syntax feature accepts JSON `number` (integer fps) and // JSON `string` (ffmpeg-style rational) on the wire, normalizing both to // the structured Fps form before invoking the adapter. it("forwards integer fps as { num, den: 1 }", async () => { const spy = vi.fn(); const { app, cleanup } = buildApp(spy); try { await app.request("http://localhost/projects/demo/render", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ fps: 60, quality: "standard", format: "mp4" }), }); expect(spy.mock.calls[0][0].fps).toEqual({ num: 60, den: 1 }); } finally { cleanup(); } }); it("parses '30000/1001' string body as exact NTSC", async () => { const spy = vi.fn(); const { app, cleanup } = buildApp(spy); try { await app.request("http://localhost/projects/demo/render", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ fps: "30000/1001", quality: "standard", format: "mp4" }), }); expect(spy.mock.calls[0][0].fps).toEqual({ num: 30000, den: 1001 }); } finally { cleanup(); } }); it("falls back to 30/1 for malformed fps values", async () => { // Matches the lenient handling of `quality` and `resolution` in the same // route — the producer surfaces a clearer downstream error if the value // is genuinely unusable. const spy = vi.fn(); const { app, cleanup } = buildApp(spy); try { await app.request("http://localhost/projects/demo/render", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ fps: "abc", quality: "standard", format: "mp4" }), }); expect(spy.mock.calls[0][0].fps).toEqual({ num: 30, den: 1 }); } finally { cleanup(); } }); it("falls back to 30/1 when fps is omitted", async () => { const spy = vi.fn(); const { app, cleanup } = buildApp(spy); try { await app.request("http://localhost/projects/demo/render", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ quality: "standard", format: "mp4" }), }); expect(spy.mock.calls[0][0].fps).toEqual({ num: 30, den: 1 }); } finally { cleanup(); } }); }); describe("POST /projects/:id/render — crf", () => { async function post(body: Record) { const spy = vi.fn(); const { app, cleanup } = buildApp(spy); try { const res = await app.request("http://localhost/projects/demo/render", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ fps: 30, quality: "standard", ...body }), }); return { res, opts: spy.mock.calls[0]?.[0] }; } finally { cleanup(); } } it("forwards a valid crf for mp4 and webm", async () => { expect((await post({ format: "mp4", crf: 12 })).opts.crf).toBe(12); expect((await post({ format: "webm", crf: 63 })).opts.crf).toBe(63); }); it("omits crf when the request does not specify one", async () => { const { res, opts } = await post({ format: "mp4" }); expect(res.status).toBe(200); expect(opts).not.toHaveProperty("crf"); }); it("ignores crf for mov, which has no CRF", async () => { const { res, opts } = await post({ format: "mov", crf: 12 }); expect(res.status).toBe(200); expect(opts).not.toHaveProperty("crf"); }); it("forwards the other encoder options and refuses crf with a bitrate", async () => { const { opts } = await post({ format: "mp4", videoBitrate: "10M", videoFrameFormat: "png", hdrMode: "force-sdr", }); expect(opts).toMatchObject({ videoBitrate: "10M", videoFrameFormat: "png", hdrMode: "force-sdr", }); const both = await post({ format: "mp4", crf: 12, videoBitrate: "10M" }); expect(both.res.status).toBe(400); expect(both.opts).toBeUndefined(); }); it("forwards a ProRes profile for mov to the render adapter and refuses an unknown one", async () => { expect((await post({ format: "mov", proresProfile: "hq" })).opts.proresProfile).toBe("hq"); const unknown = await post({ format: "mov", proresProfile: "422hq" }); expect(unknown.res.status).toBe(400); expect(unknown.opts).toBeUndefined(); }); it("forwards the keyframe interval and the rate cap to the render adapter", async () => { const { res, opts } = await post({ format: "mp4", keyframeIntervalSeconds: 2, maxBitrate: "8M", bufferSize: "12M", }); expect(res.status).toBe(200); expect(opts).toMatchObject({ keyframeIntervalSeconds: 2, maxBitrate: "8M", bufferSize: "12M" }); const webm = await post({ format: "webm", maxBitrate: "8M" }); expect(webm.res.status).toBe(400); expect(webm.opts).toBeUndefined(); }); it.each([ ["mp4", 52], ["mp4", -1], ["mp4", 12.5], ["mp4", "12"], ["webm", 64], ])("rejects %s crf %j with 400 and does not start a render", async (format, crf) => { const { res, opts } = await post({ format, crf }); expect(res.status).toBe(400); expect(opts).toBeUndefined(); }); it("forwards 4:4:4 chroma for mp4 and omits it when not requested", async () => { const chroma = await post({ format: "mp4", chromaSubsampling: "444" }); expect(chroma.res.status).toBe(200); expect(chroma.opts.chromaSubsampling).toBe("444"); expect((await post({ format: "mp4" })).opts).not.toHaveProperty("chromaSubsampling"); }); it.each([ { format: "webm", chromaSubsampling: "444" }, { format: "mp4", chromaSubsampling: "444", gpu: true }, { format: "mp4", chromaSubsampling: "422" }, ])("rejects chroma request %j with 400 and does not start a render", async (body) => { const { res, opts } = await post(body); expect(res.status).toBe(400); expect(opts).toBeUndefined(); }); }); describe("POST /projects/:id/render — composition path safety", () => { const tmpDirs: string[] = []; function buildAppWithProjectDir(spy: ReturnType): { app: Hono; projectDir: string; } { const projectDir = mkdtempSync(join(tmpdir(), "hf-render-proj-")); const rendersDir = mkdtempSync(join(tmpdir(), "hf-render-out-")); tmpDirs.push(projectDir, rendersDir); const adapter: StudioApiAdapter = { listProjects: () => [], resolveProject: async (id: string) => ({ id, dir: projectDir }), bundle: async () => null, lint: async () => ({ findings: [] }), runtimeUrl: "/api/runtime.js", rendersDir: () => rendersDir, startRender: (opts) => { spy(opts); return { id: opts.jobId, status: "rendering", progress: 0, outputPath: opts.outputPath }; }, }; const app = new Hono(); registerRenderRoutes(app, adapter); return { app, projectDir }; } afterEach(() => { for (const d of tmpDirs) rmSync(d, { recursive: true, force: true }); tmpDirs.length = 0; }); async function postComposition(app: Hono, composition: string): Promise { return app.request("http://localhost/projects/demo/render", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ fps: 30, quality: "standard", format: "mp4", composition }), }); } // Mirror the repo convention (preview.test.ts): skip symlink cases on // non-symlink-privileged Windows runners rather than crash the suite. function tryCreateSymlink(target: string, path: string, type: "dir" | "file"): boolean { try { symlinkSync(target, path, type); return true; } catch { return false; } } it("accepts a composition path inside the project directory", async () => { const spy = vi.fn(); const { app } = buildAppWithProjectDir(spy); const res = await postComposition(app, "scenes/intro.html"); expect(res.status).toBe(200); expect(spy).toHaveBeenCalledOnce(); }); it("rejects a `..` traversal in the composition path", async () => { const spy = vi.fn(); const { app } = buildAppWithProjectDir(spy); const res = await postComposition(app, "../../etc/passwd"); expect(res.status).toBe(400); expect(spy).not.toHaveBeenCalled(); }); it("rejects a composition reached through an in-project symlink pointing outside the project", async () => { const spy = vi.fn(); const { app, projectDir } = buildAppWithProjectDir(spy); const external = mkdtempSync(join(tmpdir(), "hf-render-external-")); tmpDirs.push(external); writeFileSync(join(external, "secret.html"), ""); if (!tryCreateSymlink(external, join(projectDir, "link"), "dir")) return; const res = await postComposition(app, "link/secret.html"); expect(res.status).toBe(400); expect(spy).not.toHaveBeenCalled(); }); it("allows a composition reached through an in-project symlink that stays inside the project", async () => { const spy = vi.fn(); const { app, projectDir } = buildAppWithProjectDir(spy); mkdirSync(join(projectDir, "real")); writeFileSync(join(projectDir, "real", "scene.html"), ""); if (!tryCreateSymlink(join(projectDir, "real"), join(projectDir, "alias"), "dir")) return; const res = await postComposition(app, "alias/scene.html"); expect(res.status).toBe(200); expect(spy).toHaveBeenCalledOnce(); }); }); describe("GET /projects/:id/renders/file/* — path safety", () => { const tmpDirs: string[] = []; function buildApp(): { app: Hono; rendersDir: string } { const rendersDir = mkdtempSync(join(tmpdir(), "hf-renders-out-")); tmpDirs.push(rendersDir); const adapter: StudioApiAdapter = { listProjects: () => [], resolveProject: async (id: string) => ({ id, dir: tmpdir() }), bundle: async () => null, lint: async () => ({ findings: [] }), runtimeUrl: "/api/runtime.js", rendersDir: () => rendersDir, startRender: (opts) => ({ id: opts.jobId, status: "rendering", progress: 0, outputPath: opts.outputPath, }), }; const app = new Hono(); registerRenderRoutes(app, adapter); return { app, rendersDir }; } // Mirror the repo convention (preview.test.ts / composition tests above): // skip symlink cases on non-symlink-privileged Windows runners. function tryCreateSymlink(target: string, path: string, type: "dir" | "file"): boolean { try { symlinkSync(target, path, type); return true; } catch { return false; } } afterEach(() => { for (const d of tmpDirs) rmSync(d, { recursive: true, force: true }); tmpDirs.length = 0; }); it("serves non-Latin-1 filenames with RFC 6266 content dispositions", async () => { const filename = "測試.mp4"; const { app, rendersDir } = buildApp(); const outputPath = join(rendersDir, filename); writeFileSync(outputPath, "render-bytes"); const listResponse = await app.request("http://localhost/projects/demo/renders"); expect(listResponse.status).toBe(200); const jobId = encodeURIComponent(filename.replace(/\.mp4$/, "")); const expectedFilename = `filename="__.mp4"; filename*=UTF-8''${encodeURIComponent(filename)}`; const responses = [ { response: await app.request(`http://localhost/render/${jobId}/view`), disposition: "inline", }, { response: await app.request(`http://localhost/render/${jobId}/download`), disposition: "attachment", }, { response: await app.request( `http://localhost/projects/demo/renders/file/${encodeURIComponent(filename)}`, ), disposition: "inline", }, ]; for (const { response, disposition } of responses) { expect(response.status).toBe(200); const header = response.headers.get("Content-Disposition"); expect(header).toBe(`${disposition}; ${expectedFilename}`); expect(header).toMatch(/^[\x20-\x7e]+$/); } }); it("refuses the desktop app's records when renders/ is linked into .hyperframes/", async () => { const project = mkdtempSync(join(tmpdir(), "hf-renders-project-")); tmpDirs.push(project); mkdirSync(join(project, ".hyperframes")); writeFileSync(join(project, ".hyperframes", "app-history.jsonl"), '{"asked":"secret"}'); if (!tryCreateSymlink(join(project, ".hyperframes"), join(project, "renders"), "dir")) return; const app = new Hono(); registerRenderRoutes(app, { listProjects: () => [], resolveProject: async (id: string) => ({ id, dir: project }), bundle: async () => null, lint: async () => ({ findings: [] }), runtimeUrl: "/api/runtime.js", rendersDir: () => join(project, "renders"), startRender: (opts) => ({ id: opts.jobId, status: "rendering", progress: 0, outputPath: opts.outputPath, }), }); const res = await app.request("http://localhost/projects/demo/renders/file/app-history.jsonl"); expect(res.status).toBe(403); expect(await res.text()).not.toContain("secret"); }); it("never lists, views or downloads a render that links to the app's records", async () => { const project = mkdtempSync(join(tmpdir(), "hf-renders-project-")); tmpDirs.push(project); mkdirSync(join(project, ".hyperframes")); mkdirSync(join(project, "renders")); writeFileSync(join(project, ".hyperframes", "app-history.jsonl"), '{"asked":"secret"}'); writeFileSync(join(project, "renders", "real.mp4"), "render-bytes"); const leak = join(project, "renders", "leak.mp4"); if (!tryCreateSymlink(join(project, ".hyperframes", "app-history.jsonl"), leak, "file")) return; const app = new Hono(); registerRenderRoutes(app, { listProjects: () => [], resolveProject: async (id: string) => ({ id, dir: project }), bundle: async () => null, lint: async () => ({ findings: [] }), runtimeUrl: "/api/runtime.js", rendersDir: () => join(project, "renders"), startRender: (opts) => ({ id: opts.jobId, status: "rendering", progress: 0, outputPath: opts.outputPath, }), }); const list = (await (await app.request("http://localhost/projects/demo/renders")).json()) as { renders: { id: string }[]; }; expect(list.renders.map((r) => r.id)).toEqual(["real"]); for (const kind of ["view", "download"]) { const res = await app.request(`http://localhost/render/leak/${kind}`); expect(res.status).toBe(404); expect(await res.text()).not.toContain("secret"); expect((await app.request(`http://localhost/render/real/${kind}`)).status).toBe(200); } }); it("serves a render file that lives inside rendersDir", async () => { const { app, rendersDir } = buildApp(); writeFileSync(join(rendersDir, "demo.mp4"), "render-bytes"); const res = await app.request("http://localhost/projects/demo/renders/file/demo.mp4"); expect(res.status).toBe(200); expect(await res.text()).toBe("render-bytes"); }); it("rejects a file reached through a symlink inside rendersDir pointing outside it", async () => { const { app, rendersDir } = buildApp(); // A bare join()+readFileSync followed the symlink and leaked the target; // the resolveWithinProject chokepoint canonicalizes with realpath first. const external = mkdtempSync(join(tmpdir(), "hf-renders-external-")); tmpDirs.push(external); writeFileSync(join(external, "secret.txt"), "TOP-SECRET"); if (!tryCreateSymlink(join(external, "secret.txt"), join(rendersDir, "leak.txt"), "file")) return; const res = await app.request("http://localhost/projects/demo/renders/file/leak.txt"); expect(res.status).toBe(403); expect(await res.text()).not.toContain("TOP-SECRET"); }); it("serves a render file reached through a symlink that stays inside rendersDir", async () => { const { app, rendersDir } = buildApp(); mkdirSync(join(rendersDir, "nested")); writeFileSync(join(rendersDir, "nested", "clip.mp4"), "nested-bytes"); if (!tryCreateSymlink(join(rendersDir, "nested"), join(rendersDir, "alias"), "dir")) return; const res = await app.request("http://localhost/projects/demo/renders/file/alias/clip.mp4"); expect(res.status).toBe(200); expect(await res.text()).toBe("nested-bytes"); }); }); describe("POST /render/:jobId/cancel", () => { async function startJob(app: Hono): Promise { const res = await app.request("http://localhost/projects/demo/render", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ fps: 30, quality: "standard", format: "mp4" }), }); expect(res.status).toBe(200); return ((await res.json()) as { jobId: string }).jobId; } it("marks a rendering job cancelled and invokes the adapter abort hook", async () => { const spy = vi.fn(); let aborted = false; const { adapter, rendersDir } = createAdapter(spy); const baseStartRender = adapter.startRender.bind(adapter); adapter.startRender = (opts) => { const state = baseStartRender(opts); state.cancel = () => { aborted = true; }; return state; }; const app = new Hono(); registerRenderRoutes(app, adapter); try { const jobId = await startJob(app); const res = await app.request(`http://localhost/render/${jobId}/cancel`, { method: "POST" }); expect(res.status).toBe(200); expect(((await res.json()) as { status: string }).status).toBe("cancelled"); expect(aborted).toBe(true); // SSE progress for a cancelled job must terminate (status is terminal). const progress = await app.request(`http://localhost/render/${jobId}/progress`); expect(progress.status).toBe(200); } finally { rmSync(rendersDir, { recursive: true, force: true }); } }); it("replies only once the adapter's stop has settled", async () => { const { adapter, rendersDir } = createAdapter(vi.fn()); const baseStartRender = adapter.startRender.bind(adapter); let settled = false; adapter.startRender = (opts) => { const state = baseStartRender(opts); state.cancel = () => new Promise((done) => setTimeout(() => { settled = true; state.status = "failed"; done(); }, 30), ); return state; }; const app = new Hono(); registerRenderRoutes(app, adapter); try { const jobId = await startJob(app); const res = await app.request(`http://localhost/render/${jobId}/cancel`, { method: "POST" }); expect(settled).toBe(true); expect(((await res.json()) as { status: string }).status).toBe("failed"); } finally { rmSync(rendersDir, { recursive: true, force: true }); } }); it("does not cancel a job that already completed", async () => { const spy = vi.fn(); const states: Array<{ status: string }> = []; const { adapter, rendersDir } = createAdapter(spy); const baseStartRender = adapter.startRender.bind(adapter); adapter.startRender = (opts) => { const state = baseStartRender(opts); states.push(state); return state; }; const app = new Hono(); registerRenderRoutes(app, adapter); try { const jobId = await startJob(app); const [state] = states; if (state) state.status = "complete"; const res = await app.request(`http://localhost/render/${jobId}/cancel`, { method: "POST" }); expect(res.status).toBe(200); expect(((await res.json()) as { status: string }).status).toBe("complete"); } finally { rmSync(rendersDir, { recursive: true, force: true }); } }); it("404s for unknown jobs", async () => { const spy = vi.fn(); const { app, cleanup } = buildApp(spy); try { const res = await app.request("http://localhost/render/nope/cancel", { method: "POST" }); expect(res.status).toBe(404); } finally { cleanup(); } }); }); describe("POST /projects/:id/render — telemetryDistinctId forwarding", () => { it("forwards the browser telemetryDistinctId to the adapter as distinctId", async () => { const spy = vi.fn(); const { app, cleanup } = buildApp(spy); try { const res = await app.request("http://localhost/projects/demo/render", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ fps: 30, quality: "standard", format: "mp4", telemetryDistinctId: "browser-user-123", }), }); expect(res.status).toBe(200); expect(spy.mock.calls[0][0].distinctId).toBe("browser-user-123"); } finally { cleanup(); } }); it("passes undefined when no telemetryDistinctId is sent (older clients)", async () => { const spy = vi.fn(); const { app, cleanup } = buildApp(spy); try { const res = await app.request("http://localhost/projects/demo/render", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ fps: 30, quality: "standard", format: "mp4" }), }); expect(res.status).toBe(200); expect(spy.mock.calls[0][0].distinctId).toBeUndefined(); } finally { cleanup(); } }); // Explicit suppression, forwarded so the CLI can honour a browser opt-out // it has no other way to observe. it("forwards an explicit telemetryOptOut", async () => { const spy = vi.fn(); const { app, cleanup } = buildApp(spy); try { const res = await app.request("http://localhost/projects/demo/render", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ fps: 30, quality: "standard", format: "mp4", telemetryOptOut: true, }), }); expect(res.status).toBe(200); expect(spy.mock.calls[0][0].telemetryOptOut).toBe(true); } finally { cleanup(); } }); // WYSIWYG: the browser says whether its preview could blur; only `false` is a signal, and the // route hands every adapter the final render value. it.each([ [false, "off"], [true, undefined], ["false", undefined], [undefined, undefined], ])("maps previewMotionBlur %s to pageMotionBlur %s", async (flag, expected) => { const spy = vi.fn(); const { app, cleanup } = buildApp(spy); try { await app.request("http://localhost/projects/demo/render", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ fps: 30, quality: "standard", format: "mp4", previewMotionBlur: flag, }), }); expect(spy.mock.calls[0][0].pageMotionBlur).toBe(expected); expect(spy.mock.calls[0][0]).not.toHaveProperty("previewMotionBlur"); } finally { cleanup(); } }); it("preserves explicit page motion blur off over preview capability", async () => { const spy = vi.fn(); const { app, cleanup } = buildApp(spy); try { const res = await app.request("http://localhost/projects/demo/render", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ pageMotionBlur: "off", previewMotionBlur: true }), }); expect(res.status).toBe(200); expect(spy.mock.calls[0][0].pageMotionBlur).toBe("off"); } finally { cleanup(); } }); it.each(["on", "", false, true, null, 0])( "rejects invalid page motion blur %s before starting a render", async (pageMotionBlur) => { const spy = vi.fn(); const { app, cleanup } = buildApp(spy); try { const res = await app.request("http://localhost/projects/demo/render", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ pageMotionBlur }), }); expect(res.status).toBe(400); expect(spy).not.toHaveBeenCalled(); } finally { cleanup(); } }, ); // An old client omits the flag, and a non-boolean is not a signal either. // Defaulting those to "opted out" would silently drop every pre-upgrade // render outcome. it.each([undefined, false, "true"])( "treats telemetryOptOut %s as not opted out", async (flag) => { const spy = vi.fn(); const { app, cleanup } = buildApp(spy); try { await app.request("http://localhost/projects/demo/render", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ fps: 30, quality: "standard", format: "mp4", telemetryOptOut: flag, }), }); expect(spy.mock.calls[0][0].telemetryOptOut).toBe(false); } finally { cleanup(); } }, ); it("ignores a non-string telemetryDistinctId", async () => { const spy = vi.fn(); const { app, cleanup } = buildApp(spy); try { const res = await app.request("http://localhost/projects/demo/render", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ fps: 30, quality: "standard", format: "mp4", telemetryDistinctId: 42, }), }); expect(res.status).toBe(200); expect(spy.mock.calls[0][0].distinctId).toBeUndefined(); } finally { cleanup(); } }); }); describe("POST /projects/:id/render — variables forwarding", () => { it("forwards a variables object to the adapter", async () => { const spy = vi.fn(); const { app, cleanup } = buildApp(spy); try { const res = await app.request("http://localhost/projects/demo/render", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ format: "mp4", variables: { title: "Custom", count: 5, dark: true }, }), }); expect(res.status).toBe(200); expect(spy).toHaveBeenCalledOnce(); expect(spy.mock.calls[0][0].variables).toEqual({ title: "Custom", count: 5, dark: true }); } finally { cleanup(); } }); it("omits variables from adapter opts when not provided", async () => { const spy = vi.fn(); const { app, cleanup } = buildApp(spy); try { const res = await app.request("http://localhost/projects/demo/render", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ format: "mp4" }), }); expect(res.status).toBe(200); expect(spy.mock.calls[0][0].variables).toBeUndefined(); } finally { cleanup(); } }); it("rejects non-object variables payloads with 400 (no silent drop)", async () => { const spy = vi.fn(); const { app, cleanup } = buildApp(spy); try { for (const variables of [["a"], "str", 42, null]) { const res = await app.request("http://localhost/projects/demo/render", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ format: "mp4", variables }), }); expect(res.status).toBe(400); } expect(spy).not.toHaveBeenCalled(); } finally { cleanup(); } }); }); describe("POST /projects/:id/render — GPU encoding", () => { it("passes gpu: true on an MP4 export to the adapter as useGpu, and anything else as off", async () => { const spy = vi.fn(); const { app, cleanup } = buildApp(spy); try { const requests = [ { format: "mp4", gpu: true }, { format: "mp4" }, { format: "mp4", gpu: "true" }, { format: "mp4", gpu: 1 }, { format: "webm", gpu: true }, { format: "mov", gpu: true }, ]; for (const body of requests) { const res = await app.request("http://localhost/projects/demo/render", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body), }); expect(res.status).toBe(200); } expect(spy.mock.calls.map(([opts]) => opts.useGpu)).toEqual([ true, false, false, false, false, false, ]); } finally { cleanup(); } }); }); describe("audioLoweredDb — the limiter's attenuation reaches the host", () => { async function completedJobProgress(audioLoweredDb: number | undefined): Promise { const spy = vi.fn(); const { adapter, rendersDir } = createAdapter(spy); const baseStartRender = adapter.startRender.bind(adapter); adapter.startRender = (opts) => { const state = baseStartRender(opts); state.status = "complete"; state.progress = 100; if (audioLoweredDb !== undefined) state.audioLoweredDb = audioLoweredDb; return state; }; const app = new Hono(); registerRenderRoutes(app, adapter); try { const started = await app.request("http://localhost/projects/demo/render", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ fps: 30, quality: "standard", format: "mp4" }), }); const { jobId } = (await started.json()) as { jobId: string }; return await (await app.request(`http://localhost/render/${jobId}/progress`)).text(); } finally { rmSync(rendersDir, { recursive: true, force: true }); } } it("carries audioLoweredDb in the complete progress event", async () => { const body = await completedJobProgress(1.44); expect(body).toContain('"status":"complete"'); expect(body).toContain('"audioLoweredDb":1.44'); }); it("omits it when the limiter did not engage", async () => { expect(await completedJobProgress(undefined)).not.toContain("audioLoweredDb"); }); it("lists it on the render record from the sidecar, and omits it otherwise", async () => { const { app, rendersDir, cleanup } = buildApp(vi.fn()); try { writeFileSync(join(rendersDir, "loud.mp4"), "x"); writeFileSync( join(rendersDir, "loud.meta.json"), JSON.stringify({ status: "complete", audioLoweredDb: 1.44 }), ); writeFileSync(join(rendersDir, "quiet.mp4"), "x"); writeFileSync(join(rendersDir, "quiet.meta.json"), JSON.stringify({ status: "complete" })); const { renders } = (await ( await app.request("http://localhost/projects/demo/renders") ).json()) as { renders: Array<{ id: string; audioLoweredDb?: number }> }; expect(renders.find((r) => r.id === "loud")?.audioLoweredDb).toBe(1.44); expect(renders.find((r) => r.id === "quiet")).not.toHaveProperty("audioLoweredDb"); } finally { cleanup(); } }); }); describe("Studio GIF renders", () => { it.each([undefined, null, 0, 1, 65535])("accepts GIF with gifLoop %j", async (gifLoop) => { const spy = vi.fn(); const { app, cleanup } = buildApp(spy); try { const res = await app.request("/projects/demo/render", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ format: "gif", gifLoop, gpu: true }), }); expect(res.status).toBe(200); expect(spy).toHaveBeenCalledWith( expect.objectContaining({ format: "gif", outputPath: expect.stringMatching(/\.gif$/), useGpu: false, ...(typeof gifLoop === "number" ? { gifLoop } : {}), }), ); if (gifLoop == null) expect(spy.mock.calls[0][0]).not.toHaveProperty("gifLoop"); } finally { cleanup(); } }); it.each([-1, 65536, 1.5, "2", true, {}, []])( "rejects invalid gifLoop %j before starting", async (gifLoop) => { const spy = vi.fn(); const { app, cleanup } = buildApp(spy); try { const res = await app.request("/projects/demo/render", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ format: "gif", gifLoop }), }); expect(res.status).toBe(400); expect(await res.json()).toEqual({ error: "gifLoop must be an integer from 0 to 65535" }); expect(spy).not.toHaveBeenCalled(); } finally { cleanup(); } }, ); it("leaves video exports unchanged when a valid GIF loop option is supplied", async () => { const spy = vi.fn(); const { app, cleanup } = buildApp(spy); try { const res = await app.request("/projects/demo/render", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ format: "mp4", gifLoop: 3 }), }); expect(res.status).toBe(200); expect(spy.mock.calls[0][0]).not.toHaveProperty("gifLoop"); } finally { cleanup(); } }); it("lists a saved GIF after restart, serves image bytes, and deletes its sidecar", async () => { const { app, rendersDir, cleanup } = buildApp(vi.fn()); try { const output = join(rendersDir, "saved.gif"); const meta = join(rendersDir, "saved.meta.json"); writeFileSync(output, "GIF89a"); writeFileSync(meta, JSON.stringify({ status: "complete", durationMs: 42 })); const list = await app.request("/projects/demo/renders"); expect(await list.json()).toMatchObject({ renders: [{ id: "saved", filename: "saved.gif", durationMs: 42 }], }); for (const url of [ "/projects/demo/renders/file/saved.gif", "/render/saved/view", "/render/saved/download", ]) { const res = await app.request(url); expect(res.status).toBe(200); expect(res.headers.get("content-type")).toBe("image/gif"); expect(await res.text()).toBe("GIF89a"); expect(res.headers.get("content-disposition")).toContain( url.endsWith("download") ? "attachment" : "inline", ); } expect((await app.request("/render/saved", { method: "DELETE" })).status).toBe(200); expect(existsSync(output)).toBe(false); expect(existsSync(meta)).toBe(false); expect(await (await app.request("/projects/demo/renders")).json()).toEqual({ renders: [] }); } finally { cleanup(); } }); }); describe("Studio GIF frame-rate cap", () => { it.each([ { format: "gif", fps: 60, expected: { num: 30, den: 1 } }, { format: "gif", fps: "60000/1001", expected: { num: 30, den: 1 } }, { format: "gif", fps: "30001/1000", expected: { num: 30, den: 1 } }, { format: "gif", fps: "30000/1001", expected: { num: 30000, den: 1001 } }, { format: "gif", fps: 30, expected: { num: 30, den: 1 } }, { format: "gif", fps: 24, expected: { num: 24, den: 1 } }, { format: "mp4", fps: 60, expected: { num: 60, den: 1 } }, { format: "webm", fps: 60, expected: { num: 60, den: 1 } }, { format: "mov", fps: 60, expected: { num: 60, den: 1 } }, ])("forwards $format at $fps fps as $expected", async ({ format, fps, expected }) => { const spy = vi.fn(); const { app, cleanup } = buildApp(spy); try { const res = await app.request("/projects/demo/render", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ format, fps }), }); expect(res.status).toBe(200); expect(spy).toHaveBeenCalledWith(expect.objectContaining({ format, fps: expected })); } finally { cleanup(); } }); }); describe("POST /projects/:id/render — range", () => { async function post(body: Record) { const spy = vi.fn(); const { app, cleanup } = buildApp(spy); try { const res = await app.request("http://localhost/projects/demo/render", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ fps: 30, format: "mp4", ...body }), }); return { res, opts: spy.mock.calls[0]?.[0] }; } finally { cleanup(); } } it("forwards a start and an end to the adapter as the range", async () => { const { res, opts } = await post({ start: 2.3, end: 6.7 }); expect(res.status).toBe(200); expect(opts.range).toEqual({ startSeconds: 2.3, endSeconds: 6.7 }); }); it("starts at 0 without a start and runs to the film's end without an end", async () => { expect((await post({ end: 4 })).opts.range).toEqual({ startSeconds: 0, endSeconds: 4 }); expect((await post({ start: 4 })).opts.range).toEqual({ startSeconds: 4 }); }); it("asks for the whole film when neither is sent", async () => { const { opts } = await post({}); expect(opts).not.toHaveProperty("range"); }); it.each([ [{ start: -1 }], [{ start: "2" }], [{ end: "4" }], [{ start: null }], [{ start: 5, end: 5 }], [{ start: 5, end: 2 }], ])("refuses %j with 400 and starts no render", async (range) => { const { res, opts } = await post(range); expect(res.status).toBe(400); expect(opts).toBeUndefined(); }); });