Write HTML. Render video. Built for agents.
JavaScript aiai-agentsanimationclaude-codeffmpegframeworkgsaphtmlhtml-to-videomcpmotion-graphicspuppeteerrenderingtypescriptvideo-editor
fix(cli): check warns when a video's browser-playable copy cannot be made (#5441)
Miguel Ángelbf7f6deae932
diff --git a/packages/cli/src/utils/checkBrowser.test.ts b/packages/cli/src/utils/checkBrowser.test.tsindex bc6768cf57..9ec9d5aff6 100644--- a/packages/cli/src/utils/checkBrowser.test.ts+++ b/packages/cli/src/utils/checkBrowser.test.ts@@ -13,6 +13,7 @@ import {captureOverviewShot,keepBrokenImageAborts,preResolveHostileMediaProxies,+ dropFailedProxyEchoes,runBrowserCheck,collectSeekClock,} from "./checkBrowser.js";@@ -21,7 +22,9 @@ import type { ProjectDir } from "./project.js";const mocks = vi.hoisted(() => ({bundleWithLocalizedFonts: vi.fn(async () => "<html></html>"),serverClose: vi.fn(async () => undefined),- resolveProxy: vi.fn<(projectDir: string, absoluteSourcePath: string) => Promise<string>>(),+ resolveProxy:+ vi.fn<(projectDir: string, absoluteSourcePath: string, variant?: string) => Promise<string>>(),+ FfmpegUnavailableError: class FfmpegUnavailableError extends Error {},scanProjectMediaCodecMap: vi.fn<(...args: unknown[]) => Promise<Record<@@ -75,7 +78,11 @@ vi.mock("@hyperframes/studio-server/media-codec-map", async (importOriginal) =>proxyVariantFor: (facts: { hasAlpha?: boolean }) => (facts.hasAlpha ? "vp8" : "h264"),}));vi.mock("@hyperframes/studio-server/proxy-transcoder", () => ({- resolveProxy: mocks.resolveProxy,+ FfmpegUnavailableError: mocks.FfmpegUnavailableError,+ resolveProxies: (projectDir: string, sources: Array<{ sourcePath: string; variant: string }>) =>+ Promise.allSettled(+ sources.map(({ sourcePath, variant }) => mocks.resolveProxy(projectDir, sourcePath, variant)),+ ),}));const PROJECT: ProjectDir = {@@ -361,6 +368,40 @@ it("carries validate's clip-duration audit into the runtime findings", async ()]);});+it("reports each video whose browser-playable copy could not be made as a warning finding", async () => {+ mountCanvasFixture();+ mocks.scanProjectMediaCodecMap.mockResolvedValue({+ "/media/hlg.mp4": {+ codecName: "hevc",+ browserHostile: true,+ representativeMime: null,+ hasAlpha: false,+ },+ });+ mocks.resolveProxy.mockRejectedValue(+ new Error("HDR proxying requires ffmpeg zscale/tonemap filters (libzimg)"),+ );+ vi.spyOn(console, "error").mockImplementation(() => undefined);+ installSessionMock(fakePage());++ const result = await runBrowserCheck(+ PROJECT,+ { ...DEFAULT_CHECK_OPTIONS, samples: 1, contrast: false },+ { kind: "none" },+ runAuditGrid,+ );++ expect(result.runtimeFindings).toContainEqual(+ expect.objectContaining({+ code: "media_proxy_failed",+ severity: "warning",+ message: expect.stringContaining(+ "media/hlg.mp4: HDR proxying requires ffmpeg zscale/tonemap filters (libzimg)",+ ),+ }),+ );+});+it("surfaces the runtime's media-proxy-fallback console.info line as an info finding, ignoring unrelated info logs", async () => {vi.spyOn(Date, "now").mockReturnValue(100);mountCanvasFixture();@@ -640,6 +681,53 @@ describe("keepBrokenImageAborts", () => {});});+describe("dropFailedProxyEchoes", () => {+ it("keeps one finding for a failed proxy and drops the preview's repeats of it", () => {+ const at = (code: string, message: string, url?: string) =>+ ({ code, severity: "info", message, time: 0, url }) as const;+ const failed = at("media_proxy_failed", "Could not make a copy of media/a.mov");+ const unrelated502 = at(+ "http_error",+ "502 loading media/b.mov",+ "http://127.0.0.1:3000/media/b.mov?hf-proxy=h264",+ );+ const originalMissing = at(+ "http_error",+ "404 loading media/a.mov",+ "http://127.0.0.1:3000/media/a.mov",+ );++ const kept = dropFailedProxyEchoes(+ [+ failed,+ at(+ "http_error",+ "502 loading media/my clip.mov",+ "http://127.0.0.1:3000/media/my%20clip.mov?hf-proxy=h264",+ ),+ at(+ "http_error",+ "502 loading media/a.mov",+ "http://127.0.0.1:3000/media/a.mov?hf-proxy=h264",+ ),+ at(+ "media_proxy_fallback",+ '[hyperframes] runtime_media_proxy_fallback: "media/a.mov" uses a codec (prores)',+ ),+ at(+ "media_proxy_unavailable",+ '[hyperframes] runtime_media_proxy_unavailable: "http://127.0.0.1:3000/media/a.mov" (proxy_playback_failed): x',+ ),+ unrelated502,+ originalMissing,+ ],+ new Set(["/media/a.mov", "/media/my clip.mov"]),+ );++ expect(kept).toEqual([failed, unrelated502, originalMissing]);+ });+});+describe("preResolveHostileMediaProxies", () => {const dirs: string[] = [];const mkProjectDir = (): string => {@@ -708,7 +796,7 @@ describe("preResolveHostileMediaProxies", () => {expect(mocks.resolveProxy).not.toHaveBeenCalled();});- it("swallows a resolveProxy rejection instead of throwing", async () => {+ it("returns a resolveProxy rejection as a warning instead of throwing", async () => {const projectDir = mkProjectDir();mocks.scanProjectMediaCodecMap.mockResolvedValue({"/clip.mp4": {@@ -721,14 +809,42 @@ describe("preResolveHostileMediaProxies", () => {mocks.resolveProxy.mockRejectedValue(new Error("ffmpeg exited with code 1"));const errorSpy = vi.spyOn(console, "error").mockImplementation(() => undefined);- await expect(- preResolveHostileMediaProxies(projectDir, "<html></html>"),- ).resolves.toBeUndefined();+ await expect(preResolveHostileMediaProxies(projectDir, "<html></html>")).resolves.toEqual({+ findings: [+ expect.objectContaining({+ code: "media_proxy_failed",+ severity: "warning",+ message: expect.stringContaining("clip.mp4: ffmpeg exited with code 1"),+ }),+ ],+ failedPaths: new Set(["/clip.mp4"]),+ });expect(errorSpy).toHaveBeenCalledWith(expect.stringContaining("media proxy pre-resolve: 0/1 ready, 1 failed"),);});+ it("reports an unusable ffmpeg once for every video, without promising a working render", async () => {+ const projectDir = mkProjectDir();+ const hevc = {+ codecName: "hevc",+ browserHostile: true,+ representativeMime: null,+ hasAlpha: false,+ };+ mocks.scanProjectMediaCodecMap.mockResolvedValue({ "/a.mp4": hevc, "/b.mp4": hevc });+ mocks.resolveProxy.mockRejectedValue(+ new mocks.FfmpegUnavailableError("ffmpeg binary not found"),+ );+ vi.spyOn(console, "error").mockImplementation(() => undefined);++ const { findings } = await preResolveHostileMediaProxies(projectDir, "<html></html>");++ expect(findings).toHaveLength(1);+ expect(findings[0]?.message).toContain("copies of a.mp4, b.mp4: ffmpeg binary not found");+ expect(findings[0]?.message).not.toContain("render");+ });+// `check --json` stdout must stay pure JSON, so these lines belong on stderr.it("writes the pre-resolve summary to stderr and leaves stdout untouched", async () => {const projectDir = mkProjectDir();@@ -766,9 +882,10 @@ describe("preResolveHostileMediaProxies", () => {const infoSpy = vi.spyOn(console, "info").mockImplementation(() => undefined);const stdoutSpy = vi.spyOn(process.stdout, "write").mockImplementation(() => true);- await expect(- preResolveHostileMediaProxies(projectDir, "<html></html>"),- ).resolves.toBeUndefined();+ await expect(preResolveHostileMediaProxies(projectDir, "<html></html>")).resolves.toEqual({+ findings: [],+ failedPaths: new Set(),+ });expect(errorSpy).toHaveBeenCalledWith("[hyperframes] media proxy pre-resolve: scan failed (ffprobe not found)",diff --git a/packages/cli/src/utils/checkBrowser.ts b/packages/cli/src/utils/checkBrowser.tsindex 295eee1d1a..3793aac7f3 100644--- a/packages/cli/src/utils/checkBrowser.ts+++ b/packages/cli/src/utils/checkBrowser.ts@@ -29,7 +29,10 @@ import {proxyVariantFor,scanProjectMediaCodecMap,} from "@hyperframes/studio-server/media-codec-map";-import { resolveProxy } from "@hyperframes/studio-server/proxy-transcoder";+import {+ FfmpegUnavailableError,+ resolveProxies,+} from "@hyperframes/studio-server/proxy-transcoder";import { rectToBbox } from "./checkTypes.js";import type {AnchoredLayoutIssue,@@ -110,15 +113,16 @@ interface FinishedContrast {* hostile-asset check (e.g. a fresh CI checkout) would race the timeout* instead of paying a bounded one-time transcode cost* (docs/plans/2026-07-14-002-feat-transparent-media-proxies-plan.md, unit U4).- * Best-effort: a probe or transcode failure does not fail `check`; one summary- * line records the pre-resolve outcome before the runtime attempts playback.+ * A failed copy is a warning, not an error: a default render decodes the original with+ * ffmpeg. One warning per failed file, or one for all of them when ffmpeg itself is unusable.*/export async function preResolveHostileMediaProxies(projectDir: string,html: string,autoProxyOverride?: boolean,-): Promise<void> {- if (!resolveAutoProxy(projectDir, autoProxyOverride)) return;+): Promise<ProxyPreResolution> {+ const none: ProxyPreResolution = { findings: [], failedPaths: new Set() };+ if (!resolveAutoProxy(projectDir, autoProxyOverride)) return none;let codecMap: Awaited<ReturnType<typeof scanProjectMediaCodecMap>>;try {codecMap = await scanProjectMediaCodecMap(projectDir, [{ html }]);@@ -126,27 +130,58 @@ export async function preResolveHostileMediaProxies(console.error(`[hyperframes] media proxy pre-resolve: scan failed (${normalizeErrorMessage(err)})`,);- return;+ return none;}const hostileEntries = Object.entries(codecMap).filter(([, facts]) => decideMediaProxyEligibility(facts).eligible,);- if (hostileEntries.length === 0) return;+ if (hostileEntries.length === 0) return none;const startedAt = Date.now();- const results = await Promise.allSettled(- hostileEntries.map(([pathname, facts]) =>- resolveProxy(- projectDir,- resolve(projectDir, pathname.replace(/^\/+/, "")),- proxyVariantFor(facts),- ),- ),- );- const failed = results.filter((result) => result.status === "rejected").length;+ const sources = hostileEntries.map(([pathname, facts]) => {+ const file = pathname.replace(/^\/+/, "");+ return {+ pathname,+ file,+ sourcePath: resolve(projectDir, file),+ variant: proxyVariantFor(facts),+ };+ });+ const results = await resolveProxies(projectDir, sources);+ const failures = sources.flatMap((source, index) => {+ const result = results[index]!;+ return result.status === "rejected" ? [{ ...source, reason: result.reason }] : [];+ });+ const total = hostileEntries.length;console.error(- `[hyperframes] media proxy pre-resolve: ${results.length - failed}/${results.length} ready, ${failed} failed (${Date.now() - startedAt}ms)`,+ `[hyperframes] media proxy pre-resolve: ${total - failures.length}/${total} ready, ${failures.length} failed (${Date.now() - startedAt}ms)`,);+ const unusableFfmpeg = failures.filter(({ reason }) => reason instanceof FfmpegUnavailableError);+ const findings = failures+ .filter(({ reason }) => !(reason instanceof FfmpegUnavailableError))+ .map(({ file, reason }) =>+ proxyFailedDraft(+ `Could not make a browser-playable copy of ${file}: ${normalizeErrorMessage(reason)}. A default render decodes the original with ffmpeg and does not need it, but publish stops on it (unless run with --no-proxy) and a browser that cannot decode the original will not play it in preview.`,+ ),+ );+ if (unusableFfmpeg[0]) {+ findings.unshift(+ proxyFailedDraft(+ `Could not make browser-playable copies of ${unusableFfmpeg.map(({ file }) => file).join(", ")}: ${normalizeErrorMessage(unusableFfmpeg[0].reason)}. Publish stops on them (unless run with --no-proxy) and a browser that cannot decode them will not play them in preview.`,+ ),+ );+ }+ return { findings, failedPaths: new Set(failures.map(({ pathname }) => pathname)) };+}++interface ProxyPreResolution {+ findings: RuntimeDraft[];+ /** Root-relative paths of the videos whose copy failed. */+ failedPaths: Set<string>;+}++function proxyFailedDraft(message: string): RuntimeDraft {+ return { code: "media_proxy_failed", severity: "warning", message, time: 0 };}export async function runBrowserCheck(@@ -157,7 +192,11 @@ export async function runBrowserCheck(): Promise<CheckBrowserResult> {const { bundleWithLocalizedFonts } = await import("./bundleWithLocalizedFonts.js");const html = await bundleWithLocalizedFonts(project.dir);- await preResolveHostileMediaProxies(project.dir, html, options.autoProxy);+ const { findings: drafts, failedPaths } = await preResolveHostileMediaProxies(+ project.dir,+ html,+ options.autoProxy,+ );const server = await serveStaticProjectHtml(project.dir,html,@@ -165,7 +204,6 @@ export async function runBrowserCheck([],options.autoProxy,);- const drafts: RuntimeDraft[] = [];let currentTime = 0;let chromeBrowser: import("puppeteer-core").Browser | undefined;@@ -201,9 +239,10 @@ export async function runBrowserCheck(return {...result,timings: { ...result.timings, launchSettleMs },- runtimeFindings: keepBrokenImageAborts(drafts, broken).map((draft) =>- runtimeFinding(draft, rootAnchor),- ),+ runtimeFindings: dropFailedProxyEchoes(+ keepBrokenImageAborts(drafts, broken),+ failedPaths,+ ).map((draft) => runtimeFinding(draft, rootAnchor)),};} finally {await chromeBrowser?.close().catch(() => undefined);@@ -377,6 +416,44 @@ export function keepBrokenImageAborts(drafts: RuntimeDraft[], broken: Set<stringreturn drafts.filter((draft) => !draft.abortedImage || broken.has(draft.url ?? ""));}+/** One finding per failed proxy: the preview's own 502s and swap notes for that file repeat `media_proxy_failed`. */+export function dropFailedProxyEchoes(+ drafts: RuntimeDraft[],+ failedPaths: ReadonlySet<string>,+): RuntimeDraft[] {+ if (failedPaths.size === 0) return drafts;+ return drafts.filter((draft) => !failedPaths.has(proxyEchoPath(draft) ?? ""));+}++function proxyEchoPath(draft: RuntimeDraft): string | undefined {+ if (draft.code === "http_error" || draft.code === "request_failed") {+ const url = parseUrl(draft.url);+ return url?.searchParams.has("hf-proxy") ? decodedPath(url) : undefined;+ }+ if (draft.code === "media_proxy_fallback" || draft.code === "media_proxy_unavailable") {+ return decodedPath(parseUrl(/"([^"]+)"/.exec(draft.message)?.[1]));+ }+ return undefined;+}++function parseUrl(target: string | undefined): URL | undefined {+ if (!target) return undefined;+ try {+ return new URL(target, "http://check.invalid/");+ } catch {+ return undefined;+ }+}++function decodedPath(url: URL | undefined): string | undefined {+ if (!url) return undefined;+ try {+ return decodeURIComponent(url.pathname);+ } catch {+ return undefined;+ }+}+const IMAGE_DECODE_CAP_MS = 5000;async function abortedImagesStillBroken(page: Page, drafts: RuntimeDraft[]): Promise<Set<string>> {diff --git a/packages/cli/src/utils/publishProxyBake.test.ts b/packages/cli/src/utils/publishProxyBake.test.tsindex b98f98ccbd..13b7f31b34 100644--- a/packages/cli/src/utils/publishProxyBake.test.ts+++ b/packages/cli/src/utils/publishProxyBake.test.ts@@ -20,7 +20,10 @@ const mocks = vi.hoisted(() => {}}return {- resolveProxy: vi.fn<(projectDir: string, absoluteSourcePath: string) => Promise<string>>(),+ resolveProxy:+ vi.fn<+ (projectDir: string, absoluteSourcePath: string, variant?: string) => Promise<string>+ >(),scanProjectMediaCodecMap: vi.fn<(...args: unknown[]) => Promise<Record<@@ -35,16 +38,16 @@ const mocks = vi.hoisted(() => {>>(),ProxyTranscodeError: FakeProxyTranscodeError,- waitForProxy: vi.fn(<T>(promise: Promise<T>, _timeoutMs?: number) => promise),};});const FakeProxyTranscodeError = mocks.ProxyTranscodeError;vi.mock("@hyperframes/studio-server/proxy-transcoder", () => ({- resolveProxy: mocks.resolveProxy,+ resolveProxies: (projectDir: string, sources: Array<{ sourcePath: string; variant: string }>) =>+ Promise.allSettled(+ sources.map(({ sourcePath, variant }) => mocks.resolveProxy(projectDir, sourcePath, variant)),+ ),ProxyTranscodeError: mocks.ProxyTranscodeError,- waitForProxy: mocks.waitForProxy,- TRANSCODE_TIMEOUT_MS: 15 * 60 * 1000,}));vi.mock("@hyperframes/studio-server/media-codec-map", () => ({@@ -114,7 +117,6 @@ describe("bakeMediaProxies", () => {join(PROJECT_DIR, "clip.mp4"),"h264",);- expect(mocks.waitForProxy).toHaveBeenCalledWith(expect.any(Promise), 15 * 60 * 1000);expect(manifest).toEqual({ proxied: ["/clip.mp4"], skippedAlpha: [], failed: [] });});diff --git a/packages/cli/src/utils/publishProxyBake.ts b/packages/cli/src/utils/publishProxyBake.tsindex 4bd785e47a..a9cda3ebc8 100644--- a/packages/cli/src/utils/publishProxyBake.ts+++ b/packages/cli/src/utils/publishProxyBake.ts@@ -40,12 +40,7 @@ import {scanProjectMediaCodecMap,type HtmlSourceLike,} from "@hyperframes/studio-server/media-codec-map";-import {- ProxyTranscodeError,- resolveProxy,- waitForProxy,- TRANSCODE_TIMEOUT_MS,-} from "@hyperframes/studio-server/proxy-transcoder";+import { ProxyTranscodeError, resolveProxies } from "@hyperframes/studio-server/proxy-transcoder";import { rewriteHtmlAttributes } from "./publishProject.js";/** Archive-path prefix for baked proxy files, mirroring `localizeExternalAssets`'s `_ext/`. */@@ -109,17 +104,20 @@ export async function bakeMediaProxies(// filesystem path.const proxyByAbsolutePath = new Map<string, string>();+ const sources = hostileEntries.map(([pathname, facts]) => ({+ pathname,+ sourcePath: resolve(absProjectDir, pathname.replace(/^\/+/, "")),+ variant: proxyVariantFor(facts),+ }));+ const results = await resolveProxies(absProjectDir, sources);await Promise.all(- hostileEntries.map(async ([pathname, facts]) => {- const absoluteSourcePath = resolve(absProjectDir, pathname.replace(/^\/+/, ""));+ sources.map(async ({ pathname, sourcePath }, index) => {+ const result = results[index]!;try {- const proxyPath = await waitForProxy(- resolveProxy(absProjectDir, absoluteSourcePath, proxyVariantFor(facts)),- TRANSCODE_TIMEOUT_MS,- );- const archivePath = `${PROXY_ARCHIVE_PREFIX}/${basename(proxyPath)}`;- fileContents.set(archivePath, await readFile(proxyPath));- proxyByAbsolutePath.set(absoluteSourcePath, archivePath);+ if (result.status === "rejected") throw result.reason;+ const archivePath = `${PROXY_ARCHIVE_PREFIX}/${basename(result.value)}`;+ fileContents.set(archivePath, await readFile(result.value));+ proxyByAbsolutePath.set(sourcePath, archivePath);manifest.proxied.push(pathname);} catch (err) {const reason = err instanceof ProxyTranscodeError ? err.message : String(err);diff --git a/packages/studio-server/src/helpers/proxyTranscoder.test.ts b/packages/studio-server/src/helpers/proxyTranscoder.test.tsindex 4a258c41e3..f593d41e7e 100644--- a/packages/studio-server/src/helpers/proxyTranscoder.test.ts+++ b/packages/studio-server/src/helpers/proxyTranscoder.test.ts@@ -90,6 +90,28 @@ async function flush(times = 6): Promise<void> {for (let i = 0; i < times; i++) await Promise.resolve();}+/** One more source than the queue can hold, to prove a batch never overflows it. */+function batchSources(projectDir: string): Array<{ sourcePath: string; variant: "h264" }> {+ return Array.from({ length: MAX_CONCURRENT + MAX_QUEUED + 1 }, (_, i) => {+ const sourcePath = join(projectDir, `batch-${i}.mov`);+ writeFileSync(sourcePath, `source-${i}`);+ return { sourcePath, variant: "h264" };+ });+}++/** Answers every ffmpeg spawn until no new one starts. A finished copy reaches the+ * next spawn through several promise hops, hence the deep flush. */+async function answerUntilIdle(+ calls: SpawnCall[],+ answer: (call: SpawnCall) => void,+): Promise<void> {+ for (let done = 0; ; done = calls.length) {+ await flush(50);+ if (calls.length === done) return;+ calls.slice(done).forEach(answer);+ }+}+const tempDirs: string[] = [];function tmpProject(): string {@@ -550,6 +572,34 @@ describe("resolveProxy", () => {await expect(retry).resolves.toBeTruthy();});+ it("resolves a whole project's batch past the queue cap by waiting for room, not refusing", async () => {+ const { spawn, calls } = createSpawnSpy();+ const { resolveProxies } = await loadModule(spawn, FFMPEG_PATH);+ const projectDir = tmpProject();+ const sources = batchSources(projectDir);++ const batch = resolveProxies(projectDir, sources);+ await answerUntilIdle(calls, (call) => succeed(call));++ const results = await batch;+ expect(results.map((result) => result.status)).toEqual(sources.map(() => "fulfilled"));+ });++ it("settles each request of a batch on its own when one of them fails", async () => {+ const { spawn, calls } = createSpawnSpy();+ const { resolveProxies } = await loadModule(spawn, FFMPEG_PATH);+ const projectDir = tmpProject();+ const sources = batchSources(projectDir);+ const failing = (call: SpawnCall) => call.args.some((arg) => arg.endsWith("batch-3.mov"));++ const batch = resolveProxies(projectDir, sources);+ await answerUntilIdle(calls, (call) => (failing(call) ? fail(call) : succeed(call)));++ const statuses = (await batch).map((result) => result.status);+ expect(statuses.filter((status) => status === "fulfilled")).toHaveLength(sources.length - 1);+ expect(statuses[3]).toBe("rejected");+ });+describe("queue order and callers that leave", () => {function clipOf(call: SpawnCall): string {return basename(call.args[call.args.indexOf("-i") + 1]!, ".mov");@@ -857,10 +907,21 @@ describe("resolveProxy", () => {const resultPromise = resolveProxy(projectDir, sourcePath);await flush();expect(calls).toHaveLength(1);- fail(calls[0]!, 1, "ffmpeg: unsupported codec");+ fail(+ calls[0]!,+ 1,+ [+ "Input #0, mov, from 'video.mov': unsupported codec",+ "[hevc] Error while decoding stream #0:0: Invalid data found when processing input",+ "Error submitting a packet to the muxer: No space left on device.",+ "Conversion failed!",+ ].join("\n"),+ );await expect(resultPromise).rejects.toBeInstanceOf(ProxyTranscodeError);await expect(resultPromise).rejects.toMatchObject({+ message:+ "ffmpeg exited with code 1: Error submitting a packet to the muxer: No space left on device",exitCode: 1,stderrTail: expect.stringContaining("unsupported codec"),});@@ -1091,4 +1152,18 @@ describe("resolveProxy", () => {await expect(resolveProxy(projectDir, sourcePath)).rejects.toBeInstanceOf(ProxyTranscodeError);expect(calls).toHaveLength(0);});++ it("treats an ffmpeg that cannot start as an unusable environment, not a bad source", async () => {+ const { spawn, calls } = createSpawnSpy();+ const { resolveProxy, FfmpegUnavailableError } = await loadModule(spawn, FFMPEG_PATH);+ const projectDir = tmpProject();+ const sourcePath = join(projectDir, "video.mov");+ writeFileSync(sourcePath, "source-bytes");++ const result = resolveProxy(projectDir, sourcePath);+ await flush();+ calls[0]!.proc.emit("error", new Error("EACCES"));++ await expect(result).rejects.toBeInstanceOf(FfmpegUnavailableError);+ });});diff --git a/packages/studio-server/src/helpers/proxyTranscoder.ts b/packages/studio-server/src/helpers/proxyTranscoder.tsindex 5e866f68fe..f67a33bb71 100644--- a/packages/studio-server/src/helpers/proxyTranscoder.ts+++ b/packages/studio-server/src/helpers/proxyTranscoder.ts@@ -61,12 +61,13 @@ export class ProxyTranscodeError extends Error {}}-/** "ffmpeg isn't installed" — an environment condition, not a per-source+/** ffmpeg is missing or cannot start — an environment condition, not a per-source* failure, so the negative cache below keeps it only briefly* (installing ffmpeg mid-session must recover without a server restart). */-class FfmpegUnavailableError extends ProxyTranscodeError {- constructor() {- super("ffmpeg binary not found", null, "");+export class FfmpegUnavailableError extends ProxyTranscodeError {+ constructor(message = "ffmpeg binary not found", stderrTail = "") {+ super(message, null, stderrTail);+ this.name = "FfmpegUnavailableError";}}@@ -394,6 +395,19 @@ function proxyScaleFilter(box?: PreviewProxyBox): string {return `scale=${side("iw")}:${side("ih")}`;}+const STDERR_ERROR_LINE = /error|invalid|denied|no space|not found|unknown/i;++/** ffmpeg ends most failures with "Conversion failed!"; the cause is the last error-looking line above it. */+function stderrReason(stderrTail: string): string {+ const lines = stderrTail+ .split("\n")+ .map((line) => line.trim())+ .filter(Boolean);+ const errorLines = lines.filter((line) => STDERR_ERROR_LINE.test(line));+ const line = errorLines.at(-1) ?? lines.at(-1);+ return line ? `: ${line.replace(/[.!]+$/, "")}` : "";+}+async function runFfmpeg(sourcePath: string,outputPath: string,@@ -490,7 +504,7 @@ async function runFfmpeg(stderrTail = (stderrTail + chunk.toString()).slice(-STDERR_TAIL_MAX_CHARS);});proc.on("error", (err) => {- reject(new ProxyTranscodeError(`failed to spawn ffmpeg: ${err.message}`, null, stderrTail));+ reject(new FfmpegUnavailableError(`failed to spawn ffmpeg: ${err.message}`, stderrTail));});proc.on("close", (code, signal) => {if (code === 0) {@@ -504,7 +518,13 @@ async function runFfmpeg(),);} else {- reject(new ProxyTranscodeError(`ffmpeg exited with code ${code}`, code, stderrTail));+ reject(+ new ProxyTranscodeError(+ `ffmpeg exited with code ${code}${stderrReason(stderrTail)}`,+ code,+ stderrTail,+ ),+ );}});});@@ -619,6 +639,31 @@ export async function resolveProxy(return joinJob(entry.promise, entry.job, options.signal);}+/** Batch resolve for check and publish: at most MAX_CONCURRENT_TRANSCODES of its own requests in+ * flight (other callers can still fill the queue); each waits at most TRANSCODE_TIMEOUT_MS. */+export async function resolveProxies(+ projectDir: string,+ sources: ReadonlyArray<{ sourcePath: string; variant: ProxyVariant }>,+): Promise<PromiseSettledResult<string>[]> {+ const results: PromiseSettledResult<string>[] = [];+ let next = 0;+ const worker = async (): Promise<void> => {+ for (let index = next++; index < sources.length; index = next++) {+ const { sourcePath, variant } = sources[index]!;+ results[index] = await waitForProxy(+ resolveProxy(projectDir, sourcePath, variant),+ TRANSCODE_TIMEOUT_MS,+ ).then(+ (value) => ({ status: "fulfilled", value }),+ (reason: unknown) => ({ status: "rejected", reason }),+ );+ }+ };+ const workers = Math.min(MAX_CONCURRENT_TRANSCODES, sources.length);+ await Promise.all(Array.from({ length: workers }, worker));+ return results;+}+export interface ResolveProxyOptions {priority?: boolean;signal?: AbortSignal;