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.

API: a model list for scripts (GET /api/models) and a priced preview of a generation (?preview=1)

Claudeaafabe4afcbe
diff --git a/src/app/api/generations/route.ts b/src/app/api/generations/route.ts
index 62e0ca47..90d379ae 100644
--- a/src/app/api/generations/route.ts
+++ b/src/app/api/generations/route.ts
@@ -1,6 +1,7 @@
import { connection } from "next/server";
import { z } from "zod";
-import { createGenerations, listGenerations } from "@/server/generations";
+import { OPERATION_LABELS } from "@/lib/catalog/types";
+import { createGenerations, listGenerations, outputKind, previewGeneration } from "@/server/generations";
import { ensureTrashPurge, listOptionsFrom } from "@/server/library";
import { SignatureSchema } from "@/server/palettes";
@@ -75,12 +76,17 @@ export async function GET(request: Request) {
return Response.json({ items: listGenerations(listOptionsFrom(new URL(request.url).searchParams)) });
}
+/** Start a generation; `?preview=1` only says what it would run as (model, operation, jobs, outputs, cost). */
export async function POST(request: Request) {
const parsed = RequestSchema.safeParse(await request.json().catch(() => null));
if (!parsed.success) {
return Response.json({ error: parsed.error.issues.map((i) => `${i.path.join(".")}: ${i.message}`).join("; ") }, { status: 400 });
}
try {
+ if (new URL(request.url).searchParams.get("preview") === "1") {
+ const { model, ...p } = previewGeneration(parsed.data as Parameters<typeof previewGeneration>[0]);
+ return Response.json({ ...p, modelId: model.id, modelName: model.name, engine: model.engine, kind: outputKind(p.op, model), opLabel: OPERATION_LABELS[p.op] ?? p.op });
+ }
const items = createGenerations(parsed.data as Parameters<typeof createGenerations>[0]);
return Response.json({ items }, { status: 201 });
} catch (e) {
diff --git a/src/app/api/models/route.ts b/src/app/api/models/route.ts
new file mode 100644
index 00000000..87436e04
--- /dev/null
+++ b/src/app/api/models/route.ts
@@ -0,0 +1,39 @@
+import { connection } from "next/server";
+import { MODELS } from "@/lib/catalog";
+import { OPERATION_LABELS, type Engine, type MediaKind, type ModelDef, type Operation } from "@/lib/catalog/types";
+import { findModels, MODEL_KINDS, toModelInfo } from "@/lib/model-list";
+import { AUDIO_STUDIO, EDIT_STUDIO, IMAGE_STUDIO, VIDEO_STUDIO } from "@/lib/studios";
+import { provider } from "@/server/providers";
+import { llmBackends } from "@/server/providers/llm";
+import { engineMode } from "@/server/settings";
+
+/** A provider for one of its routes is set up (else it runs as a demo). */
+const connected = (m: ModelDef) => m.routes.some((r) => (r.provider === "llm" ? llmBackends(r).length > 0 : provider(r.provider).isConfigured()));
+
+/**
+ * Models this install can run, for scripts and the `fuobe` CLI. Filters: kind, engine (open |
+ * cloud), op, q (words that must all match), hidden=1 (chain helpers too). Models of an engine the
+ * install has switched off (Settings → Engine mode) are left out. `defaults` are the studios' own
+ * picks (image, edit, video, audio) per engine.
+ */
+export async function GET(request: Request) {
+ await connection();
+ const p = new URL(request.url).searchParams;
+ const kind = p.get("kind") || undefined;
+ if (kind && !MODEL_KINDS.includes(kind as MediaKind)) return Response.json({ error: `kind is one of ${MODEL_KINDS.join(", ")}` }, { status: 400 });
+ const engine = p.get("engine") || undefined;
+ if (engine && engine !== "open" && engine !== "cloud") return Response.json({ error: "engine is open or cloud" }, { status: 400 });
+ const op = p.get("op") || undefined;
+ if (op && !(op in OPERATION_LABELS)) return Response.json({ error: `Unknown operation ${op}` }, { status: 400 });
+ const mode = engineMode();
+ const list = findModels(MODELS, { kind: kind as MediaKind | undefined, engine: engine as Engine | undefined, op: op as Operation | undefined, q: p.get("q") ?? undefined, hidden: p.get("hidden") === "1" }).filter(
+ (m) => mode === "both" || m.engine === mode,
+ );
+ const defaults = Object.fromEntries(
+ Object.entries({ image: IMAGE_STUDIO, edit: EDIT_STUDIO, video: VIDEO_STUDIO, audio: AUDIO_STUDIO }).map(([k, s]) => [
+ k,
+ { ...(mode !== "open" && s.defaultModels.cloud && { cloud: s.defaultModels.cloud }), ...(mode !== "cloud" && s.defaultModels.open && { open: s.defaultModels.open }) },
+ ]),
+ );
+ return Response.json({ engineMode: mode, defaults, items: list.map((m) => ({ ...toModelInfo(m), connected: connected(m) })) });
+}
diff --git a/src/lib/model-list.ts b/src/lib/model-list.ts
new file mode 100644
index 00000000..22b0481e
--- /dev/null
+++ b/src/lib/model-list.ts
@@ -0,0 +1,67 @@
+/**
+ * The model list scripts and the `fuobe` CLI read (`GET /api/models`): the Models page's row plus
+ * what a request needs (operation ids, the sizes and lengths a model takes), filtered the way the
+ * CLI asks (kind, engine, operation, search words).
+ */
+import { modelSearchText, toModelRow, type ModelRow } from "./model-rows";
+import type { Engine, MediaKind, ModelDef, Operation } from "./catalog/types";
+
+export const MODEL_KINDS: MediaKind[] = ["image", "video", "audio", "text", "model3d"];
+
+export interface ModelInfo extends ModelRow {
+ /** Operation ids it runs (t2i, i2v, tts…): what a request's `op` can be. */
+ opIds: Operation[];
+ aspectRatios?: string[];
+ resolutions?: string[];
+ durations?: number[];
+ /** Reference / input images it takes at most. */
+ maxImages?: number;
+ /** Outputs one run can make. */
+ maxOutputs?: number;
+ /** Native sound: true = can be switched on, "always" = always on. */
+ audio?: boolean | "always";
+ endFrame?: boolean;
+ /** Premade voice ids (text to speech, voice change). */
+ voices?: string[];
+ /** Not offered by any studio picker (chain helpers); runs when asked for by id. */
+ hidden?: true;
+}
+
+export function toModelInfo(m: ModelDef): ModelInfo {
+ const o = m.options;
+ return {
+ ...toModelRow(m),
+ opIds: [...new Set(m.routes.map((r) => r.op))],
+ ...(o.aspectRatios?.length && { aspectRatios: o.aspectRatios }),
+ ...(o.resolutions?.length && { resolutions: o.resolutions }),
+ ...(o.durations?.length && { durations: o.durations }),
+ ...(o.maxImages && { maxImages: o.maxImages }),
+ ...(o.maxOutputs && { maxOutputs: o.maxOutputs }),
+ ...(o.audio && { audio: o.audio }),
+ ...(o.endFrame && { endFrame: true }),
+ ...(o.voices?.length && { voices: o.voices.map((v) => v.id) }),
+ ...(m.hidden && { hidden: true as const }),
+ };
+}
+
+export interface ModelQuery {
+ kind?: MediaKind;
+ engine?: Engine;
+ op?: Operation;
+ /** Words that must all appear in the name, vendor, description, operations or id. */
+ q?: string;
+ /** Include hidden helper models. */
+ hidden?: boolean;
+}
+
+/** The models matching a query, in catalog order. */
+export function findModels(models: ModelDef[], query: ModelQuery): ModelDef[] {
+ const words = (query.q ?? "").toLowerCase().split(/\s+/).filter(Boolean);
+ return models.filter((m) => {
+ if ((m.hidden && !query.hidden) || (query.kind && m.kind !== query.kind) || (query.engine && m.engine !== query.engine)) return false;
+ if (query.op && !m.routes.some((r) => r.op === query.op)) return false;
+ if (!words.length) return true;
+ const text = `${modelSearchText(toModelRow(m))} ${m.family} ${m.routes.map((r) => r.op).join(" ")}`.toLowerCase();
+ return words.every((w) => text.includes(w));
+ });
+}
diff --git a/tests/cli-api.test.ts b/tests/cli-api.test.ts
new file mode 100644
index 00000000..ec47deae
--- /dev/null
+++ b/tests/cli-api.test.ts
@@ -0,0 +1,103 @@
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { afterAll, describe, expect, it, vi } from "vitest";
+import { MODELS } from "@/lib/catalog";
+import { findModels, toModelInfo } from "@/lib/model-list";
+
+/** The REST routes the fuobe CLI added: GET /api/models and POST /api/generations?preview=1. */
+
+// Route handlers are called directly, outside a Next request: connection() has nothing to wait for.
+vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));
+
+const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-cli-api-"));
+process.env.FUOBE_DATA_DIR = dir;
+process.env.COMFYUI_URL = "http://127.0.0.1:9";
+process.env.OLLAMA_URL = "http://127.0.0.1:9";
+const { GET: listModels } = await import("@/app/api/models/route");
+const { POST: postGeneration } = await import("@/app/api/generations/route");
+const { listGenerations } = await import("@/server/generations");
+const { setSetting } = await import("@/server/settings");
+afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));
+
+type ModelsBody = { engineMode: string; defaults: Record<string, { cloud?: string; open?: string }>; items: (ReturnType<typeof toModelInfo> & { connected: boolean })[]; error?: string };
+const models = async (query = "") => {
+ const res = await listModels(new Request(`http://localhost/api/models${query}`));
+ return { status: res.status, body: (await res.json()) as ModelsBody };
+};
+
+describe("GET /api/models", () => {
+ it("filters by kind, engine, operation and search words, and leaves hidden helpers out", async () => {
+ const { body } = await models("?kind=video&engine=open");
+ expect(body.items.length).toBeGreaterThan(3);
+ expect(body.items.every((m) => m.kind === "video" && m.engine === "open")).toBe(true);
+ const kling = (await models("?q=kling%20motion")).body.items.map((m) => m.id);
+ expect(kling).toContain("kling-motion-control");
+ expect(kling.every((id) => id.includes("kling"))).toBe(true);
+ const tts = (await models("?op=tts")).body.items;
+ expect(tts.length).toBeGreaterThan(2);
+ expect(tts.every((m) => m.opIds.includes("tts"))).toBe(true);
+ const all = (await models()).body.items;
+ expect(all.some((m) => m.hidden)).toBe(false);
+ expect((await models("?hidden=1")).body.items.some((m) => m.hidden)).toBe(true);
+ });
+
+ it("gives what a request needs: operation ids, sizes, lengths, voices, and whether it would run as a demo", async () => {
+ const { body } = await models("?q=kling-3");
+ const k = body.items.find((m) => m.id === "kling-3")!;
+ expect(k).toMatchObject({ name: "Kling 3.0", engine: "cloud", kind: "video", connected: false });
+ expect(k.opIds).toEqual(expect.arrayContaining(["t2v", "i2v"]));
+ expect(k.durations?.length).toBeGreaterThan(0);
+ expect(k.aspectRatios).toContain("16:9");
+ const voice = (await models("?q=elevenlabs-v4")).body.items.find((m) => m.id === "elevenlabs-v4")!;
+ expect(voice.voices?.length).toBeGreaterThan(5);
+ // No field maps or endpoints beyond the route list.
+ expect(Object.keys(k)).not.toContain("options");
+ });
+
+ it("names the studios' default models, and follows the engine mode", async () => {
+ expect((await models()).body.defaults).toMatchObject({ image: { cloud: "nano-banana-pro", open: "oss-z-image-turbo" }, video: { cloud: "seedance-2-5", open: "oss-wan22-14b-fast" } });
+ setSetting("engineMode", "open");
+ try {
+ const { body } = await models("?kind=image");
+ expect(body.engineMode).toBe("open");
+ expect(body.items.every((m) => m.engine === "open")).toBe(true);
+ expect(body.defaults.image).toEqual({ open: "oss-z-image-turbo" });
+ } finally {
+ setSetting("engineMode", "both");
+ }
+ });
+
+ it("refuses unknown filters with a sentence", async () => {
+ expect(await models("?kind=smell")).toMatchObject({ status: 400, body: { error: "kind is one of image, video, audio, text, model3d" } });
+ expect((await models("?engine=gpu")).status).toBe(400);
+ expect((await models("?op=dance")).body.error).toBe("Unknown operation dance");
+ });
+
+ it("matches every word, in the catalog's order (pure helper)", () => {
+ expect(findModels(MODELS, { q: "wan zzqx" })).toEqual([]);
+ const open = findModels(MODELS, { q: "wan 2.2", engine: "open", kind: "video" });
+ expect(open.length).toBeGreaterThan(0);
+ expect(open.every((m) => m.engine === "open" && /wan/i.test(`${m.name} ${m.id}`))).toBe(true);
+ });
+});
+
+describe("POST /api/generations?preview=1", () => {
+ const post = (body: unknown, query = "") => postGeneration(new Request(`http://localhost/api/generations${query}`, { method: "POST", body: JSON.stringify(body) }));
+
+ it("prices a request without creating anything", async () => {
+ const before = listGenerations({ limit: 200 }).length;
+ const res = await post({ feature: "cli", modelId: "nano-banana-pro", prompt: "a fox", params: { numOutputs: 2 } }, "?preview=1");
+ expect(res.status).toBe(200);
+ const p = await res.json();
+ expect(p).toMatchObject({ modelId: "nano-banana-pro", modelName: "Nano Banana Pro", engine: "cloud", kind: "image", op: "t2i", opLabel: "Text to image", outputs: 2, demo: true, providerId: "mock" });
+ expect(p).not.toHaveProperty("model");
+ expect(listGenerations({ limit: 200 }).length).toBe(before);
+ });
+
+ it("answers a request it can't run with the planner's reason", async () => {
+ const res = await post({ feature: "cli", modelId: "kling-3", prompt: "x", op: "i2v" }, "?preview=1");
+ expect(res.status).toBe(422);
+ expect((await res.json()).error).toBe("Add a start frame");
+ });
+});