The open creative studio on ComfyUI: images, video, 3D and audio on open weights, on your own GPU or the cloud. Camera motions, effects, apps, Cinema, Layers, Image to 3D and an AI agent.
TypeScript ai-videocomfyuicreative-toolsgenerative-aiideogramimage-generationimage-to-3dimage-to-videoltx-videominimax-h3nextjsopen-sourceopen-weightsqwen-imagetext-to-imagevideo-generationwan
Green screen: an EXR key of a clip longer than one pass waits for the last pass and keeps every pass's frames
Claudeddbdb72cf1af
diff --git a/src/lib/computer-runner.ts b/src/lib/computer-runner.tsindex 7b74855a..d01e1549 100644--- a/src/lib/computer-runner.ts+++ b/src/lib/computer-runner.ts@@ -10,7 +10,7 @@import { isGuard } from "./comfy-guard";import { parseComfyBinary, parseComfyText } from "./comfy-ws";import { graphProblem, localBase, mayDownload, readPath, statsFacts, viewPath, writePath, type SystemStats } from "./local-comfy";-import { DONE_SHOWN_MS, RELAY_LIMITS, RELAY_TIMES, type BeatAnswer, type ClaimedTask, type ComputerFacts, type HistoryEntryLike, type RelayState, type ReportEvent, type TabFailure, type WantedFile } from "./relay";+import { DONE_SHOWN_MS, META_BATCH_HISTORY, RELAY_LIMITS, RELAY_TIMES, type BeatAnswer, type ClaimedTask, type ComputerFacts, type HistoryEntryLike, type RelayState, type ReportEvent, type TabFailure, type WantedFile } from "./relay";/** The parts of a WebSocket the runner uses (the browser's, or Node's). */export interface SocketLike {@@ -522,7 +522,7 @@ export class ComputerRunner {/** The job's own entries on ComfyUI here, to check a resumed upload against. */private async ownEntries(t: ClaimedTask): Promise<HistoryEntryLike[]> {const own = (await this.read<Record<string, HistoryEntryLike>>(`/history/${t.promptId}`).catch(() => ({}) as Record<string, HistoryEntryLike>))[t.promptId];- const passes = t.prefix ? Object.values(await this.read<Record<string, HistoryEntryLike>>("/history?max_items=64").catch(() => ({}))).filter((e) => hasPrefix(e.prompt?.[2], t.prefix!)) : [];+ const passes = t.prefix ? Object.values(await this.read<Record<string, HistoryEntryLike>>(`/history?max_items=${META_BATCH_HISTORY}`).catch(() => ({}))).filter((e) => hasPrefix(e.prompt?.[2], t.prefix!)) : [];return [...(own ? [own] : []), ...passes];}@@ -621,7 +621,8 @@ export class ComputerRunner {continue;}const running = [...(q.queue_running ?? []), ...(q.queue_pending ?? [])].some((r) => hasPrefix(r[2], following!));- const passes = Object.values(await this.read<Record<string, HistoryEntryLike>>("/history?max_items=64").catch(() => ({}))).filter((e) => hasPrefix(e.prompt?.[2], following!));+ // Every pass once the last is done (an EXR export saves frames in each one).+ const passes = running ? [] : Object.values(await this.read<Record<string, HistoryEntryLike>>(`/history?max_items=${META_BATCH_HISTORY}`).catch(() => ({}))).filter((e) => hasPrefix(e.prompt?.[2], following!));const a = await this.report(t, { event: "passes", running, entries: running ? [] : passes.map(slim) });if (a.stop) throw new Stopped();if (!running) return { entries: passes, answer: a };diff --git a/src/lib/relay.ts b/src/lib/relay.tsindex 4a6fce4f..faee95e4 100644--- a/src/lib/relay.ts+++ b/src/lib/relay.ts@@ -215,6 +215,12 @@ export const RELAY_TIMES = {*/export const RELAY_LIMITS = { partBytes: 16 * 2 ** 20, reportBytes: 8 * 2 ** 20, refusalBytes: 256 * 1024, smallReportBytes: 8 * 1024, keptRefusalBytes: 16 * 1024, inputReads: 6 };+/**+ * How many recent ComfyUI /history entries are read for a meta-batch job's passes: an EXR export saves frames in every+ * pass, so all of them are needed (1,800 frames is 57 passes of 32).+ */+export const META_BATCH_HISTORY = 512;+/** A ComfyUI prompt id the server mints, and what the tab may name in a URL. */export const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;diff --git a/src/server/providers/comfyui.ts b/src/server/providers/comfyui.tsindex 96bd7085..9f69de65 100644--- a/src/server/providers/comfyui.ts+++ b/src/server/providers/comfyui.ts@@ -82,7 +82,7 @@ import { outsideTenant, runAsTenant, tenantAccount } from "../tenant";import { ask, checkReach, reachSync, sharedCheck, type Reach } from "./reach";import { ProviderError, type PollResult, type ProviderAdapter, type RemoteOutput } from "./types";import { isOutOfMemory } from "@/lib/gpu/fix-codes";-import { makingWords, queueWords, RELAY_TIMES, RELAY_WORDS, savingWords, sendingWords, tabFailureWords, type HistoryEntryLike, type TabFailure, type WantedFile } from "@/lib/relay";+import { makingWords, META_BATCH_HISTORY, queueWords, RELAY_TIMES, RELAY_WORDS, savingWords, sendingWords, tabFailureWords, type HistoryEntryLike, type TabFailure, type WantedFile } from "@/lib/relay";import type { GenerationFix } from "@/lib/catalog/types";import {checkClocks,@@ -1935,6 +1935,30 @@ const executionError = (entry: HistoryEntry) => entry.status?.messages?.find(([tconst promptHasPrefix = (prompt: unknown, prefix: string) =>!!prompt && typeof prompt === "object" && Object.values(prompt as ComfyWorkflow).some((n) => n?.inputs?.filename_prefix === prefix);+/** An EXR export's per-frame files (bundleFrames zips them); everything else is a finished result. */+const isFrame = (o: ComfyOutput) => o.meta?.role === "frames";++/**+ * A meta-batch pass's place in its job. ComfyUI numbers the first pass as queued (0 or more); VHS re-queues each later+ * pass under the negated, growing server count (-k, -k-1, …), so a later pass has a more negative number.+ */+const passOrder = (e: { prompt?: unknown[] }) => {+ const n = Number(e.prompt?.[0] ?? 0);+ return n >= 0 ? 0 : -n;+};++/**+ * A meta-batch job's results from its passes (in any order): the clips the last pass saved (only the last pass saves+ * a video), then every pass's EXR frames in pass order (a frame saver writes in each pass). Empty while no pass saved a+ * finished result. `collect` reads one pass's files.+ */+export function metaBatchResults<E extends { prompt?: unknown[] }>(passes: E[], collect: (e: E) => ComfyOutput[]): ComfyOutput[] {+ const files = [...passes].sort((a, c) => passOrder(a) - passOrder(c)).map(collect);+ const last = files.findLastIndex((f) => f.some((o) => !isFrame(o)));+ if (last < 0) return [];+ return [...files[last].filter((o) => !isFrame(o)), ...files.flatMap((f) => f.filter(isFrame))];+}+/*** VHS meta-batching re-queues the prompt (new prompt ids) until every frame is done; only the last pass* saves the video. Follow the passes by their shared filename prefix.@@ -1942,18 +1966,16 @@ const promptHasPrefix = (prompt: unknown, prefix: string) =>async function followMetaBatch(prefix: string, manifest: ManifestWorkflow | undefined, worker: ComfyWorker): Promise<ComfyOutput[] | "running" | { error: string } | null> {const queue = await comfyJson<{ queue_running?: unknown[][]; queue_pending?: unknown[][] }>("/queue", worker);if ([...(queue.queue_running ?? []), ...(queue.queue_pending ?? [])].some((q) => promptHasPrefix(q[2], prefix))) return "running";- const hist = await comfyJson<Record<string, HistoryEntry>>("/history?max_items=64", worker);- const passes = Object.values(hist)- .filter((e) => promptHasPrefix(e.prompt?.[2], prefix))- .sort((a, c) => Number(c.prompt?.[0] ?? 0) - Number(a.prompt?.[0] ?? 0));+ const read = async (n: number) => Object.values(await comfyJson<Record<string, HistoryEntry>>(`/history?max_items=${n}`, worker)).filter((e) => promptHasPrefix(e.prompt?.[2], prefix));+ const collect = (e: HistoryEntry) => collectOutputs(e, manifest, baseUrl(worker), authHeaders(worker));+ let passes = await read(64);+ // Frames in each pass: every pass is needed, so look further back.+ if (passes.some((e) => collect(e).some(isFrame))) passes = await read(META_BATCH_HISTORY);// A pass that failed (out of memory, a node exception) ends the job: say why instead of "no output".const failed = passes.find((e) => e.status?.status_str === "error");if (failed) return { error: explainExecutionError(executionError(failed), manifest) };- for (const e of passes) {- const files = collectOutputs(e, manifest, baseUrl(worker), authHeaders(worker));- if (files.length) return files;- }- return null;+ const files = metaBatchResults(passes, collect);+ return files.length ? files : null;}/** Upload a file to a worker's input folder; returns the name LoadImage / LoadAudio / LoadVideo take there. */@@ -2048,19 +2070,18 @@ export function planRelayOutputs(t: Pick<TaskRow, "id" | "workflow_id" | "meta_btry {manifest = t.workflow_id ? getWorkflow(t.workflow_id).manifest : undefined;} catch {}- const list = (passes ? [...entries].sort((a, c) => Number(c.prompt?.[0] ?? 0) - Number(a.prompt?.[0] ?? 0)) : entries.slice(0, 1)) as HistoryEntry[];+ const list = (passes ? entries : entries.slice(0, 1)) as HistoryEntry[];// A pass that failed (out of memory, a node exception) ends the job: say why instead of "no output".const failed = list.find((e) => e?.status?.status_str === "error");if (failed) {const interrupted = failed.status?.messages?.some(([type]) => type === "execution_interrupted");return { error: interrupted ? RELAY_WORDS.stopped : explainExecutionError(executionError(failed), manifest) };}- let outputs: ComfyOutput[] = [];- for (const e of list) {- outputs = collectOutputs(e, manifest, `relay:${t.id}`);- if (outputs.length) break;- }- if (!outputs.length) return t.meta_batch && !passes && t.prefix ? { follow: t.prefix } : { error: "This run finished without a result. Press Retry." };+ const collect = (e: HistoryEntry) => collectOutputs(e, manifest, `relay:${t.id}`);+ let outputs: ComfyOutput[] = passes ? metaBatchResults(list, collect) : list[0] ? collect(list[0]) : [];+ // A meta-batch's first pass may have saved only its EXR frames: the clip comes with the last pass.+ if (t.meta_batch && !passes && t.prefix && !outputs.some((o) => !isFrame(o))) return { follow: t.prefix };+ if (!outputs.length) return { error: "This run finished without a result. Press Retry." };const account = tenantAccount();let budget = Infinity;if (account) {@@ -2266,7 +2287,8 @@ export const comfyProvider: ProviderAdapter = {return { state: "failed" as const, error: explainExecutionError(executionError(entry), manifest) };}let outputs = collectOutputs(entry, manifest, baseUrl(worker), authHeaders(worker));- if (!outputs.length && meta.metaBatch && typeof meta.prefix === "string") {+ // A meta-batch's first pass may have saved only its EXR frames: the clip comes with the last pass.+ if (meta.metaBatch && typeof meta.prefix === "string" && !outputs.some((o) => !isFrame(o))) {const next = await followMetaBatch(meta.prefix, manifest, worker);if (next === "running") return { state: "running" as const, message: "Rendering the next batch of frames" };if (next && "error" in next) {diff --git a/tests/comfy-provider.test.ts b/tests/comfy-provider.test.tsindex 1d6f378c..2577932b 100644--- a/tests/comfy-provider.test.ts+++ b/tests/comfy-provider.test.ts@@ -307,6 +307,64 @@ describe("ComfyUI output mapping", () => {expect(res).toMatchObject({ state: "succeeded", outputs: [{ kind: "video", url: expect.stringContaining("gen-mm_00001.mp4") }] });});+ it("keeps every pass's EXR frames when a meta-batch key saves frames in each pass and its clip in the last", async () => {+ const prefix = "fuobe/gen-exr";+ const graph = { "7": { class_type: "VHS_VideoCombine", inputs: { filename_prefix: prefix } }, "11": { class_type: "SaveImageAdvanced", inputs: { filename_prefix: prefix } } };+ const frames = (from: number) => ({ "11": { images: [0, 1].map((i) => file(`gen-exr_${String(from + i).padStart(5, "0")}_.exr`)) } });+ // ComfyUI numbers the first pass as queued; VHS re-queues each later pass under a more negative number.+ const first = { prompt: [5, "p-exr", graph], ...done(frames(1)) };+ const passes = { "pass-b": { prompt: [-7, "pass-b", graph], ...done({ ...frames(5), "7": { gifs: [file("gen-exr_00001.webm")] } }) }, "p-exr": first, "pass-a": { prompt: [-6, "pass-a", graph], ...done(frames(3)) } };+ let queued = true;+ const fetched: string[] = [];+ handler = (url) => {+ if (url.includes("/history/p-exr")) return json({ "p-exr": first });+ if (url.endsWith("/queue")) return json({ queue_running: queued ? [[-6, "pass-a", graph]] : [], queue_pending: [] });+ if (url.includes("/history?max_items")) return json(passes);+ if (url.includes("/view?")) {+ fetched.push(new URL(url).searchParams.get("filename")!);+ return new Response(new Uint8Array([1, 2, 3]));+ }+ return json({});+ };+ const meta = { workflowId: "video-key-corridorkey", nodeCount: 11, prefix, metaBatch: true, generationId: "gen-exr" };+ // The first pass's frames alone are not the result: the job is still running.+ expect(await comfyProvider.poll(pollCtx("p-exr", meta))).toMatchObject({ state: "running", message: "Rendering the next batch of frames" });+ queued = false;+ const res = await comfyProvider.poll(pollCtx("p-exr", meta));+ expect(res).toMatchObject({ state: "succeeded", outputs: [{ kind: "video", url: expect.stringContaining("gen-exr_00001.webm"), meta: { frames: 6, artifacts: { exr: expect.any(String) } } }] });+ // Every pass's frames, in pass order.+ expect(fetched).toEqual([1, 2, 3, 4, 5, 6].map((n) => `gen-exr_0000${n}_.exr`));+ });++ it("has a computer's tab follow a meta-batch key whose first pass saved only frames, then collect every pass's frames", async () => {+ const { planRelayOutputs } = await import("@/server/providers/comfyui");+ const prefix = "fuobe/gen-relay-exr";+ const t = { id: "task-exr", workflow_id: "video-key-corridorkey", meta_batch: 1, prefix } as unknown as Parameters<typeof planRelayOutputs>[0];+ const frames = (from: number) => ({ "11": { images: [file(`gen_${from}_.exr`)] } });+ const first = { prompt: [3, "p1"], ...done(frames(1)) };+ expect(planRelayOutputs(t, [first], false)).toEqual({ follow: prefix });+ const plan = planRelayOutputs(t, [{ prompt: [-5, "p3"], ...done({ ...frames(3), "7": { gifs: [file("gen.webm")] } }) }, first, { prompt: [-4, "p2"], ...done(frames(2)) }], true);+ expect("wanted" in plan && plan.wanted.map((w) => [w.kind, w.filename])).toEqual([+ ["video", "gen.webm"],+ ["frame", "gen_1_.exr"],+ ["frame", "gen_2_.exr"],+ ["frame", "gen_3_.exr"],+ ]);+ });++ it("orders a meta-batch's passes and keeps the last clip with every pass's frames", async () => {+ const { metaBatchResults } = await import("@/server/providers/comfyui");+ const out = (url: string, role?: string) => ({ url, kind: role === "frames" ? ("image" as const) : ("video" as const), ...(role && { meta: { role } }) });+ const passes = [+ { prompt: [-9], files: [out("f3", "frames"), out("clip")] },+ { prompt: [0], files: [out("f1", "frames")] },+ { prompt: [-8], files: [out("f2", "frames")] },+ ];+ expect(metaBatchResults(passes, (p) => p.files).map((o) => o.url)).toEqual(["clip", "f1", "f2", "f3"]);+ // Frames with no clip yet: not a result.+ expect(metaBatchResults(passes.slice(1), (p) => p.files)).toEqual([]);+ });+it("reports a meta-batch pass that failed instead of 'no output'", async () => {const prefix = "fuobe/gen-mm-fail";const graph = { "22": { class_type: "VHS_VideoCombine", inputs: { filename_prefix: prefix } } };