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.

Canvas: a skill's settings and empty words survive Save back, and a swapped model gets a check that fits it

Claude3baadb01c06e
diff --git a/src/components/skills/skill-builder.tsx b/src/components/skills/skill-builder.tsx
index 6a62a4f2..efbba5c6 100644
--- a/src/components/skills/skill-builder.tsx
+++ b/src/components/skills/skill-builder.tsx
@@ -309,14 +309,14 @@ function Review({ draft, refusals, source, onClose, onSaved, header }: { draft:
)}
<div className="grid gap-3 sm:grid-cols-[minmax(0,1fr)_minmax(0,1fr)]">
<Field label="Title" id="sb-title">
- <Input id="sb-title" value={title} maxLength={SKILL_LIMITS.title} onChange={(e) => setTitle(e.target.value)} />
+ <Input id="sb-title" value={title} maxLength={SKILL_LIMITS.title} onChange={(e) => setTitle(e.target.value)} disabled={replace} />
</Field>
<Field label="Name" id="sb-name" hint="Run it as /name in Assist">
<div className="flex items-center rounded-md border bg-background pl-2.5 focus-within:border-ring focus-within:ring-[3px] focus-within:ring-ring/50">
<span className="text-[14px] text-muted-foreground">/</span>
<input
id="sb-name"
- value={name}
+ value={replace && draft.replaces ? draft.replaces.name : name}
maxLength={SKILL_LIMITS.name}
onChange={(e) => setName(e.target.value.toLowerCase().replace(/[^a-z0-9-]/g, "-"))}
onBlur={() => setName((n) => slugify(n) || draft.name)}
@@ -328,10 +328,10 @@ function Review({ draft, refusals, source, onClose, onSaved, header }: { draft:
</Field>
</div>
<Field label="Description" id="sb-desc">
- <Textarea id="sb-desc" rows={2} value={description} maxLength={SKILL_LIMITS.description} onChange={(e) => setDescription(e.target.value)} />
+ <Textarea id="sb-desc" rows={2} value={description} maxLength={SKILL_LIMITS.description} onChange={(e) => setDescription(e.target.value)} disabled={replace} />
</Field>
<Field label="When to use it" id="sb-when">
- <Textarea id="sb-when" rows={2} value={whenToUse} maxLength={SKILL_LIMITS.whenToUse} onChange={(e) => setWhenToUse(e.target.value)} />
+ <Textarea id="sb-when" rows={2} value={whenToUse} maxLength={SKILL_LIMITS.whenToUse} onChange={(e) => setWhenToUse(e.target.value)} disabled={replace} />
</Field>
<Collapsible className="overflow-hidden rounded-xl border">
<CollapsibleTrigger className="group flex w-full items-center gap-2 px-4 py-2.5 text-left text-[13px] font-medium hover:bg-accent">
@@ -660,6 +660,12 @@ function Words({ c, varies, slots, setSlots, takenIds }: { c: DraftCandidate; va
setSlotLabel("");
setTyping(false);
};
+ if (varies && c.kept) {
+ return <p className="mt-2 rounded-lg bg-muted/60 px-3 py-2 text-[12px] text-muted-foreground">These words are an input, asked for in the Run form.</p>;
+ }
+ if (c.kept) {
+ return <p className="mt-2 rounded-lg bg-muted/60 px-3 py-2 text-[12px] text-muted-foreground">Fixed leaves these words empty in the skill.</p>;
+ }
if (varies) {
return <p className="mt-2 line-clamp-3 rounded-lg bg-muted/60 px-3 py-2 text-[12px] break-words text-muted-foreground">{c.part ? "These words are an input" : "The whole prompt is an input"}. Was: “{text}”</p>;
}
diff --git a/src/lib/catalog/canvas.ts b/src/lib/catalog/canvas.ts
index a32da8c5..76ab7a51 100644
--- a/src/lib/catalog/canvas.ts
+++ b/src/lib/catalog/canvas.ts
@@ -2577,6 +2577,11 @@ export interface SkillStepMark {
/** Request fields the board doesn't hold (LoRAs, a preset, a negative prompt), and settings it has no field for. */
extra?: Record<string, unknown>;
check?: RecipeCheck;
+ /**
+ * Settings inputs (a number or a choice) by the setting they fill: the node shows the value, and the way back puts the
+ * input there again while the node keeps its model and a value the input takes. `at`: its place in the form.
+ */
+ settings?: Record<string, { param: RecipeParam; at: number }>;
/** The skill it was drawn from (Save as skill offers to save it back). */
from?: string;
}
@@ -2643,18 +2648,32 @@ function ownWords(prompt: string, texts: Set<string>): { own: string; order: str
/**
* A recipe skill drawn as a board: each input an input node, each generate step a model node (on its model, op,
* words and settings), each chain slot an edge into the port it fills. Only when every slot maps to a port (prompt,
- * images, endImage, video, videos, audio, voice ↔ voiceAudio): a recipe with a studio step, a settings input (a number
- * or a choice), `audio2`, `audios`, `model3d` or `mask`, or a chain slot with a stem, an index or a position isn't
- * drawn. The drawing is read back (canvasToRecipe) before it's offered: what wouldn't come back the same isn't drawn.
+ * images, endImage, video, videos, audio, voice ↔ voiceAudio): a recipe with a studio step, `audio2`, `audios`,
+ * `model3d` or `mask`, a chain slot with a stem, an index or a position, or a settings input (a number or a choice)
+ * that isn't a whole setting with a value isn't drawn. A settings input rides on the nodes it fills (data.skill.settings). The drawing is read back (canvasToRecipe) before it's offered: what wouldn't come back the same isn't drawn.
*/
export function recipeToCanvas(recipe: Recipe, opts: { elements?: readonly ElementInfo[]; from?: string } = {}): RecipeDrawing {
const refuse = (detail: string, studio?: string): RecipeDrawing => ({ ok: false, reason: CANT_DRAW, detail, ...(studio && { studio }) });
const tool = recipe.steps.find((s): s is Extract<RecipeStep, { kind: "tool" }> => s.kind === "tool");
if (tool) return refuse("It runs one studio step, which shows as a note: open it from Skills", tool.tool);
- const settings = recipe.params.filter((p) => p.type === "number" || p.type === "choice");
- if (settings.length) return refuse(`A canvas has no node for ${words(settings.map((p) => p.label))} yet`);
const params = new Map(recipe.params.map((p) => [p.id, p]));
const steps = recipe.steps as GenerateStep[];
+ // A settings input (a number or a choice) rides on the nodes whose settings it fills: each node shows its value and
+ // keeps the input for the way back. It must be a whole setting (params.<name>) with a value to show.
+ const isSetting = (p: RecipeParam | undefined) => p?.type === "number" || p?.type === "choice";
+ const settingAt = (r: GenerationRequest): Map<string, RecipeParam> => {
+ const out = new Map<string, RecipeParam>();
+ for (const [k, v] of Object.entries((r.params ?? {}) as Record<string, unknown>)) {
+ const ph = typeof v === "string" ? EXACT_PH.exec(v) : null;
+ if (ph && isSetting(params.get(ph[1]))) out.set(k, params.get(ph[1])!);
+ }
+ return out;
+ };
+ const placedSettings = new Set(steps.flatMap((s) => [...settingAt(s.request).values()].map((p) => p.id)));
+ const loose = recipe.params.filter((p) => isSetting(p) && !placedSettings.has(p.id));
+ if (loose.length) return refuse(`A canvas has no node for ${words(loose.map((p) => p.label))} yet`);
+ const blank = recipe.params.filter((p) => isSetting(p) && (p.example ?? p.default) == null);
+ if (blank.length) return refuse(`Give ${words(blank.map((p) => p.label))} a default first: a canvas draws a setting with its value`);
const keys = new Set(steps.map((s) => s.key));
for (const s of steps) {
const r = s.request;
@@ -2675,6 +2694,10 @@ export function recipeToCanvas(recipe: Recipe, opts: { elements?: readonly Eleme
if (found.some((f) => !f.exact || !params.has(f.id) || !["image", "video", "audio"].includes(params.get(f.id)!.type))) return refuse(`“${name}” takes a file input a canvas can't wire yet`);
} else if (k === "prompt") {
if (found.some((f) => !params.has(f.id) || !["text", "element"].includes(params.get(f.id)!.type))) return refuse(`“${name}” puts an input into its words that a canvas can't draw yet`);
+ } else if (k === "params") {
+ const whole = settingAt(r);
+ const rest = Object.fromEntries(Object.entries(v as Record<string, unknown>).filter(([pk]) => !whole.has(pk)));
+ if (placeholdersIn(rest).length) return refuse(`An input changes “${name}”'s settings, which a canvas can't draw yet`);
} else return refuse(`An input changes “${name}”'s settings, which a canvas can't draw yet`);
}
}
@@ -2706,7 +2729,12 @@ export function recipeToCanvas(recipe: Recipe, opts: { elements?: readonly Eleme
}
const boardParams: GenParams = {};
const extraParams: Record<string, unknown> = {};
- for (const [k, v] of Object.entries((r.params ?? {}) as Record<string, unknown>)) {
+ const stepSettings = settingAt(r);
+ const settingMarks: NonNullable<SkillStepMark["settings"]> = {};
+ for (const [k, raw] of Object.entries((r.params ?? {}) as Record<string, unknown>)) {
+ const setting = stepSettings.get(k);
+ const v = setting ? (setting.example ?? setting.default) : raw;
+ if (setting) settingMarks[k] = { param: setting, at: recipe.params.indexOf(setting) };
const scalar = k === "extra" && v && typeof v === "object" && Object.values(v).every((x) => ["string", "number", "boolean"].includes(typeof x));
if (BOARD_PARAMS.has(k) || scalar) (boardParams as Record<string, unknown>)[k] = v;
else extraParams[k] = v;
@@ -2720,7 +2748,8 @@ export function recipeToCanvas(recipe: Recipe, opts: { elements?: readonly Eleme
...(r.feature !== "skill" && { feature: r.feature }),
modelId: model.id,
...(Object.keys(extra).length && { extra }),
- ...(recipe.checks?.[s.key] && { check: recipe.checks[s.key] }),
+ ...(recipe.checks?.[s.key] && { check: { ...recipe.checks[s.key] } }),
+ ...(Object.keys(settingMarks).length && { settings: settingMarks }),
...(opts.from && { from: opts.from }),
};
const id = `step-${s.key}`.slice(0, 80);
@@ -2839,6 +2868,12 @@ export interface CanvasRecipe {
nodes: Record<string, string>;
}
+/** A value a settings input takes: one of a choice's options, a number in its range. */
+function settingFits(p: RecipeParam, v: unknown): boolean {
+ if (p.type === "choice") return typeof v === "string" && (!p.options || p.options.includes(v));
+ return typeof v === "number" && Number.isFinite(v) && (p.min === undefined || v >= p.min) && (p.max === undefined || v <= p.max);
+}
+
const nodeValue = (n: CanvasNode): string =>
n.type === "prompt" ? (n.data.text ?? "") : n.type === "element" ? (n.data.handle ? `@${n.data.handle}` : "") : (n.data.url ?? "");
const INPUT_TYPE: Partial<Record<CanvasNodeType, "text" | "image" | "video" | "audio" | "element">> = { prompt: "text", "image-input": "image", "video-input": "video", "audio-input": "audio", "clone-voice": "audio", element: "element" };
@@ -2946,6 +2981,7 @@ export function canvasToRecipe(graph: CanvasGraph, page: { canvas?: string } = {
};
const steps: GenerateStep[] = [];
const checks: Record<string, RecipeCheck> = {};
+ const settingParams = new Map<string, { p: RecipeParam; at: number }>();
const stepNodes: Record<string, string> = {};
const fromSkills = new Set<string>();
/** A chain slot's position only where it matters: before the step's own files in that list ("last" is the default). */
@@ -2977,6 +3013,18 @@ export function canvasToRecipe(graph: CanvasGraph, page: { canvas?: string } = {
Object.assign(out, rest);
if (params) out.params = { ...out.params, ...params } as GenParams;
}
+ // Settings inputs come back where the node still has the model and a value the input takes (else the value stays).
+ if (main && mark?.settings && mark.modelId === req.modelId) {
+ for (const [k, { param, at }] of Object.entries(mark.settings)) {
+ const v = (out.params as Record<string, unknown> | undefined)?.[k];
+ if (!settingFits(param, v) || taken.has(param.id)) continue;
+ const was = param.example ?? param.default;
+ const now = v as string | number;
+ const p: RecipeParam = now === was ? param : param.default !== undefined ? { ...param, default: now } : { ...param, example: now };
+ if (!settingParams.has(p.id)) settingParams.set(p.id, { p, at });
+ out.params = { ...out.params, [k]: `{{${p.id}}}` } as GenParams;
+ }
+ }
return out;
};
for (const id of order) {
@@ -3019,9 +3067,12 @@ export function canvasToRecipe(graph: CanvasGraph, page: { canvas?: string } = {
});
}
}
- if (mark?.check) checks[key] = mark.check;
- else if (!mark) {
- const kind = d.plan ? OPERATION_OUTPUT[d.plan.op] : undefined;
+ const kind = d.plan ? OPERATION_OUTPUT[d.plan.op] : undefined;
+ // A step's own check holds while its model does (like its extra fields): a model swapped on the board gets the
+ // kind-only check a board made from scratch gets, so an image check never stays on a step that now makes a video.
+ const same = !!mark && mark.modelId === d.request.modelId;
+ if (mark && same && mark.check && (!mark.check.kind || mark.check.kind === kind)) checks[key] = { ...mark.check };
+ else if (!same || mark?.check) {
if (kind && kind !== "text" && !graph.edges.some((e) => e.source === n.id && isGenerator(nodes.get(e.target) ?? n) && e.target !== n.id)) checks[key] = { kind: kind as RecipeCheck["kind"] };
}
}
@@ -3032,7 +3083,7 @@ export function canvasToRecipe(graph: CanvasGraph, page: { canvas?: string } = {
}
// Inputs no step uses (a text joined nowhere, an element whose node isn't wired) are left out.
const used = new Set(steps.flatMap((s) => placeholdersIn(s.request).map((p) => p.id)));
- const params: RecipeParam[] = [];
+ const placed: { p: RecipeParam; at: number }[] = [];
const varies: string[] = [];
for (const n of inputs) {
const id = idOf.get(n.id)!;
@@ -3041,13 +3092,29 @@ export function canvasToRecipe(graph: CanvasGraph, page: { canvas?: string } = {
const value = nodeValue(n);
const type = INPUT_TYPE[n.type]!;
const label = nodeLabel(n).slice(0, 60);
+ const at = n.data.input?.at ?? Infinity;
if (mark) {
const was = mark.example ?? mark.default;
const p: RecipeParam = { ...mark, id, label, type };
if (value && value !== was) p.example = value.length > 2000 ? undefined : value;
- params.push(p);
+ placed.push({ p, at });
varies.push(id);
- } else params.push({ id, label, type, required: true, ...(value && value.length <= 2000 && { example: value }) });
+ } else placed.push({ p: { id, label, type, required: true, ...(value && value.length <= 2000 && { example: value }) }, at });
+ }
+ for (const s of settingParams.values()) {
+ placed.push(s);
+ varies.push(s.p.id);
+ }
+ // The form's order as the skill had it (a stable sort: inputs made on the board stay after, as they were).
+ placed.sort((a, b) => (a.at === b.at ? 0 : a.at - b.at));
+ const params: RecipeParam[] = placed.map((x) => x.p);
+ // A check that follows a settings input that didn't come back (its value no longer fits) drops that part.
+ const known = new Set(params.map((p) => p.id));
+ for (const c of Object.values(checks)) {
+ for (const [k, v] of Object.entries(c)) {
+ const ph = typeof v === "string" ? EXACT_PH.exec(v) : null;
+ if (ph && !known.has(ph[1])) delete (c as Record<string, unknown>)[k];
+ }
}
for (const c of columns) {
if (!used.has(c.id)) continue;
diff --git a/src/lib/recipe-builder.ts b/src/lib/recipe-builder.ts
index c8083e6b..e75a7a15 100644
--- a/src/lib/recipe-builder.ts
+++ b/src/lib/recipe-builder.ts
@@ -72,6 +72,13 @@ export interface DraftCandidate {
part?: boolean;
/** It starts as Varies (an input of the skill a canvas was drawn from, a Table's column). */
varies?: boolean;
+ /**
+ * Its `{{id}}` is still at each spot (W5: words a skill asks for that have no example yet). Varies keeps it there
+ * under its input id; Fixed puts in the empty words.
+ */
+ kept?: boolean;
+ /** A kept candidate's input as the skill had it (its id and label are the review's). */
+ param?: RecipeParam;
}
export type SettingId = "numOutputs" | "aspectRatio" | "duration" | "resolution";
@@ -344,6 +351,8 @@ export function buildRecipe(draft: Pick<SkillDraft, "recipe" | "candidates">, ch
const byKey = new Map(recipe.steps.map((s) => [s.key, s]));
const checks = recipe.checks ?? {};
const varying = draft.candidates.filter((c) => choices.varies[c.id] && !c.locked);
+ // Inputs kept as `{{id}}` (W5) that end up Fixed: the value they had, in the steps and the checks.
+ for (const c of draft.candidates) if (c.kept && !varying.includes(c)) putKept(recipe, c, null);
// Elements last: a prompt that varies as a whole has replaced its words by then, so an element named only there
// finds no @handle and adds no input (the whole prompt's input carries it).
const order = [...varying.filter((c) => c.kind !== "element"), ...varying.filter((c) => c.kind === "element")];
@@ -351,6 +360,13 @@ export function buildRecipe(draft: Pick<SkillDraft, "recipe" | "candidates">, ch
for (const c of order) {
const id = idOf(c, choices);
const label = (choices.labels?.[c.id]?.trim() || c.label).slice(0, 60);
+ if (c.kept && c.param) {
+ // As the skill had it, under the id and label the review gives it.
+ if (!putKept(recipe, c, id)) continue;
+ const required = choices.required?.[c.id];
+ placed.push({ ...c.param, id, label, ...(required !== undefined && { required }) });
+ continue;
+ }
let used = 0;
for (const spot of c.at) {
const step = byKey.get(spot.step);
@@ -420,6 +436,30 @@ export function buildRecipe(draft: Pick<SkillDraft, "recipe" | "candidates">, ch
// ---------------------------------------------------------------------------
// A recipe made elsewhere (a canvas, W5) as a draft
+/**
+ * A kept candidate's `{{id}}` at each of its spots and in the checks: under `to` (it varies), or its value (Fixed; a
+ * number stays a number where it's the whole value). How many spots it changed.
+ */
+function putKept(recipe: Recipe, c: DraftCandidate, to: string | null): number {
+ const re = new RegExp(`\\{\\{\\s*${c.id}\\s*\\}\\}`, "g");
+ const swap = (v: string): unknown => (to !== null ? v.replace(re, `{{${to}}}`) : v.replace(re, "").trim() === "" && typeof c.example === "number" ? c.example : v.replace(re, String(c.example)));
+ let n = 0;
+ const byKey = new Map(recipe.steps.map((s) => [s.key, s]));
+ for (const spot of c.at) {
+ const step = byKey.get(spot.step);
+ if (!step) continue;
+ const body = bodyOf(step);
+ const cur = getAt(body, spot.path);
+ if (typeof cur !== "string" || !cur.match(re)) continue;
+ setAt(body, spot.path, swap(cur));
+ n++;
+ }
+ for (const check of Object.values(recipe.checks ?? {})) {
+ for (const [k, v] of Object.entries(check)) if (typeof v === "string" && v.match(re)) (check as Record<string, unknown>)[k] = swap(v);
+ }
+ return n;
+}
+
/** Every spot of each placeholder in a value: its path, and whether the placeholder is the whole string there. */
function spotsIn(v: unknown, path: (string | number)[], out: Map<string, { path: (string | number)[]; whole: boolean }[]>): void {
if (typeof v === "string") {
@@ -451,7 +491,11 @@ export function fixedDraft(recipe: Recipe, varies: string[] = []): Pick<SkillDra
const at = spots.get(p.id) ?? [];
if (!at.length) continue;
const value = p.example ?? p.default ?? "";
- for (const spot of at) {
+ // An input of the skill the board was drawn from that a canvas holds no value for (words with no example yet, a
+ // setting): its `{{id}}` stays where it is, in the steps and the checks, and it starts as Varies as the skill had
+ // it, so saving back keeps the input instead of fixing it.
+ const kept = varies.includes(p.id) && ((p.type === "text" && !String(value).trim()) || p.type === "number" || p.type === "choice");
+ for (const spot of kept ? [] : at) {
const body = bodyOf(byKey.get(spot.step)!);
const cur = getAt(body, spot.path);
if (typeof cur !== "string") continue;
@@ -460,7 +504,7 @@ export function fixedDraft(recipe: Recipe, varies: string[] = []): Pick<SkillDra
const kind: CandidateKind = isMediaType(p.type) ? "media" : p.type === "element" ? "element" : p.type === "text" ? "text" : "setting";
const part = kind === "text" && at.some((x) => !x.whole);
const text = String(value);
- const locked = kind === "text" && !text.trim() ? "Write its words on the canvas first" : kind === "text" && text.length > 2000 ? "Too long to change in a form (over 2000 characters)" : undefined;
+ const locked = kept ? undefined : kind === "text" && !text.trim() ? "Write its words on the canvas first" : kind === "text" && text.length > 2000 ? "Too long to change in a form (over 2000 characters)" : undefined;
candidates.push({
id: p.id,
label: p.label,
@@ -468,9 +512,12 @@ export function fixedDraft(recipe: Recipe, varies: string[] = []): Pick<SkillDra
kind,
example: value,
at: at.map(({ step, path }) => ({ step, path })),
- ...(part && { part: true }),
+ ...(part && !kept && { part: true }),
+ ...(kept && { kept: true, param: p }),
+ ...(kind === "setting" && p.default !== undefined && { optional: true }),
...(p.max !== undefined && { max: p.max }),
...(p.min !== undefined && { min: p.min }),
+ ...(p.step !== undefined && { step: p.step }),
...(p.options && { options: p.options }),
...(locked && { locked }),
...(!locked && varies.includes(p.id) && { varies: true }),
diff --git a/src/server/canvas-skills.ts b/src/server/canvas-skills.ts
index 524a4991..591d48bb 100644
--- a/src/server/canvas-skills.ts
+++ b/src/server/canvas-skills.ts
@@ -99,7 +99,8 @@ export function draftFromCanvas(id: string, page?: string): { draft: SkillDraft
recipe: fixed,
steps,
candidates,
- name: replaces?.name ?? freeName(title),
+ // A free name for a new skill: saving back into the skill it was drawn from (replaces) doesn't use it.
+ name: freeName(title),
title,
description: from?.description || cut(`${steps.length === 1 ? flow : `${steps.length} steps: ${flow}`}, with ${models.join(", ")}. Made on a canvas and run again with new inputs.`, 1000),
whenToUse: from?.whenToUse || cut(`When you want the “${canvas.name}” canvas run again with new inputs, from a form, Assist or a schedule.`, 1000),
diff --git a/src/server/canvas.ts b/src/server/canvas.ts
index 2a497cb7..ff96fe22 100644
--- a/src/server/canvas.ts
+++ b/src/server/canvas.ts
@@ -210,6 +210,7 @@ const NodeData = z.object({
modelId: z.string().max(120),
extra: z.record(z.string(), z.unknown()).optional(),
check: z.record(z.string(), z.unknown()).optional(),
+ settings: z.record(z.string().max(40), z.object({ param: z.record(z.string(), z.unknown()), at: z.number().int().min(0).max(100) })).optional(),
from: z.string().max(64).optional(),
})
.refine((m) => JSON.stringify(m).length <= 20_000, "too much kept from its skill")
diff --git a/tests/canvas-recipe.test.ts b/tests/canvas-recipe.test.ts
index 69568412..b22f2a07 100644
--- a/tests/canvas-recipe.test.ts
+++ b/tests/canvas-recipe.test.ts
@@ -116,12 +116,17 @@ describe("what isn't drawn", () => {
expect(refused(withStep({ request: { ...base.request, inputs: { mask: "/api/files/m.png" } } }))).toMatch(/no port/);
});
- it("a settings input (a number or a choice)", () => {
- const r = recipe({
+ it("a settings input (a number or a choice) that isn't a whole setting, or has no value to show", () => {
+ const inWords = recipe({
params: [{ id: "takes", label: "Takes", type: "number", default: 1, min: 1, max: 4 }],
- steps: [{ key: "a", kind: "generate", request: { feature: "skill", modelId: "nano-banana-pro", op: "t2i", prompt: "a lamp", params: { numOutputs: "{{takes}}" as unknown as number } } }],
+ steps: [{ key: "a", kind: "generate", request: { feature: "skill", modelId: "nano-banana-pro", op: "t2i", prompt: "a lamp, {{takes}} takes" } }],
+ });
+ expect(refused(inWords)).toMatch(/no node for Takes/);
+ const blank = recipe({
+ params: [{ id: "shape", label: "Shape", type: "choice", options: ["1:1", "16:9"] }],
+ steps: [{ key: "a", kind: "generate", request: { feature: "skill", modelId: "nano-banana-pro", op: "t2i", prompt: "a lamp", params: { aspectRatio: "{{shape}}" as unknown as string } } }],
});
- expect(refused(r)).toMatch(/no node for Takes/);
+ expect(refused(blank)).toMatch(/Give Shape a default first/);
});
it("a studio step shows as one note, never nodes", () => {
@@ -229,3 +234,136 @@ describe("canvas → recipe", () => {
expect(out.problems[0]).toMatchObject({ nodeId: "m" });
});
});
+
+describe("settings inputs ride on their nodes", () => {
+ /** What W2 makes when the takes and the shape vary: optional inputs with defaults, followed by the step's check. */
+ const posters = recipe({
+ params: [
+ { id: "subject", label: "Subject", type: "text", required: true, example: "a red fox" },
+ { id: "takes", label: "Takes", type: "number", default: 2, min: 1, max: 4, step: 1 },
+ { id: "shape", label: "Shape", type: "choice", default: "1:1", options: ["1:1", "16:9", "9:16"] },
+ ],
+ steps: [
+ {
+ key: "poster",
+ kind: "generate",
+ request: { feature: "skill", modelId: "nano-banana-pro", op: "t2i", prompt: "{{subject}}, poster style", params: { numOutputs: "{{takes}}" as unknown as number, aspectRatio: "{{shape}}" as unknown as string } },
+ },
+ ],
+ checks: { poster: { kind: "image", count: "{{takes}}", aspect: "{{shape}}" } },
+ });
+ const node = (g: CanvasGraph) => g.nodes.find((n) => n.id === "step-poster")!;
+ const withParams = (g: CanvasGraph, patch: object, data: object = {}): CanvasGraph => ({
+ ...g,
+ nodes: g.nodes.map((n) => (n.id === "step-poster" ? { ...n, data: { ...n.data, ...data, params: { ...n.data.params, ...patch } } } : n)),
+ });
+
+ it("draws the values on the node and comes back as the same recipe", () => {
+ const g = drawn(posters);
+ expect(node(g).data.params).toMatchObject({ numOutputs: 2, aspectRatio: "1:1" });
+ const back = canvasToRecipe(g);
+ expect(back.problems).toEqual([]);
+ expect(recipeShape(back.recipe!)).toBe(recipeShape(posters));
+ expect(back.varies.sort()).toEqual(["shape", "subject", "takes"]);
+ });
+
+ it("follows a value changed on the board, and lets go of one the input doesn't take or a swapped model", () => {
+ const changed = canvasToRecipe(withParams(drawn(posters), { aspectRatio: "16:9" })).recipe!;
+ expect(changed.params.find((p) => p.id === "shape")).toMatchObject({ default: "16:9" });
+ expect((changed.steps[0] as { request: { params: object } }).request.params).toMatchObject({ aspectRatio: "{{shape}}" });
+ // 21:9 isn't one of the input's options: the setting stays as the board has it, and the check stops following it.
+ const out = canvasToRecipe(withParams(drawn(posters), { aspectRatio: "21:9" })).recipe!;
+ expect(out.params.map((p) => p.id)).toEqual(["subject", "takes"]);
+ expect((out.steps[0] as { request: { params: object } }).request.params).toMatchObject({ aspectRatio: "21:9", numOutputs: "{{takes}}" });
+ expect(out.checks).toEqual({ poster: { kind: "image", count: "{{takes}}" } });
+ expect(recipeProblems(out)).toEqual([]);
+ const swapped = canvasToRecipe(withParams(drawn(posters), {}, { modelId: "qwen-image-2512-cloud" })).recipe;
+ expect(swapped!.params.map((p) => p.id)).toEqual(["subject"]);
+ });
+
+ it("starts as Varies in the review and saves back as the skill had it; Fixed puts the value in the steps and checks", () => {
+ const back = canvasToRecipe(drawn(posters));
+ const draft = fixedDraft(back.recipe!, back.varies);
+ const takes = draft.candidates.find((c) => c.id === "takes")!;
+ expect(takes).toMatchObject({ kind: "setting", kept: true, varies: true, optional: true, example: 2 });
+ const start = buildRecipe(draft, { varies: Object.fromEntries(draft.candidates.filter((c) => c.varies).map((c) => [c.id, true])) });
+ expect(start.steps).toEqual(posters.steps);
+ expect(start.checks).toEqual(posters.checks);
+ expect([...start.params].sort((a, b) => a.id.localeCompare(b.id))).toEqual([...posters.params].sort((a, b) => a.id.localeCompare(b.id)));
+ const fixed = buildRecipe(draft, { varies: { subject: true, shape: true } });
+ expect((fixed.steps[0] as { request: { params: object } }).request.params).toEqual({ numOutputs: 2, aspectRatio: "{{shape}}" });
+ expect(fixed.checks).toEqual({ poster: { kind: "image", count: 2, aspect: "{{shape}}" } });
+ expect(recipeProblems(fixed)).toEqual([]);
+ });
+});
+
+describe("the way back keeps what the skill asks for", () => {
+ it("keeps words a skill asks for with no example as an input, and Fixed leaves them empty", () => {
+ const r = recipe({
+ params: [{ id: "subject", label: "Subject", type: "text", required: true }],
+ steps: [{ key: "a", kind: "generate", request: { feature: "skill", modelId: "nano-banana-pro", op: "t2i", prompt: "A photo of {{subject}}" } }],
+ });
+ const back = canvasToRecipe(drawn(r));
+ const draft = fixedDraft(back.recipe!, back.varies);
+ expect(draft.candidates[0]).toMatchObject({ id: "subject", kept: true, varies: true });
+ expect(draft.candidates[0].locked).toBeUndefined();
+ const start = buildRecipe(draft, { varies: { subject: true } });
+ expect(start.params).toEqual(r.params);
+ expect(start.steps).toEqual(r.steps);
+ const fixed = buildRecipe(draft, { varies: {} });
+ expect(fixed.params).toEqual([]);
+ expect((fixed.steps[0] as { request: { prompt: string } }).request.prompt).toBe("A photo of ");
+ });
+
+ it("drops a step's check when its model is swapped for one that makes something else", () => {
+ const r = recipe({
+ params: [{ id: "subject", label: "Subject", type: "text", required: true, example: "a lamp" }],
+ steps: [{ key: "a", kind: "generate", request: { feature: "skill", modelId: "nano-banana-pro", op: "t2i", prompt: "{{subject}}" } }],
+ checks: { a: { kind: "image", count: 1 } },
+ });
+ const g = drawn(r);
+ expect(canvasToRecipe(g).recipe!.checks).toEqual(r.checks);
+ const video: CanvasGraph = { ...g, nodes: g.nodes.map((n) => (n.type === "model" ? { ...n, data: { ...n.data, modelId: "kling-3", op: "t2v" as const, mediaKind: "video" as const } } : n)) };
+ const out = canvasToRecipe(video);
+ expect(out.problems).toEqual([]);
+ expect(out.recipe!.checks).toEqual({ a: { kind: "video" } });
+ // A skill whose step had no check gets none on the way back while its model stays.
+ const none = recipe({ ...r, checks: undefined });
+ expect(canvasToRecipe(drawn(none)).recipe!.checks).toBeUndefined();
+ });
+});
+
+describe("a Video concatenator", () => {
+ it("compiles to its cuts and join as a run of the board does, with its clips as inputs", () => {
+ const g: CanvasGraph = {
+ nodes: [
+ { id: "a", type: "video-input", position: { x: 0, y: 0 }, data: { url: "/api/files/uploads/a.mp4", label: "First clip" } },
+ { id: "b", type: "video-input", position: { x: 0, y: 200 }, data: { url: "/api/files/uploads/b.mp4", label: "Second clip" } },
+ { id: "f", type: "concat", position: { x: 400, y: 0 }, data: { label: "Film", modelId: "oss-join-encoded", params: { aspectRatio: "16:9" }, clips: { a: { start: 1, end: 3, mute: true } } } },
+ ],
+ edges: [
+ { id: "e1", source: "a", sourceHandle: "out", target: "f", targetHandle: "videos" },
+ { id: "e2", source: "b", sourceHandle: "out", target: "f", targetHandle: "videos" },
+ ],
+ };
+ const out = canvasToRecipe(g);
+ expect(out.problems).toEqual([]);
+ const r = out.recipe!;
+ expect(r.params.map((p) => [p.id, p.type])).toEqual([
+ ["first_clip", "video"],
+ ["second_clip", "video"],
+ ]);
+ expect(r.steps.length).toBeGreaterThan(1);
+ const steps = r.steps as Extract<Recipe["steps"][number], { kind: "generate" }>[];
+ // The join is the node's own step (its label and the skill's feature); every cut before it is a helper step.
+ const join = steps.find((s) => s.label === "Film")!;
+ expect(join.request).toMatchObject({ feature: "skill", modelId: "oss-join-encoded" });
+ expect(steps.filter((s) => s !== join).every((s) => s.request.feature === "canvas-step")).toBe(true);
+ expect(steps.indexOf(join)).toBe(steps.length - 1);
+ // Each clip reaches a cut through its input, and the first clip keeps its window.
+ expect(JSON.stringify(steps)).toContain("{{first_clip}}");
+ expect(JSON.stringify(steps)).toContain("{{second_clip}}");
+ expect(recipeProblems(r)).toEqual([]);
+ expect(RecipeSchema.safeParse(r).success).toBe(true);
+ });
+});
diff --git a/tests/canvas-skills.test.ts b/tests/canvas-skills.test.ts
index e1e4341c..738c6584 100644
--- a/tests/canvas-skills.test.ts
+++ b/tests/canvas-skills.test.ts
@@ -92,7 +92,7 @@ describe("Save as skill from a canvas", () => {
const c = await (await canvasesRoute.POST(post("/api/canvases", { skill: "lamp-scene" }))).json();
const { draft } = await draftOf(c.id);
expect(draft!.replaces).toEqual({ name: "lamp-scene", title: "Lamp scene" });
- expect(draft!.name).toBe("lamp-scene");
+ expect(draft!.name).toBe("lamp-scene-2");
expect(draft!.recipe.params).toEqual([]);
expect(draft!.candidates.map((x) => [x.id, x.kind, x.varies])).toEqual([
["product", "media", true],
@@ -169,4 +169,31 @@ describe("Save as skill from a canvas", () => {
const { draft } = await draftOf(c.id);
expect(recipeShape(buildRecipe(draft!, startChoices(draft!)))).toBe(recipeShape({ ...r, checks: r.checks }));
});
+
+ it("saves back a skill's inputs a canvas holds no value for: words with no example, and settings", async () => {
+ skills.createSkill({ name: "fox-shots", title: "Fox shots", description: "Shots of anything.", body: "# Fox shots" });
+ recipes.saveRecipe("fox-shots", {
+ fuobeRecipe: 1,
+ params: [
+ { id: "subject", label: "Subject", type: "text", required: true },
+ { id: "takes", label: "Takes", type: "number", default: 1, min: 1, max: 4 },
+ ],
+ steps: [{ key: "a", kind: "generate", request: { feature: "skill", modelId: "nano-banana-pro", op: "t2i", prompt: "A photo of {{subject}}", params: { numOutputs: "{{takes}}" as unknown as number } } }],
+ checks: { a: { kind: "image", count: "{{takes}}" } },
+ });
+ expect(recipes.recipeView("fox-shots").canvas).toEqual({ ok: true });
+ const c = await (await canvasesRoute.POST(post("/api/canvases", { skill: "fox-shots" }))).json();
+ const { draft } = await draftOf(c.id);
+ expect(draft!.candidates.map((x) => [x.id, x.varies ?? false, x.locked ?? null])).toEqual([
+ ["subject", true, null],
+ ["takes", true, null],
+ ]);
+ const recipe = buildRecipe(draft!, startChoices(draft!));
+ const saved = await saveRoute.POST(post("/api/assist/skills/draft/save", { name: "fox-shots", title: "Fox shots", description: "Shots of anything.", body: "# Fox shots", recipe, replace: true }));
+ expect(saved.status).toBe(201);
+ const now = recipes.getRecipe("fox-shots").recipe;
+ expect(now.params.map((p) => p.id).sort()).toEqual(["subject", "takes"]);
+ expect((now.steps[0] as { request: { prompt: string; params: object } }).request).toMatchObject({ prompt: "A photo of {{subject}}", params: { numOutputs: "{{takes}}" } });
+ expect(now.checks).toEqual({ a: { kind: "image", count: "{{takes}}" } });
+ });
});
diff --git a/tests/e2e/canvas-smoke.mjs b/tests/e2e/canvas-smoke.mjs
index 3053ee05..5cb3ea99 100644
--- a/tests/e2e/canvas-smoke.mjs
+++ b/tests/e2e/canvas-smoke.mjs
@@ -114,14 +114,18 @@ try {
method: "PUT",
body: JSON.stringify({
fuobeRecipe: 1,
- params: [{ id: "subject", label: "Subject", type: "text", required: true, example: "a red fox in snow" }],
- steps: [{ key: "poster", kind: "generate", label: "Poster", request: { feature: "skill", modelId: "nano-banana-pro", op: "t2i", prompt: "{{subject}}, a bold travel poster", params: { aspectRatio: "3:4" } } }],
+ params: [
+ { id: "subject", label: "Subject", type: "text", required: true, example: "a red fox in snow" },
+ { id: "shape", label: "Shape", type: "choice", default: "3:4", options: ["3:4", "1:1", "16:9"] },
+ ],
+ steps: [{ key: "poster", kind: "generate", label: "Poster", request: { feature: "skill", modelId: "nano-banana-pro", op: "t2i", prompt: "{{subject}}, a bold travel poster", params: { aspectRatio: "{{shape}}" } } }],
}),
});
check("the canvas skill is seeded", put.canvas?.ok === true, JSON.stringify(put.canvas ?? put.error));
const noSideScroll = (pg) => pg.evaluate(() => document.documentElement.scrollWidth <= document.documentElement.clientWidth);
const seen = (loc, timeout = 30_000) => loc.waitFor({ timeout }).then(() => true).catch(() => false);
let flowDone = false;
+ const made = [];
for (const [width, height] of [
[1440, 900],
[390, 844],
@@ -139,6 +143,7 @@ try {
if (!flowDone && width === 1440) {
await open.click();
await pg.waitForURL(/\/canvas\/[^/?]+$/, { timeout: 30_000 });
+ made.push(new URL(pg.url()).pathname.split("/").pop());
await pg.locator(".react-flow__node").first().waitFor({ timeout: 60_000 });
check(`${tag}: the canvas has the skill's input and step`, (await pg.locator(".react-flow__node").count()) === 2);
await pg.getByRole("button", { name: "More run options" }).click();
@@ -157,7 +162,8 @@ try {
await dialog.getByRole("button", { name: "Save back" }).click();
check(`${tag}: saved back, its Run form opens`, await seen(pg.getByText(/Saved back into/).first(), 60_000));
const after = await api(`/api/assist/skills/${NAME}/recipe`);
- check(`${tag}: the skill kept its input and is checked`, after.recipe?.params?.[0]?.id === "subject" && after.ready?.length > 0, JSON.stringify(after.recipe?.params));
+ const ids = (after.recipe?.params ?? []).map((p) => p.id).sort().join(",");
+ check(`${tag}: the skill kept its inputs (words and a setting) and is checked`, ids === "shape,subject" && after.ready?.length > 0, JSON.stringify(after.recipe?.params));
flowDone = true;
} else if (width < 500) {
// On a phone: the review fills the screen without scrolling sideways.
@@ -172,6 +178,9 @@ try {
await ctx.close();
}
}
+ // Leave nothing behind: the canvases Open as canvas made, and the skill.
+ for (const id of made) await fetch(`${app}/api/canvases/${id}`, { method: "DELETE" });
+ await fetch(`${app}/api/assist/skills/${NAME}`, { method: "DELETE" });
}
// 4. A big board stays responsive.