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
Text steps: open-source translation runs on ComfyUI's Qwen3.5 4B when Ollama isn't running
Claudefad0bb6804ca
diff --git a/src/lib/catalog/llm-models.ts b/src/lib/catalog/llm-models.tsindex 88a57fb3..ea78b4ba 100644--- a/src/lib/catalog/llm-models.ts+++ b/src/lib/catalog/llm-models.ts@@ -5,7 +5,8 @@ import type { ModelDef, ModelRoute, Operation } from "./types";* server (src/server/providers/llm.ts). Kind "text": they only show up where a studio asks for* text models (dubbing, scripts, ad copy) and in pipelines, never in the image/video/audio pickers.* The route endpoint says which LLMs a model may use: "auto" = Claude when an Anthropic key is- * set, else a local Ollama; "ollama" = Ollama only (open-source installs never call a paid API).+ * set, else a local Ollama; "ollama" = Ollama only (open-source installs never call a paid API),+ * and its translations run on ComfyUI's Qwen3.5 4B workflow when Ollama isn't running.*/const llm = (op: Operation, endpoint: "auto" | "ollama"): ModelRoute => ({ op, provider: "llm", endpoint });@@ -39,7 +40,7 @@ export const LLM_MODELS: ModelDef[] = [family: "llm",engine: "open",kind: "text",- tagline: "Translation and writing on your own machine with Ollama (qwen3, llama, mistral…)",+ tagline: "Translation and writing on your own machine with Ollama (qwen3, llama, mistral…); without Ollama, translations run on ComfyUI (Qwen3.5 4B)",badges: ["open"],routes: [llm("translate", "ollama"), llm("write", "ollama")],options: { languages: LLM_LANGUAGES },diff --git a/src/server/providers/llm.ts b/src/server/providers/llm.tsindex 4e69e541..afd6f760 100644--- a/src/server/providers/llm.ts+++ b/src/server/providers/llm.ts@@ -2,21 +2,28 @@ import "server-only";import { Worker } from "node:worker_threads";import Anthropic from "@anthropic-ai/sdk";import { nanoid } from "nanoid";+import { getModel } from "@/lib/catalog";import { cueText, parseCues, toSrt, type Cue } from "@/lib/cues";-import type { GenInput, ModelRoute } from "@/lib/catalog/types";+import type { GenInput, ModelRoute, Operation } from "@/lib/catalog/types";import { engineMode, getSetting } from "../settings";import { toDataUri } from "../storage";-import type { ProviderAdapter, RemoteOutput } from "./types";+import { comfyProvider } from "./comfyui";+import type { PollResult, ProviderAdapter, RemoteOutput } from "./types";/*** The "llm" provider: text steps (translate, write) run inside this server on the LLM the* install is set up with — Claude when an Anthropic key is set (and the install isn't open- * source only), else a local Ollama. Route endpoint "ollama" (the open model) never uses Claude.+ * source only), else a local Ollama. Route endpoint "ollama" (the open model) never uses Claude;+ * when Ollama isn't running, its translations run on ComfyUI instead (Qwen3.5 4B through the+ * translate-qwen35-textgen workflow, one prompt per batch of lines, so cue timing is kept the same way).* Jobs run in the background of this process and are polled like any provider; a restart* loses a job that was still writing (it fails as interrupted and can be retried).*/-type Backend = "claude" | "ollama";+type Backend = "claude" | "ollama" | "comfyui";++/** The ComfyUI model and workflow open-source translations fall back to without Ollama. */+export const COMFY_TRANSLATE_MODEL = "oss-qwen35-translate";/** A text output: the words in `text`, the same words saved as a file (.txt, or .srt for timed text). */export type TextOutput = RemoteOutput & { text: string; meta?: Record<string, unknown> };@@ -85,23 +92,32 @@ function ollamaReady(): boolean {return cur.ok;}+/** A route, or the part of one that decides its LLMs (the op: only translations fall back to ComfyUI). */+type LlmRoute = Pick<ModelRoute, "endpoint"> & { op?: Operation };+/*** The LLMs a route may use right now, in the order they're tried. Follows Settings → AI helper- * ("none" turns text steps off; "ollama" never calls Claude) and the engine mode.+ * ("none" turns text steps off; "ollama" never calls Claude) and the engine mode. An open-source+ * translation with no Ollama answering runs on ComfyUI when that answers.*/-export function llmBackends(route: Pick<ModelRoute, "endpoint">): Backend[] {+export function llmBackends(route: LlmRoute): Backend[] {const choice = getSetting("enhanceProvider");if (choice === "none") return [];const out: Backend[] = [];const claude = route.endpoint !== "ollama" && !!getSetting("anthropicKey") && (choice === "anthropic" || (choice === "auto" && engineMode() !== "open"));if (claude) out.push("claude");if ((route.endpoint === "ollama" || choice !== "anthropic") && ollamaReady()) out.push("ollama");+ else if (route.endpoint === "ollama" && route.op === "translate" && comfyProvider.isConfigured()) out.push("comfyui");return out;}/** What to tell the user when no LLM can run a route (demo mode off). */-export const llmMissing = (route: Pick<ModelRoute, "endpoint">) =>- route.endpoint === "ollama" ? "Connect Ollama in Settings to run this model (open-source text runs on your own machine)" : "Connect Claude or Ollama in Settings to run this model";+export const llmMissing = (route: LlmRoute) =>+ route.endpoint !== "ollama"+ ? "Connect Claude or Ollama in Settings to run this model"+ : route.op === "translate"+ ? "Connect Ollama, or start ComfyUI with Qwen3.5 4B, in Settings to translate on your own machine"+ : "Connect Ollama in Settings to run this model (open-source text runs on your own machine)";/** Claude is the one that costs money. */export const llmUsesClaude = (route: Pick<ModelRoute, "endpoint">) => llmBackends(route)[0] === "claude";@@ -109,7 +125,7 @@ export const llmUsesClaude = (route: Pick<ModelRoute, "endpoint">) => llmBackend// ---------------------------------------------------------------------------// Calls-const BACKEND_LABEL: Record<Backend, string> = { claude: "Claude", ollama: "Ollama" };+const BACKEND_LABEL: Record<Backend, string> = { claude: "Claude", ollama: "Ollama", comfyui: "Qwen3.5 on ComfyUI" };async function viaClaude(system: string, user: string, signal: AbortSignal): Promise<string> {const client = new Anthropic({ apiKey: getSetting("anthropicKey") });@@ -173,13 +189,63 @@ async function viaOllama(system: string, user: string, signal: AbortSignal): Proreturn text;}+const COMFY_POLL_MS = 500;+/** One answer may take this long on ComfyUI (a GPU busy with other jobs queues it). */+const COMFY_ANSWER_MS = 15 * 60_000;++/**+ * One answer from Qwen3.5 4B inside ComfyUI: the system prompt is the workflow's instruction and the+ * user text follows it (TextGenerate reads them as one message). Submitted and polled like any+ * ComfyUI job; canceling the text step cancels the prompt.+ */+async function viaComfy(system: string, user: string, signal: AbortSignal): Promise<string> {+ const model = getModel(COMFY_TRANSLATE_MODEL);+ const route = model?.routes.find((r) => r.provider === "comfyui");+ if (!model || !route) throw new Error("The ComfyUI translate workflow is missing from the catalog");+ // Room for a long chunk of plain text (~8k characters) translated in one go.+ const { externalId, meta = {} } = await comfyProvider.submit({ generationId: `llm_${nanoid(8)}`, model, route, input: { prompt: user, extra: { instruction: `${system}\n\n`, maxTokens: 4096 } } });+ const ctx = { externalId, meta, route, model, createdAt: Date.now() };+ const stop = () => void comfyProvider.cancel?.(ctx).catch(() => {});+ signal.addEventListener("abort", stop, { once: true });+ try {+ let misses = 0;+ for (const end = Date.now() + COMFY_ANSWER_MS; Date.now() < end; ) {+ await new Promise((r) => setTimeout(r, COMFY_POLL_MS));+ if (signal.aborted) throw new Error("Canceled");+ let r: PollResult;+ try {+ r = await comfyProvider.poll(ctx);+ misses = 0;+ } catch (e) {+ // A proxy hiccup: ask again, a few times.+ if (++misses >= 5) throw new Error(`ComfyUI stopped answering (${(e as Error).message})`);+ continue;+ }+ if (r.state === "failed") throw new Error(`ComfyUI couldn't translate: ${r.error}`);+ if (r.state !== "succeeded") continue;+ const out = r.outputs.find((o) => o.kind === "text");+ // SaveText hands the words back with the file; read the file when they're missing.+ const raw = out?.text ?? (out ? await (await fetch(out.url, { headers: out.headers, signal })).text() : "");+ const text = raw.replace(/<think>[\s\S]*?<\/think>/g, "").trim();+ if (!text) throw new Error("ComfyUI returned no text");+ return text;+ }+ stop();+ throw new Error("ComfyUI took too long to translate");+ } finally {+ signal.removeEventListener("abort", stop);+ }+}++const CALL: Record<Backend, (system: string, user: string, signal: AbortSignal) => Promise<string>> = { claude: viaClaude, ollama: viaOllama, comfyui: viaComfy };+/** Ask the first backend; if it fails, the next (Claude → Ollama). Throws the first error when all fail. */async function complete(backends: Backend[], system: string, user: string, job: LlmJob): Promise<string> {let first: Error | null = null;for (const b of backends) {try {job.backend = b;- return await (b === "claude" ? viaClaude : viaOllama)(system, user, job.abort.signal);+ return await CALL[b](system, user, job.abort.signal);} catch (e) {if (job.abort.signal.aborted) throw e;first ??= e as Error;diff --git a/tests/llm.test.ts b/tests/llm.test.tsindex d2a5ff91..c88d71b1 100644--- a/tests/llm.test.ts+++ b/tests/llm.test.ts@@ -15,6 +15,7 @@ const { setSetting } = await import("@/server/settings");const gens = await import("@/server/generations");const llm = await import("@/server/providers/llm");const { getModel, modelsFor } = await import("@/lib/catalog");+const { probeComfy } = await import("@/server/providers/comfyui");// A stand-in Ollama: answers numbered subtitle lines line by line, anything else with a prefix.const seen: { system: string; user: string; model: string }[] = [];@@ -286,3 +287,109 @@ describe("LLM provider", () => {expect(res).toMatchObject({ state: "failed", error: expect.stringMatching(/Interrupted/) });});});++describe("open translation without Ollama: Qwen3.5 on ComfyUI", () => {+ // A stand-in ComfyUI: runs the translate workflow by answering its instruction + text the way the+ // stand-in Ollama does, and reports the text through SaveText's history entry.+ const prompts: { instruction: string; text: string; maxTokens: unknown; clip: unknown }[] = [];+ const answers = new Map<string, string>();+ let fail: string | null = null;+ const comfy = http.createServer((req, res) => {+ const reply = (v: unknown, status = 200) => {+ res.writeHead(status, { "content-type": "application/json" });+ res.end(JSON.stringify(v));+ };+ if (req.url === "/system_stats") return reply({ system: { comfyui_version: "0.41.0" } });+ if (req.url === "/queue") return reply({ queue_running: [], queue_pending: [] });+ if (req.url?.startsWith("/history/")) {+ const id = req.url.slice("/history/".length);+ const text = answers.get(id);+ return reply(text === undefined ? {} : { [id]: { status: { status_str: "success", completed: true }, outputs: { "4": { text: [text], files: [{ filename: `${id}.txt`, subfolder: "fuobe", type: "output" }] } } } });+ }+ let body = "";+ req.on("data", (c) => (body += c));+ req.on("end", () => {+ if (req.url !== "/prompt") return reply({ error: "not found" }, 404);+ if (fail) return reply({ error: { type: "prompt_outputs_failed_validation", message: fail }, node_errors: {} }, 400);+ const wf = (JSON.parse(body) as { prompt: Record<string, { class_type: string; inputs: Record<string, unknown> }> }).prompt;+ const join = Object.values(wf).find((n) => n.class_type === "StringConcatenate")!.inputs;+ const gen = Object.values(wf).find((n) => n.class_type === "TextGenerate")!.inputs;+ const clip = Object.values(wf).find((n) => n.class_type === "CLIPLoader")!.inputs.clip_name;+ const instruction = String(join.string_a);+ const text = String(join.string_b);+ prompts.push({ instruction, text, maxTokens: gen.max_length, clip });+ const lang = /into (\w+)/.exec(instruction)?.[1] ?? "??";+ const id = `p${prompts.length}`;+ answers.set(id, /^\[\d+\]/.test(text) ? text.split("\n").map((l) => l.replace(/^\[(\d+)\]\s*/, (_, n) => `[${n}] (${lang}·qwen) `)).join("\n") : `(${lang}·qwen) ${text}`);+ reply({ prompt_id: id, number: prompts.length });+ });+ });+ let comfyUrl = "";++ beforeAll(async () => {+ await new Promise<void>((r) => comfy.listen(0, "127.0.0.1", r));+ comfyUrl = `http://127.0.0.1:${(comfy.address() as { port: number }).port}`;+ });+ afterAll(() => {+ comfy.close();+ setSetting("comfyUrl", "");+ });+ beforeEach(async () => {+ prompts.length = 0;+ fail = null;+ setSetting("comfyUrl", comfyUrl);+ // Routing reads the cached reachability; this server shares the test's thread, so answer it here first.+ await probeComfy(true);+ });++ it("translates subtitles in the same numbered batches on ComfyUI, keeps the timing and costs nothing", async () => {+ await useOllama(false);+ expect(llm.llmBackends({ endpoint: "ollama", op: "translate" })).toEqual(["comfyui"]);+ // Only translations: writing still needs Ollama, and the cloud model never goes to ComfyUI.+ expect(llm.llmBackends({ endpoint: "ollama", op: "write" })).toEqual([]);+ expect(llm.llmBackends({ endpoint: "auto", op: "translate" })).toEqual([]);+ const [g] = gens.createGenerations({ feature: "dub", modelId: "oss-text-llm", op: "translate", prompt: CUES, params: { targetLanguage: "Spanish", sourceLanguage: "English" } });+ expect(g.provider).toBe("llm");+ expect(g.costUsd).toBe(0);+ const done = await settle(g.id);+ expect(done.status, done.error ?? "").toBe("succeeded");+ expect(done.outputs[0]).toMatchObject({ kind: "text", contentType: "application/x-subrip" });+ expect(done.outputs[0].meta?.cues).toEqual([+ { start: 0, end: 1.8, text: "(Spanish·qwen) Hello there." },+ { start: 2, end: 4.25, text: "(Spanish·qwen) This is a test\nwith two lines." },+ ]);+ // One prompt for the batch: the subtitle instructions, then the numbered lines, on Qwen3.5 4B.+ expect(prompts).toHaveLength(1);+ expect(prompts[0].instruction).toMatch(/^You translate subtitles from English into Spanish\./);+ expect(prompts[0].instruction.endsWith("\n\n")).toBe(true);+ expect(prompts[0].text).toBe("[1] Hello there.\n[2] This is a test <br> with two lines.");+ expect(prompts[0]).toMatchObject({ maxTokens: 4096, clip: "qwen3.5_4b_bf16.safetensors" });+ expect(seen).toHaveLength(0);+ });++ it("plain text too; with Ollama up, Ollama does it", async () => {+ await useOllama(false);+ const [a] = gens.createGenerations({ feature: "captions", modelId: "oss-text-llm", op: "translate", prompt: "Good morning, friends.", params: { targetLanguage: "German" } });+ expect((await settle(a.id)).outputs[0]).toMatchObject({ kind: "text", text: "(German·qwen) Good morning, friends." });+ await useOllama(true);+ prompts.length = 0;+ expect(llm.llmBackends({ endpoint: "ollama", op: "translate" })).toEqual(["ollama"]);+ const [b] = gens.createGenerations({ feature: "captions", modelId: "oss-text-llm", op: "translate", prompt: "Good night.", params: { targetLanguage: "German" } });+ expect((await settle(b.id)).outputs[0].text).toBe("(German) Good night.");+ expect(prompts).toHaveLength(0);+ });++ it("a ComfyUI error fails the step with its words; with neither running, the message names both", async () => {+ await useOllama(false);+ fail = "Value not in list: clip_name: 'qwen3.5_4b_bf16.safetensors' not in []";+ const [g] = gens.createGenerations({ feature: "dub", modelId: "oss-text-llm", op: "translate", prompt: "Hello.", params: { targetLanguage: "French" } });+ const done = await settle(g.id);+ expect(done.status).toBe("failed");+ expect(done.error).toMatch(/qwen3\.5_4b_bf16\.safetensors/);+ setSetting("comfyUrl", "http://127.0.0.1:9");+ await probeComfy(true);+ expect(llm.llmBackends({ endpoint: "ollama", op: "translate" })).toEqual([]);+ setSetting("demoMode", "off");+ expect(() => gens.createGenerations({ feature: "dub", modelId: "oss-text-llm", op: "translate", prompt: "x", params: { targetLanguage: "French" } })).toThrow(/Connect Ollama, or start ComfyUI with Qwen3\.5 4B/);+ });+});