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
LLM provider for translate and write; demo outputs for every round-3 operation
Claude735217cfc904
diff --git a/public/samples/demo-model.glb b/public/samples/demo-model.glbnew file mode 100644index 00000000..535d7219Binary files /dev/null and b/public/samples/demo-model.glb differdiff --git a/public/samples/demo-turntable.mp4 b/public/samples/demo-turntable.mp4new file mode 100644index 00000000..c825c78dBinary files /dev/null and b/public/samples/demo-turntable.mp4 differdiff --git a/scripts/gen-demo-3d.mjs b/scripts/gen-demo-3d.mjsnew file mode 100644index 00000000..23a74b36--- /dev/null+++ b/scripts/gen-demo-3d.mjs@@ -0,0 +1,204 @@+#!/usr/bin/env node+/**+ * Demo-mode assets for "image to 3D": a small, valid glTF 2.0 binary (public/samples/demo-model.glb)+ * and a turntable clip of the same mesh (public/samples/demo-turntable.mp4, needs ffmpeg).+ * The mock provider returns both when no 3D provider is connected. Run: node scripts/gen-demo-3d.mjs+ */+import { spawnSync } from "node:child_process";+import fs from "node:fs";+import path from "node:path";+import { fileURLToPath } from "node:url";++const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");+const out = path.join(root, "public", "samples");++// ---------------------------------------------------------------------------+// Mesh: a faceted crystal (octagonal bipyramid with a flat girdle band), flat-shaded.++const SIDES = 8;+const ring = (y, r, twist = 0) => Array.from({ length: SIDES }, (_, i) => {+ const a = (i / SIDES) * Math.PI * 2 + twist;+ return [Math.cos(a) * r, y, Math.sin(a) * r];+});+const top = [0, 1.05, 0];+const bottom = [0, -1.25, 0];+const upper = ring(0.25, 0.62, Math.PI / SIDES);+const lower = ring(-0.05, 0.62, Math.PI / SIDES);++/** Triangles, each [a, b, c] counter-clockwise seen from outside. */+const tris = [];+for (let i = 0; i < SIDES; i++) {+ const j = (i + 1) % SIDES;+ tris.push([top, upper[j], upper[i]]);+ tris.push([upper[i], upper[j], lower[j]], [upper[i], lower[j], lower[i]]);+ tris.push([bottom, lower[i], lower[j]]);+}++const sub = (a, b) => [a[0] - b[0], a[1] - b[1], a[2] - b[2]];+const cross = (a, b) => [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]];+const norm = (v) => {+ const l = Math.hypot(...v) || 1;+ return v.map((x) => x / l);+};++// Iris-to-violet facets (the brand colour, #5d4bdb), alternating so the facets read in any viewer.+const PALETTE = [+ [0.365, 0.294, 0.859],+ [0.51, 0.44, 0.95],+ [0.27, 0.2, 0.7],+ [0.62, 0.55, 0.98],+];+const positions = [];+const normals = [];+const colors = [];+tris.forEach((t, k) => {+ const n = norm(cross(sub(t[1], t[0]), sub(t[2], t[0])));+ const c = PALETTE[(k + Math.floor(k / 4)) % PALETTE.length];+ for (const v of t) {+ positions.push(...v);+ normals.push(...n);+ colors.push(...c);+ }+});+const count = positions.length / 3;+const indices = Array.from({ length: count }, (_, i) => i);++// ---------------------------------------------------------------------------+// GLB writer++function glb() {+ const f32 = (a) => Buffer.from(new Float32Array(a).buffer);+ const pos = f32(positions);+ const nor = f32(normals);+ const col = f32(colors);+ const idx = Buffer.from(new Uint16Array(indices).buffer);+ const views = [pos, nor, col, idx];+ let offset = 0;+ const bufferViews = views.map((b, i) => {+ const v = { buffer: 0, byteOffset: offset, byteLength: b.length, target: i === 3 ? 34963 : 34962 };+ offset += b.length;+ return v;+ });+ const bin = Buffer.concat(views);+ const binPadded = Buffer.concat([bin, Buffer.alloc((4 - (bin.length % 4)) % 4)]);+ const min = [0, 1, 2].map((a) => Math.min(...positions.filter((_, i) => i % 3 === a)));+ const max = [0, 1, 2].map((a) => Math.max(...positions.filter((_, i) => i % 3 === a)));+ const gltf = {+ asset: { version: "2.0", generator: "Fuobe demo (scripts/gen-demo-3d.mjs)", copyright: "Fuobe demo output" },+ scene: 0,+ scenes: [{ name: "Demo", nodes: [0] }],+ nodes: [{ name: "Demo crystal", mesh: 0 }],+ meshes: [{ name: "Demo crystal", primitives: [{ attributes: { POSITION: 0, NORMAL: 1, COLOR_0: 2 }, indices: 3, material: 0, mode: 4 }] }],+ materials: [{ name: "Demo facets", pbrMetallicRoughness: { baseColorFactor: [1, 1, 1, 1], metallicFactor: 0.1, roughnessFactor: 0.4 } }],+ buffers: [{ byteLength: binPadded.length }],+ bufferViews,+ accessors: [+ { bufferView: 0, componentType: 5126, count, type: "VEC3", min, max },+ { bufferView: 1, componentType: 5126, count, type: "VEC3" },+ { bufferView: 2, componentType: 5126, count, type: "VEC3" },+ { bufferView: 3, componentType: 5123, count, type: "SCALAR" },+ ],+ };+ const json = Buffer.from(JSON.stringify(gltf));+ const jsonPadded = Buffer.concat([json, Buffer.alloc((4 - (json.length % 4)) % 4, 0x20)]);+ const header = Buffer.alloc(12);+ const total = 12 + 8 + jsonPadded.length + 8 + binPadded.length;+ header.writeUInt32LE(0x46546c67, 0); // "glTF"+ header.writeUInt32LE(2, 4);+ header.writeUInt32LE(total, 8);+ const chunk = (data, type) => {+ const h = Buffer.alloc(8);+ h.writeUInt32LE(data.length, 0);+ h.writeUInt32LE(type, 4);+ return Buffer.concat([h, data]);+ };+ return Buffer.concat([header, chunk(jsonPadded, 0x4e4f534a), chunk(binPadded, 0x004e4942)]);+}++// ---------------------------------------------------------------------------+// Turntable: a tiny software rasterizer → raw RGB frames → ffmpeg (H.264).++const W = 512;+const H = 512;+const FRAMES = 72;++function frame(angle) {+ const rgb = Buffer.alloc(W * H * 3);+ const depth = new Float32Array(W * H).fill(Infinity);+ for (let y = 0; y < H; y++) {+ // Dark violet backdrop with a soft vertical falloff.+ const t = y / H;+ for (let x = 0; x < W; x++) {+ const dx = (x - W / 2) / W;+ const glow = Math.max(0, 1 - Math.hypot(dx, t - 0.45) * 2.2);+ const i = (y * W + x) * 3;+ rgb[i] = 22 + glow * 30;+ rgb[i + 1] = 18 + glow * 22;+ rgb[i + 2] = 40 + glow * 60;+ }+ }+ const tilt = -0.32;+ const rot = (v) => {+ const [x, y, z] = v;+ const x1 = x * Math.cos(angle) + z * Math.sin(angle);+ const z1 = -x * Math.sin(angle) + z * Math.cos(angle);+ return [x1, y * Math.cos(tilt) - z1 * Math.sin(tilt), y * Math.sin(tilt) + z1 * Math.cos(tilt)];+ };+ const project = ([x, y, z]) => {+ const d = 4.2 - z;+ return [W / 2 + (x * 640) / d, H * 0.52 - (y * 640) / d, d];+ };+ const light = norm([0.5, 0.8, 0.9]);+ for (let k = 0; k < tris.length; k++) {+ const v = tris[k].map(rot);+ const n = norm(cross(sub(v[1], v[0]), sub(v[2], v[0])));+ if (n[2] <= 0) continue; // facing away+ const shade = 0.35 + 0.65 * Math.max(0, n[0] * light[0] + n[1] * light[1] + n[2] * light[2]);+ const c = colors.slice(k * 9, k * 9 + 3).map((x) => Math.min(255, x * 255 * shade + 18));+ const p = v.map(project);+ const minX = Math.max(0, Math.floor(Math.min(p[0][0], p[1][0], p[2][0])));+ const maxX = Math.min(W - 1, Math.ceil(Math.max(p[0][0], p[1][0], p[2][0])));+ const minY = Math.max(0, Math.floor(Math.min(p[0][1], p[1][1], p[2][1])));+ const maxY = Math.min(H - 1, Math.ceil(Math.max(p[0][1], p[1][1], p[2][1])));+ const area = (p[1][0] - p[0][0]) * (p[2][1] - p[0][1]) - (p[2][0] - p[0][0]) * (p[1][1] - p[0][1]);+ if (Math.abs(area) < 1e-6) continue;+ for (let y = minY; y <= maxY; y++) {+ for (let x = minX; x <= maxX; x++) {+ const px = x + 0.5;+ const py = y + 0.5;+ const w0 = ((p[1][0] - px) * (p[2][1] - py) - (p[2][0] - px) * (p[1][1] - py)) / area;+ const w1 = ((p[2][0] - px) * (p[0][1] - py) - (p[0][0] - px) * (p[2][1] - py)) / area;+ const w2 = 1 - w0 - w1;+ if (w0 < 0 || w1 < 0 || w2 < 0) continue;+ const z = w0 * p[0][2] + w1 * p[1][2] + w2 * p[2][2];+ const i = y * W + x;+ if (z >= depth[i]) continue;+ depth[i] = z;+ rgb[i * 3] = c[0];+ rgb[i * 3 + 1] = c[1];+ rgb[i * 3 + 2] = c[2];+ }+ }+ }+ return rgb;+}++fs.mkdirSync(out, { recursive: true });+const model = glb();+fs.writeFileSync(path.join(out, "demo-model.glb"), model);+console.log(`wrote demo-model.glb (${model.length} bytes, ${tris.length} triangles)`);++const font = ["/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf", "/usr/share/fonts/truetype/freefont/FreeSansBold.ttf"].find((f) => fs.existsSync(f));+const label = font ? `,drawtext=fontfile=${font}:text='DEMO OUTPUT · 3D':[email protected]:fontsize=20:x=28:y=28:box=1:[email protected]:boxborderw=10` : "";+const frames = Buffer.concat(Array.from({ length: FRAMES }, (_, f) => frame((f / FRAMES) * Math.PI * 2)));+const ff = spawnSync(+ "ffmpeg",+ ["-y", "-loglevel", "error", "-f", "rawvideo", "-pix_fmt", "rgb24", "-s", `${W}x${H}`, "-r", "24", "-i", "-", "-vf", `format=yuv420p${label}`, "-c:v", "libx264", "-preset", "slow", "-crf", "30", "-pix_fmt", "yuv420p", "-movflags", "+faststart", path.join(out, "demo-turntable.mp4")],+ { input: frames },+);+if (ff.status !== 0) {+ console.error(`ffmpeg failed (${ff.error?.message ?? ff.stderr?.toString()}); demo-turntable.mp4 not written`);+ process.exitCode = 1;+} else {+ console.log(`wrote demo-turntable.mp4 (${fs.statSync(path.join(out, "demo-turntable.mp4")).size} bytes, ${FRAMES} frames)`);+}diff --git a/src/app/api/files/[...path]/route.ts b/src/app/api/files/[...path]/route.tsindex 6e784445..ee5dda27 100644--- a/src/app/api/files/[...path]/route.ts+++ b/src/app/api/files/[...path]/route.ts@@ -13,9 +13,11 @@ export async function GET(request: Request, ctx: RouteContext<"/api/files/[...paconst size = fs.statSync(abs).size;const type = contentTypeFor(abs);const headers: Record<string, string> = {- "Content-Type": type,+ // Transcripts, subtitles and scripts are UTF-8 text.+ "Content-Type": /^text\/|^application\/(json|x-subrip)$/.test(type) ? `${type}; charset=utf-8` : type,"Accept-Ranges": "bytes","Cache-Control": "private, max-age=31536000, immutable",+ "X-Content-Type-Options": "nosniff",};if (type === "image/svg+xml") headers["Content-Security-Policy"] = "default-src 'none'; style-src 'unsafe-inline'";const download = new URL(request.url).searchParams.get("download");diff --git a/src/lib/catalog/index.ts b/src/lib/catalog/index.tsindex 73b2142e..8e49ab57 100644--- a/src/lib/catalog/index.ts+++ b/src/lib/catalog/index.ts@@ -1,9 +1,11 @@import { APPS as RAW_APPS } from "./apps";import { EFFECTS as RAW_EFFECTS, MOTIONS as RAW_MOTIONS } from "./motions";import { MODELS } from "./models";+import { LLM_MODELS } from "./llm-models";import { OSS_LORAS } from "./oss-loras.generated";import type { Engine, MediaKind, ModelDef, Operation, Preset } from "./types";+MODELS.push(...LLM_MODELS.filter((m) => !MODELS.some((x) => x.id === m.id))); // text steps (translate, write) on the configured LLM; once per hot reloadexport { MODELS };const modelIndex = new Map(MODELS.map((m) => [m.id, m]));diff --git a/src/lib/catalog/llm-models.ts b/src/lib/catalog/llm-models.tsnew file mode 100644index 00000000..88a57fb3--- /dev/null+++ b/src/lib/catalog/llm-models.ts@@ -0,0 +1,47 @@+import type { ModelDef, ModelRoute, Operation } from "./types";++/**+ * Text steps (translate, write) run on the LLM this install is set up with, inside the Fuobe+ * 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).+ */++const llm = (op: Operation, endpoint: "auto" | "ollama"): ModelRoute => ({ op, provider: "llm", endpoint });++/** Languages offered in the translate picker (any language name works). */+export const LLM_LANGUAGES = [+ "English", "Spanish", "French", "German", "Italian", "Portuguese", "Dutch", "Polish", "Russian", "Turkish", "Arabic", "Hebrew",+ "Hindi", "Bengali", "Japanese", "Korean", "Chinese (Simplified)", "Chinese (Traditional)", "Indonesian", "Vietnamese", "Thai",+ "Swedish", "Danish", "Norwegian", "Finnish", "Greek", "Czech", "Ukrainian", "Romanian", "Hungarian", "Swahili", "Tagalog",+];++export const LLM_MODELS: ModelDef[] = [+ {+ id: "text-llm",+ name: "Claude",+ vendor: "Anthropic",+ family: "llm",+ engine: "cloud",+ kind: "text",+ tagline: "Translates subtitles cue by cue and writes scripts, captions and ad copy (Ollama when no Anthropic key is set)",+ badges: ["top"],+ routes: [llm("translate", "auto"), llm("write", "auto")],+ options: { languages: LLM_LANGUAGES },+ // Claude Opus 5.5 at $4 / $20 per million tokens: a few cents for a page of text.+ pricing: { unit: "request", usd: 0.02, note: "≈ a page of text; free when it runs on Ollama" },+ },+ {+ id: "oss-text-llm",+ name: "Local LLM",+ vendor: "Ollama",+ family: "llm",+ engine: "open",+ kind: "text",+ tagline: "Translation and writing on your own machine with Ollama (qwen3, llama, mistral…)",+ badges: ["open"],+ routes: [llm("translate", "ollama"), llm("write", "ollama")],+ options: { languages: LLM_LANGUAGES },+ },+];diff --git a/src/lib/cues.ts b/src/lib/cues.tsnew file mode 100644index 00000000..1947d14e--- /dev/null+++ b/src/lib/cues.ts@@ -0,0 +1,72 @@+/**+ * Timed text (transcripts, subtitles): the shape transcribe outputs carry in OutputFile.meta.cues,+ * and readers/writers for the formats people paste (JSON cue lists, SRT, WebVTT).+ */++export interface Cue {+ /** Seconds from the start. */+ start: number;+ end: number;+ text: string;+}++const isCue = (c: unknown): c is Cue =>+ !!c && typeof c === "object" && typeof (c as Cue).start === "number" && typeof (c as Cue).end === "number" && typeof (c as Cue).text === "string";++/** "00:01:02,500" / "01:02.500" / "62.5" → seconds. */+function seconds(t: string): number {+ const parts = t.trim().replace(",", ".").split(":").map(Number);+ return parts.reduce((acc, p) => acc * 60 + p, 0);+}++const TIME = /((?:\d+:)?\d{1,2}:\d{2}[,.]\d{1,3})\s*-->\s*((?:\d+:)?\d{1,2}:\d{2}[,.]\d{1,3})/;++/** Read a cue list from JSON ([{start, end, text}] or {cues: [...]}), SRT or WebVTT; null for plain text. */+export function parseCues(input: string): Cue[] | null {+ const s = input.trim();+ if (!s) return null;+ if (s.startsWith("[") || s.startsWith("{")) {+ try {+ const j = JSON.parse(s) as unknown;+ const list = Array.isArray(j) ? j : (j as { cues?: unknown }).cues;+ if (Array.isArray(list) && list.length && list.every(isCue)) return list.map((c) => ({ start: c.start, end: c.end, text: c.text }));+ } catch {+ // Not JSON: maybe a transcript that starts with a bracket.+ }+ return null;+ }+ if (!TIME.test(s)) return null;+ const cues: Cue[] = [];+ for (const block of s.replace(/\r/g, "").split(/\n{2,}/)) {+ const lines = block.split("\n");+ const at = lines.findIndex((l) => TIME.test(l));+ if (at < 0) continue;+ const m = TIME.exec(lines[at])!;+ const text = lines+ .slice(at + 1)+ .join("\n")+ .trim();+ if (text) cues.push({ start: seconds(m[1]), end: seconds(m[2]), text });+ }+ return cues.length ? cues : null;+}++const stamp = (t: number, sep: "," | ".") => {+ const ms = Math.max(0, Math.round(t * 1000));+ const h = Math.floor(ms / 3_600_000);+ const m = Math.floor((ms % 3_600_000) / 60_000);+ const sec = Math.floor((ms % 60_000) / 1000);+ const pad = (n: number, w = 2) => String(n).padStart(w, "0");+ return `${pad(h)}:${pad(m)}:${pad(sec)}${sep}${pad(ms % 1000, 3)}`;+};++export function toSrt(cues: Cue[]): string {+ return cues.map((c, i) => `${i + 1}\n${stamp(c.start, ",")} --> ${stamp(c.end, ",")}\n${c.text.trim()}\n`).join("\n");+}++export function toVtt(cues: Cue[]): string {+ return `WEBVTT\n\n${cues.map((c) => `${stamp(c.start, ".")} --> ${stamp(c.end, ".")}\n${c.text.trim()}\n`).join("\n")}`;+}++/** The words alone, one cue per line. */+export const cueText = (cues: Cue[]) => cues.map((c) => c.text.trim()).join("\n");diff --git a/src/server/providers/index.ts b/src/server/providers/index.tsindex bd5c107b..3c6fec67 100644--- a/src/server/providers/index.ts+++ b/src/server/providers/index.ts@@ -3,6 +3,7 @@ import type { ProviderId } from "@/lib/catalog/types";import { comfyProvider } from "./comfyui";import { falProvider } from "./fal";import { higgsfieldProvider } from "./higgsfield";+import { llmProvider } from "./llm";import { mockProvider } from "./mock";import { replicateProvider } from "./replicate";import type { ProviderAdapter } from "./types";@@ -43,7 +44,7 @@ export const PROVIDERS: Record<ProviderId, ProviderAdapter> = {local: localProvider,openai: notImplemented("openai", "OpenAI"),google: notImplemented("google", "Google"),- llm: notImplemented("llm", "LLM"),+ llm: llmProvider,};export function provider(id: ProviderId): ProviderAdapter {diff --git a/src/server/providers/llm.ts b/src/server/providers/llm.tsnew file mode 100644index 00000000..27845f94--- /dev/null+++ b/src/server/providers/llm.ts@@ -0,0 +1,305 @@+import "server-only";+import Anthropic from "@anthropic-ai/sdk";+import { nanoid } from "nanoid";+import { cueText, parseCues, toSrt, type Cue } from "@/lib/cues";+import type { GenInput, ModelRoute } from "@/lib/catalog/types";+import { engineMode, getSetting } from "../settings";+import { toDataUri } from "../storage";+import type { 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.+ * 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";++/** 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> };++export function textOutput(text: string, cues?: Cue[] | null, meta: Record<string, unknown> = {}): TextOutput {+ if (cues?.length) {+ return { url: toDataUri(Buffer.from(toSrt(cues)), "application/x-subrip"), kind: "text", contentType: "application/x-subrip", text, meta: { ...meta, cues } };+ }+ return { url: toDataUri(Buffer.from(text), "text/plain"), kind: "text", contentType: "text/plain", text, ...(Object.keys(meta).length && { meta }) };+}++// ---------------------------------------------------------------------------+// Which LLM++declare global {+ var __fuobeOllamaReach: { ok: boolean; at: number; url: string } | undefined;+ var __fuobeLlmJobs: Map<string, LlmJob> | undefined;+}++const ollamaUrl = () => getSetting("ollamaUrl").replace(/\/+$/, "");+const PROBE_MS = 15_000;++/** Is Ollama answering? Cached for 15 s; routing reads the cached answer (see llmBackends). */+export async function probeOllama(force = false): Promise<boolean> {+ const cur = globalThis.__fuobeOllamaReach;+ const url = ollamaUrl();+ if (!force && cur && cur.url === url && Date.now() - cur.at < PROBE_MS) return cur.ok;+ const ok = await fetch(`${url}/api/tags`, { signal: AbortSignal.timeout(1500) })+ .then((r) => r.ok)+ .catch(() => false);+ globalThis.__fuobeOllamaReach = { ok, at: Date.now(), url };+ return ok;+}++function ollamaReady(): boolean {+ const cur = globalThis.__fuobeOllamaReach;+ const url = ollamaUrl();+ if (!cur || cur.url !== url || Date.now() - cur.at > PROBE_MS) void probeOllama();+ return !!cur && cur.url === url && cur.ok;+}++/**+ * 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.+ */+export function llmBackends(route: Pick<ModelRoute, "endpoint">): 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");+ 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";++/** Claude is the one that costs money. */+export const llmUsesClaude = (route: Pick<ModelRoute, "endpoint">) => llmBackends(route)[0] === "claude";++// ---------------------------------------------------------------------------+// Calls++const BACKEND_LABEL: Record<Backend, string> = { claude: "Claude", ollama: "Ollama" };++async function viaClaude(system: string, user: string, signal: AbortSignal): Promise<string> {+ const client = new Anthropic({ apiKey: getSetting("anthropicKey") });+ let res: Anthropic.Beta.BetaMessage;+ try {+ res = (await client.beta.messages.create(+ {+ model: "claude-opus-5-5",+ max_tokens: 16000,+ output_config: { effort: "low" },+ betas: ["server-side-fallback-2026-07-01"],+ fallbacks: "default",+ system,+ messages: [{ role: "user", content: user }],+ } as Parameters<typeof client.beta.messages.create>[0] & { fallbacks: string },+ { signal },+ )) as Anthropic.Beta.BetaMessage;+ } catch (e) {+ if (e instanceof Anthropic.AuthenticationError) throw new Error("Your Anthropic API key was rejected. Check it in Settings → API keys.");+ if (e instanceof Anthropic.RateLimitError) throw new Error("Claude is rate-limited right now. Try again in a minute.");+ if (e instanceof Anthropic.APIError) throw new Error(`Claude returned an error (${e.status ?? "network"}): ${e.message}`);+ throw e;+ }+ if (res.stop_reason === "refusal") throw new Error("Claude declined this text");+ if (res.stop_reason === "max_tokens") throw new Error("That text is too long for one pass — split it and try again");+ const text = res.content+ .filter((b): b is Anthropic.Beta.BetaTextBlock => b.type === "text")+ .map((b) => b.text)+ .join("")+ .trim();+ if (!text) throw new Error("Claude returned no text");+ return text;+}++async function viaOllama(system: string, user: string, signal: AbortSignal): Promise<string> {+ const url = ollamaUrl();+ const model = getSetting("ollamaModel");+ const res = await fetch(`${url}/api/chat`, {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ model,+ stream: false,+ think: false,+ messages: [+ { role: "system", content: system },+ { role: "user", content: user },+ ],+ options: { num_ctx: 16384 },+ }),+ signal: AbortSignal.any([signal, AbortSignal.timeout(300_000)]),+ }).catch((e: Error) => {+ if (signal.aborted) throw e;+ throw new Error(`Couldn't reach Ollama at ${url} (${e.message}). Is it running?`);+ });+ if (res.status === 404) throw new Error(`Ollama doesn't have ${model} yet — run \`ollama pull ${model}\``);+ if (!res.ok) throw new Error(`Ollama returned ${res.status}: ${(await res.text()).slice(0, 200)}`);+ const j = (await res.json()) as { message?: { content?: string } };+ const text = (j.message?.content ?? "").replace(/<think>[\s\S]*?<\/think>/g, "").trim();+ if (!text) throw new Error("Ollama returned no text");+ return text;+}++/** 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);+ } catch (e) {+ if (job.abort.signal.aborted) throw e;+ first ??= e as Error;+ }+ }+ throw first ?? new Error(llmMissing({ endpoint: "auto" }));+}++// ---------------------------------------------------------------------------+// Translate and write++const translateSystem = (lang: string, from?: string) => `You are a professional translator. Translate the user's text ${from ? `from ${from} ` : ""}into ${lang}.+- Keep the meaning, tone, register, names, numbers and formatting (line breaks, lists, markdown).+- Reply with the translation only: no notes, no quotes around it, no explanations.`;++const cuesSystem = (lang: string, from?: string) => `You translate subtitles ${from ? `from ${from} ` : ""}into ${lang}.+The user sends numbered subtitle lines like "[3] text". Translate each line on its own and reply with every number, in order, one line each: "[3] translation".+- Never merge, split, skip or reorder lines; keep "<br>" where it appears.+- Keep each line about as short as the original so it still reads as a subtitle.+- Reply with the numbered lines only.`;++const WRITE_SYSTEM = `You are a writer for a video and image studio: scripts, voice-overs, captions, shot lists, hooks and ad copy.+- Follow the brief: length, format, tone, audience and language.+- Write words meant to be spoken as natural speech, with no stage directions unless asked.+- Reply with the text only: no preamble, no notes, no quotes around it.`;++const CUE_BATCH = 30;+const CHUNK_CHARS = 8000;++/** Plain text in pieces that fit one call: paragraphs grouped up to ~8k characters. */+function chunks(text: string): string[] {+ const out: string[] = [];+ let cur = "";+ for (const p of text.split(/\n{2,}/)) {+ if (cur && cur.length + p.length + 2 > CHUNK_CHARS) {+ out.push(cur);+ cur = p;+ } else cur = cur ? `${cur}\n\n${p}` : p;+ }+ if (cur) out.push(cur);+ return out;+}++/** "[n] text" answers back into the batch's order; null if any line is missing. */+function readNumbered(answer: string, from: number, count: number): string[] | null {+ const got = new Map<number, string>();+ for (const line of answer.split("\n")) {+ const m = /^\s*\[(\d+)\]\s*(.*)$/.exec(line);+ if (m) got.set(Number(m[1]), m[2].trim());+ }+ const out = Array.from({ length: count }, (_, i) => got.get(from + i));+ return out.every((x) => x !== undefined && x !== "") ? (out as string[]) : null;+}++export async function translateCues(cues: Cue[], lang: string, from: string | undefined, ask: (system: string, user: string) => Promise<string>, onProgress?: (done: number) => void): Promise<Cue[]> {+ const out: Cue[] = [];+ for (let i = 0; i < cues.length; i += CUE_BATCH) {+ const batch = cues.slice(i, i + CUE_BATCH);+ const answer = await ask(cuesSystem(lang, from), batch.map((c, k) => `[${i + k + 1}] ${c.text.trim().replace(/\n/g, " <br> ")}`).join("\n"));+ let lines = readNumbered(answer, i + 1, batch.length);+ // The model merged or dropped a line: translate this batch cue by cue instead.+ if (!lines) lines = await Promise.all(batch.map((c) => ask(translateSystem(lang, from), c.text)));+ batch.forEach((c, k) => out.push({ start: c.start, end: c.end, text: lines![k].replace(/\s*<br>\s*/gi, "\n").trim() }));+ onProgress?.(out.length);+ }+ return out;+}++interface LlmJob {+ state: "running" | "succeeded" | "failed";+ progress?: number;+ backend?: Backend;+ outputs?: RemoteOutput[];+ error?: string;+ abort: AbortController;+ at: number;+}++const jobs = (): Map<string, LlmJob> => (globalThis.__fuobeLlmJobs ??= new Map<string, LlmJob>());++async function runJob(op: string, input: GenInput, backends: Backend[], job: LlmJob): Promise<RemoteOutput[]> {+ const ask = (system: string, user: string) => complete(backends, system, user, job);+ const source = (input.prompt ?? "").trim();+ if (op === "write") {+ const custom = typeof input.extra?.system === "string" ? input.extra.system.trim() : "";+ if (!source) throw new Error("Write a brief first");+ return [textOutput(await ask(custom || WRITE_SYSTEM, source), null, { op: "write" })];+ }+ if (op !== "translate") throw new Error(`The LLM can't do ${op}`);+ const lang = input.targetLanguage ?? (typeof input.extra?.targetLanguage === "string" ? input.extra.targetLanguage : "");+ if (!lang) throw new Error("Pick a language to translate into");+ if (!source) throw new Error("Nothing to translate");+ const from = input.sourceLanguage;+ const cues = parseCues(source);+ if (cues) {+ const translated = await translateCues(cues, lang, from, ask, (done) => (job.progress = Math.min(0.95, done / cues.length)));+ return [textOutput(cueText(translated), translated, { language: lang })];+ }+ const parts = chunks(source);+ const done: string[] = [];+ for (const p of parts) {+ done.push(await ask(translateSystem(lang, from), p));+ job.progress = Math.min(0.95, done.length / parts.length);+ }+ return [textOutput(done.join("\n\n"), null, { language: lang })];+}++export const llmProvider: ProviderAdapter = {+ id: "llm",+ label: "Claude or Ollama",+ isConfigured: () => llmBackends({ endpoint: "auto" }).length > 0,++ // Text steps read their text from the prompt; files aren't sent anywhere.+ async prepareFile(_data, _contentType, name) {+ return `local:${name}`;+ },++ async submit({ route, input }) {+ const backends = llmBackends(route);+ if (!backends.length) throw new Error(llmMissing(route));+ const all = jobs();+ for (const [id, j] of all) if (Date.now() - j.at > 6 * 3_600_000) all.delete(id);+ const id = `llm_${nanoid(10)}`;+ const job: LlmJob = { state: "running", abort: new AbortController(), at: Date.now(), backend: backends[0] };+ all.set(id, job);+ runJob(route.op, input, backends, job).then(+ (outputs) => Object.assign(job, { state: "succeeded", outputs }),+ (e: Error) => Object.assign(job, { state: "failed", error: e.message || "The LLM failed" }),+ );+ return { externalId: id, meta: { backends }, payload: { op: route.op, backends, targetLanguage: input.targetLanguage, chars: input.prompt?.length ?? 0 } };+ },++ async poll({ externalId }) {+ const job = jobs().get(externalId);+ if (!job) return { state: "failed", error: "Interrupted — the server restarted while this was being written. Try again." };+ if (job.state === "running") return { state: "running", progress: job.progress, message: `Writing with ${BACKEND_LABEL[job.backend ?? "claude"]}` };+ jobs().delete(externalId);+ return job.state === "succeeded" ? { state: "succeeded", outputs: job.outputs ?? [] } : { state: "failed", error: job.error ?? "The LLM failed" };+ },++ async cancel({ externalId }) {+ jobs().get(externalId)?.abort.abort();+ jobs().delete(externalId);+ },++ async test() {+ await probeOllama(true);+ const b = llmBackends({ endpoint: "auto" });+ return b.length ? { ok: true, detail: `Text steps run on ${b.map((x) => BACKEND_LABEL[x]).join(", then ")}` } : { ok: false, detail: "Add an Anthropic key or start Ollama" };+ },+};diff --git a/src/server/providers/mock.ts b/src/server/providers/mock.tsindex 8372f21b..c73ecb74 100644--- a/src/server/providers/mock.ts+++ b/src/server/providers/mock.ts@@ -1,13 +1,17 @@import "server-only";import { nanoid } from "nanoid";-import { OPERATION_OUTPUT } from "@/lib/catalog/types";-import type { ProviderAdapter } from "./types";+import { cueText, parseCues, type Cue } from "@/lib/cues";+import { OPERATION_OUTPUT, type MediaKind, type Operation } from "@/lib/catalog/types";+import type { ProviderAdapter, RemoteOutput } from "./types";+import { textOutput } from "./llm";import { toDataUri } from "../storage";/*** Demo provider: lets anyone click through the whole product with no API keys or GPU.- * Produces abstract placeholder art (SVG) for images, a bundled sample clip for video- * and a short tone for audio. Clearly labelled as demo output.+ * Produces abstract placeholder art (SVG) for images, a bundled sample clip for video, a short+ * tone for audio, labelled text for transcripts/translations/scripts and a sample .glb for 3D,+ * with the structured extras real providers return (layer boxes, cues, text blocks, stems).+ * Clearly labelled as demo output.*/function hash(s: string): number {@@ -66,7 +70,7 @@ ${text}</svg>`;}-function demoWav(seconds = 2): Buffer {+function demoWav(seconds = 2, tones: [number, number] = [440, 660], wobble = 0): Buffer {const rate = 22050;const n = rate * seconds;const buf = Buffer.alloc(44 + n * 2);@@ -84,13 +88,174 @@ function demoWav(seconds = 2): Buffer {buf.writeUInt32LE(n * 2, 40);for (let i = 0; i < n; i++) {const env = Math.min(1, i / 2000, (n - i) / 2000);- const v = Math.sin((2 * Math.PI * 440 * i) / rate) * 0.25 * env + Math.sin((2 * Math.PI * 660 * i) / rate) * 0.12 * env;+ // A slow tremolo makes the "voice" stem sound different from the steady "background" one.+ const am = wobble ? 0.55 + 0.45 * Math.sin((2 * Math.PI * wobble * i) / rate) : 1;+ const v = (Math.sin((2 * Math.PI * tones[0] * i) / rate) * 0.25 + Math.sin((2 * Math.PI * tones[1] * i) / rate) * 0.12) * env * am;buf.writeInt16LE(Math.round(v * 32767), 44 + i * 2);}return buf;}-const DURATION_MS = { image: 3500, video: 7000, audio: 3000 };+const DURATION_MS: Record<MediaKind, number> = { image: 3500, video: 7000, audio: 3000, text: 2500, model3d: 6000 };++type DemoOutput = RemoteOutput & { text?: string; meta?: Record<string, unknown> };++const svgUri = (svg: string) => toDataUri(Buffer.from(svg), "image/svg+xml");++function canvas(aspectRatio: string) {+ const [aw, ah] = (aspectRatio.match(/^(\d+(?:\.\d+)?):(\d+(?:\.\d+)?)$/)?.slice(1).map(Number) ?? [1, 1]) as number[];+ return { w: 1024, h: Math.round((1024 * ah) / aw) };+}++/** Layers: a full-frame background plus 2–3 cut-out shapes on transparency, each with name, z and bbox [x, y, w, h]. */+function demoLayers(prompt: string, aspectRatio: string, n: number): DemoOutput[] {+ const { w, h } = canvas(aspectRatio);+ const hue = Math.floor(rng(hash(`${prompt}#layers`))() * 360);+ const layer = (body: string) => `<svg xmlns="http://www.w3.org/2000/svg" width="${w}" height="${h}" viewBox="0 0 ${w} ${h}">${body}</svg>`;+ const label = escapeXml(prompt.split(/\s+/).slice(0, 3).join(" ") || "Demo");+ const all: { name: string; box: number[]; draw: (b: number[]) => string }[] = [+ { name: "Subject", box: [w * 0.28, h * 0.22, w * 0.44, h * 0.6], draw: (b) => `<ellipse cx="${b[0] + b[2] / 2}" cy="${b[1] + b[3] / 2}" rx="${b[2] / 2}" ry="${b[3] / 2}" fill="oklch(0.72 0.17 ${(hue + 40) % 360})"/>` },+ { name: "Prop", box: [w * 0.08, h * 0.62, w * 0.26, h * 0.3], draw: (b) => `<rect x="${b[0]}" y="${b[1]}" width="${b[2]}" height="${b[3]}" rx="28" fill="oklch(0.8 0.14 ${(hue + 150) % 360})"/>` },+ {+ name: "Text",+ box: [w * 0.06, h * 0.06, w * 0.6, h * 0.1],+ draw: (b) => `<text x="${b[0]}" y="${b[1] + b[3] * 0.75}" font-size="${Math.round(b[3] * 0.7)}" font-family="ui-sans-serif, system-ui" font-weight="700" fill="white">${label}</text>`,+ },+ ];+ const shapes = all.slice(0, Math.max(2, Math.min(3, n - 1)));+ const background: DemoOutput = {+ url: svgUri(+ layer(+ `<rect width="100%" height="100%" fill="oklch(0.32 0.07 ${hue})"/><rect x="40" y="${h - 76}" rx="14" width="300" height="40" fill="white" fill-opacity="0.18"/><text x="58" y="${h - 49}" font-size="20" font-family="ui-sans-serif, system-ui" font-weight="600" fill="white">DEMO OUTPUT · layers</text>`,+ ),+ ),+ kind: "image",+ contentType: "image/svg+xml",+ meta: { name: "Background", z: 0, bbox: [0, 0, w, h], demo: true },+ };+ return [+ background,+ ...shapes.map((s, i) => ({+ url: svgUri(layer(s.draw(s.box))),+ kind: "image" as const,+ contentType: "image/svg+xml",+ meta: { name: s.name, z: i + 1, bbox: s.box.map(Math.round), demo: true },+ })),+ ];+}++/** Text layers: the picture with its text removed, plus the text blocks that were on it. */+function demoTextLayers(prompt: string, aspectRatio: string): DemoOutput[] {+ const { w, h } = canvas(aspectRatio);+ const headline = prompt.split(/\s+/).slice(0, 4).join(" ") || "Your headline";+ const box = (x: number, y: number, bw: number, bh: number) => [x * w, y * h, bw * w, bh * h].map(Math.round);+ return [+ {+ url: svgUri(demoSvg("", aspectRatio, 7)),+ kind: "image",+ contentType: "image/svg+xml",+ meta: {+ name: "Background",+ z: 0,+ bbox: [0, 0, w, h],+ demo: true,+ textBlocks: [+ { text: headline.toUpperCase(), bbox: box(0.08, 0.1, 0.84, 0.12), fontFamily: "Inter", fontWeight: 800, fontSize: Math.round(h * 0.08), color: "#ffffff", align: "left" },+ { text: "Demo text block — connect a provider to read the real text", bbox: box(0.08, 0.24, 0.7, 0.05), fontFamily: "Inter", fontWeight: 500, fontSize: Math.round(h * 0.03), color: "#e8e6ff", align: "left" },+ ],+ },+ },+ ];+}++/** A demo transcript: a few timed lines that say what they are. */+function demoCues(prompt: string): Cue[] {+ const lines = [+ "This is a demo transcript.",+ "Connect a speech-to-text provider in Settings,",+ "or start ComfyUI, to transcribe your clip for real.",+ prompt ? `You asked for: ${prompt.slice(0, 80)}` : "Every line keeps its timing.",+ ];+ return lines.map((text, i) => ({ start: i * 2.5, end: i * 2.5 + 2.3, text }));+}++/** Demo translation: each line (or cue) tagged with the language, timing kept. */+function demoTranslate(source: string, language: string): DemoOutput {+ const tag = (t: string) => `[${language}] ${t}`;+ const cues = parseCues(source);+ if (cues) {+ const out = cues.map((c) => ({ ...c, text: tag(c.text) }));+ return textOutput(cueText(out), out, { language, demo: true });+ }+ const body = source.trim()+ ? source+ .split("\n")+ .map((l) => (l.trim() ? tag(l) : l))+ .join("\n")+ : tag("Demo translation");+ return textOutput(`${body}\n\n(Demo translation — connect Claude or Ollama in Settings to translate for real.)`, null, { language, demo: true });+}++function demoWrite(brief: string): DemoOutput {+ const topic = brief.trim().replace(/[.\s]+$/, "") || "your idea";+ return textOutput(+ [+ `Demo script for: ${topic}`,+ "",+ "HOOK — Open on the most striking image, no intro.",+ "BEAT 1 — Show the problem in one shot.",+ "BEAT 2 — Reveal the product or idea solving it.",+ "BEAT 3 — A close-up detail that makes it feel real.",+ "CLOSE — One line call to action.",+ "",+ "(Demo text — connect Claude or Ollama in Settings to write for real.)",+ ].join("\n"),+ null,+ { demo: true },+ );+}++const sampleClip = (ar: string) => (ar === "9:16" || ar === "3:4" || ar === "2:3" ? "demo-portrait.mp4" : ar === "1:1" ? "demo-square.mp4" : "demo-landscape.mp4");++function demoOutputs(op: Operation | undefined, kind: MediaKind, prompt: string, ar: string, meta: Record<string, unknown>): DemoOutput[] {+ // The prompt falls back to the op name when a step has none.+ const brief = prompt === op ? "" : prompt;+ switch (op) {+ case "layers":+ return demoLayers(brief, ar, Math.max(3, Math.min(4, Number(meta.numLayers ?? 4))));+ case "text-layers":+ return demoTextLayers(brief, ar);+ case "transcribe": {+ const cues = demoCues(brief);+ return [textOutput(cueText(cues), cues, { language: meta.sourceLanguage ?? "English", demo: true })];+ }+ case "translate":+ return [demoTranslate(brief, String(meta.targetLanguage ?? "Spanish"))];+ case "write":+ return [demoWrite(brief)];+ case "separate-audio":+ return [+ { url: toDataUri(demoWav(3, [220, 330], 3), "audio/wav"), kind: "audio", contentType: "audio/wav", meta: { stem: "voice", demo: true } },+ { url: toDataUri(demoWav(3, [110, 165]), "audio/wav"), kind: "audio", contentType: "audio/wav", meta: { stem: "background", demo: true } },+ ];+ case "image-to-3d":+ return [+ { url: "sample:demo-model.glb", kind: "model3d", contentType: "model/gltf-binary", meta: { demo: true, format: "glb" } },+ { url: "sample:demo-turntable.mp4", kind: "video", contentType: "video/mp4", meta: { demo: true, turntable: true } },+ ];+ case "trim":+ case "captions":+ case "mux":+ return [{ url: `sample:${sampleClip(ar)}`, kind: "video", contentType: "video/mp4", meta: { demo: true } }];+ }+ if (kind === "image") {+ return Array.from({ length: Number(meta.count) }, (_, i) => ({ url: svgUri(demoSvg(prompt, ar, i)), kind: "image" as const, contentType: "image/svg+xml" }));+ }+ if (kind === "audio") return [{ url: toDataUri(demoWav(), "audio/wav"), kind: "audio", contentType: "audio/wav" }];+ if (kind === "text") return [textOutput(`Demo text for: ${brief || "your request"}`, null, { demo: true })];+ if (kind === "model3d") return [{ url: "sample:demo-model.glb", kind: "model3d", contentType: "model/gltf-binary", meta: { demo: true } }];+ return [{ url: `sample:${sampleClip(ar)}`, kind: "video", contentType: "video/mp4", ...(meta.draft ? { draftId: `demo_draft_${nanoid(8)}` } : {}) }];+}export const mockProvider: ProviderAdapter = {id: "mock",@@ -101,47 +266,34 @@ export const mockProvider: ProviderAdapter = {return toDataUri(data.subarray(0, 64), contentType); // never sent anywhere; keep it tiny},- async submit({ route, input }) {+ async submit({ route, input, model }) {return {externalId: `demo_${nanoid(10)}`,meta: {startedAt: Date.now(),- kind: OPERATION_OUTPUT[route.op],+ op: route.op,+ // Colour matching keeps the input's kind (an image or a video).+ kind: route.op === "color-match" ? model.kind : OPERATION_OUTPUT[route.op],prompt: input.prompt ?? route.op,aspectRatio: input.aspectRatio ?? "1:1",count: Math.max(1, Math.min(4, input.numOutputs ?? 1)),// Let draft mode be tried end to end in demo mode.draft: !!(input.draft && route.map?.draft),+ targetLanguage: input.targetLanguage,+ sourceLanguage: input.sourceLanguage,+ numLayers: input.numLayers,},payload: { demo: true, ...input },};},async poll({ meta }) {- const kind = meta.kind as "image" | "video" | "audio";+ const kind = meta.kind as MediaKind;const elapsed = Date.now() - Number(meta.startedAt);- const total = DURATION_MS[kind];+ const total = DURATION_MS[kind] ?? DURATION_MS.image;if (elapsed < 600) return { state: "queued", message: "Queued (demo)" };if (elapsed < total) return { state: "running", progress: elapsed / total, message: "Generating demo output" };- if (kind === "image") {- return {- state: "succeeded",- outputs: Array.from({ length: Number(meta.count) }, (_, i) => ({- url: toDataUri(Buffer.from(demoSvg(String(meta.prompt), String(meta.aspectRatio), i)), "image/svg+xml"),- kind: "image" as const,- contentType: "image/svg+xml",- })),- };- }- if (kind === "audio") {- return { state: "succeeded", outputs: [{ url: toDataUri(demoWav(), "audio/wav"), kind: "audio", contentType: "audio/wav" }] };- }- const ar = String(meta.aspectRatio);- const sample = ar === "9:16" || ar === "3:4" || ar === "2:3" ? "demo-portrait.mp4" : ar === "1:1" ? "demo-square.mp4" : "demo-landscape.mp4";- return {- state: "succeeded",- outputs: [{ url: `sample:${sample}`, kind: "video", contentType: "video/mp4", ...(meta.draft ? { draftId: `demo_draft_${nanoid(8)}` } : {}) }],- };+ return { state: "succeeded", outputs: demoOutputs(meta.op as Operation | undefined, kind, String(meta.prompt), String(meta.aspectRatio), meta) };},async test() {diff --git a/tests/catalog.test.ts b/tests/catalog.test.tsindex 710d5acb..0454b833 100644--- a/tests/catalog.test.ts+++ b/tests/catalog.test.ts@@ -19,8 +19,11 @@ describe("catalog integrity", () => {const d = m.defaults ?? {};if (d.aspectRatio && m.options.aspectRatios) expect(m.options.aspectRatios, `${m.id} aspect`).toContain(d.aspectRatio);if (d.resolution && m.options.resolutions) expect(m.options.resolutions, `${m.id} resolution`).toContain(d.resolution);- // ComfyUI and browser-only tools are the open engine; every API provider is cloud.- for (const r of m.routes) expect(r.provider === "comfyui" || r.provider === "local" ? "open" : "cloud", `${m.id} engine/provider`).toBe(m.engine);+ // ComfyUI, browser-only tools and Ollama-only text steps are the open engine; every API provider is cloud.+ for (const r of m.routes) {+ const open = r.provider === "comfyui" || r.provider === "local" || (r.provider === "llm" && r.endpoint === "ollama");+ expect(open ? "open" : "cloud", `${m.id} engine/provider`).toBe(m.engine);+ }}});