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.

CLI: review fixes (the saved token stays with its server, safe file names, voice samples, Ctrl+C)

Claude68c0bcb1a323
diff --git a/.agents/skills/fuobe/SKILL.md b/.agents/skills/fuobe/SKILL.md
index 15ebaa47..6c21f991 100644
--- a/.agents/skills/fuobe/SKILL.md
+++ b/.agents/skills/fuobe/SKILL.md
@@ -27,7 +27,8 @@ an open-source model on their GPU (ComfyUI). Results land in the Fuobe Library a
`fuobe models --kind video --search kling --json`. When the user doesn't care, the studios' own picks:
images `nano-banana-pro` (cloud) / `oss-z-image-turbo` (open); edits `nano-banana-pro` / `oss-qwen-edit`;
video `seedance-2-5` / `oss-wan22-14b-fast`; speech `elevenlabs-v4` / `oss-chatterbox` (it speaks in
-a cloned voice, so it needs a voice sample: `voice_audio`, or `--voice-audio` on the CLI).
+a cloned voice, so it needs a voice sample: `voice_audio`, or `--voice-audio` on the CLI). In the
+user's own voice on the cloud: `chatterbox-cloud` (the CLI picks it for `--kind audio --voice-audio`).
Open models cost nothing but GPU time; cloud models are billed by the user's provider.
## 3. Price, confirm, run
@@ -36,7 +37,8 @@ Open models cost nothing but GPU time; cloud models are billed by the user's pro
- CLI: `fuobe estimate "<prompt>" --model <id> …`, then
`fuobe generate "<prompt>" --model <id> --image ./photo.png --aspect 16:9 --duration 5 --out ./renders --json`
(`--out` waits and saves the files; `--wait` waits and prints the URLs).
-- A result marked demo means no provider is connected for that model: say it's placeholder media.
+- A result marked demo means no provider is connected for that model, or Demo mode is on: say it's
+ placeholder media.
## 4. Files
- Inputs: the CLI's `--image`, `--video` and `--audio` take local paths (uploaded for you) or links.
diff --git a/bin/fuobe.mjs b/bin/fuobe.mjs
index 4ca6f851..c877f3e4 100755
--- a/bin/fuobe.mjs
+++ b/bin/fuobe.mjs
@@ -54,7 +54,13 @@ process.exitCode = await main(process.argv.slice(2), {
stdinIsTTY: !!process.stdin.isTTY,
stderrIsTTY: !!process.stderr.isTTY,
now: () => Date.now(),
- sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
+ /** Resolves after `ms`, or at once when `signal` aborts (Ctrl+C mustn't wait out a long --interval). */
+ sleep: (ms, signal) =>
+ new Promise((resolve) => {
+ if (signal?.aborted) return resolve();
+ const timer = setTimeout(resolve, ms);
+ signal?.addEventListener("abort", () => (clearTimeout(timer), resolve()), { once: true });
+ }),
/** Ctrl+C while waiting stops the wait (the job keeps running on the server). */
onInterrupt: (fn) => {
process.on("SIGINT", fn);
diff --git a/bin/lib/build.mjs b/bin/lib/build.mjs
index 576c3b80..e561f0e5 100644
--- a/bin/lib/build.mjs
+++ b/bin/lib/build.mjs
@@ -116,29 +116,65 @@ export function generationRequest({ prompt, modelId, values: v, uploaded = new M
};
}
+/** Which of GET /api/models' `defaults` a request without --model takes. */
+function defaultKey(kind, want) {
+ if (kind === "image") return want.hasImages ? "edit" : "image";
+ if (kind !== "audio") return kind;
+ // Voice samples (--voice-audio): a model that clones them; two are a dialogue's speakers.
+ if (want.op === "dialogue" || want.voices === 2) return want.voices ? "cloneDialogue" : "dialogue";
+ return want.voices ? "clone" : "audio";
+}
+
+const DEFAULT_WHAT = { clone: "model that clones a voice sample", cloneDialogue: "dialogue model that clones two voice samples", dialogue: "dialogue model" };
+
/**
* The studio's own model when none is named: the Image studio's (Edit's when there are images),
- * Video's or Audio's, on the engine asked for (else cloud, unless the install is open source only).
+ * Video's or Audio's (one that clones the voice for --voice-audio, a dialogue for two samples),
+ * on the engine asked for (else cloud, unless the install is open source only).
* @param {{ engineMode?: string, defaults?: Record<string, { cloud?: string, open?: string }> }} list GET /api/models
- * @param {{ kind?: string, engine?: string, hasImages?: boolean, hasMedia?: boolean }} want `hasMedia`: a video or audio input
+ * @param {{ kind?: string, engine?: string, op?: string, hasImages?: boolean, hasMedia?: boolean, voices?: number }} want
+ * `hasMedia`: a video or audio input; `voices`: how many voice samples
*/
export function defaultModel(list, want) {
// A clip or a recording can go to many kinds of model (edit, extend, lipsync, transcribe…): that's the user's pick.
if (want.hasMedia) throw new UsageError("Name the model for a video or audio input with --model (fuobe models --search lipsync, for example).", "generate");
const kind = want.kind ?? "image";
- const key = kind === "image" && want.hasImages ? "edit" : kind;
+ const key = defaultKey(kind, want);
const engine = want.engine ?? (list.engineMode === "open" ? "open" : "cloud");
const id = list.defaults?.[key]?.[engine];
- if (!id) {
- const off = list.engineMode && list.engineMode !== "both" && list.engineMode !== engine;
- throw new UsageError(
- off
- ? `This Fuobe runs ${list.engineMode === "open" ? "open-source" : "cloud"} models only (Settings → Engine mode). Leave out --engine, or pick a model with --model.`
- : `There's no default ${engine === "open" ? "open-source" : "cloud"} ${kind} model. Pick one with --model (fuobe models --kind ${kind}).`,
- "generate",
- );
+ if (id) return id;
+ if (list.engineMode && list.engineMode !== "both" && list.engineMode !== engine) {
+ throw new UsageError(`This Fuobe runs ${list.engineMode === "open" ? "open-source" : "cloud"} models only (Settings → Engine mode). Leave out --engine, or pick a model with --model.`, "generate");
+ }
+ const other = engine === "open" ? "cloud" : "open";
+ const alt = list.defaults?.[key]?.[other];
+ const fix = alt ? `Add --engine ${other} (${alt}), or pick a model with --model` : "Pick one with --model";
+ throw new UsageError(`There's no default ${engine === "open" ? "open-source" : "cloud"} ${DEFAULT_WHAT[key] ?? `${kind} model`}. ${fix} (fuobe models --kind ${kind}).`, "generate");
+}
+
+/**
+ * Why a model can't take the voice samples given (null when it can): one sample needs a model
+ * that clones voices, two a dialogue that clones both speakers. The server would otherwise run it
+ * in a premade voice, or as one speaker, without a word.
+ * @param {{ id: string, opIds?: string[], voiceClone?: boolean } | undefined} info the model's GET /api/models item
+ * @param {number} voices how many --voice-audio samples
+ * @param {Record<string, { cloud?: string, open?: string }>} [defaults] GET /api/models' defaults, for a suggestion
+ */
+export function voiceSampleProblem(info, voices, defaults = {}) {
+ if (!info || !voices) return null;
+ const alternatives = (key) => {
+ const ids = Object.values(defaults[key] ?? {}).filter(Boolean);
+ return ids.length ? `--model ${ids.join(" or --model ")}` : null;
+ };
+ if (voices === 2 && !(info.voiceClone && info.opIds?.includes("dialogue"))) {
+ const clone = alternatives("cloneDialogue");
+ return `${info.id} doesn't clone two voices. Two --voice-audio samples are a dialogue's speakers${clone ? `: use ${clone}` : " (fuobe models --op dialogue)"}.`;
+ }
+ if (!info.voiceClone) {
+ const clone = alternatives("clone");
+ return `${info.id} speaks in premade voices (--voice <id>) and doesn't clone a voice sample. Leave out --voice-audio, or use a model that clones one${clone ? ` (${clone})` : " (fuobe models --op tts)"}.`;
}
- return id;
+ return null;
}
/** What the planner asks for ("Add a portrait and a voice track") → the options that give it. */
diff --git a/bin/lib/cli.mjs b/bin/lib/cli.mjs
index 7fec4f1a..07e2bc3a 100644
--- a/bin/lib/cli.mjs
+++ b/bin/lib/cli.mjs
@@ -101,7 +101,8 @@ export async function main(argv, io) {
print(commandHelp(name));
return EXIT.ok;
}
- const target = { ...resolveTarget(values, io.env, readConfig(configPath(io.env, io.home))), fetch: io.fetch };
+ // login and logout read (or replace) the saved config themselves, so a broken file doesn't stop them.
+ const target = { ...resolveTarget(values, io.env, cmd.ownConfig ? {} : readConfig(configPath(io.env, io.home))), fetch: io.fetch };
const connect = (t) => createClient({ fetch: io.fetch, ...t });
const ctx = {
command: name,
diff --git a/bin/lib/client.mjs b/bin/lib/client.mjs
index 3b1f2905..e11bab01 100644
--- a/bin/lib/client.mjs
+++ b/bin/lib/client.mjs
@@ -33,14 +33,16 @@ export function statusMessage(status, body, ctx) {
if (status === 401) {
return ctx.token
? `Fuobe at ${ctx.url} refused the API token${ctx.tokenFrom ? ` (from ${ctx.tokenFrom})` : ""}. It may have been revoked: create a new one in Settings → Security → API tokens (${ctx.url}/settings#security), then run "fuobe login".`
- : `Fuobe at ${ctx.url} has a password, so the CLI needs an API token. Create one in Settings → Security → API tokens (${ctx.url}/settings#security), then run "fuobe login" or set FUOBE_TOKEN.`;
+ : ctx.savedTokenFor
+ ? `Fuobe at ${ctx.url} has a password, so the CLI needs an API token. The token "fuobe login" saved is for ${ctx.savedTokenFor}, so it isn't sent here: pass --token, set FUOBE_TOKEN, or run "fuobe login --url ${ctx.url}" (create a token in Settings → Security → API tokens, ${ctx.url}/settings#security).`
+ : `Fuobe at ${ctx.url} has a password, so the CLI needs an API token. Create one in Settings → Security → API tokens (${ctx.url}/settings#security), then run "fuobe login" or set FUOBE_TOKEN.`;
}
if (status === 404 && !said) return `Not found on ${ctx.url}. Is it a Fuobe server, and up to date?`;
return said || `Fuobe answered HTTP ${status}${status >= 500 ? " — check the server's log" : ""}`;
}
/**
- * @param {{ url: string, token?: string, tokenFrom?: string, fetch?: typeof fetch }} target
+ * @param {{ url: string, token?: string, tokenFrom?: string, savedTokenFor?: string, fetch?: typeof fetch }} target
*/
export function createClient(target) {
const { url, token } = target;
diff --git a/bin/lib/commands.mjs b/bin/lib/commands.mjs
index 366b0714..ebb6345d 100644
--- a/bin/lib/commands.mjs
+++ b/bin/lib/commands.mjs
@@ -5,7 +5,7 @@ import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { keyValue, UsageError } from "./args.mjs";
-import { defaultModel, fileInputs, generationRequest, localFiles, withInputHint } from "./build.mjs";
+import { defaultModel, fileInputs, generationRequest, localFiles, voiceSampleProblem, withInputHint } from "./build.mjs";
import { ApiError } from "./client.mjs";
import { configPath, normalizeUrl, readConfig, removeConfig, writeConfig } from "./config.mjs";
import { clip, countOutputs, formatCost, formatDuration, previewText, statusText, table, TERMINAL, timeAgo } from "./format.mjs";
@@ -92,8 +92,8 @@ async function promptFrom(ctx) {
return (await ctx.io.readStdin()).trim();
}
-/** Upload a local file through /api/uploads; returns its /api/files/… URL. */
-export async function uploadFile(ctx, file) {
+/** A local input that exists, is a file and isn't too big; returns its absolute path. */
+function checkFile(ctx, file) {
const abs = path.resolve(ctx.io.cwd, file);
let st;
try {
@@ -103,6 +103,15 @@ export async function uploadFile(ctx, file) {
}
if (!st.isFile()) throw new UsageError(`${file} isn't a file`);
if (st.size > MAX_UPLOAD) throw new UsageError(`${file} is ${Math.round(st.size / 1024 / 1024)} MB; Fuobe takes files up to 200 MB`);
+ return abs;
+}
+
+/** Check every file first, so a missing second one fails before the first (maybe big) one goes up. */
+const checkFiles = (ctx, files) => files.forEach((f) => checkFile(ctx, f));
+
+/** Upload a local file through /api/uploads; returns its /api/files/… URL. */
+export async function uploadFile(ctx, file) {
+ const abs = checkFile(ctx, file);
const ext = path.extname(abs).slice(1).toLowerCase();
const type = UPLOAD_TYPES[ext] ?? "application/octet-stream";
const blob = typeof fs.openAsBlob === "function" ? await fs.openAsBlob(abs, { type }) : new Blob([fs.readFileSync(abs)], { type });
@@ -114,23 +123,38 @@ export async function uploadFile(ctx, file) {
}
async function uploadAll(ctx, values) {
+ const files = localFiles(fileInputs(values));
+ checkFiles(ctx, files);
const uploaded = new Map();
- for (const file of localFiles(fileInputs(values))) uploaded.set(file, await uploadFile(ctx, file));
+ for (const file of files) uploaded.set(file, await uploadFile(ctx, file));
return uploaded;
}
-/** The model to use: --model, else the studio default for --kind / --engine (said on stderr). */
+/**
+ * The model to use: --model, else the studio default for --kind / --engine (said on stderr). With
+ * --voice-audio, a model that clones the sample (a dialogue for two), so none is silently ignored.
+ */
async function modelFor(ctx) {
const v = ctx.values;
- if (v.model) return v.model;
const inputs = fileInputs(v);
+ const voices = inputs.filter(([slot]) => slot === "voiceAudio" || slot === "voiceAudio2").length;
+ if (v.model) {
+ if (voices) {
+ const list = await ctx.client.request("GET", "/api/models", { query: { q: v.model, hidden: 1 } });
+ const problem = voiceSampleProblem(list.items?.find((m) => m.id === v.model), voices, list.defaults);
+ if (problem) throw new UsageError(problem, ctx.command);
+ }
+ return v.model;
+ }
const list = await ctx.client.request("GET", "/api/models", { query: { kind: v.kind ?? "image" } });
const id = defaultModel(list, {
kind: v.kind,
engine: v.engine,
+ op: v.op,
hasImages: inputs.some(([slot]) => slot === "images"),
- // A voice sample with --kind audio is the voice the default speech model clones.
+ // With --kind audio, voice samples are the voices a cloning model speaks in.
hasMedia: inputs.some(([slot]) => !["images", "endImage", "mask", ...(v.kind === "audio" ? ["voiceAudio", "voiceAudio2"] : [])].includes(slot)),
+ voices: v.kind === "audio" ? voices : 0,
});
const name = list.items?.find((m) => m.id === id)?.name;
ctx.note(`Using ${name ? `${name} (${id})` : id}. Pick another with --model; fuobe models lists them.`);
@@ -160,10 +184,15 @@ async function postGeneration(ctx, body, { preview = false } = {}) {
const absolute = (ctx, url) => ctx.client.resolve(url);
-/** File name for output `i` of a generation: <id>.<ext>, or <id>-<n>.<ext> when it has several. */
+/**
+ * File name for output `i` of a generation: <id>.<ext>, or <id>-<n>.<ext> when it has several. The
+ * id and extension come from the server, so anything but letters, digits, - and _ is replaced: a
+ * name can't climb out of --out or hide as a dot-file.
+ */
export function outputName(g, i) {
- const ext = path.extname(new URL(g.outputs[i].url, "http://x").pathname) || ".bin";
- return `${g.id}${g.outputs.length > 1 ? `-${i + 1}` : ""}${ext}`;
+ const ext = /^\.[a-z\d]{1,10}$/i.exec(path.extname(new URL(g.outputs[i].url, "http://x").pathname))?.[0] ?? ".bin";
+ const id = String(g.id ?? "").replace(/[^\w-]/g, "_") || "output";
+ return `${id}${g.outputs.length > 1 ? `-${i + 1}` : ""}${ext}`;
}
const megabytes = (n) => (n >= 1024 * 1024 ? `${(n / 1024 / 1024).toFixed(1)} MB` : `${Math.max(1, Math.round(n / 1024))} KB`);
@@ -197,9 +226,10 @@ export async function waitFor(ctx, ids) {
const started = ctx.io.now();
const gens = new Map();
const seen = new Map();
- let stop;
- const stopped = new Promise((resolve) => (stop = resolve));
- const off = ctx.io.onInterrupt(() => stop("interrupted"));
+ // Ctrl+C ends the pending sleep too, so the process exits at once (not after --interval).
+ const pause = new AbortController();
+ const stopped = new Promise((resolve) => pause.signal.addEventListener("abort", resolve, { once: true }));
+ const off = ctx.io.onInterrupt(() => pause.abort());
const live = ctx.io.stderrIsTTY && !v.json;
try {
for (;;) {
@@ -217,8 +247,8 @@ export async function waitFor(ctx, ids) {
}
if (done === all.length) return { gens: all };
if (timeout > 0 && ctx.io.now() - started >= timeout) return { gens: all, stopped: "timeout" };
- const why = await Promise.race([ctx.io.sleep(interval).then(() => null), stopped]);
- if (why) return { gens: all, stopped: why };
+ await Promise.race([ctx.io.sleep(interval, pause.signal), stopped]);
+ if (pause.signal.aborted) return { gens: all, stopped: "interrupted" };
}
} finally {
off();
@@ -229,10 +259,12 @@ export async function waitFor(ctx, ids) {
/** Save every output of the finished generations into `dir`. */
async function saveOutputs(ctx, gens, dir) {
const files = [];
+ const root = path.resolve(ctx.io.cwd, dir);
for (const g of gens) {
if (g.status !== "succeeded") continue;
for (let i = 0; i < g.outputs.length; i++) {
- const dest = path.join(path.resolve(ctx.io.cwd, dir), outputName(g, i));
+ const dest = path.join(root, outputName(g, i));
+ if (path.dirname(dest) !== root) throw new ApiError(`The server sent an output name (${g.id}) that would land outside ${dir}; nothing was saved for it.`);
const bytes = await ctx.client.download(g.outputs[i].url, dest);
files.push({ id: g.id, url: absolute(ctx, g.outputs[i].url), path: dest, bytes });
if (!ctx.values.json) ctx.print(`Saved ${path.relative(ctx.io.cwd, dest) || dest} (${megabytes(bytes)})`);
@@ -281,7 +313,12 @@ function needIds(ctx, what = "a generation id") {
async function login(ctx) {
const { io, values: v } = ctx;
const file = configPath(io.env, io.home);
- const saved = readConfig(file);
+ let saved = {};
+ try {
+ saved = readConfig(file);
+ } catch {
+ ctx.note(`${file} isn't valid JSON; signing in replaces it.`);
+ }
let url = v.url ?? io.env.FUOBE_URL ?? (io.stdinIsTTY ? await io.ask(`Fuobe server [${saved.url ?? "http://localhost:3000"}]: `) : "") ?? "";
url = normalizeUrl(url.trim() || saved.url || "http://localhost:3000");
// Reachable, and does it ask for a token? (A 401 answers both.)
@@ -329,14 +366,18 @@ async function status(ctx) {
// Reads need the token too once a password is set: this says whether ours works.
await ctx.client.request("GET", "/api/generations", { query: { limit: 1 } });
const t = ctx.target;
- if (ctx.values.json) return ctx.json({ url: t.url, urlFrom: t.urlFrom, token: !!t.token, tokenFrom: t.tokenFrom ?? null, ...s });
+ if (ctx.values.json) return ctx.json({ url: t.url, urlFrom: t.urlFrom, token: !!t.token, tokenFrom: t.tokenFrom ?? null, ...(t.savedTokenFor && { savedTokenFor: t.savedTokenFor }), ...s });
const providers = Object.values(s.providers ?? {})
.filter((p) => p.label)
.map((p) => `${p.label} ${p.configured ? "✓" : "–"}`);
ctx.print(`Fuobe at ${t.url}${t.urlFrom === "default" ? "" : ` (from ${t.urlFrom})`}`);
ctx.print(`Engine mode: ${s.engineMode} · Demo mode: ${s.demoMode} · Preferred cloud: ${s.cloudProvider}`);
ctx.print(`Providers: ${providers.join(", ")}`);
- ctx.print(t.token ? `API token: accepted (from ${t.tokenFrom})` : "API token: none (this Fuobe has no password)");
+ ctx.print(
+ t.token
+ ? `API token: accepted (from ${t.tokenFrom})`
+ : `API token: none (this Fuobe has no password)${t.savedTokenFor ? `. The saved one is for ${t.savedTokenFor}, so it isn't sent here` : ""}`,
+ );
return EXIT.ok;
}
@@ -352,10 +393,17 @@ async function models(ctx) {
ctx.print(`No models match.${res.engineMode !== "both" ? ` This Fuobe runs ${res.engineMode === "open" ? "open-source" : "cloud"} models only (Settings → Engine mode).` : ""}`);
return EXIT.ok;
}
- const rows = items.map((m) => [m.id, m.name, m.engine === "open" ? "open" : "cloud", m.connected ? m.price : `${m.price} (demo)`, m.ops.join(", ")]);
+ // How a run goes today (Settings → Demo mode decides with the providers); an older server only says `connected`.
+ const runs = (m) => m.runs ?? (m.connected ? "real" : "demo");
+ const mark = { real: "", demo: " (demo)", refused: " (not set up)" };
+ const rows = items.map((m) => [m.id, m.name, m.engine === "open" ? "open" : "cloud", `${m.price}${mark[runs(m)] ?? ""}`, m.ops.join(", ")]);
ctx.print(table(["ID", "NAME", "ENGINE", "PRICE", "DOES"], rows, ctx.io.columns));
- const demo = items.filter((m) => !m.connected).length;
- ctx.note(`${items.length} model${items.length === 1 ? "" : "s"}${items.length < res.items.length ? ` of ${res.items.length}` : ""}.${demo ? " Those marked (demo) have no provider set up here yet: they return demo media, for free." : ""}`);
+ const count = (r) => items.filter((m) => runs(m) === r).length;
+ const notes = [`${items.length} model${items.length === 1 ? "" : "s"}${items.length < res.items.length ? ` of ${res.items.length}` : ""}.`];
+ if (res.demoMode === "on") notes.push("Demo mode is on (Settings → Demo mode): every run returns demo media, for free.");
+ else if (count("demo")) notes.push("Those marked (demo) have no provider set up here yet: they return demo media, for free.");
+ if (count("refused")) notes.push("Those marked (not set up) need their provider set up in Settings first (Demo mode is off, so they won't run as a demo).");
+ ctx.note(notes.join(" "));
return EXIT.ok;
}
@@ -364,6 +412,7 @@ const standIns = (values) => new Map(localFiles(fileInputs(values)).map((f) => [
async function estimate(ctx) {
const prompt = await promptFrom(ctx);
+ checkFiles(ctx, localFiles(fileInputs(ctx.values)));
const modelId = await modelFor(ctx);
const body = generationRequest({ prompt, modelId, values: ctx.values, uploaded: standIns(ctx.values) });
const p = await postGeneration(ctx, body, { preview: true });
@@ -376,6 +425,7 @@ async function estimate(ctx) {
async function generate(ctx) {
const v = ctx.values;
const prompt = await promptFrom(ctx);
+ checkFiles(ctx, localFiles(fileInputs(v)));
const modelId = await modelFor(ctx);
// Built with stand-ins first, so a bad option or a missing input fails before anything is uploaded.
const draft = generationRequest({ prompt, modelId, values: v, uploaded: standIns(v) });
@@ -384,12 +434,12 @@ async function generate(ctx) {
const { items } = await postGeneration(ctx, generationRequest({ prompt, modelId, values: v, uploaded }));
const ids = items.map((g) => g.id);
if (v.wait || v.out) {
- if (!v.json) ctx.note(`Started ${ids.length === 1 ? ids[0] : `${ids.length} jobs`} on ${items[0]?.modelName ?? modelId}${items[0]?.provider === "mock" ? " (demo: no provider connected)" : ""}.`);
+ if (!v.json) ctx.note(`Started ${ids.length === 1 ? ids[0] : `${ids.length} jobs`} on ${items[0]?.modelName ?? modelId}${items[0]?.provider === "mock" ? " (a demo: placeholder media, free)" : ""}.`);
return finish(ctx, ids, { download: !!v.out });
}
if (v.json) return ctx.json({ items });
const g = items[0];
- ctx.print(`Started ${ids.join(" ")} on ${g?.modelName ?? modelId}${g?.provider === "mock" ? " (demo: no provider connected)" : ""}${g?.costUsd ? `, about ${formatCost(g.costUsd * items.length)}` : ""}.`);
+ ctx.print(`Started ${ids.join(" ")} on ${g?.modelName ?? modelId}${g?.provider === "mock" ? " (a demo: placeholder media, free)" : ""}${g?.costUsd ? `, about ${formatCost(g.costUsd * items.length)}` : ""}.`);
ctx.print(`Wait for it: fuobe wait ${ids.join(" ")} Save it: fuobe download ${ids.join(" ")} --out .`);
return EXIT.ok;
}
@@ -439,6 +489,7 @@ async function cancel(ctx) {
async function upload(ctx) {
const files = needIds(ctx, "a file to upload");
+ checkFiles(ctx, files);
const urls = [];
for (const f of files) urls.push({ file: f, url: await uploadFile(ctx, f) });
if (ctx.values.json) return ctx.json({ items: urls });
@@ -675,6 +726,8 @@ async function mcp(ctx) {
ctx.print(setup.command);
ctx.note(`\nOther MCP clients (Claude Desktop, Cursor, Codex…) take this server entry:\n${JSON.stringify(setup.config, null, 2)}`);
if (ctx.target.token) ctx.note("These lines include your API token: keep them out of shared places.");
+ else if (ctx.target.savedTokenFor)
+ ctx.note(`No token in these lines: the one "fuobe login" saved is for ${ctx.target.savedTokenFor}. If ${ctx.target.url} has a password, add --token fuobe_… for it.`);
return EXIT.ok;
}
@@ -686,6 +739,7 @@ async function mcp(ctx) {
* @property {string} usage
* @property {Record<string, OptionSpec>} [options]
* @property {string[]} [examples]
+ * @property {true} [ownConfig] reads the saved config itself (login, logout), so a broken one doesn't stop it
* @property {(ctx: any) => Promise<number | void>} run
*/
@@ -695,9 +749,10 @@ export const COMMANDS = {
summary: "Save the server address and API token",
usage: "fuobe login [--url <url>] [--token <token>]",
examples: ["fuobe login", "fuobe login --url https://studio.example.com --token fuobe_…"],
+ ownConfig: true,
run: login,
},
- logout: { summary: "Forget the saved address and token", usage: "fuobe logout", run: logout },
+ logout: { summary: "Forget the saved address and token", usage: "fuobe logout", ownConfig: true, run: logout },
status: {
summary: "The server (engine, providers, sign-in), or the state of generations",
usage: "fuobe status [<id>…]",
diff --git a/bin/lib/config.mjs b/bin/lib/config.mjs
index 554a42a0..2a8c3099 100644
--- a/bin/lib/config.mjs
+++ b/bin/lib/config.mjs
@@ -1,5 +1,6 @@
// Where the CLI finds its server and token: --url / --token, then FUOBE_URL / FUOBE_TOKEN, then
-// the file `fuobe login` writes (~/.config/fuobe/config.json, readable by you only).
+// the file `fuobe login` writes (~/.config/fuobe/config.json, readable by you only). The saved
+// token is only ever sent to the saved server.
import fs from "node:fs";
import path from "node:path";
import { UsageError } from "./args.mjs";
@@ -58,21 +59,41 @@ export function normalizeUrl(raw) {
return `${u.origin}${u.pathname.replace(/\/+$/, "")}`;
}
+/** The saved config's server, normalized (null when the saved address isn't one). */
+function savedServer(config) {
+ try {
+ return normalizeUrl(config.url ?? DEFAULT_URL);
+ } catch {
+ return null;
+ }
+}
+
/**
- * The server and token to use, and where each came from (shown by `fuobe status`).
+ * The server and token to use, and where each came from (shown by `fuobe status`). The token
+ * `fuobe login` saved belongs to the server it was saved with: a --url or FUOBE_URL that names
+ * another server doesn't get it (`savedTokenFor` then says whose it is). --token and FUOBE_TOKEN
+ * go to whichever server the command talks to.
* @param {{ url?: string, token?: string }} flags
* @param {Record<string, string | undefined>} env
* @param {{ url?: string, token?: string }} config
*/
export function resolveTarget(flags, env, config) {
- const pick = (flag, envName) =>
- flags[flag] ? { value: flags[flag], from: `--${flag}` } : env[envName] ? { value: env[envName], from: envName } : config[flag] ? { value: config[flag], from: "config" } : null;
- const url = pick("url", "FUOBE_URL");
- const token = pick("token", "FUOBE_TOKEN");
+ const url = flags.url ? { value: flags.url, from: "--url" } : env.FUOBE_URL ? { value: env.FUOBE_URL, from: "FUOBE_URL" } : config.url ? { value: config.url, from: "config" } : null;
+ const resolved = normalizeUrl(url?.value ?? DEFAULT_URL);
+ const saved = config.token?.trim() ? savedServer(config) : null;
+ const token = flags.token
+ ? { value: flags.token, from: "--token" }
+ : env.FUOBE_TOKEN
+ ? { value: env.FUOBE_TOKEN, from: "FUOBE_TOKEN" }
+ : saved && saved === resolved
+ ? { value: config.token, from: "config" }
+ : null;
+ const value = token?.value?.trim() || undefined;
return {
- url: normalizeUrl(url?.value ?? DEFAULT_URL),
+ url: resolved,
urlFrom: url?.from ?? "default",
- token: token?.value?.trim() || undefined,
- tokenFrom: token?.from,
+ token: value,
+ tokenFrom: value ? token?.from : undefined,
+ ...(!value && config.token?.trim() && saved !== resolved && { savedTokenFor: saved ?? String(config.url) }),
};
}
diff --git a/bin/lib/format.mjs b/bin/lib/format.mjs
index be17c4b2..c4866763 100644
--- a/bin/lib/format.mjs
+++ b/bin/lib/format.mjs
@@ -50,7 +50,7 @@ export function statusText(g) {
export function previewText(p) {
const runs = p.jobs > 1 ? ` in ${p.jobs} jobs` : "";
const outputs = p.outputs ? `${plural(p.outputs, p.kind === "audio" ? "audio file" : p.kind === "model3d" ? "3D model" : p.kind === "text" ? "text" : p.kind)}${runs}` : "";
- const price = p.demo ? "a demo (no provider connected), costs nothing" : p.engine === "open" ? "free (open source, your GPU)" : formatCost(p.costUsd) === "price unknown" ? "price unknown" : `about ${formatCost(p.costUsd)}`;
+ const price = p.demo ? "a demo (placeholder media), costs nothing" : p.engine === "open" ? "free (open source, your GPU)" : formatCost(p.costUsd) === "price unknown" ? "price unknown" : `about ${formatCost(p.costUsd)}`;
return `${p.modelName} (${p.engine === "open" ? "open source" : "cloud"}) · ${p.opLabel ?? p.op}${outputs ? ` · ${outputs}` : ""} · ${price}`;
}
diff --git a/docs/cli.md b/docs/cli.md
index e3f7f11c..a020673c 100644
--- a/docs/cli.md
+++ b/docs/cli.md
@@ -36,9 +36,13 @@ The CLI finds its server and token in this order:
|---|---|---|
| 1 | `--url` | `--token` |
| 2 | `FUOBE_URL` | `FUOBE_TOKEN` |
-| 3 | the file `fuobe login` saved | the same file |
+| 3 | the file `fuobe login` saved | the same file, for that server only |
| 4 | `http://localhost:3000` | none |
+The saved token goes only to the server it was saved with. A `--url` or `FUOBE_URL` that names
+another server gets no token unless you pass `--token` or set `FUOBE_TOKEN` (those two go to
+whichever server the command talks to); `fuobe status` says when the saved token was left out.
+
A Fuobe without a password (the default for local use) needs no token. Once a password is set, the
CLI needs an **API token**: open **Settings → Security → API tokens** in the browser
(`http://localhost:3000/settings#security`), create one and copy it. It starts with `fuobe_` and is
@@ -74,9 +78,12 @@ fuobe models --op tts --json # models that run one operation,
fuobe models --hidden # also the helper models studios use behind the scenes
```
-`--kind` is `image`, `video`, `audio`, `text` or `model3d`; `--engine` is `open` or `cloud`. A model
-whose provider isn't set up yet is marked "(demo)": it runs, but returns demo media for free. An
-install set to one engine only (Settings → Engine mode) lists that engine's models only.
+`--kind` is `image`, `video`, `audio`, `text` or `model3d`; `--engine` is `open` or `cloud`. The
+price says how a run goes today, following Settings → Demo mode: "(demo)" runs but returns demo
+media for free (no provider set up yet, or Demo mode is on); "(not set up)" won't run until its
+provider is set up, because Demo mode is off. `--json` gives the same as `runs` (`real`, `demo` or
+`refused`) per model. An install set to one engine only (Settings → Engine mode) lists that
+engine's models only.
### `fuobe estimate` — price a run first
@@ -96,7 +103,7 @@ fuobe generate "make it blue" --image photo.jpg --engine open --out . # a
fuobe generate "she turns and smiles" --model kling-3 --image portrait.jpg \
--aspect 9:16 --duration 5 --out renders/ # image to video
fuobe generate "Welcome to the studio." --kind audio --out audio/ # speech (ElevenLabs v4)
-fuobe generate "Hello there." --kind audio --engine open --voice-audio me.wav --wait # Chatterbox in your voice
+fuobe generate "Hello there." --kind audio --voice-audio me.wav --wait # in your voice (Chatterbox; --engine open runs it on ComfyUI)
fuobe generate --model oss-join-clips --video a.mp4 --video b.mp4 --out . # join two clips
fuobe generate "make it rain" --model kling-o3 --video clip.mp4 --wait # edit a video
echo "a long prompt…" | fuobe generate - --model seedance-2-5 --wait # the prompt from stdin
@@ -104,8 +111,12 @@ echo "a long prompt…" | fuobe generate - --model seedance-2-5 --wait #
With no `--model`, the studio's own pick is used and named on stderr: `--kind image` (the default;
the Edit studio's model when you pass `--image`), `video` or `audio`, on `--engine` (else the cloud,
-unless the install runs open source only). A video or audio input needs `--model`, because many
-kinds of model take one (edit, extend, lip-sync, transcribe…).
+unless the install runs open source only). With `--kind audio`, a `--voice-audio` sample picks a
+model that clones it (`chatterbox-cloud`, or `oss-chatterbox` on the open engine), and two samples
+pick the open dialogue model (`oss-chatterbox-dialogue`; no cloud dialogue model clones voices). A
+model named with `--model` that would ignore a sample (premade voices only, or one speaker for two
+samples) is refused with a sentence instead. Any other video or audio input needs `--model`,
+because many kinds of model take one (edit, extend, lip-sync, transcribe…).
| option | goes to |
|---|---|
@@ -128,9 +139,10 @@ kinds of model take one (edit, extend, lip-sync, transcribe…).
Inputs can be local files, `https://` links or `/api/files/…` URLs from earlier results. Local files
are uploaded through `/api/uploads` first (up to 200 MB each; a file named twice is uploaded once),
-after the request has been checked, so a missing input fails before a big upload. When the server
-can't run a request it says what's missing, and the CLI names the option:
-`Add a portrait and a voice track (use --image <file|url> and --audio <file|url>)`.
+after every file has been found and the request has been checked, so a missing input fails before
+a big upload. Downloads are named `<id>.<ext>` (`<id>-<n>.<ext>` for several outputs) and always
+land in `--out`. When the server can't run a request it says what's missing, and the CLI names the
+option: `Add a portrait and a voice track (use --image <file|url> and --audio <file|url>)`.
Without `--wait` or `--out`, `generate` prints the job ids and returns at once.
@@ -253,16 +265,23 @@ server too (`fuobe mcp`).
- **"… has a password, so the CLI needs an API token"** — create one in Settings → Security → API
tokens, then `fuobe login` (or set `FUOBE_TOKEN`).
- **"… refused the API token"** — it was revoked, or belongs to another server: create a new one.
-- **"(demo)" results** — no provider is set up for that model: add a key in Settings (cloud), or
- start ComfyUI (open source). Demo results cost nothing and are labelled in the Library.
+- **"The token "fuobe login" saved is for …, so it isn't sent here"** — `--url` or `FUOBE_URL` names
+ another server than the one you signed in to: pass `--token`, or `fuobe login --url <that server>`.
+- **"(demo)" results** — no provider is set up for that model, or Settings → Demo mode is on: add a
+ key in Settings (cloud), or start ComfyUI (open source). Demo results cost nothing and are
+ labelled in the Library.
+- **"(not set up)" in `fuobe models`, or "Connect … in Settings to run this model"** — Demo mode is
+ off and the model's provider isn't set up yet.
- **"… is a cloud model, but you asked for --engine open"** — pick a model of that engine
(`fuobe models --engine open`) or leave out `--engine`.
## What it calls
For script writers who'd rather call the API directly: `GET /api/models` (`kind`, `engine`, `op`,
-`q`, `hidden=1`), `POST /api/generations` (with `?preview=1` to price), `GET /api/generations[/<id>]`,
+`q`, `hidden=1`; it answers with the studios' `defaults` per engine, `demoMode`, and per model
+`connected` and `runs`), `POST /api/generations` (with `?preview=1` to price), `GET /api/generations[/<id>]`,
`POST /api/generations/<id>/cancel`, `POST /api/uploads` (multipart `file`), `GET /api/files/…`,
`GET /api/status`, `GET|PATCH /api/assist/skills[/<name>]`, `POST /api/assist/skills/upload`
(`?replace=1`) and `POST /api/mcp` (JSON-RPC). Every call carries `Authorization: Bearer <token>`
-when there is one, and only to the Fuobe server.
+when there is one, and only to the Fuobe server (never to a link elsewhere, and the saved token only
+to the server it was saved for).
diff --git a/tests/cli-run.test.ts b/tests/cli-run.test.ts
index 1e913c22..bbf432fe 100644
--- a/tests/cli-run.test.ts
+++ b/tests/cli-run.test.ts
@@ -74,7 +74,21 @@ beforeAll(async () => {
const route = `${s.method} ${url.pathname}`;
if (route === "POST /api/uploads") return send(201, { id: "up1", url: "/api/files/uploads/2026-10-22/up1.png" });
if (route === "GET /api/models")
- return send(200, { engineMode: "both", defaults: { image: { cloud: "nano-banana-pro", open: "oss-z-image-turbo" }, edit: { cloud: "nano-banana-pro", open: "oss-qwen-edit" } }, items: [{ id: "nano-banana-pro", name: "Nano Banana Pro" }] });
+ return send(200, {
+ engineMode: "both",
+ defaults: {
+ image: { cloud: "nano-banana-pro", open: "oss-z-image-turbo" },
+ edit: { cloud: "nano-banana-pro", open: "oss-qwen-edit" },
+ audio: { cloud: "elevenlabs-v4", open: "oss-chatterbox" },
+ clone: { cloud: "chatterbox-cloud", open: "oss-chatterbox" },
+ cloneDialogue: { open: "oss-chatterbox-dialogue" },
+ },
+ items: [
+ { id: "nano-banana-pro", name: "Nano Banana Pro" },
+ { id: "elevenlabs-v4", name: "ElevenLabs v4", opIds: ["tts"] },
+ { id: "chatterbox-cloud", name: "Chatterbox", opIds: ["tts"], voiceClone: true },
+ ],
+ });
if (route === "POST /api/generations" && (s.json as { modelId?: string }).modelId === "kling-3") return send(422, { error: "Add a start frame" });
if (route === "POST /api/generations" && url.searchParams.get("preview") === "1")
return send(200, { modelId: "nano-banana-pro", modelName: "Nano Banana Pro", engine: "cloud", kind: "image", op: "edit", opLabel: "Edit", jobs: 1, outputs: 1, demo: false, providerId: "fal", costUsd: 0.15 });
@@ -83,6 +97,9 @@ beforeAll(async () => {
polls++;
return send(200, polls < 2 ? generation("running") : generation("succeeded", { outputs: [{ url: "/api/files/outputs/2026-10-22/out1.png", kind: "image" }], completedAt: 5_000 }));
}
+ // A server that names its output after a path, and a job that never finishes.
+ if (route === "GET /api/generations/evil") return send(200, generation("succeeded", { id: "../escaped", outputs: [{ url: "/api/files/outputs/2026-10-22/out1.png", kind: "image" }] }));
+ if (route === "GET /api/generations/slow") return send(200, generation("running", { id: "slow" }));
if (route === "GET /api/generations") return send(200, { items: [generation("succeeded")] });
if (route === "GET /api/files/outputs/2026-10-22/out1.png") {
res.writeHead(200, { "content-type": "image/png" });
@@ -115,7 +132,11 @@ beforeEach(() => {
requireAuth = true;
});
-function run(args: string[], env: Record<string, string | undefined> = {}): Promise<{ code: number | null; stdout: string; stderr: string }> {
+function run(
+ args: string[],
+ env: Record<string, string | undefined> = {},
+ started?: (child: ReturnType<typeof spawn>) => void,
+): Promise<{ code: number | null; stdout: string; stderr: string }> {
return new Promise((resolve) => {
const child = spawn(process.execPath, [CLI, ...args], {
cwd: tmp,
@@ -123,6 +144,7 @@ function run(args: string[], env: Record<string, string | undefined> = {}): Prom
env: { PATH: process.env.PATH, HOME: tmp, FUOBE_CONFIG: path.join(tmp, "config.json"), FUOBE_URL: base, FUOBE_TOKEN: TOKEN, ...env } as unknown as NodeJS.ProcessEnv,
stdio: ["ignore", "pipe", "pipe"],
});
+ started?.(child);
let stdout = "";
let stderr = "";
child.stdout.on("data", (d) => (stdout += d));
@@ -253,6 +275,101 @@ describe("fuobe CLI against a Fuobe server", () => {
expect(seen.some((s) => s.path.endsWith("/cancel"))).toBe(false);
});
+ it("never sends the saved token to another server, nor prints it for one", async () => {
+ const file = path.join(tmp, "config.json");
+ fs.writeFileSync(file, JSON.stringify({ url: "https://studio.example.com", token: "fuobe_secret-for-studio" }));
+ const signedOut = { FUOBE_TOKEN: undefined, FUOBE_URL: undefined };
+ try {
+ const list = await run(["list", "--url", base], signedOut);
+ expect(list.code).toBe(1);
+ expect(list.stderr).toMatch(/The token "fuobe login" saved is for https:\/\/studio\.example\.com, so it isn't sent here/);
+ const viaEnv = await run(["list"], { FUOBE_TOKEN: undefined, FUOBE_URL: base });
+ expect(viaEnv.code).toBe(1);
+ expect(seen.length).toBeGreaterThan(1);
+ expect(seen.every((s) => s.auth === null)).toBe(true);
+ const mcp = await run(["mcp", "--url", base], signedOut);
+ expect(mcp.stdout.trim()).toBe(`claude mcp add --transport http fuobe ${base}/api/mcp`);
+ expect(mcp.stdout + mcp.stderr).not.toContain("fuobe_secret-for-studio");
+ expect(mcp.stderr).toMatch(/No token in these lines: the one "fuobe login" saved is for https:\/\/studio\.example\.com/);
+ const status = await run(["status", "--url", base, "--json"], signedOut);
+ expect(JSON.parse(status.stderr)).toMatchObject({ status: 401 });
+ } finally {
+ fs.rmSync(file, { force: true });
+ }
+ });
+
+ it("logs in and out over a broken config file (the commands its message names)", async () => {
+ const file = path.join(tmp, "config.json");
+ const signedOut = { FUOBE_TOKEN: undefined, FUOBE_URL: undefined };
+ fs.writeFileSync(file, "{broken");
+ try {
+ const list = await run(["list"], signedOut);
+ expect(list.code).toBe(1);
+ expect(list.stderr).toMatch(/isn't valid JSON\. Run "fuobe login" again, or delete the file\./);
+ const login = await run(["login", "--url", base, "--token", TOKEN], signedOut);
+ expect(login.code).toBe(0);
+ expect(login.stderr).toMatch(/isn't valid JSON; signing in replaces it/);
+ expect(JSON.parse(fs.readFileSync(file, "utf8"))).toEqual({ url: base, token: TOKEN });
+ fs.writeFileSync(file, "{broken");
+ const logout = await run(["logout"], signedOut);
+ expect(logout.code).toBe(0);
+ expect(fs.existsSync(file)).toBe(false);
+ } finally {
+ fs.rmSync(file, { force: true });
+ }
+ });
+
+ it("saves a download inside --out whatever id the server sends", async () => {
+ const r = await run(["download", "evil", "--out", "safe"]);
+ expect(r.code).toBe(0);
+ expect(r.stdout).toMatch(/^Saved safe\/___escaped\.png \(1 KB\)$/m);
+ expect(fs.existsSync(path.join(tmp, "escaped.png"))).toBe(false);
+ expect(fs.readdirSync(path.join(tmp, "safe"))).toEqual(["___escaped.png"]);
+ });
+
+ it("stops waiting at once on Ctrl+C, not after the next --interval", async () => {
+ const t0 = Date.now();
+ let child: ReturnType<typeof spawn> | undefined;
+ const done = run(["wait", "slow", "--interval", "30"], {}, (c) => (child = c));
+ // Interrupt once the first check has reached the server (the CLI is then asleep for 30 s).
+ while (!seen.some((s) => s.path === "/api/generations/slow")) await new Promise((r) => setTimeout(r, 20));
+ await new Promise((r) => setTimeout(r, 150));
+ child!.kill("SIGINT");
+ const r = await done;
+ expect(r.code).toBe(130);
+ expect(r.stderr).toMatch(/Stopped waiting\. It keeps running on the server: fuobe wait slow/);
+ expect(Date.now() - t0).toBeLessThan(10_000);
+ });
+
+ it("finds every local file before uploading any", async () => {
+ fs.writeFileSync(path.join(tmp, "me.png"), PNG);
+ const r = await run(["generate", "x", "-m", "nano-banana-pro", "--image", "me.png", "--image", "missin.png"]);
+ expect(r.code).toBe(2);
+ expect(r.stderr).toMatch(/^Can't find missin\.png\./);
+ expect(seen).toHaveLength(0);
+ const up = await run(["upload", "me.png", "missin.png"]);
+ expect(up.code).toBe(2);
+ expect(seen).toHaveLength(0);
+ });
+
+ it("clones a voice sample with a model that takes one, and refuses one that would ignore it", async () => {
+ fs.writeFileSync(path.join(tmp, "me.wav"), "RIFF");
+ const r = await run(["generate", "Hello", "--kind", "audio", "--voice-audio", "me.wav", "--json"]);
+ expect(r.code).toBe(0);
+ expect(r.stderr).toContain("Using Chatterbox (chatterbox-cloud)");
+ expect(seen.find((s) => s.path === "/api/generations" && s.method === "POST")!.json).toMatchObject({ modelId: "chatterbox-cloud", inputs: { voiceAudio: "/api/files/uploads/2026-10-22/up1.png" } });
+ seen = [];
+ const two = await run(["generate", "Hi", "--kind", "audio", "--voice-audio", "me.wav", "--voice-audio", "me.wav"]);
+ expect(two.code).toBe(2);
+ expect(two.stderr).toMatch(/no default cloud dialogue model that clones two voice samples\. Add --engine open \(oss-chatterbox-dialogue\)/);
+ seen = [];
+ const named = await run(["generate", "Hello", "-m", "elevenlabs-v4", "--voice-audio", "me.wav"]);
+ expect(named.code).toBe(2);
+ expect(named.stderr).toMatch(/^elevenlabs-v4 speaks in premade voices .* \(--model chatterbox-cloud or --model oss-chatterbox\)\./);
+ expect(seen.find((s) => s.path.startsWith("/api/models?"))!.path).toBe("/api/models?q=elevenlabs-v4&hidden=1");
+ expect(seen.some((s) => s.path.startsWith("/api/uploads") || s.path.startsWith("/api/generations"))).toBe(false);
+ });
+
it("answers usage mistakes with exit code 2 and help with 0", async () => {
const typo = await run(["generat", "x"]);
expect(typo.code).toBe(2);
diff --git a/tests/cli.test.ts b/tests/cli.test.ts
index de1b9eb1..39674b93 100644
--- a/tests/cli.test.ts
+++ b/tests/cli.test.ts
@@ -3,7 +3,7 @@ import os from "node:os";
import path from "node:path";
import { afterAll, describe, expect, it } from "vitest";
import { keyValue, parseArgs, suggest, UsageError } from "../bin/lib/args.mjs";
-import { defaultModel, fileInputs, generationRequest, isRemoteRef, localFiles, withInputHint } from "../bin/lib/build.mjs";
+import { defaultModel, fileInputs, generationRequest, isRemoteRef, localFiles, voiceSampleProblem, withInputHint } from "../bin/lib/build.mjs";
import { createClient, networkMessage, statusMessage } from "../bin/lib/client.mjs";
import { GEN_OPTIONS, mcpSetup, outputName, toolFailure } from "../bin/lib/commands.mjs";
import { configPath, normalizeUrl, readConfig, resolveTarget, writeConfig } from "../bin/lib/config.mjs";
@@ -167,6 +167,45 @@ describe("the generation request", () => {
expect(usage(() => defaultModel({ engineMode: "open", defaults: { image: { open: "oss-z-image-turbo" } } }, { engine: "cloud" }))).toMatch(/open-source models only/);
expect(usage(() => defaultModel(list, { hasMedia: true }))).toMatch(/--model/);
});
+
+ const audio = {
+ engineMode: "both",
+ defaults: {
+ audio: { cloud: "elevenlabs-v4", open: "oss-chatterbox" },
+ dialogue: { cloud: "elevenlabs-dialogue", open: "oss-chatterbox-dialogue" },
+ clone: { cloud: "chatterbox-cloud", open: "oss-chatterbox" },
+ cloneDialogue: { open: "oss-chatterbox-dialogue" },
+ },
+ };
+
+ it("picks a model that clones the voice samples, and a dialogue for two", () => {
+ expect(defaultModel(audio, { kind: "audio" })).toBe("elevenlabs-v4");
+ expect(defaultModel(audio, { kind: "audio", voices: 1 })).toBe("chatterbox-cloud");
+ expect(defaultModel(audio, { kind: "audio", voices: 1, engine: "open" })).toBe("oss-chatterbox");
+ expect(defaultModel(audio, { kind: "audio", voices: 2, engine: "open" })).toBe("oss-chatterbox-dialogue");
+ expect(defaultModel(audio, { kind: "audio", op: "dialogue" })).toBe("elevenlabs-dialogue");
+ // No cloud dialogue clones voices: the open one is named instead of dropping a speaker.
+ expect(usage(() => defaultModel(audio, { kind: "audio", voices: 2 }))).toBe(
+ "There's no default cloud dialogue model that clones two voice samples. Add --engine open (oss-chatterbox-dialogue), or pick a model with --model (fuobe models --kind audio).",
+ );
+ expect(usage(() => defaultModel({ engineMode: "cloud", defaults: { cloneDialogue: {} } }, { kind: "audio", voices: 2 }))).toMatch(/^There's no default cloud dialogue model .* Pick one with --model/);
+ });
+
+ it("refuses a named model that would ignore a voice sample", () => {
+ const tts = { id: "elevenlabs-v4", opIds: ["tts"] };
+ const clone = { id: "chatterbox-cloud", opIds: ["tts"], voiceClone: true };
+ const dialogue = { id: "oss-chatterbox-dialogue", opIds: ["dialogue"], voiceClone: true };
+ expect(voiceSampleProblem(tts, 0, audio.defaults)).toBeNull();
+ expect(voiceSampleProblem(clone, 1, audio.defaults)).toBeNull();
+ expect(voiceSampleProblem(dialogue, 2, audio.defaults)).toBeNull();
+ // An unknown id is the server's to answer.
+ expect(voiceSampleProblem(undefined, 1, audio.defaults)).toBeNull();
+ expect(voiceSampleProblem(tts, 1, audio.defaults)).toBe(
+ "elevenlabs-v4 speaks in premade voices (--voice <id>) and doesn't clone a voice sample. Leave out --voice-audio, or use a model that clones one (--model chatterbox-cloud or --model oss-chatterbox).",
+ );
+ expect(voiceSampleProblem(clone, 2, audio.defaults)).toBe("chatterbox-cloud doesn't clone two voices. Two --voice-audio samples are a dialogue's speakers: use --model oss-chatterbox-dialogue.");
+ expect(voiceSampleProblem({ id: "elevenlabs-dialogue", opIds: ["dialogue"] }, 2)).toMatch(/doesn't clone two voices.*\(fuobe models --op dialogue\)/);
+ });
});
describe("output", () => {
@@ -184,7 +223,7 @@ describe("output", () => {
);
expect(previewText({ modelName: "Wan 2.2", engine: "open", op: "t2v", outputs: 1, jobs: 1, kind: "video", costUsd: 0, demo: false })).toMatch(/free \(open source/);
expect(previewText({ modelName: "Kling", engine: "cloud", opLabel: "Image to video", outputs: 2, jobs: 2, kind: "video", costUsd: 1, demo: true })).toBe(
- "Kling (cloud) · Image to video · 2 videos in 2 jobs · a demo (no provider connected), costs nothing",
+ "Kling (cloud) · Image to video · 2 videos in 2 jobs · a demo (placeholder media), costs nothing",
);
});
@@ -201,6 +240,15 @@ describe("output", () => {
const g = { id: "abc", outputs: [{ url: "/api/files/outputs/2026-10-22/x1.png" }, { url: "/api/files/outputs/2026-10-22/x2.mp4?v=1" }] };
expect([outputName(g, 0), outputName(g, 1)]).toEqual(["abc-1.png", "abc-2.mp4"]);
expect(outputName({ id: "z", outputs: [{ url: "/api/files/x/y.srt" }] }, 0)).toBe("z.srt");
+ // nanoid ids keep their - and _.
+ expect(outputName({ id: "V1St-GX_8", outputs: [{ url: "/api/files/a.webp" }] }, 0)).toBe("V1St-GX_8.webp");
+ });
+
+ it("keeps a server-sent id or extension from naming a path outside --out", () => {
+ expect(outputName({ id: "../escaped", outputs: [{ url: "/api/files/x.sh" }] }, 0)).toBe("___escaped.sh");
+ expect(outputName({ id: "../../.config/fish/config", outputs: [{ url: "/api/files/x.fish" }] }, 0)).toBe("_______config_fish_config.fish");
+ expect(outputName({ id: "a\\b", outputs: [{ url: "/api/files/x.png%2F..%2Fy" }] }, 0)).toBe("a_b.bin");
+ expect(outputName({ id: "", outputs: [{ url: "/api/files/x" }] }, 0)).toBe("output.bin");
});
});
@@ -219,6 +267,21 @@ describe("config and the server address", () => {
expect(resolveTarget({ url: "https://f.example.com", token: "fuobe_flag" }, { FUOBE_TOKEN: "fuobe_env" }, saved)).toMatchObject({ url: "https://f.example.com", tokenFrom: "--token" });
});
+ it("sends the saved token only to the server it was saved for", () => {
+ const saved = { url: "https://studio.example.com", token: "fuobe_secret-for-studio" };
+ const elsewhere = { url: "http://127.0.0.1:4000", urlFrom: "--url", token: undefined, tokenFrom: undefined, savedTokenFor: "https://studio.example.com" };
+ expect(resolveTarget({ url: "http://127.0.0.1:4000" }, {}, saved)).toEqual(elsewhere);
+ expect(resolveTarget({}, { FUOBE_URL: "127.0.0.1:4000" }, saved)).toEqual({ ...elsewhere, urlFrom: "FUOBE_URL" });
+ // The same server, however it's spelled, gets it.
+ expect(resolveTarget({ url: "studio.example.com" }, {}, { ...saved, url: "http://studio.example.com/" })).toMatchObject({ token: saved.token, tokenFrom: "config" });
+ expect(resolveTarget({ url: "HTTPS://Studio.Example.com/" }, {}, saved)).toMatchObject({ token: saved.token, tokenFrom: "config" });
+ // A token saved without an address is the default server's.
+ expect(resolveTarget({}, {}, { token: "fuobe_local" })).toMatchObject({ url: "http://localhost:3000", token: "fuobe_local" });
+ expect(resolveTarget({ url: "https://other.test" }, {}, { token: "fuobe_local" })).toMatchObject({ token: undefined, savedTokenFor: "http://localhost:3000" });
+ // A token given for this run goes where the run goes.
+ expect(resolveTarget({ url: "http://127.0.0.1:4000" }, { FUOBE_TOKEN: "fuobe_env" }, saved)).toEqual({ url: "http://127.0.0.1:4000", urlFrom: "--url", token: "fuobe_env", tokenFrom: "FUOBE_TOKEN" });
+ });
+
it("normalizes addresses and refuses what isn't one", () => {
expect(normalizeUrl("localhost:3000")).toBe("http://localhost:3000");
expect(normalizeUrl("https://host/fuobe/")).toBe("https://host/fuobe");
@@ -264,6 +327,9 @@ describe("the REST client", () => {
const ctx = { url: "http://localhost:3000" };
expect(statusMessage(401, { error: "Sign in" }, ctx)).toMatch(/has a password, so the CLI needs an API token\. Create one in Settings → Security → API tokens \(http:\/\/localhost:3000\/settings#security\)/);
expect(statusMessage(401, null, { ...ctx, token: "fuobe_x", tokenFrom: "FUOBE_TOKEN" })).toMatch(/refused the API token \(from FUOBE_TOKEN\)/);
+ expect(statusMessage(401, null, { ...ctx, savedTokenFor: "https://studio.example.com" })).toMatch(
+ /The token "fuobe login" saved is for https:\/\/studio\.example\.com, so it isn't sent here: pass --token, set FUOBE_TOKEN, or run "fuobe login --url http:\/\/localhost:3000"/,
+ );
expect(statusMessage(422, { error: "Add an image" }, ctx)).toBe("Add an image");
expect(statusMessage(500, "<html>", ctx)).toMatch(/HTTP 500 — check the server's log/);
});