Skip to content

armgit / fuobe

Public Imported from GitHub
0

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.

ComfyUI: an isolated worker URL; LatentSync 1.6 in Lipsync and ThinkSound in Sound effects

Claude4f7d3fd85652
diff --git a/scripts/comfy/README.md b/scripts/comfy/README.md
index 36b2044d..f43aea49 100644
--- a/scripts/comfy/README.md
+++ b/scripts/comfy/README.md
@@ -118,8 +118,12 @@ ISO_DIR=/srv/comfyui-isolated scripts/comfy/install-isolated-worker.sh
cd /srv/comfyui-isolated/ComfyUI && HOME=/srv/comfyui-isolated/home /srv/comfyui-isolated/.venv/bin/python main.py --listen 127.0.0.1 --port 8189
```
-Point a second Fuobe install (or Settings → ComfyUI URL while you use those models) at port 8189. Build and
-validate them against that server (placeholder models go into the shared main `models/` folder the worker reads):
+Then set **Settings → Open-source engine · ComfyUI → Isolated worker URL** (or `COMFYUI_ISOLATED_URL`) to
+`http://127.0.0.1:8189`: Fuobe sends these two workflows, their uploads and their polls there, and everything else
+to the main ComfyUI (the Lipsync studio offers LatentSync 1.6 and Audio → Sound effects offers ThinkSound, marked
+"Runs on the isolated ComfyUI worker"; without the setting, or when the worker doesn't answer, the job fails with a
+message that names the setting). Build and validate them against that server (placeholder models go into the shared
+main `models/` folder the worker reads):
```bash
COMFYUI_URL=http://127.0.0.1:8189 npm run build -- lipsync-latentsync16 sfx-thinksound
diff --git a/src/components/models-table.tsx b/src/components/models-table.tsx
index 482ee632..cb177db4 100644
--- a/src/components/models-table.tsx
+++ b/src/components/models-table.tsx
@@ -71,6 +71,7 @@ const Row = memo(function Row({ m }: { m: ModelRow }) {
<div className="text-[12px] text-muted-foreground">
{m.vendor} — {m.tagline}
</div>
+ {m.note && <div className="mt-0.5 text-[11px] text-subtle-foreground">{m.note}</div>}
<div className="mt-1 text-[11px] text-subtle-foreground md:hidden">
<span className="font-mono text-muted-foreground sm:hidden">{m.price} · </span>
{m.ops.join(" · ")}
diff --git a/src/components/settings-form.tsx b/src/components/settings-form.tsx
index f2f72787..60ba20ee 100644
--- a/src/components/settings-form.tsx
+++ b/src/components/settings-form.tsx
@@ -323,6 +323,13 @@ export function SettingsForm() {
>
<Field setting={get("comfyUrl")} label="ComfyUI server URL" placeholder="http://127.0.0.1:8188" onSave={set("comfyUrl")} />
<Field setting={get("comfyToken")} label="Auth token (optional)" hint="Sent as a Bearer token, for ComfyUI behind a proxy." onSave={set("comfyToken")} />
+ <Field
+ setting={get("comfyIsolatedUrl")}
+ label="Isolated worker URL (optional)"
+ placeholder="http://127.0.0.1:8189"
+ hint="A second ComfyUI for LatentSync 1.6 and ThinkSound, whose node packs can't share the main install. scripts/comfy/README.md shows how to start one."
+ onSave={set("comfyIsolatedUrl")}
+ />
<TestButton provider="comfyui" />
</Section>
diff --git a/src/components/studio/model-picker.tsx b/src/components/studio/model-picker.tsx
index 7c721425..eff5850b 100644
--- a/src/components/studio/model-picker.tsx
+++ b/src/components/studio/model-picker.tsx
@@ -1,6 +1,6 @@
"use client";
-import { ChevronDown, Cloud, Cpu, SearchX, Star } from "lucide-react";
+import { ChevronDown, Cloud, Cpu, SearchX, Server, Star } from "lucide-react";
import Link from "next/link";
import { useMemo, useState } from "react";
import { Badge } from "@/components/ui/badge";
@@ -11,6 +11,7 @@ import { type Engine, type ModelDef } from "@/lib/catalog/types";
import { useEngineMode, useStatus } from "@/lib/api";
import { bestForStudio, groupModels, toggleIn } from "@/lib/composer";
import { formatCost } from "@/lib/format";
+import { ISOLATED_NOTE } from "@/lib/model-rows";
import { cn } from "@/lib/utils";
import { EngineSwitch } from "./engine-switch";
import { ResponsivePanel } from "./responsive-panel";
@@ -107,6 +108,12 @@ function ModelRow({
<span className="block truncate text-[12px] leading-snug text-muted-foreground">
{m.vendor} · {m.tagline}
</span>
+ {m.worker === "isolated" && (
+ <span className="mt-0.5 flex items-center gap-1 text-[11px] leading-snug text-subtle-foreground">
+ <Server className="size-3! shrink-0" aria-hidden />
+ {ISOLATED_NOTE}
+ </span>
+ )}
</span>
<span className="shrink-0 text-right text-[11px] text-subtle-foreground tabular-nums">{priceHint(m)}</span>
{/* Pointer only: inside an option it would be a nested control. Keyboard: Alt+S on the highlighted row (starKey). */}
diff --git a/src/lib/catalog/models.ts b/src/lib/catalog/models.ts
index 3fe71e27..9dced0aa 100644
--- a/src/lib/catalog/models.ts
+++ b/src/lib/catalog/models.ts
@@ -887,11 +887,11 @@ const open: ModelDef[] = [
vendor: "FunAudioLLM",
family: "thinksound",
kind: "audio",
- tagline: "Apache-2.0 sound effects with a step-by-step sound description · 12 GB GPU · needs a separate ComfyUI worker",
+ tagline: "Apache-2.0 sound effects from a description, up to 30 s · 12 GB GPU",
routes: [comfy("sfx", "sfx-thinksound", "isolated worker (scripts/comfy/README.md)")],
options: { durations: [3, 5, 8, 10, 20, 30], seed: true },
defaults: { duration: 8 },
- hidden: true,
+ worker: "isolated",
}),
// Voice, transcription, captions, translation, lip re-sync, soundtrack
o({
@@ -986,10 +986,16 @@ const open: ModelDef[] = [
vendor: "ByteDance",
family: "latentsync",
kind: "video",
- tagline: "Mouth-only lip re-sync, identity untouched · 20 GB GPU · OpenRAIL++ · needs a separate ComfyUI worker",
+ tagline: "Re-syncs only the mouth of real footage to a new voice; face, camera and background untouched · 20 GB GPU · OpenRAIL++",
routes: [comfy("lipsync", "lipsync-latentsync16", "isolated worker (scripts/comfy/README.md)")],
- options: { seed: true },
- hidden: true,
+ options: {
+ seed: true,
+ sliders: [
+ { param: "lipsExpression", label: "Lip movement", min: 1, max: 3, step: 0.1, default: 1.5 },
+ { param: "steps", label: "Steps", min: 10, max: 50, step: 1, default: 20 },
+ ],
+ },
+ worker: "isolated",
}),
o({
id: "oss-mux",
diff --git a/src/lib/catalog/types.ts b/src/lib/catalog/types.ts
index 6f77b271..cd2bd81b 100644
--- a/src/lib/catalog/types.ts
+++ b/src/lib/catalog/types.ts
@@ -362,6 +362,11 @@ export interface ModelDef {
identity?: { provider: "higgsfield"; version: "v1" | "v2" | "cinema" };
/** Hidden from pickers (used only internally by presets). */
hidden?: boolean;
+ /**
+ * Open models whose workflow runs on the isolated ComfyUI worker (Settings → Isolated worker URL), not
+ * the main server: the picker says so.
+ */
+ worker?: "isolated";
}
/** User-facing generation parameters (canonical, provider-agnostic). */
diff --git a/src/lib/model-rows.ts b/src/lib/model-rows.ts
index adc087d7..5f68a36d 100644
--- a/src/lib/model-rows.ts
+++ b/src/lib/model-rows.ts
@@ -16,8 +16,13 @@ export interface ModelRow {
/** Provider routes ("fal: fal-ai/flux/dev"), shown in the row's details popover. */
routes: string[];
price: string;
+ /** Where it runs when that's not the obvious place ("Runs on the isolated ComfyUI worker"). */
+ note?: string;
}
+/** The picker's and the Models page's note on models that run on the isolated ComfyUI worker. */
+export const ISOLATED_NOTE = "Runs on the isolated ComfyUI worker";
+
const BADGE_LABEL: Record<string, string> = {
new: "New",
top: "Top",
@@ -42,6 +47,7 @@ export function toModelRow(m: ModelDef): ModelRow {
ops: [...new Set(m.routes.map((r) => OPERATION_LABELS[r.op] ?? r.op))],
routes: [...new Set(m.routes.map((r) => `${r.provider}: ${r.endpoint}`))],
price: m.engine === "open" ? "Free" : m.pricing ? `${formatCost(m.pricing.usd)} / ${m.pricing.unit}` : "—",
+ ...(m.worker === "isolated" && { note: ISOLATED_NOTE }),
};
}
diff --git a/src/server/generations.ts b/src/server/generations.ts
index 672b29db..0c055acd 100644
--- a/src/server/generations.ts
+++ b/src/server/generations.ts
@@ -604,14 +604,14 @@ async function submit(
const prep = async (ref?: string) => {
if (!ref) return undefined;
const f = await readRef(ref);
- return adapter.prepareFile(f.data, f.contentType, f.name);
+ return adapter.prepareFile(f.data, f.contentType, f.name, route);
};
const prepMask = async (ref?: string) => {
if (!ref) return undefined;
const f = await readRef(ref);
const fmt = route.map?.maskFormat;
const data = fmt && fmt !== "white" && f.contentType === "image/png" ? convertMask(f.data, fmt) : f.data;
- return adapter.prepareFile(data, f.contentType, f.name);
+ return adapter.prepareFile(data, f.contentType, f.name, route);
};
let prompt = plan.prompt;
if (req.params?.enhancePrompt && prompt) {
diff --git a/src/server/providers/comfyui.ts b/src/server/providers/comfyui.ts
index 5d58d128..6d7e843a 100644
--- a/src/server/providers/comfyui.ts
+++ b/src/server/providers/comfyui.ts
@@ -30,7 +30,7 @@ import {
} from "@/lib/comfy";
import { expandTimelineWorkflow, readTimeline } from "@/lib/av/timeline";
import { guessKind } from "@/lib/catalog/payload";
-import type { GenInput, MediaKind, Operation } from "@/lib/catalog/types";
+import type { GenInput, MediaKind, ModelRoute, Operation } from "@/lib/catalog/types";
import { probeMedia, type MediaInfo } from "@/lib/media-probe";
import { getSetting } from "../settings";
import { decodePng, encodePng } from "../png";
@@ -58,8 +58,23 @@ export function getWorkflow(id: string): { manifest: ManifestWorkflow; workflow:
return { manifest, workflow };
}
-function baseUrl(): string {
- return getSetting("comfyUrl").replace(/\/+$/, "");
+/**
+ * Which ComfyUI runs a workflow: the main server, or the isolated worker — a second ComfyUI with its own
+ * code copy and virtualenv for node packs that change process-wide state or pin old packages (LatentSync
+ * 1.6, ThinkSound; manifest `worker: "isolated"`, scripts/comfy/README.md). Both take the same token.
+ */
+export type ComfyWorker = "main" | "isolated";
+
+/** Where the isolated worker's address is set, for messages. */
+export const ISOLATED_SETTING = "Settings → Open-source engine · ComfyUI → Isolated worker URL";
+
+function baseUrl(worker: ComfyWorker = "main"): string {
+ return getSetting(worker === "isolated" ? "comfyIsolatedUrl" : "comfyUrl").replace(/\/+$/, "");
+}
+
+/** The worker a workflow runs on. */
+export function workerFor(endpoint: string | undefined): ComfyWorker {
+ return endpoint && loadManifest().workflows.find((w) => w.id === endpoint)?.worker === "isolated" ? "isolated" : "main";
}
function authHeaders(): Record<string, string> {
@@ -67,17 +82,22 @@ function authHeaders(): Record<string, string> {
return t ? { Authorization: `Bearer ${t}` } : {};
}
-async function comfyFetch(p: string, init: RequestInit = {}): Promise<Response> {
+async function comfyFetch(p: string, init: RequestInit = {}, worker: ComfyWorker = "main"): Promise<Response> {
+ const base = baseUrl(worker);
+ if (worker === "isolated" && !base) {
+ throw new ProviderError(`This model runs on the isolated ComfyUI worker, which isn't set up yet: add its address in ${ISOLATED_SETTING} (or COMFYUI_ISOLATED_URL). scripts/comfy/README.md shows how to start one, usually on port 8189`);
+ }
try {
- return await fetch(`${baseUrl()}${p}`, { ...init, headers: { ...authHeaders(), ...(init.headers ?? {}) } });
+ return await fetch(`${base}${p}`, { ...init, headers: { ...authHeaders(), ...(init.headers ?? {}) } });
} catch (e) {
- throw new ProviderError(`Can't reach ComfyUI at ${baseUrl()} (${(e as Error).message}). Is it running?`);
+ if (worker === "isolated") throw new ProviderError(`The isolated ComfyUI worker at ${base} doesn't answer (${(e as Error).message}). Start it (scripts/comfy/README.md) or check ${ISOLATED_SETTING}`);
+ throw new ProviderError(`Can't reach ComfyUI at ${base} (${(e as Error).message}). Is it running?`);
}
}
/** GET a ComfyUI JSON endpoint. A non-2xx answer or a body that isn't JSON (a proxy's error page) throws, so the runner retries. */
-async function comfyJson<T>(p: string): Promise<T> {
- const res = await comfyFetch(p);
+async function comfyJson<T>(p: string, worker: ComfyWorker = "main"): Promise<T> {
+ const res = await comfyFetch(p, {}, worker);
if (!res.ok) throw new ProviderError(`ComfyUI ${p.split("?")[0]} answered HTTP ${res.status}`, res.status);
try {
return (await res.json()) as T;
@@ -87,7 +107,7 @@ async function comfyJson<T>(p: string): Promise<T> {
}
// ---------------------------------------------------------------------------
-// Live progress over the ComfyUI websocket (one connection per server URL).
+// Live progress over the ComfyUI websocket (one connection per worker, reopened when its URL changes).
interface Progress {
value: number;
@@ -96,15 +116,25 @@ interface Progress {
nodesDone: number;
}
+type ComfySocket = { url: string; ws: WebSocket; clientId: string; progress: Map<string, Progress> };
+
declare global {
- var __fuobeComfyWs: { url: string; ws: WebSocket; clientId: string; progress: Map<string, Progress> } | undefined;
+ var __fuobeComfyWs: ComfySocket | undefined;
+ /** The isolated worker's socket. */
+ var __fuobeComfyWsIsolated: ComfySocket | undefined;
/** Consecutive polls that found a prompt in neither the queue nor the history. */
var __fuobeComfyMisses: Map<string, number> | undefined;
}
-function ensureSocket(): { clientId: string; progress: Map<string, Progress> } {
- const url = baseUrl();
- const cur = globalThis.__fuobeComfyWs;
+const socketOf = (worker: ComfyWorker) => (worker === "isolated" ? globalThis.__fuobeComfyWsIsolated : globalThis.__fuobeComfyWs);
+function setSocket(worker: ComfyWorker, s: ComfySocket | undefined) {
+ if (worker === "isolated") globalThis.__fuobeComfyWsIsolated = s;
+ else globalThis.__fuobeComfyWs = s;
+}
+
+function ensureSocket(worker: ComfyWorker = "main"): { clientId: string; progress: Map<string, Progress> } {
+ const url = baseUrl(worker);
+ const cur = socketOf(worker);
if (cur && cur.url === url && cur.ws.readyState <= 1) return cur;
const clientId = cur?.clientId ?? `fuobe-${nanoid(8)}`;
// Same server: keep the progress of prompts in flight. Another server: those prompt ids mean nothing there.
@@ -142,9 +172,9 @@ function ensureSocket(): { clientId: string; progress: Map<string, Progress> } {
} catch {}
};
ws.onerror = () => {};
- globalThis.__fuobeComfyWs = { url, ws, clientId, progress };
+ setSocket(worker, { url, ws, clientId, progress });
} catch {
- globalThis.__fuobeComfyWs = undefined;
+ setSocket(worker, undefined);
}
return { clientId, progress };
}
@@ -152,6 +182,7 @@ function ensureSocket(): { clientId: string; progress: Map<string, Progress> } {
/** Forget a finished prompt's progress and missed-poll count. */
function forget(promptId: string) {
globalThis.__fuobeComfyWs?.progress.delete(promptId);
+ globalThis.__fuobeComfyWsIsolated?.progress.delete(promptId);
globalThis.__fuobeComfyMisses?.delete(promptId);
}
@@ -663,10 +694,10 @@ const promptHasPrefix = (prompt: unknown, prefix: string) =>
* 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.
*/
-async function followMetaBatch(prefix: string, manifest: ManifestWorkflow | undefined): Promise<ComfyOutput[] | "running" | { error: string } | null> {
- const queue = await comfyJson<{ queue_running?: unknown[][]; queue_pending?: unknown[][] }>("/queue");
+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");
+ 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));
@@ -674,12 +705,31 @@ async function followMetaBatch(prefix: string, manifest: ManifestWorkflow | unde
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(), authHeaders());
+ const files = collectOutputs(e, manifest, baseUrl(worker), authHeaders());
if (files.length) return files;
}
return null;
}
+/** Upload a file to a worker's input folder; returns the name LoadImage / LoadAudio / LoadVideo take there. */
+async function uploadTo(worker: ComfyWorker, data: Buffer, contentType: string, name: string): Promise<string> {
+ const form = new FormData();
+ const ext = name.includes(".") ? name.split(".").pop() : contentType.split("/")[1];
+ form.append("image", new Blob([new Uint8Array(data)], { type: contentType }), `fuobe_${nanoid(8)}.${ext}`);
+ form.append("type", "input");
+ form.append("overwrite", "true");
+ const res = await comfyFetch("/upload/image", { method: "POST", body: form }, worker);
+ if (!res.ok) throw new ProviderError(`ComfyUI upload failed: ${res.status} ${await res.text()}`);
+ const j = (await res.json()) as { name: string; subfolder?: string };
+ const uploaded = j.subfolder ? `${j.subfolder}/${j.name}` : j.name;
+ // Remember a clip's / track's header facts (length, size, fps, audio) for prepareWorkflow.
+ if (MEDIA_FILE.test(contentType) || MEDIA_EXT.test(name)) {
+ const info = probeMedia(data);
+ if (info) rememberMedia(uploaded, info);
+ }
+ return uploaded;
+}
+
export const comfyProvider: ProviderAdapter = {
id: "comfyui",
label: "ComfyUI",
@@ -691,51 +741,45 @@ export const comfyProvider: ProviderAdapter = {
return cur.ok;
},
- async prepareFile(data, contentType, name) {
- const form = new FormData();
- const ext = name.includes(".") ? name.split(".").pop() : contentType.split("/")[1];
- form.append("image", new Blob([new Uint8Array(data)], { type: contentType }), `fuobe_${nanoid(8)}.${ext}`);
- form.append("type", "input");
- form.append("overwrite", "true");
- const res = await comfyFetch("/upload/image", { method: "POST", body: form });
- if (!res.ok) throw new ProviderError(`ComfyUI upload failed: ${res.status} ${await res.text()}`);
- const j = (await res.json()) as { name: string; subfolder?: string };
- const uploaded = j.subfolder ? `${j.subfolder}/${j.name}` : j.name;
- // Remember a clip's / track's header facts (length, size, fps, audio) for prepareWorkflow.
- if (MEDIA_FILE.test(contentType) || MEDIA_EXT.test(name)) {
- const info = probeMedia(data);
- if (info) rememberMedia(uploaded, info);
- }
- return uploaded;
+ // Inputs go to the server that runs the route's workflow (the isolated worker has its own input folder).
+ async prepareFile(data, contentType, name, route?: ModelRoute) {
+ return uploadTo(workerFor(route?.endpoint), data, contentType, name);
},
async submit({ route, input, generationId }) {
+ const worker = workerFor(route.endpoint);
const { manifest, workflow: wf, meta } = await prepareWorkflow(route.endpoint, input, {
generationId,
op: route.op,
- upload: (data, contentType, name) => comfyProvider.prepareFile(data, contentType, name),
+ upload: (data, contentType, name) => uploadTo(worker, data, contentType, name),
media: mediaInfoFor,
- serverRam: async () => (await comfyJson<{ system?: { ram_total?: number } }>("/system_stats").catch(() => undefined))?.system?.ram_total,
- });
- const { clientId } = ensureSocket();
- const res = await comfyFetch("/prompt", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ prompt: wf, client_id: clientId }),
+ serverRam: async () => (await comfyJson<{ system?: { ram_total?: number } }>("/system_stats", worker).catch(() => undefined))?.system?.ram_total,
});
+ const { clientId } = ensureSocket(worker);
+ const res = await comfyFetch(
+ "/prompt",
+ {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ prompt: wf, client_id: clientId }),
+ },
+ worker,
+ );
const body = (await res.json().catch(() => ({}))) as { prompt_id?: string; error?: { type?: string; message?: string }; node_errors?: unknown };
if (!res.ok || !body.prompt_id) {
// A node class the server doesn't have: name the pack to install (opt-in packs like ComfyUI-Whisper).
const packs = manifest.customNodes.map((c) => c.name);
+ const where = worker === "isolated" ? "the isolated ComfyUI worker" : "your ComfyUI";
const missingPack =
- body.error?.type === "missing_node_type" && packs.length ? `This workflow needs the ${packs.join(" + ")} node pack${packs.length > 1 ? "s" : ""} on your ComfyUI (see scripts/comfy/README.md)` : undefined;
+ body.error?.type === "missing_node_type" && packs.length ? `This workflow needs the ${packs.join(" + ")} node pack${packs.length > 1 ? "s" : ""} on ${where} (see scripts/comfy/README.md)` : undefined;
const detail = body.node_errors && Object.keys(body.node_errors as object).length ? explainComfyError(body.node_errors, { ...manifest, models: [...manifest.models, ...(input.loras ?? []).map((l) => ({ file: l.file, folder: "loras", url: l.url }))] }) : (missingPack ?? body.error?.message);
throw new ProviderError(detail ?? `ComfyUI /prompt failed (${res.status})`, res.status);
}
- return { externalId: body.prompt_id, meta, payload: wf };
+ return { externalId: body.prompt_id, meta: { ...meta, ...(worker === "isolated" && { worker }) }, payload: wf };
},
async poll({ externalId, meta }) {
+ const worker: ComfyWorker = meta.worker === "isolated" ? "isolated" : "main";
let manifest: ManifestWorkflow | undefined;
try {
manifest = getWorkflow(String(meta.workflowId)).manifest;
@@ -745,9 +789,9 @@ export const comfyProvider: ProviderAdapter = {
forget(externalId);
return { state: "failed" as const, error: explainExecutionError(executionError(entry), manifest) };
}
- let outputs = collectOutputs(entry, manifest, baseUrl(), authHeaders());
+ let outputs = collectOutputs(entry, manifest, baseUrl(worker), authHeaders());
if (!outputs.length && meta.metaBatch && typeof meta.prefix === "string") {
- const next = await followMetaBatch(meta.prefix, manifest);
+ 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) {
forget(externalId);
@@ -761,18 +805,18 @@ export const comfyProvider: ProviderAdapter = {
};
const isDone = (e: HistoryEntry | undefined): e is HistoryEntry => !!e && (!!e.status?.completed || e.status?.status_str === "success" || e.status?.status_str === "error");
- const entry = (await comfyJson<Record<string, HistoryEntry>>(`/history/${externalId}`))[externalId];
+ const entry = (await comfyJson<Record<string, HistoryEntry>>(`/history/${externalId}`, worker))[externalId];
if (isDone(entry)) return finished(entry);
// Still queued or running?
- const { progress } = ensureSocket();
+ const { progress } = ensureSocket(worker);
const p = progress.get(externalId);
- const queue = await comfyJson<{ queue_running?: unknown[][]; queue_pending?: unknown[][] }>("/queue");
+ const queue = await comfyJson<{ queue_running?: unknown[][]; queue_pending?: unknown[][] }>("/queue", worker);
const running = queue.queue_running?.some((q) => q[1] === externalId);
const pendingIdx = queue.queue_pending?.findIndex((q) => q[1] === externalId) ?? -1;
if (!running && pendingIdx < 0 && !entry) {
// It may have finished between the two requests (ComfyUI moves it from the queue to the history at once).
- const again = (await comfyJson<Record<string, HistoryEntry>>(`/history/${externalId}`))[externalId];
+ const again = (await comfyJson<Record<string, HistoryEntry>>(`/history/${externalId}`, worker))[externalId];
if (isDone(again)) return finished(again);
const misses = globalThis.__fuobeComfyMisses ?? (globalThis.__fuobeComfyMisses = new Map());
const n = (misses.get(externalId) ?? 0) + 1;
@@ -789,40 +833,42 @@ export const comfyProvider: ProviderAdapter = {
return {
state: "running",
progress: progressValue && progressValue > 0 ? progressValue : undefined,
- message: p?.max ? `Sampling ${p.value}/${p.max}` : "Running on ComfyUI",
+ message: p?.max ? `Sampling ${p.value}/${p.max}` : worker === "isolated" ? "Running on the isolated ComfyUI worker" : "Running on ComfyUI",
};
},
- async cancel({ externalId }) {
+ async cancel({ externalId, meta }) {
+ const worker: ComfyWorker = meta.worker === "isolated" ? "isolated" : "main";
forget(externalId);
- await comfyFetch("/queue", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ delete: [externalId] }),
- }).catch(() => {});
- const q = (await (await comfyFetch("/queue")).json().catch(() => ({}))) as { queue_running?: unknown[][] };
- if (q.queue_running?.some((r) => r[1] === externalId)) {
- await comfyFetch("/interrupt", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ prompt_id: externalId }),
- }).catch(() => {});
- }
+ const post = (path: string, body: unknown) => comfyFetch(path, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) }, worker);
+ await post("/queue", { delete: [externalId] }).catch(() => {});
+ const q = (await comfyJson<{ queue_running?: unknown[][] }>("/queue", worker).catch(() => ({}))) as { queue_running?: unknown[][] };
+ if (q.queue_running?.some((r) => r[1] === externalId)) await post("/interrupt", { prompt_id: externalId }).catch(() => {});
},
async test() {
- try {
- const res = await comfyFetch("/system_stats");
- if (!res.ok) return { ok: false, detail: `HTTP ${res.status}` };
+ const describe = async (worker: ComfyWorker) => {
+ const res = await comfyFetch("/system_stats", {}, worker);
+ if (!res.ok) throw new ProviderError(`HTTP ${res.status}`);
const s = (await res.json()) as { system?: { comfyui_version?: string }; devices?: { name?: string; vram_total?: number }[] };
const dev = s.devices?.[0];
- return {
- ok: true,
- detail: `ComfyUI ${s.system?.comfyui_version ?? ""} · ${dev?.name ?? "unknown device"}${dev?.vram_total ? ` · ${(dev.vram_total / 2 ** 30).toFixed(0)} GB` : ""}`,
- };
+ return `ComfyUI ${s.system?.comfyui_version ?? ""} · ${dev?.name ?? "unknown device"}${dev?.vram_total ? ` · ${(dev.vram_total / 2 ** 30).toFixed(0)} GB` : ""}`;
+ };
+ let detail: string;
+ try {
+ detail = await describe("main");
} catch (e) {
return { ok: false, detail: (e as Error).message };
}
+ // The isolated worker is optional: say whether it answers, without failing the main server's test.
+ if (baseUrl("isolated")) {
+ const iso = await describe("isolated").then(
+ (d) => `isolated worker: ${d}`,
+ () => `the isolated worker at ${baseUrl("isolated")} doesn't answer`,
+ );
+ detail = `${detail} · ${iso}`;
+ }
+ return { ok: true, detail };
},
};
diff --git a/src/server/providers/types.ts b/src/server/providers/types.ts
index 17513b54..5d8c3312 100644
--- a/src/server/providers/types.ts
+++ b/src/server/providers/types.ts
@@ -46,8 +46,11 @@ export interface ProviderAdapter {
id: ProviderId;
label: string;
isConfigured(): boolean;
- /** Turn a local file into something the provider accepts (URL, data URI, uploaded filename). */
- prepareFile(data: Buffer, contentType: string, name: string): Promise<string>;
+ /**
+ * Turn a local file into something the provider accepts (URL, data URI, uploaded filename). `route` is
+ * the route the file is for (ComfyUI uploads an isolated-worker workflow's inputs to that worker).
+ */
+ prepareFile(data: Buffer, contentType: string, name: string, route?: ModelRoute): Promise<string>;
submit(ctx: SubmitContext): Promise<SubmitResult>;
poll(ctx: PollContext): Promise<PollResult>;
cancel?(ctx: PollContext): Promise<void>;
diff --git a/src/server/settings.ts b/src/server/settings.ts
index ce2e58d6..eadd3061 100644
--- a/src/server/settings.ts
+++ b/src/server/settings.ts
@@ -29,6 +29,8 @@ export const SETTINGS = {
anthropicKey: { key: "anthropic.key", env: "ANTHROPIC_API_KEY", secret: true },
comfyUrl: { key: "comfyui.url", env: "COMFYUI_URL", default: "http://127.0.0.1:8188" },
comfyToken: { key: "comfyui.token", env: "COMFYUI_TOKEN", secret: true },
+ /** A second ComfyUI for workflows whose node packs can't share the main install (LatentSync 1.6, ThinkSound; scripts/comfy/README.md). */
+ comfyIsolatedUrl: { key: "comfyui.isolatedUrl", env: "COMFYUI_ISOLATED_URL" },
/** ComfyUI's models/loras folder, when it's on this machine: trained LoRAs are copied there. */
comfyLorasDir: { key: "comfyui.lorasDir", env: "COMFYUI_LORAS_DIR" },
/** AI-Toolkit UI (ostris/ai-toolkit, port 8675) for open-source character LoRA training. */
diff --git a/tests/isolated-worker.test.ts b/tests/isolated-worker.test.ts
new file mode 100644
index 00000000..bd87e3cd
--- /dev/null
+++ b/tests/isolated-worker.test.ts
@@ -0,0 +1,161 @@
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { afterAll, afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import type { Generation, ModelDef } from "@/lib/catalog/types";
+
+vi.setConfig({ testTimeout: 30_000 });
+const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-isolated-"));
+process.env.FUOBE_DATA_DIR = dir;
+process.env.COMFYUI_URL = "http://comfy.test:8188";
+
+const { setSetting } = await import("@/server/settings");
+const { comfyProvider, workerFor } = await import("@/server/providers/comfyui");
+const gens = await import("@/server/generations");
+const { saveFile } = await import("@/server/storage");
+const { getModel } = await import("@/lib/catalog");
+const { studioCatalog } = await import("@/lib/studio-catalog");
+const { LIPSYNC_STUDIO, SFX_STUDIO, FOLEY_STUDIO } = await import("@/lib/studios");
+const { toModelRow } = await import("@/lib/model-rows");
+
+afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));
+
+// fetch + WebSocket stubs, as in comfy-provider.test.ts
+type Handler = (url: string, init?: RequestInit) => Response | Promise<Response>;
+const realFetch = globalThis.fetch;
+const realWs = globalThis.WebSocket;
+let handler: Handler = () => new Response("not stubbed", { status: 599 });
+const calls: string[] = [];
+class FakeSocket {
+ static all: FakeSocket[] = [];
+ readyState = 1;
+ onmessage: ((ev: { data: unknown }) => void) | null = null;
+ onerror: (() => void) | null = null;
+ constructor(public url: string) {
+ FakeSocket.all.push(this);
+ }
+ close() {
+ this.readyState = 3;
+ }
+}
+beforeEach(() => {
+ calls.length = 0;
+ globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
+ const url = String(input);
+ calls.push(url);
+ return handler(url, init);
+ }) as typeof fetch;
+ globalThis.WebSocket = FakeSocket as unknown as typeof WebSocket;
+ setSetting("comfyUrl", "http://comfy.test:8188");
+ setSetting("comfyIsolatedUrl", "");
+});
+afterEach(() => {
+ globalThis.fetch = realFetch;
+ globalThis.WebSocket = realWs;
+});
+
+const json = (v: unknown, status = 200) => new Response(JSON.stringify(v), { status, headers: { "Content-Type": "application/json" } });
+const latent = getModel("oss-latentsync")! as ModelDef;
+const route = latent.routes[0];
+let uploads = 0;
+/** A ComfyUI that takes uploads, accepts prompts and reports one finished video. */
+const comfy: Handler = (url) => {
+ if (url.endsWith("/upload/image")) return json({ name: `fuobe_up${++uploads}.bin`, subfolder: "" });
+ if (url.endsWith("/prompt")) return json({ prompt_id: "iso-1" });
+ if (url.includes("/history/iso-1")) return json({ "iso-1": { status: { status_str: "success", completed: true }, outputs: { "5": { gifs: [{ filename: "fuobe_00001.mp4", subfolder: "fuobe", type: "output" }] } } } });
+ if (url.endsWith("/system_stats")) return json({ system: { comfyui_version: "0.41.0", ram_total: 2 ** 34 }, devices: [{ name: "cuda:0", vram_total: 24 * 2 ** 30 }] });
+ return json({ queue_running: [], queue_pending: [] });
+};
+
+describe("isolated ComfyUI worker", () => {
+ it("knows which workflows run there", () => {
+ expect(workerFor("lipsync-latentsync16")).toBe("isolated");
+ expect(workerFor("sfx-thinksound")).toBe("isolated");
+ expect(workerFor("lipsync-v2v-infinitetalk")).toBe("main");
+ expect(workerFor("video-concat-{n}")).toBe("main");
+ expect(workerFor(undefined)).toBe("main");
+ });
+
+ it("sends an isolated workflow's uploads, prompt, progress socket and polls to the isolated worker", async () => {
+ setSetting("comfyIsolatedUrl", "http://iso.test:8189/");
+ handler = comfy;
+ const video = await comfyProvider.prepareFile(Buffer.from("video"), "video/mp4", "clip.mp4", route);
+ const audio = await comfyProvider.prepareFile(Buffer.from("voice"), "audio/wav", "voice.wav", route);
+ const res = await comfyProvider.submit({ generationId: "g1", model: latent, route, input: { video, audio, extra: { lipsExpression: 2 } } });
+ expect(res.meta).toMatchObject({ workflowId: "lipsync-latentsync16", worker: "isolated" });
+ expect(calls).toEqual(["http://iso.test:8189/upload/image", "http://iso.test:8189/upload/image", "http://iso.test:8189/prompt"]);
+ expect(FakeSocket.all.at(-1)!.url).toMatch(/^ws:\/\/iso\.test:8189\/ws\?clientId=/);
+ // The sliders reach the graph.
+ expect((res.payload as Record<string, { inputs: Record<string, unknown> }>)["4"].inputs.lips_expression).toBe(2);
+ calls.length = 0;
+ const polled = await comfyProvider.poll({ externalId: "iso-1", meta: res.meta!, route, model: latent, createdAt: Date.now() });
+ expect(polled.state).toBe("succeeded");
+ expect(polled.state === "succeeded" && polled.outputs[0].url).toMatch(/^http:\/\/iso\.test:8189\/view\?filename=fuobe_00001\.mp4/);
+ expect(calls.every((u) => u.startsWith("http://iso.test:8189/"))).toBe(true);
+ // Cancel goes there too.
+ calls.length = 0;
+ await comfyProvider.cancel!({ externalId: "iso-1", meta: res.meta!, route, model: latent, createdAt: Date.now() });
+ expect(calls.length).toBeGreaterThan(0);
+ expect(calls.every((u) => u.startsWith("http://iso.test:8189/"))).toBe(true);
+ // Everything else stays on the main server.
+ calls.length = 0;
+ await comfyProvider.prepareFile(Buffer.from("png"), "image/png", "a.png", { op: "edit", provider: "comfyui", endpoint: "selftest-image" });
+ await comfyProvider.prepareFile(Buffer.from("png"), "image/png", "b.png");
+ expect(calls).toEqual(["http://comfy.test:8188/upload/image", "http://comfy.test:8188/upload/image"]);
+ });
+
+ it("names the setting when the isolated worker isn't set up or doesn't answer", async () => {
+ handler = comfy;
+ await expect(comfyProvider.prepareFile(Buffer.from("video"), "video/mp4", "clip.mp4", route)).rejects.toThrow(/isolated ComfyUI worker, which isn't set up yet: add its address in Settings → Open-source engine · ComfyUI → Isolated worker URL \(or COMFYUI_ISOLATED_URL\)/);
+ expect(calls).toEqual([]);
+ setSetting("comfyIsolatedUrl", "http://iso.test:8189");
+ handler = (url) => {
+ if (url.startsWith("http://iso.test")) throw new TypeError("fetch failed");
+ return comfy(url);
+ };
+ await expect(comfyProvider.prepareFile(Buffer.from("video"), "video/mp4", "clip.mp4", route)).rejects.toThrow(/The isolated ComfyUI worker at http:\/\/iso\.test:8189 doesn't answer \(fetch failed\)\. Start it \(scripts\/comfy\/README\.md\) or check Settings → Open-source engine · ComfyUI → Isolated worker URL/);
+ // The connection test reports it next to the main server, which still passes.
+ expect(await comfyProvider.test!()).toEqual({ ok: true, detail: "ComfyUI 0.41.0 · cuda:0 · 24 GB · the isolated worker at http://iso.test:8189 doesn't answer" });
+ handler = comfy;
+ expect((await comfyProvider.test!()).detail).toBe("ComfyUI 0.41.0 · cuda:0 · 24 GB · isolated worker: ComfyUI 0.41.0 · cuda:0 · 24 GB");
+ setSetting("comfyIsolatedUrl", "");
+ expect((await comfyProvider.test!()).detail).toBe("ComfyUI 0.41.0 · cuda:0 · 24 GB");
+ });
+
+ it("a generation on an isolated model fails with that message, instead of running on the main server", async () => {
+ setSetting("demoMode", "auto");
+ handler = comfy;
+ // The main ComfyUI answers (routing picks the open route), the isolated worker isn't set up.
+ globalThis.__fuobeComfyReach = { ok: true, at: Date.now(), url: "http://comfy.test:8188" };
+ const video = saveFile({ data: Buffer.from("video"), contentType: "video/mp4", name: "clip.mp4", source: "upload" }).url;
+ const audio = saveFile({ data: Buffer.from("voice"), contentType: "audio/wav", name: "voice.wav", source: "upload" }).url;
+ const [g] = gens.createGenerations({ feature: "lipsync", modelId: "oss-latentsync", op: "lipsync", inputs: { video, audio } });
+ expect(g.provider).toBe("comfyui");
+ expect(g.costUsd).toBe(0);
+ const end = Date.now() + 10_000;
+ let done: Generation = g;
+ while (Date.now() < end && !["failed", "succeeded"].includes(done.status)) {
+ await new Promise((r) => setTimeout(r, 50));
+ done = gens.getGeneration(g.id)!;
+ }
+ expect(done.status).toBe("failed");
+ expect(done.error).toMatch(/isolated ComfyUI worker.*Isolated worker URL/);
+ expect(calls.some((u) => u.startsWith("http://comfy.test:8188/upload"))).toBe(false);
+ });
+});
+
+describe("isolated-worker models in the studios", () => {
+ const ids = (c: { models: ModelDef[] }) => c.models.map((m) => m.id);
+ it("LatentSync is in the Lipsync studio and ThinkSound in Sound effects, both marked", () => {
+ const lips = studioCatalog(LIPSYNC_STUDIO);
+ expect(ids(lips)).toContain("oss-latentsync");
+ expect(lips.models.find((m) => m.id === "oss-latentsync")).toMatchObject({ worker: "isolated", engine: "open" });
+ expect(ids(studioCatalog(SFX_STUDIO))).toContain("oss-thinksound");
+ // ThinkSound's workflow makes sound from words only, so it isn't offered for a video.
+ expect(ids(studioCatalog(FOLEY_STUDIO))).not.toContain("oss-thinksound");
+ // Neither is a default: they need a second ComfyUI.
+ expect([LIPSYNC_STUDIO.defaultModels.open, SFX_STUDIO.defaultModels.open]).toEqual(["oss-infinitetalk", "oss-stable-audio-3"]);
+ expect(toModelRow(getModel("oss-latentsync")!).note).toBe("Runs on the isolated ComfyUI worker");
+ expect(toModelRow(getModel("oss-infinitetalk")!).note).toBeUndefined();
+ });
+});
diff --git a/tests/open-engine.test.ts b/tests/open-engine.test.ts
index 6f5459c8..ad0372da 100644
--- a/tests/open-engine.test.ts
+++ b/tests/open-engine.test.ts
@@ -108,8 +108,11 @@ describe("round-3 open models", () => {
expect(getModel("oss-captions-whisper")!.tagline).toMatch(/non-commercial/);
expect(getModel("oss-hunyuan-foley")!.tagline).toMatch(/EU, UK and South Korea/);
expect(getModel("oss-stable-audio-3")!.tagline).toMatch(/US\$1M/);
- expect(getModel("oss-thinksound")!.hidden).toBe(true); // isolated worker only
- expect(getModel("oss-latentsync")!.hidden).toBe(true);
+ // Offered in their studios, and marked as running on the isolated worker.
+ for (const id of ["oss-thinksound", "oss-latentsync"]) {
+ expect(getModel(id)!.worker, id).toBe("isolated");
+ expect(getModel(id)!.hidden, id).toBeFalsy();
+ }
});
it("every open model's sliders and controls are bindings of its workflows", () => {