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.

Skills W1: a check never overwrites a recipe edited while it ran; tool runs carry the skill's stamp

Claudead8a9b34b3d1
diff --git a/src/lib/recipe.ts b/src/lib/recipe.ts
index bf8dc1fe..d3fac550 100644
--- a/src/lib/recipe.ts
+++ b/src/lib/recipe.ts
@@ -214,7 +214,8 @@ function valueSchema(p: RecipeParam): z.ZodType<RecipeValue | undefined> {
let n = z.number({ error: `${label}: a number` }).refine(Number.isFinite, `${label}: a number`);
if (p.min !== undefined) n = n.refine((x) => x >= p.min!, `${label}: at least ${p.min}`);
if (p.max !== undefined) n = n.refine((x) => x <= p.max!, `${label}: at most ${p.max}`);
- base = z.union([z.number(), z.string().trim().regex(/^-?\d+(\.\d+)?$/, `${label}: a number`).transform(Number)]).pipe(n);
+ // Text (a form, a CSV) counts as it is being typed: "0." and ".5" are numbers; anything else isn't.
+ base = z.preprocess((v) => (typeof v === "string" && /^-?(\d+(\.\d*)?|\.\d+)$/.test(v.trim()) ? Number(v.trim()) : v), n) as z.ZodType<RecipeValue>;
break;
}
case "choice": {
@@ -579,6 +580,7 @@ export function parseRows(csv: string, recipe: Pick<Recipe, "params">): ParsedRo
if (p.required && p.default === undefined && !columns.includes(p.id)) errors.push(`No column for “${p.label}”`);
}
if (body.length > RECIPE_LIMITS.rows) errors.push(`At most ${RECIPE_LIMITS.rows} rows at a time — this has ${body.length}`);
+ if (!body.length && columns.some(Boolean)) errors.push("Add a row under the header: one row per run");
const rows = body.slice(0, RECIPE_LIMITS.rows).map((r): RecipeRow => {
const raw: Record<string, unknown> = {};
columns.forEach((id, i) => {
@@ -695,8 +697,18 @@ export function stripExamples(recipe: Recipe): Recipe {
return out;
}
+/** The recipe as kept with its examples (a backup, a move between installs): only this install's checks are left out. */
+export function stripChecks(recipe: Recipe): Recipe {
+ const out: Recipe = { ...recipe };
+ delete out.verified;
+ return out;
+}
+
const TYPE_WORDS: Record<ParamType, string> = { image: "an image", video: "a video", audio: "an audio file", text: "text", number: "a number", choice: "one of", element: "an element's @handle" };
+/** A line's text cut to `n` characters (the Run it section stays a few pages, whatever a recipe holds). */
+const cut = (s: string, n: number) => (s.length > n ? `${s.slice(0, n - 1)}…` : s);
+
function paramLine(p: RecipeParam): string {
const what = p.type === "choice" ? `${TYPE_WORDS.choice} ${(p.options ?? []).map((o) => `\`${o}\``).join(", ")}` : TYPE_WORDS[p.type];
const limits = [
@@ -704,80 +716,114 @@ function paramLine(p: RecipeParam): string {
p.type === "number" && p.max !== undefined ? `to ${p.max}` : "",
p.type === "text" && p.max !== undefined ? `up to ${p.max} characters` : "",
].filter(Boolean);
- const need = p.required && p.default === undefined ? "required" : p.default !== undefined ? `default \`${p.default}\`` : "optional";
- return `- \`${p.id}\` — ${p.label}: ${what}${limits.length ? ` (${limits.join(" ")})` : ""}; ${need}${p.hint ? `. ${p.hint}` : ""}`;
+ const need = p.required && p.default === undefined ? "required" : p.default !== undefined ? `default \`${cut(String(p.default), 120)}\`` : "optional";
+ return cut(`- \`${p.id}\` — ${p.label}: ${what}${limits.length ? ` (${limits.join(" ")})` : ""}; ${need}${p.hint ? `. ${p.hint}` : ""}`, 600);
}
/** A step as a line: its model and operation, its words with the inputs as {{id}}, what it waits for. */
function stepLine(s: RecipeStep, i: number, keys: string[]): string {
- if (s.kind === "tool") return `${i + 1}. \`${s.tool}\` with ${JSON.stringify(s.input)}`;
+ if (s.kind === "tool") return `${i + 1}. \`${s.tool}\` with ${cut(JSON.stringify(s.input), 400)}`;
const r = s.request;
const waits = asList(s.after).map((a) => `step ${keys.indexOf(a) + 1}`);
- return `${i + 1}. ${s.label ? `${s.label}: ` : ""}\`${r.modelId}\`${r.op ? ` (${r.op})` : ""}${r.prompt ? ` — “${r.prompt}”` : ""}${waits.length ? `, from the result of ${waits.join(" and ")}` : ""}`;
-}
+ return `${i + 1}. ${s.label ? `${s.label}: ` : ""}\`${r.modelId}\`${r.op ? ` (${r.op})` : ""}${r.prompt ? ` — “${cut(String(r.prompt), 240)}”` : ""}${waits.length ? `, from the result of ${waits.join(" and ")}` : ""}`;
+}
+
+/** Request fields the `generate` tool's job takes (src/server/assist/tools.ts Job → asRequest), by its name for each. */
+const JOB_INPUTS: Record<string, string> = { images: "images", endImage: "end_image", video: "video", audio: "audio", audio2: "background_audio", voiceAudio: "voice_audio" };
+const JOB_PARAMS: Record<string, string> = {
+ aspectRatio: "aspect_ratio",
+ resolution: "resolution",
+ duration: "duration",
+ numOutputs: "outputs",
+ generateAudio: "generate_audio",
+ voice: "voice",
+ targetLanguage: "target_language",
+ sourceLanguage: "source_language",
+ startTime: "start_time",
+ endTime: "end_time",
+ numLayers: "num_layers",
+};
+/** Request fields that don't change what is made (or that `after` stands for). */
+const JOB_IGNORED = new Set(["feature", "modelId", "op", "prompt", "negativePrompt", "presetId", "inputs", "params", "engine", "chain", "chainFrom", "title", "step"]);
+const LEFT_OUT_WORDS: Record<string, string> = { loras: "its LoRAs", presetOptions: "its preset options", presetStrength: "its preset strength", mix: "its second preset (mix)" };
/**
* The equivalent `generate` call, when every step waits for at most one earlier step (Assist's `after`), with the
- * inputs left as {{id}} for the agent to fill in.
+ * inputs left as {{id}} for the agent to fill in, and what it can't carry (the generate tool has no field for it).
*/
-function generateCall(recipe: Recipe): string | null {
+function generateCall(recipe: Recipe): { json: string; leftOut: string[] } | null {
const steps = recipe.steps as GenerateStep[];
if (steps.some((s) => s.kind !== "generate" || asList(s.after).length > 1)) return null;
const keys = steps.map((s) => s.key);
+ const leftOut = new Set<string>();
const jobs = steps.map((s) => {
- const r = s.request;
+ const r = s.request as Record<string, unknown>;
const p = (r.params ?? {}) as Record<string, unknown>;
const inputs = (r.inputs ?? {}) as Record<string, unknown>;
+ const extra = (p.extra ?? {}) as Record<string, unknown>;
const after = asList(s.after)[0];
+ for (const [k, v] of Object.entries(r)) if (v !== undefined && !JOB_IGNORED.has(k)) leftOut.add(LEFT_OUT_WORDS[k] ?? `\`${k}\``);
+ for (const [k, v] of Object.entries(inputs)) if (v !== undefined && !JOB_INPUTS[k]) leftOut.add(`the input \`${k}\``);
+ for (const [k, v] of Object.entries(p)) if (v !== undefined && !JOB_PARAMS[k] && k !== "extra") leftOut.add(`\`params.${k}\``);
+ for (const k of Object.keys(extra)) if (k !== "system") leftOut.add(`\`params.extra.${k}\``);
return Object.fromEntries(
Object.entries({
model_id: r.modelId,
op: r.op,
prompt: r.prompt,
- images: inputs.images,
- end_image: inputs.endImage,
- video: inputs.video,
- audio: inputs.audio,
- aspect_ratio: p.aspectRatio,
- resolution: p.resolution,
- duration: p.duration,
- outputs: p.numOutputs,
+ negative_prompt: r.negativePrompt,
+ look: r.presetId,
+ ...Object.fromEntries(Object.entries(JOB_INPUTS).map(([k, name]) => [name, inputs[k]])),
+ ...Object.fromEntries(Object.entries(JOB_PARAMS).map(([k, name]) => [name, p[k]])),
+ system: extra.system,
engine: r.engine,
after: after === undefined ? undefined : keys.indexOf(after),
}).filter(([, v]) => v !== undefined),
);
});
- return JSON.stringify({ summary: "…", jobs }, null, 2);
+ return { json: JSON.stringify({ summary: "…", jobs }, null, 2), leftOut: [...leftOut] };
}
+/** The longest Run it section (load_skill, the chat's context, MCP prompts): about the size of a long playbook. */
+export const RECIPE_MARKDOWN_MAX = 20_000;
+
/**
* The "Run it" section for agents (load_skill appends it): the inputs, the steps, and how another agent runs the
* same job with Fuobe's tools: the `run_skill` call (Assist and MCP, W3), else the equivalent `generate` or studio
- * tool call.
+ * tool call. At most RECIPE_MARKDOWN_MAX characters: a call too long to show is left to run_skill.
*/
export function recipeMarkdown(recipe: Recipe, skill?: { name: string }): string {
const keys = recipe.steps.map((s) => s.key);
const tool = recipe.steps.find((s): s is ToolStep => s.kind === "tool");
- const call = tool ? JSON.stringify({ tool: tool.tool, input: tool.input }, null, 2) : generateCall(recipe);
+ const gen = tool ? null : generateCall(recipe);
+ const call = tool ? JSON.stringify({ tool: tool.tool, input: tool.input }, null, 2) : gen?.json;
const values = Object.fromEntries(recipe.params.map((p) => [p.id, `{{${p.id}}}`]));
- return [
- "## Run it",
- "",
- `This skill runs by itself in Fuobe: the same steps with new inputs, priced first, no LLM needed (Skills → ${skill ? `/${skill.name}` : "this skill"} → Run…).`,
- "",
- recipe.params.length ? "**Inputs**" : "It takes no inputs.",
- ...recipe.params.map(paramLine),
- "",
- "**Steps**",
- ...recipe.steps.map((s, i) => stepLine(s, i, keys)),
- "",
- "**From an agent**",
- "",
- `With Fuobe's MCP server, \`run_skill\` runs it with values for the inputs${skill ? `: \`${JSON.stringify({ name: skill.name, values })}\`` : ""}. Where that tool isn't available, ${tool ? `call the studio tool \`${tool.tool}\` the same way` : call ? "make the same `generate` call" : "run the steps with `generate`, in order"}, with the inputs put in for {{id}}${call ? ":" : "."}`,
- ...(call ? ["", "```json", call, "```"] : []),
- "",
- "Price it first with `estimate_cost` (or `estimate_job` for a studio tool) and confirm with the user.",
- ].join("\n");
+ const build = (withCall: boolean) => {
+ const shown = withCall && !!call;
+ const how = tool ? `call the studio tool \`${tool.tool}\` the same way` : call ? "make the same `generate` call" : "run the steps with `generate`, in order";
+ return [
+ "## Run it",
+ "",
+ `This skill runs by itself in Fuobe: the same steps with new inputs, priced first, no LLM needed (Skills → ${skill ? `/${skill.name}` : "this skill"} → Run…).`,
+ "",
+ recipe.params.length ? "**Inputs**" : "It takes no inputs.",
+ ...recipe.params.map(paramLine),
+ "",
+ "**Steps**",
+ ...recipe.steps.map((s, i) => stepLine(s, i, keys)),
+ "",
+ "**From an agent**",
+ "",
+ `With Fuobe's MCP server, \`run_skill\` runs it with values for the inputs${skill ? `: \`${JSON.stringify({ name: skill.name, values })}\`` : ""}. Where that tool isn't available, ${how}, with the inputs put in for {{id}}${shown ? ":" : call ? " (the call is too long to show here)." : "."}`,
+ ...(shown ? ["", "```json", call, "```"] : []),
+ ...(gen?.leftOut.length ? ["", `That call leaves out ${gen.leftOut.join(", ")} (the \`generate\` tool has no field for ${gen.leftOut.length === 1 ? "it" : "them"}), so its result can differ: only \`run_skill\` makes the same thing.`] : []),
+ "",
+ "Price it first with `estimate_cost` (or `estimate_job` for a studio tool) and confirm with the user.",
+ ].join("\n");
+ };
+ const full = build(true);
+ if (full.length <= RECIPE_MARKDOWN_MAX) return full;
+ return cut(build(false), RECIPE_MARKDOWN_MAX);
}
/** "29 Oct" from a stored day. */
@@ -820,6 +866,8 @@ export interface RecipeView {
/** The skill's icon (a lucide name from SKILL_ICONS). */
icon?: string;
builtin: boolean;
+ /** Switched on on the Skills page: a skill that's off doesn't run. */
+ enabled: boolean;
recipe: Recipe;
/** Engines its steps allow on this install. */
engines: RecipeEngine[];
diff --git a/src/server/enhance.ts b/src/server/enhance.ts
index 1a4552d1..d674912a 100644
--- a/src/server/enhance.ts
+++ b/src/server/enhance.ts
@@ -102,6 +102,38 @@ export async function llmText(system: string, user: string, images: LlmImage[] =
return null;
}
+declare global {
+ var __fuobeOllamaVision: Map<string, { sees: boolean; at: number }> | undefined;
+}
+const VISION_TTL_MS = 10 * 60_000;
+
+/**
+ * Whether the LLM llmText would ask (with the same `ollamaOnly`) sees the pictures it is sent: Claude does; an Ollama
+ * model does when Ollama lists "vision" among its capabilities (qwen3-vl, gemma3…). A text-only model, an Ollama too
+ * old to say, or none answering: false, so nothing is judged by a model that only reads the words.
+ */
+export async function llmSeesImages(o: { ollamaOnly?: boolean } = {}): Promise<boolean> {
+ const backend = o.ollamaOnly && llmTextBackend() === "claude" ? "ollama" : llmTextBackend();
+ if (backend === "claude") return true;
+ if (backend !== "ollama") return false;
+ const url = getSetting("ollamaUrl").replace(/\/+$/, "");
+ const model = getSetting("ollamaModel");
+ const key = `${url} ${model}`;
+ const cache = (globalThis.__fuobeOllamaVision ??= new Map());
+ const known = cache.get(key);
+ if (known && Date.now() - known.at < VISION_TTL_MS) return known.sees;
+ try {
+ const res = await fetch(`${url}/api/show`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ model }), signal: AbortSignal.timeout(10_000) });
+ if (!res.ok) return false;
+ const j = (await res.json()) as { capabilities?: unknown };
+ const sees = Array.isArray(j.capabilities) && j.capabilities.includes("vision");
+ cache.set(key, { sees, at: Date.now() });
+ return sees;
+ } catch {
+ return false;
+ }
+}
+
/** Deterministic fallback so the toggle always does something useful offline. */
export function heuristicEnhance(prompt: string, kind: MediaKind, op: Operation): string {
const p = prompt.trim().replace(/[.\s]+$/, "");
diff --git a/src/server/generations.ts b/src/server/generations.ts
index d698ac25..57a9eb32 100644
--- a/src/server/generations.ts
+++ b/src/server/generations.ts
@@ -152,6 +152,24 @@ function update(id: string, fields: Partial<Row>): void {
.run({ ...fields, __now: Date.now(), __id: id });
}
+/**
+ * Set server fields on rows a studio tool made, after it made them (a skill recipe's tool run: the `skill` stamp and the
+ * skill's `batchTitle`), and on every row of their batches (the tool's helper steps). Returns those batches.
+ */
+export function stampRequests(ids: string[], fields: (batches: string[]) => Pick<GenerationRequest, "skill" | "batchTitle">): string[] {
+ if (!ids.length) return [];
+ const marks = (n: number) => Array.from({ length: n }, () => "?").join(", ");
+ const batches = (db().prepare(`SELECT DISTINCT batch_id FROM generations WHERE id IN (${marks(ids.length)}) AND batch_id IS NOT NULL`).all(...ids) as { batch_id: string }[]).map((r) => r.batch_id);
+ const rows = db()
+ .prepare(`SELECT id, request_json FROM generations WHERE id IN (${marks(ids.length)})${batches.length ? ` OR batch_id IN (${marks(batches.length)})` : ""}`)
+ .all(...ids, ...batches) as Pick<Row, "id" | "request_json">[];
+ const set = fields(batches);
+ db().transaction(() => {
+ for (const r of rows) update(r.id, { request_json: JSON.stringify({ ...(JSON.parse(r.request_json) as GenerationRequest), ...set }) });
+ })();
+ return batches;
+}
+
/** One generation; a row in the Trash reads as missing unless `includeDeleted`. */
export function getGeneration(id: string, opts: { includeDeleted?: boolean } = {}): Generation | null {
ensureRunner();
diff --git a/src/server/recipes.ts b/src/server/recipes.ts
index 67aa32c3..5f7584ac 100644
--- a/src/server/recipes.ts
+++ b/src/server/recipes.ts
@@ -41,8 +41,8 @@ import type { Skill } from "@/lib/assist";
import { planSteps } from "./assist/studio-tools";
import { executeTool, getTool, planFor, validateInput } from "./assist/tools";
import { createPipeline } from "./chains";
-import { llmText, llmTextBackend } from "./enhance";
-import { cancelGeneration, createGenerations, currentRequest, getGeneration, previewChained } from "./generations";
+import { llmSeesImages, llmText } from "./enhance";
+import { cancelGeneration, createGenerations, currentRequest, getGeneration, previewChained, stampRequests } from "./generations";
import { trashGenerations } from "./library";
import { isOffered, modelLicence } from "./model-access";
import { GenerationRequestSchema } from "./request-schema";
@@ -194,8 +194,16 @@ interface RunPlan {
total: number | null;
errors: string[];
place?: RecipePlace;
+ /** Every error is only a provider to connect (with Settings → Demo mode off): this install's, not the recipe's. */
+ connectOnly?: boolean;
}
+/**
+ * Whether a run's refusals are all "connect a provider" (chooseRoute's when nothing on a route is connected and Demo
+ * mode is off, and llmMissing's): what only this install lacks, which the demo route may stand in for.
+ */
+export const onlyConnect = (errors: string[]): boolean => errors.length > 0 && errors.every((e) => /^Connect\b/.test(e));
+
/** Price one compiled run the way it would start (planSteps / planFor), with what stops it. */
function planRun(c: Compiled, engine: Engine): RunPlan {
if (c.kind === "tool") {
@@ -204,9 +212,10 @@ function planRun(c: Compiled, engine: Engine): RunPlan {
return { jobs: p.jobs, total: p.total, errors, place: { ...(p.studio && { studio: p.studio }), ...(p.href && { href: p.href }), ...(p.fallback && { fallback: p.fallback }) } };
}
const jobs = planSteps("run_skill", c.steps);
- const errors = jobs.filter((j) => j.error).map((j) => `${j.note && j.note !== j.modelName ? `${j.note} (${j.modelName})` : j.modelName}: ${j.error}`);
+ const failed = jobs.filter((j) => j.error);
+ const errors = failed.map((j) => `${j.note && j.note !== j.modelName ? `${j.note} (${j.modelName})` : j.modelName}: ${j.error}`);
if (!errors.length && !planRunnable(jobs)) errors.push("Nothing to run");
- return { jobs, total: totalCost(jobs), errors };
+ return { jobs, total: totalCost(jobs), errors, connectOnly: failed.length === errors.length && onlyConnect(failed.map((j) => j.error!)) };
}
/** The run with every request on the demo provider: valid and priced the same whether or not a provider is connected. */
@@ -215,14 +224,15 @@ function asDemo(c: Compiled): Compiled {
}
/**
- * The plan check: the run as it would start. When only this install stops it (no provider connected, with Settings →
+ * The plan check: the run as it would start. When the only thing stopping it is a provider to connect (with Settings →
* Demo mode off), the recipe itself is fine: the same run on the demo provider passes it, and the reason is a note.
+ * Any other refusal (a route's image limit, a LoRA a route can't carry…) fails the check: the demo route skips those.
*/
function planCheck(c: Compiled, engine: Engine): RunPlan & { notes: string[] } {
const plan = planRun(c, engine);
- if (!plan.errors.length || c.kind === "tool") return { ...plan, notes: [] };
+ if (!plan.errors.length || c.kind === "tool" || !plan.connectOnly) return { ...plan, notes: [] };
const demo = planRun(asDemo(c), engine);
- return demo.errors.length ? { ...plan, notes: [] } : { ...demo, notes: [...new Set(plan.errors.map((e) => e.replace(/^[^:]+: /, "")))] };
+ return demo.errors.length ? { ...plan, notes: [] } : { ...demo, notes: [...new Set(plan.jobs.flatMap((j) => (j.error ? [j.error] : [])))] };
}
/**
@@ -333,6 +343,7 @@ export function recipeView(name: string): RecipeView {
title: skill.title,
...(skill.icon && { icon: skill.icon }),
builtin: skill.source === "builtin",
+ enabled: skill.enabled,
recipe,
engines,
ready,
@@ -412,11 +423,17 @@ function rowsOf(recipe: Recipe, input: RunInput): { rows: Row[]; errors: string[
};
}
+/** The engine asked for, else the first one its plan check passed on (else the first its steps allow). */
function engineFor(recipe: Recipe, asked: Engine | undefined): Engine {
const engines = recipeEngines(recipe);
if (!engines.length) throw new SkillError(noEngine(recipe), 422);
if (asked && !engines.includes(asked)) throw new SkillError(`This skill doesn't run on ${ENGINE_NAME[asked]}: its steps run on ${engines.map((e) => ENGINE_NAME[e]).join(" or ")}`, 422);
- return asked ?? engines[0];
+ return asked ?? engines.find((e) => !!recipe.verified?.[e]?.plan) ?? engines[0];
+}
+
+/** A skill switched off on the Skills page doesn't run (by its form, a link or the API) until it's switched on. */
+function mustBeOn(skill: Skill): void {
+ if (!skill.enabled) throw new SkillError(`/${skill.name} is switched off — switch it on in Skills to run it`, 409);
}
// ---------------------------------------------------------------------------
@@ -425,6 +442,7 @@ function engineFor(recipe: Recipe, asked: Engine | undefined): Engine {
/** Price one run or many (rows priced together, with a total) on an engine, without starting anything. */
export function estimateRecipe(name: string, input: RunInput, asked?: Engine): RecipeEstimate {
const { skill, recipe } = getRecipe(name);
+ mustBeOn(skill);
const engine = engineFor(recipe, asked);
const { rows, errors } = rowsOf(recipe, input);
let place: RecipePlace | undefined;
@@ -453,16 +471,31 @@ export function estimateRecipe(name: string, input: RunInput, asked?: Engine): R
};
}
+/**
+ * A studio tool makes its own requests: once it has, they get the run's stamp and the skill's title as their batch's
+ * name, as a pipeline's are given when compiled. The run is the tool's batch (else `run`), which is returned.
+ */
+function stampToolRun(skill: { name: string; title: string }, ids: string[], run: string): string | undefined {
+ let batch: string | undefined;
+ stampRequests(ids, (batches) => {
+ batch = batches[0];
+ return { skill: { name: skill.name, run: batch ?? run }, batchTitle: skill.title.slice(0, 200) };
+ });
+ return batch;
+}
+
/**
* Run a recipe once or once per row on an engine whose plan check passed. Every row is validated and priced first:
* one bad row starts nothing. A pipeline is one createPipeline per row; a tool recipe one executeTool call per row.
*/
export async function runRecipe(name: string, input: RunInput, asked?: Engine): Promise<{ engine: Engine; runs: RecipeRun[]; demo: boolean }> {
const { skill, recipe } = getRecipe(name);
+ mustBeOn(skill);
const engine = engineFor(recipe, asked);
if (!recipe.verified?.[engine]?.plan) throw new SkillError(`Check this skill on ${ENGINE_NAME[engine]} first — the check is free`, 409);
const { rows, errors } = rowsOf(recipe, input);
if (errors.length) throw new RecipeError(errors);
+ if (!rows.length) throw new RecipeError(["Add a row to run"]);
const bad = rows.flatMap((r) => (r.errors.length ? [`${rows.length > 1 ? `Row ${r.line}: ` : ""}${r.errors.join("; ")}`] : []));
if (bad.length) throw new RecipeError(bad);
// Compile and price every row before anything starts.
@@ -476,7 +509,7 @@ export async function runRecipe(name: string, input: RunInput, asked?: Engine):
const runs: RecipeRun[] = [];
let demo = true;
if (compiled[0].c.kind === "tool") {
- for (const { c } of compiled) {
+ for (const { run, c } of compiled) {
if (c.kind !== "tool") continue;
const out = await executeTool(c.tool, c.input, { engine });
const text = typeof out.content === "string" ? out.content : "";
@@ -494,8 +527,9 @@ export async function runRecipe(name: string, input: RunInput, asked?: Engine):
href = undefined;
}
const ids = (out.items ?? []).flatMap((i) => (i.role === "generations" ? i.ids : []));
+ const batchId = stampToolRun(skill, ids, run);
demo &&= ids.every((id) => getGeneration(id)?.provider === "mock");
- runs.push({ ids, ...(href && { href }) });
+ runs.push({ ...(batchId && { batchId }), ids, ...(href && { href }) });
}
if (!runs.some((r) => !r.error)) throw new SkillError(runs[0]?.error ?? "Nothing could start", 422);
return { engine, runs, demo };
@@ -522,6 +556,12 @@ export async function runRecipe(name: string, input: RunInput, asked?: Engine):
export type VerifyLevel = "plan" | "demo" | "real";
+/** Whether two recipes are the same but for what was checked (`verified`). */
+const sameRecipe = (a: Recipe, b: Recipe) => {
+ const bare = (r: Recipe) => JSON.stringify({ ...r, verified: undefined });
+ return bare(a) === bare(b);
+};
+
const TERMINAL = new Set(["succeeded", "failed", "canceled"]);
/** Wait for generations to finish (the runner moves them), at most `ms`; cancels what's left when time runs out. */
@@ -584,15 +624,21 @@ async function infoOf(url: string, kind: MediaKind): Promise<MediaInfo | null> {
}
}
-/** Whether a picture shows a sentence, by a model that sees images; null when none answers. */
-async function judgeLook(look: string, image: string): Promise<boolean | null> {
- if (!llmTextBackend()) return null;
+/**
+ * Whether a picture shows a sentence, judged only by a model that sees images (llmSeesImages): null when there is none
+ * (a text-only model would answer from the words alone) or it doesn't answer. On the open engine only a local model is
+ * asked, as everywhere the open engine runs: never a paid API.
+ */
+async function judgeLook(look: string, image: string, engine: Engine): Promise<boolean | null> {
+ const local = { ollamaOnly: engine === "open" };
+ if (!(await llmSeesImages(local))) return null;
try {
const f = await readRef(image);
const answer = await llmText(
"You check whether a picture matches a short description. Answer yes or no first, then one short reason.",
`Description: ${look}`,
[{ data: f.data, contentType: f.contentType }],
+ local,
);
if (!answer) return null;
return /^\W*yes\b/i.test(answer) ? true : /^\W*no\b/i.test(answer) ? false : null;
@@ -625,6 +671,7 @@ async function realRun(skill: Skill, recipe: Recipe, engine: Engine): Promise<No
const out = await executeTool(c.tool, c.input, { engine });
if (out.isError) return { ok: false, problems: [typeof out.content === "string" ? out.content : "The tool couldn't start"], notes, demo: false };
const ids = (out.items ?? []).flatMap((i) => (i.role === "generations" ? i.ids : []));
+ stampToolRun(skill, ids, nanoid(10));
made = await settle(ids, REAL_RUN_MS);
if (ids.length) byKey = { [c.key]: ids[0] };
} else {
@@ -652,7 +699,7 @@ async function realRun(skill: Skill, recipe: Recipe, engine: Engine): Promise<No
const clip = still ? undefined : g!.outputs.find((o) => o.kind === "video")?.url;
const frame = clip ? await frameOf(clip, engine) : { url: still, ids: [] };
helpers.push(...frame.ids);
- const verdict = frame.url ? await judgeLook(check.look, frame.url) : null;
+ const verdict = frame.url ? await judgeLook(check.look, frame.url, engine) : null;
if (verdict === false) problems.push(`Step “${key}” doesn't look like “${check.look}”`);
else if (verdict === null) notes.push(`Step “${key}”: the look wasn't judged (no model that sees images${clip && engine === "open" ? ", and no frame extractor on your GPU" : ""})`);
}
@@ -722,7 +769,12 @@ export async function verifyRecipe(name: string, level: VerifyLevel, asked?: Eng
verified[e] = next;
checks.push(check);
}
- saveRecipe(name, { ...recipe, verified }, { keepVerified: true });
+ // A check takes a while (a dry run, a real test): a recipe saved or uploaded meanwhile is never overwritten, and what
+ // was checked is never written onto it. Checks of other engines that finished meanwhile are kept.
+ const now = getRecipe(name).recipe;
+ if (!sameRecipe(now, found.recipe)) throw new SkillError("The recipe changed while it was being checked — check it again", 409);
+ const merged: NonNullable<Recipe["verified"]> = { ...now.verified, ...Object.fromEntries(engines.map((e) => [e, verified[e] ?? null])) };
+ saveRecipe(name, { ...recipe, verified: merged }, { keepVerified: true });
const ok = checks.every((c) => c.plan.ok && (c.dryRun?.ok ?? true) && (c.real?.ok ?? true));
return { ok, engines: checks, view: recipeView(name) };
}
diff --git a/src/server/skills.ts b/src/server/skills.ts
index 761ba220..c5c6ac00 100644
--- a/src/server/skills.ts
+++ b/src/server/skills.ts
@@ -2,7 +2,7 @@ import "server-only";
import fs from "node:fs";
import path from "node:path";
import { parseSkillMd, SKILL_LIMITS, SKILL_NAME_RE, toSkillMd, type Skill, type SkillMeta, type SkillSummary } from "@/lib/assist";
-import { parseRecipe, RECIPE_FILE, stripExamples, type Recipe } from "@/lib/recipe";
+import { parseRecipe, RECIPE_FILE, stripChecks, stripExamples, type Recipe } from "@/lib/recipe";
import { unzip, ZipError } from "./assist/unzip";
import { db } from "./db";
import { zip } from "./zip";
@@ -207,17 +207,17 @@ export function setSkillFile(name: string, file: string, content: string | null)
}
/**
- * The skill with its files as a .zip (one folder, as importSkill reads it). A recipe's examples, source and checks
- * stay home unless `examples` (they name this install's files, faces and words); files fixed in its steps become
- * inputs the other install asks for (stripExamples).
+ * The skill with its files as a .zip (one folder, as importSkill reads it). A recipe's examples and source stay home
+ * unless `examples` (they name this install's files, faces and words), and files fixed in its steps become inputs the
+ * other install asks for (stripExamples). Its checks never travel: they were this install's (stripChecks).
*/
export function skillArchive(name: string, o: { examples?: boolean } = {}): Buffer | null {
const s = getSkill(name);
if (!s) return null;
const files = skillFiles(name).map((f) => {
- if (f.path !== RECIPE_FILE || o.examples) return f;
+ if (f.path !== RECIPE_FILE) return f;
const parsed = parseRecipe(f.content);
- return parsed.ok ? { ...f, content: `${JSON.stringify(stripExamples(parsed.recipe), null, 2)}\n` } : f;
+ return parsed.ok ? { ...f, content: `${JSON.stringify(o.examples ? stripChecks(parsed.recipe) : stripExamples(parsed.recipe), null, 2)}\n` } : f;
});
return zip([{ name: `${name}/SKILL.md`, data: Buffer.from(toSkillMd(s)) }, ...files.map((f) => ({ name: `${name}/${f.path}`, data: Buffer.from(f.content) }))]);
}
@@ -354,9 +354,7 @@ export function setSkillEnabled(name: string, enabled: boolean): Skill {
function unverified(text: string): string {
const parsed = parseRecipe(text);
if (!parsed.ok || !parsed.recipe.verified) return text;
- const r: Recipe = { ...parsed.recipe };
- delete r.verified;
- return `${JSON.stringify(r, null, 2)}\n`;
+ return `${JSON.stringify(stripChecks(parsed.recipe), null, 2)}\n`;
}
export interface ImportResult {
diff --git a/tests/assist-skills.test.ts b/tests/assist-skills.test.ts
index d8f9ab3b..f4e631de 100644
--- a/tests/assist-skills.test.ts
+++ b/tests/assist-skills.test.ts
@@ -379,6 +379,8 @@ describe("skills on the server", () => {
// &examples=1 keeps them (and the source), but never this install's checks.
const full = JSON.parse(unzip(skills.skillArchive("lamp-turntable", { examples: true })!).find((e) => e.name.endsWith("recipe.json"))!.data.toString("utf8"));
expect(full).toMatchObject({ params: [{ example: "/api/files/uploads/2026-10-20/lamp.png" }], source: { from: "library" } });
+ expect(full.verified).toBeUndefined();
+ expect(JSON.stringify(full)).not.toContain("sha256:abc");
// Round trip: Upload reads the zip back, with its recipe (an uploaded recipe is never "checked" here).
const back = skills.importSkill({ name: "lamp-turntable.zip", data: skills.skillArchive("lamp-turntable", { examples: true })! }, { replace: true });
expect(back.skill).toMatchObject({ name: "lamp-turntable", recipe: true, files: expect.arrayContaining([expect.objectContaining({ path: "recipe.json" }), expect.objectContaining({ path: "notes.md" })]) });
diff --git a/tests/recipe.test.ts b/tests/recipe.test.ts
index 49c72f5b..48d80383 100644
--- a/tests/recipe.test.ts
+++ b/tests/recipe.test.ts
@@ -11,9 +11,11 @@ import {
parseRecipe,
parseRows,
RECIPE_LIMITS,
+ RECIPE_MARKDOWN_MAX,
recipeMarkdown,
recipeProblems,
RecipeSchema,
+ stripChecks,
stripExamples,
valuesSchema,
verifiedLine,
@@ -159,6 +161,14 @@ describe("values", () => {
expect(checkValues(r, { product: "https://example.com/a.jpg", name: "Lamp", takes: "0" }).errors.takes).toBe("Takes: at least 1");
});
+ it("reads a number as it is being typed: “0.” and “.5” are numbers, words aren't", () => {
+ const strength = RecipeSchema.parse({ ...r, params: [{ id: "s", label: "Strength", type: "number", min: 0, max: 1, step: 0.1, default: 0.5 }], steps: [{ key: "a", kind: "generate", request: { feature: "skill", modelId: "m", prompt: "x", params: { extra: { s: "{{s}}" } } } }] });
+ expect(checkValues(strength, { s: "0." }).values).toEqual({ s: 0 });
+ expect(checkValues(strength, { s: ".5" }).values).toEqual({ s: 0.5 });
+ expect(checkValues(strength, { s: "0.75" }).values).toEqual({ s: 0.75 });
+ expect(checkValues(strength, { s: "a lot" }).errors.s).toBe("Strength: a number");
+ });
+
it("reads text from a form or a CSV: numbers as numbers, choices without minding case, @handles", () => {
const withEl = RecipeSchema.parse({ ...r, params: [...r.params, { id: "hero", label: "Hero", type: "element", required: true }] });
const ok = checkValues(withEl, { product: "/api/files/a.png", name: "Lamp", takes: "3", aspect: "16:9", hero: "Maya_Lopez" });
@@ -274,6 +284,10 @@ describe("rows from a CSV", () => {
expect(parseRows("name\nLamp", r).errors).toEqual(["No column for “Product photo”"]);
expect(parseRows("", r).errors[0]).toMatch(/Paste a table/);
expect(parseRows("foo,bar\n1,2", r).errors[0]).toMatch(/names no input/);
+ // A header and no rows: nothing to run, said as such (not "fix the rows").
+ const empty = parseRows("product,name\n\n", r);
+ expect(empty.rows).toEqual([]);
+ expect(empty.errors).toEqual(["Add a row under the header: one row per run"]);
});
it("takes at most 50 rows, as a Canvas table does", () => {
@@ -325,6 +339,11 @@ describe("sharing and reading", () => {
expect(s.params.at(-1)).toEqual({ id: "file_1", label: "Audio for “Turntable”", type: "audio", required: true });
expect(JSON.stringify(s.steps)).not.toContain("/api/files/");
expect(recipeProblems(s)).toEqual([]);
+ // Kept with its examples (a backup): only this install's checks are left out.
+ const kept = stripChecks(withLogo);
+ expect(kept.verified).toBeUndefined();
+ expect(kept.params[0].example).toBe("/api/files/uploads/2026-10-20/lamp.png");
+ expect(kept.source).toEqual(withLogo.source);
});
it("writes a Run it section with the inputs, the steps and the equivalent generate call", () => {
@@ -336,6 +355,39 @@ describe("sharing and reading", () => {
expect(md).toContain('"model_id": "kling-3"');
expect(md).toContain('"after": 1');
expect(md).toContain("run_skill");
+ expect(md).not.toContain("leaves out");
+ });
+
+ it("puts a look, a negative prompt and a voice into the generate call, and says what it can't carry", () => {
+ const soul = RecipeSchema.parse({
+ fuobeRecipe: 1,
+ params: [{ id: "subject", label: "Subject", type: "text", required: true }],
+ steps: [
+ {
+ key: "portrait",
+ kind: "generate",
+ request: { feature: "skill", modelId: "fuobe-soul", presetId: "v1-y2k", prompt: "{{subject}}", negativePrompt: "blurry", params: { aspectRatio: "4:5", seed: 7, generateAudio: false }, loras: [{ file: "maya.safetensors", strength: 0.8 }] },
+ },
+ ],
+ });
+ const md = recipeMarkdown(soul, { name: "soul" });
+ expect(md).toContain('"look": "v1-y2k"');
+ expect(md).toContain('"negative_prompt": "blurry"');
+ expect(md).toContain('"generate_audio": false');
+ expect(md).toContain("That call leaves out its LoRAs, `params.seed` (the `generate` tool has no field for them)");
+ });
+
+ it("keeps the Run it section to a few pages, whatever the recipe holds", () => {
+ const long = "word ".repeat(1900);
+ const big = RecipeSchema.parse({
+ fuobeRecipe: 1,
+ params: Array.from({ length: 12 }, (_, i) => ({ id: `p${i}`, label: `Input ${i}`, type: "choice", options: Array.from({ length: 24 }, (_, j) => `option ${j} ${"x".repeat(60)}`), hint: "h".repeat(200) })),
+ steps: Array.from({ length: 24 }, (_, i) => ({ key: `s${i}`, kind: "generate", request: { feature: "skill", modelId: "fuobe-soul", prompt: `${long} {{p${i % 12}}}` } })),
+ });
+ const md = recipeMarkdown(big, { name: "big" });
+ expect(md.length).toBeLessThanOrEqual(RECIPE_MARKDOWN_MAX);
+ expect(md).toContain("the call is too long to show here");
+ expect(md).toContain("**Steps**");
});
it("says when and where it was checked", () => {
diff --git a/tests/recipes.test.ts b/tests/recipes.test.ts
index ccc37ef8..f2c0907c 100644
--- a/tests/recipes.test.ts
+++ b/tests/recipes.test.ts
@@ -1,4 +1,6 @@
import fs from "node:fs";
+import http from "node:http";
+import type { AddressInfo } from "node:net";
import os from "node:os";
import path from "node:path";
import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
@@ -222,6 +224,48 @@ describe("running a recipe", () => {
expect(out.runs[0].href).toMatch(/^\/video-tools\/captions\?video=/);
expect(out.runs[0].ids.length).toBeGreaterThan(0);
expect(gens.getGeneration(out.runs[0].ids[0])).toMatchObject({ op: "captions" });
+ // The tool made its own requests: each one in its batch (the transcript too) carries the run's stamp and the
+ // skill's title, as a pipeline's do, so the Library groups the run and its history reads back.
+ const batch = out.runs[0].batchId!;
+ expect(batch).toBeTruthy();
+ const made = db().prepare("SELECT request_json FROM generations WHERE batch_id = ?").all(batch) as { request_json: string }[];
+ expect(made.length).toBeGreaterThanOrEqual(out.runs[0].ids.length);
+ for (const r of made) expect(JSON.parse(r.request_json)).toMatchObject({ skill: { name: "caption-it", run: batch }, batchTitle: "Caption it" });
+ });
+
+ it("a header with no rows is refused with the reason, not a crash", async () => {
+ const res = await runRoute.POST(json({ csv: "product,name\n" }), ctx("lamp"));
+ expect(res.status).toBe(422);
+ expect(await res.json()).toMatchObject({ error: "Add a row under the header: one row per run" });
+ expect(recipes.estimateRecipe("lamp", { csv: "product,name\n" })).toMatchObject({ runnable: false, errors: ["Add a row under the header: one row per run"] });
+ await expect(recipes.runRecipe("lamp", { rows: [] })).rejects.toThrow(/Add a row to run/);
+ });
+
+ it("without an engine, runs where it was checked", async () => {
+ makeSkill("gpu-only", soul(), "GPU only");
+ await recipes.verifyRecipe("gpu-only", "plan", "open");
+ expect(recipes.recipeView("gpu-only").ready).toEqual(["open"]);
+ expect(recipes.estimateRecipe("gpu-only", { values: { subject: "a potter" } }).engine).toBe("open");
+ const out = await recipes.runRecipe("gpu-only", { values: { subject: "a potter" } });
+ expect(out.engine).toBe("open");
+ expect(gens.getGeneration(out.runs[0].ids[0])).toMatchObject({ engine: "open" });
+ // Asked for the cloud, it still says to check it there first.
+ await expect(recipes.runRecipe("gpu-only", { values: { subject: "a potter" } }, "cloud")).rejects.toThrow(/Check this skill on the cloud first/);
+ });
+
+ it("a skill switched off doesn't run until it's switched on", async () => {
+ skills.setSkillEnabled("gpu-only", false);
+ try {
+ expect(recipes.recipeView("gpu-only").enabled).toBe(false);
+ const before = count();
+ await expect(recipes.runRecipe("gpu-only", { values: { subject: "a potter" } })).rejects.toThrow(/switched off — switch it on in Skills/);
+ expect(() => recipes.estimateRecipe("gpu-only", { values: { subject: "a potter" } })).toThrow(/switched off/);
+ expect((await runRoute.POST(json({ values: { subject: "a potter" } }), ctx("gpu-only"))).status).toBe(409);
+ expect(count()).toBe(before);
+ } finally {
+ skills.setSkillEnabled("gpu-only", true);
+ }
+ expect(recipes.recipeView("gpu-only").enabled).toBe(true);
});
});
@@ -300,6 +344,72 @@ describe("checking a recipe", () => {
expect(recipes.recipeView("lamp").recheck.cloud).toEqual(["The models, routes or prices it uses changed since it was checked"]);
});
+ it("never writes a check over a recipe saved while it ran, and keeps checks that finished meanwhile", async () => {
+ makeSkill("race", soul(), "Race");
+ // The dry run waits for its rows: the recipe is edited (a PUT, an upload) before it ends.
+ const checking = recipes.verifyRecipe("race", "demo", "open");
+ const edited = { ...soul(), params: [{ ...soul().params[0], example: "a baker at dawn" }] };
+ recipes.saveRecipe("race", edited);
+ await expect(checking).rejects.toThrow(/changed while it was being checked/);
+ const stored = JSON.parse(skills.skillFile("race", "recipe.json")!);
+ expect(stored.params[0].example).toBe("a baker at dawn");
+ expect(stored.verified).toBeUndefined();
+ // A check of the other engine that ends meanwhile only adds what it checked: both are kept.
+ const open = recipes.verifyRecipe("race", "demo", "open");
+ await recipes.verifyRecipe("race", "plan", "cloud");
+ const r = await open;
+ expect(r.view.recipe.verified).toMatchObject({ cloud: { plan: today() }, open: { plan: today(), dryRun: today() } });
+ });
+
+ it("only falls back to the demo route when a provider to connect is all that stops a run", () => {
+ expect(recipes.onlyConnect(["Connect fal.ai or Replicate in Settings to run this model"])).toBe(true);
+ expect(recipes.onlyConnect(["Connect Ollama in Settings to run this model (open-source text runs on your own machine)"])).toBe(true);
+ expect(recipes.onlyConnect(["This model takes up to 3 images on fal.ai — remove some"])).toBe(false);
+ expect(recipes.onlyConnect(["Connect fal.ai in Settings to run this model", "Fuobe Try-On runs with the LoRA “Try-On”, which this run leaves out. Pick another model or engine"])).toBe(false);
+ expect(recipes.onlyConnect([])).toBe(false);
+ });
+
+ it("judges a look only with a model that sees images, and on the GPU never with a paid one", async () => {
+ let vision = false;
+ let asked = 0;
+ const ollama = http.createServer((req, res) => {
+ req.resume();
+ req.on("end", () => {
+ res.setHeader("Content-Type", "application/json");
+ if (req.url === "/api/show") return res.end(JSON.stringify({ capabilities: vision ? ["completion", "vision"] : ["completion"] }));
+ if (req.url === "/api/chat") {
+ asked++;
+ return res.end(JSON.stringify({ message: { content: "No — a grey square, no one at a wheel." } }));
+ }
+ res.statusCode = 404;
+ res.end("{}");
+ });
+ });
+ await new Promise<void>((r) => ollama.listen(0, "127.0.0.1", () => r()));
+ setSetting("ollamaUrl", `http://127.0.0.1:${(ollama.address() as AddressInfo).port}`);
+ setSetting("enhanceProvider", "ollama");
+ try {
+ makeSkill("looked", { ...soul(), checks: { portrait: { kind: "image", look: "a ceramicist at her wheel" } } }, "Looked");
+ // A text-only model would answer from the words alone: the look isn't judged, and the test doesn't fail on it.
+ let r = await recipes.verifyRecipe("looked", "real", "open", { confirm: true });
+ expect(asked).toBe(0);
+ expect(r.engines[0].real).toMatchObject({ ok: true, notes: expect.arrayContaining([expect.stringContaining("the look wasn't judged")]) });
+ // A model that sees images judges it; with a Claude key set and the helper on auto, the GPU still asks Ollama.
+ vision = true;
+ globalThis.__fuobeOllamaVision?.clear();
+ setSetting("enhanceProvider", "auto");
+ setSetting("anthropicKey", "sk-ant-test");
+ r = await recipes.verifyRecipe("looked", "real", "open", { confirm: true });
+ expect(asked).toBe(1);
+ expect(r.engines[0].real).toMatchObject({ ok: false, problems: ["Step “portrait” doesn't look like “a ceramicist at her wheel”"] });
+ } finally {
+ setSetting("anthropicKey", "");
+ setSetting("enhanceProvider", "none");
+ setSetting("ollamaUrl", "");
+ ollama.close();
+ }
+ });
+
it("a real test asks first, and measures what it made", async () => {
await expect(recipes.verifyRecipe("lamp-unchecked", "real")).rejects.toThrow(/confirm it with its price first/);
const r = await recipes.verifyRecipe("lamp-unchecked", "real", undefined, { confirm: true });