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: a recipe skill opens as a new canvas, and a canvas drafts a skill that can be saved back into it

Claude7e24cd396dda
diff --git a/src/app/api/assist/skills/draft/name/route.ts b/src/app/api/assist/skills/draft/name/route.ts
index 5eab4601..ded6b385 100644
--- a/src/app/api/assist/skills/draft/name/route.ts
+++ b/src/app/api/assist/skills/draft/name/route.ts
@@ -1,4 +1,5 @@
import { badBody, DraftSource, recipeFailure } from "@/server/recipe-routes";
+import { draftFromCanvas } from "@/server/canvas-skills";
import { draftFromGenerations, draftFromThread, nameDraft } from "@/server/recipe-builder";
/**
@@ -10,7 +11,8 @@ export async function POST(request: Request) {
const parsed = DraftSource.safeParse(await request.json().catch(() => ({})));
if (!parsed.success) return badBody(parsed.error.issues);
try {
- const { draft, words } = "thread" in parsed.data ? draftFromThread(parsed.data.thread) : { ...draftFromGenerations(parsed.data.generations), words: [] };
+ const src = parsed.data;
+ const { draft, words } = "thread" in src ? draftFromThread(src.thread) : "canvas" in src ? { ...draftFromCanvas(src.canvas, src.page), words: [] } : { ...draftFromGenerations(src.generations), words: [] };
return Response.json({ naming: draft ? await nameDraft(draft, words) : null });
} catch (e) {
return recipeFailure(e);
diff --git a/src/app/api/assist/skills/draft/route.ts b/src/app/api/assist/skills/draft/route.ts
index d4025910..b6b63850 100644
--- a/src/app/api/assist/skills/draft/route.ts
+++ b/src/app/api/assist/skills/draft/route.ts
@@ -1,15 +1,17 @@
import { badBody, DraftSource, recipeFailure } from "@/server/recipe-routes";
+import { draftFromCanvas } from "@/server/canvas-skills";
import { draftFromGenerations, draftFromThread } from "@/server/recipe-builder";
/**
- * A skill drafted from results in the Library (W2) or from an Assist chat (W3): the steps behind them rebuilt from
- * their requests, every input Fixed, with the inputs that could vary and proposed checks; `refusals` say which picks
- * (or which of the chat's steps) couldn't be used and why.
+ * A skill drafted from results in the Library (W2), from an Assist chat (W3) or from a canvas page (W5): the steps
+ * behind them rebuilt from their requests (a canvas's from its nodes), every input Fixed, with the inputs that could vary
+ * and proposed checks; `refusals` say which picks (the chat's steps, the board's nodes) couldn't be used and why.
*/
export async function POST(request: Request) {
const parsed = DraftSource.safeParse(await request.json().catch(() => ({})));
if (!parsed.success) return badBody(parsed.error.issues);
try {
+ if ("canvas" in parsed.data) return Response.json(draftFromCanvas(parsed.data.canvas, parsed.data.page));
if ("thread" in parsed.data) {
const { draft, refusals } = draftFromThread(parsed.data.thread);
return Response.json({ draft, refusals });
diff --git a/src/app/api/assist/skills/draft/save/route.ts b/src/app/api/assist/skills/draft/save/route.ts
index d2835d89..ef2c0c77 100644
--- a/src/app/api/assist/skills/draft/save/route.ts
+++ b/src/app/api/assist/skills/draft/save/route.ts
@@ -3,7 +3,7 @@ import { SkillBody } from "@/server/assist/schemas";
import { badBody, recipeFailure } from "@/server/recipe-routes";
import { saveDraft } from "@/server/recipes";
-const Body = SkillBody.extend({ recipe: z.unknown() });
+const Body = SkillBody.extend({ recipe: z.unknown(), replace: z.boolean().optional() });
/** Save a drafted skill: its SKILL.md and recipe.json, once its plan passes on an engine (checked again here, free). */
export async function POST(request: Request) {
diff --git a/src/app/api/canvases/route.ts b/src/app/api/canvases/route.ts
index 8507f4b4..e84cb06a 100644
--- a/src/app/api/canvases/route.ts
+++ b/src/app/api/canvases/route.ts
@@ -1,7 +1,9 @@
import { connection } from "next/server";
import { z } from "zod";
import { createCanvas, listCanvases, parseGraph, parsePages } from "@/server/canvas";
+import { canvasFromSkill } from "@/server/canvas-skills";
import { refusedRun } from "@/server/connect-refusal";
+import { SkillError } from "@/server/skills";
const Body = z.object({
name: z.string().max(80).optional(),
@@ -9,6 +11,8 @@ const Body = z.object({
engine: z.enum(["cloud", "open"]).optional(),
graph: z.unknown().optional(),
pages: z.unknown().optional(),
+ /** Open a recipe skill as a new canvas (W5): its inputs and steps drawn as nodes. */
+ skill: z.string().min(1).max(64).optional(),
});
export async function GET() {
@@ -19,7 +23,15 @@ export async function GET() {
export async function POST(request: Request) {
const parsed = Body.safeParse(await request.json().catch(() => ({})));
if (!parsed.success) return Response.json({ error: "Invalid canvas" }, { status: 400 });
- const { graph: rawGraph, pages: rawPages, ...rest } = parsed.data;
+ const { graph: rawGraph, pages: rawPages, skill, ...rest } = parsed.data;
+ if (skill) {
+ try {
+ return Response.json(canvasFromSkill(skill), { status: 201 });
+ } catch (e) {
+ if (e instanceof SkillError) return Response.json({ error: e.message }, { status: e.status });
+ throw e;
+ }
+ }
const graph = rawGraph === undefined ? undefined : parseGraph(rawGraph);
const pages = rawPages === undefined ? undefined : parsePages(rawPages);
if (graph === null || pages === null) return Response.json({ error: "That board couldn't be read" }, { status: 400 });
diff --git a/src/server/canvas-skills.ts b/src/server/canvas-skills.ts
new file mode 100644
index 00000000..524a4991
--- /dev/null
+++ b/src/server/canvas-skills.ts
@@ -0,0 +1,116 @@
+import "server-only";
+import { getModel } from "@/lib/catalog";
+import { canvasToRecipe, nodeLabel, recipeToCanvas, runOutput, withCurrentElements } from "@/lib/catalog/canvas";
+import { pageOf } from "@/lib/catalog/canvas-board";
+import { OPERATION_LABELS, type Operation } from "@/lib/catalog/types";
+import { leafKeys, today, type GenerateStep } from "@/lib/recipe";
+import { fixedDraft, slugify, type DraftRefusal, type DraftStep, type SkillDraft } from "@/lib/recipe-builder";
+import { createCanvas, getCanvas, silenceWriter } from "./canvas";
+import { listElements } from "./elements";
+import { llmTextBackend } from "./enhance";
+import { getGeneration } from "./generations";
+import { videoPoster } from "@/lib/output-actions";
+import { getRecipe } from "./recipes";
+import { getSkill, SkillError } from "./skills";
+
+/**
+ * Skills as canvases (package W5, docs/research/work2skill-7.md §10): open a recipe skill as a new canvas to see and
+ * change its steps, and draft a skill from a canvas for W2's review screen, so a board runs from a form, Assist, MCP,
+ * the CLI and schedules. The drawing and the reading are pure (recipeToCanvas, canvasToRecipe in
+ * src/lib/catalog/canvas.ts); this module reads and writes the records.
+ */
+
+const elementInfos = () => listElements().map((e) => ({ id: e.id, handle: e.handle, name: e.name, references: e.references }));
+
+/** A new canvas with a recipe skill drawn on it; a skill that can't be drawn is refused with the reason (422). */
+export function canvasFromSkill(name: string) {
+ const { skill, recipe } = getRecipe(name);
+ const drawing = recipeToCanvas(recipe, { elements: elementInfos(), ...(skill.source !== "builtin" && { from: name }) });
+ if (!drawing.ok) throw new SkillError(`${drawing.reason}: ${drawing.detail}`, 422);
+ return createCanvas({ name: skill.title || name, graph: drawing.graph });
+}
+
+const cut = (s: string, n: number) => (s.length > n ? `${s.slice(0, n - 1).trimEnd()}…` : s);
+
+/** A free skill name like the title ("lamp-turntable", "lamp-turntable-2"…). */
+function freeName(title: string): string {
+ const base = slugify(title).slice(0, 56).replace(/-+$/, "") || "my-skill";
+ let name = base;
+ for (let i = 2; getSkill(name) || ["upload", "new", "draft"].includes(name); i++) name = `${base}-${i}`;
+ return name;
+}
+
+/**
+ * The draft of a skill from a canvas page (the canvas is the "demo"): the board read as a recipe, each input put back
+ * Fixed (an input of the skill the board was drawn from, and a Table's columns, start as Varies), each step with the
+ * node's last result as its picture. A node that can't run is a refusal naming it.
+ */
+export function draftFromCanvas(id: string, page?: string): { draft: SkillDraft | null; refusals: DraftRefusal[] } {
+ const canvas = getCanvas(id);
+ if (!canvas) throw new SkillError("No such canvas", 404);
+ if (page && !canvas.pages.some((p) => p.id === page)) throw new SkillError("That page isn't on this canvas any more — reload it", 409);
+ const on = pageOf(canvas.pages, page);
+ const graph = withCurrentElements(on.graph, elementInfos());
+ const read = canvasToRecipe(graph, { canvas: id });
+ if (!read.recipe) {
+ const byId = new Map(graph.nodes.map((n) => [n.id, n]));
+ return { draft: null, refusals: read.problems.map((p) => ({ id: p.nodeId ?? id, title: p.nodeId && byId.get(p.nodeId) ? nodeLabel(byId.get(p.nodeId)!) : canvas.name, reason: p.message })) };
+ }
+ const recipe = read.recipe;
+ // A muted clip's silence is a file the run reads (as Run all writes it).
+ const withSilence = silenceWriter();
+ for (const s of recipe.steps as GenerateStep[]) s.request = withSilence(s.request) as GenerateStep["request"];
+ recipe.source = { from: "canvas", canvas: id, at: today() };
+ const { recipe: fixed, candidates } = fixedDraft(recipe, read.varies);
+ const leaves = leafKeys(fixed);
+ const byNode = new Map(graph.nodes.map((n) => [n.id, n]));
+ const labelOf = new Map<string, string>();
+ const steps: DraftStep[] = (fixed.steps as GenerateStep[]).map((s) => {
+ const node = byNode.get(read.nodes[s.key] ?? "");
+ const model = getModel(s.request.modelId);
+ const op = s.request.op ? (OPERATION_LABELS[s.request.op as Operation] ?? s.request.op) : undefined;
+ const label = s.label ?? (node ? nodeLabel(node) : (op ?? model?.name ?? s.key));
+ labelOf.set(s.key, label);
+ const run = node ? canvas.runs[node.id] : undefined;
+ const g = run ? getGeneration(runOutput(run)) : null;
+ const o = g?.status === "succeeded" ? (g.outputs.find((x) => x.kind === g.kind) ?? g.outputs[0]) : undefined;
+ const poster = g && o ? videoPoster(g, o) : undefined;
+ return {
+ key: s.key,
+ kind: "generate",
+ label,
+ modelName: model?.name ?? s.request.modelId,
+ ...(s.request.engine && { engine: s.request.engine }),
+ generation: g?.id ?? "",
+ ...(o && { thumb: { url: o.url, kind: o.kind, ...(poster && { poster }) } }),
+ waits: [],
+ leaf: leaves.has(s.key),
+ notes: [],
+ };
+ });
+ for (const [i, s] of (fixed.steps as GenerateStep[]).entries()) steps[i].waits = (Array.isArray(s.after) ? s.after : s.after ? [s.after] : []).map((a) => labelOf.get(a) ?? a);
+ const from = read.from ? getSkill(read.from) : null;
+ const replaces = from && from.source !== "builtin" ? { name: from.name, title: from.title || from.name } : undefined;
+ const title = cut(from?.title || canvas.name || "Canvas skill", 60);
+ const models = [...new Set(steps.map((s) => s.modelName))];
+ const flow = steps.map((s) => s.label).join(" → ");
+ const rows = read.rows?.map((r) => Object.fromEntries(Object.entries(r).map(([k, v]) => [k, String(v ?? "")])));
+ const draft: SkillDraft = {
+ recipe: fixed,
+ steps,
+ candidates,
+ name: replaces?.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),
+ demo: false,
+ notes: [
+ ...(rows?.length ? [`The table's ${rows.length} row${rows.length === 1 ? "" : "s"} become the runs of the Many tab once it's saved`] : []),
+ ...(graph.nodes.some((n) => n.data.pinned) ? ["Pinned nodes run again each time: a skill makes every step afresh"] : []),
+ ],
+ llm: llmTextBackend(),
+ ...(rows?.length && { rows }),
+ ...(replaces && { replaces }),
+ };
+ return { draft, refusals: [] };
+}
diff --git a/src/server/canvas.ts b/src/server/canvas.ts
index 0c99062a..2a497cb7 100644
--- a/src/server/canvas.ts
+++ b/src/server/canvas.ts
@@ -201,6 +201,23 @@ const NodeData = z.object({
orbit: ExactOrbitSchema.optional(),
keys: z.array(CameraKeySchema).min(1).max(MAX_KEYS).optional(),
duration: z.number().min(1).max(15).optional(),
+ // Drawn from a skill (W5): what a step or an input keeps for the way back (read again through RecipeSchema when saved).
+ skill: z
+ .object({
+ key: z.string().max(40),
+ label: clamped(80).optional(),
+ feature: z.string().max(60).optional(),
+ modelId: z.string().max(120),
+ extra: z.record(z.string(), z.unknown()).optional(),
+ check: z.record(z.string(), z.unknown()).optional(),
+ from: z.string().max(64).optional(),
+ })
+ .refine((m) => JSON.stringify(m).length <= 20_000, "too much kept from its skill")
+ .optional(),
+ input: z
+ .object({ param: z.record(z.string(), z.unknown()).optional(), at: z.number().int().min(0).max(100).optional(), fixed: z.boolean().optional() })
+ .refine((m) => JSON.stringify(m).length <= 8_000, "too much kept from its skill")
+ .optional(),
});
const Num = z.number().finite();
diff --git a/src/server/recipe-routes.ts b/src/server/recipe-routes.ts
index 1d924d4f..3c0cd15a 100644
--- a/src/server/recipe-routes.ts
+++ b/src/server/recipe-routes.ts
@@ -19,8 +19,9 @@ export function recipeFailure(e: unknown): Response {
export const badBody = (issues: z.core.$ZodIssue[]) => Response.json({ error: issues.map((i) => `${i.path.join(".") || "body"}: ${i.message}`).join("; ") }, { status: 400 });
-/** What a skill is drafted from: results picked in the Library (W2), or an Assist chat whose plans ran (W3). */
+/** What a skill is drafted from: results picked in the Library (W2), an Assist chat whose plans ran (W3), or a canvas page (W5). */
export const DraftSource = z.union([
z.object({ generations: z.array(z.string().min(1).max(40)).min(1).max(200) }),
z.object({ thread: z.string().min(1).max(40) }),
+ z.object({ canvas: z.string().min(1).max(40), page: z.string().min(1).max(40).optional() }),
]);
diff --git a/src/server/recipes.ts b/src/server/recipes.ts
index 22f521fa..6f0b6bdd 100644
--- a/src/server/recipes.ts
+++ b/src/server/recipes.ts
@@ -900,6 +900,8 @@ export interface DraftSave {
body: string;
icon?: string;
recipe: unknown;
+ /** Put the steps back into this existing user skill (a skill opened as a canvas, W5): its SKILL.md stays as it is. */
+ replace?: boolean;
}
/**
@@ -914,6 +916,13 @@ export async function saveDraft(input: DraftSave): Promise<RecipeView> {
const known = draftChecks().get(key)?.verified;
const { checks, verified } = await checkEngines({ name: input.name, title: input.title }, recipe, "plan", engines, known);
if (!checks.some((c) => c.plan.ok)) throw new RecipeError([...new Set(checks.flatMap((c) => c.plan.errors))]);
+ if (input.replace) {
+ // saveRecipe refuses a built-in ("Duplicate it first") and a skill that's gone.
+ saveRecipe(input.name, { ...recipe, verified }, { keepVerified: true });
+ draftChecks().delete(key);
+ draftChecks().set(key, { verified: { ...known, ...verified }, at: Date.now(), saved: input.name });
+ return recipeView(input.name);
+ }
createSkill({ name: input.name, title: input.title, description: input.description, whenToUse: input.whenToUse, body: input.body, ...(input.icon && { icon: input.icon }) });
try {
saveRecipe(input.name, { ...recipe, verified }, { keepVerified: true });
diff --git a/tests/canvas-recipe.test.ts b/tests/canvas-recipe.test.ts
index 1f1b8e0d..69568412 100644
--- a/tests/canvas-recipe.test.ts
+++ b/tests/canvas-recipe.test.ts
@@ -119,7 +119,7 @@ describe("what isn't drawn", () => {
it("a settings input (a number or a choice)", () => {
const r = 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}}" } } }],
+ steps: [{ key: "a", kind: "generate", request: { feature: "skill", modelId: "nano-banana-pro", op: "t2i", prompt: "a lamp", params: { numOutputs: "{{takes}}" as unknown as number } } }],
});
expect(refused(r)).toMatch(/no node for Takes/);
});
diff --git a/tests/canvas-skills.test.ts b/tests/canvas-skills.test.ts
new file mode 100644
index 00000000..3f7fe449
--- /dev/null
+++ b/tests/canvas-skills.test.ts
@@ -0,0 +1,169 @@
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
+
+// Route handlers call connection() (no request scope in a test).
+vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));
+vi.setConfig({ testTimeout: 120_000 });
+
+const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-canvas-skills-"));
+process.env.FUOBE_DATA_DIR = dir;
+// Nothing listens: open models run on the demo provider, and there's no LLM.
+process.env.COMFYUI_URL = "http://127.0.0.1:9";
+process.env.OLLAMA_URL = "http://127.0.0.1:9";
+
+const { setSetting } = await import("@/server/settings");
+const { saveFile } = await import("@/server/storage");
+const { encodePng } = await import("@/server/png");
+const { createCanvas, getCanvas, updateCanvas } = await import("@/server/canvas");
+const recipes = await import("@/server/recipes");
+const skills = await import("@/server/skills");
+const gens = await import("@/server/generations");
+const { buildRecipe } = await import("@/lib/recipe-builder");
+const { CANT_DRAW, recipeShape } = await import("@/lib/catalog/canvas");
+const canvasesRoute = await import("@/app/api/canvases/route");
+const draftRoute = await import("@/app/api/assist/skills/draft/route");
+const saveRoute = await import("@/app/api/assist/skills/draft/save/route");
+type Recipe = import("@/lib/recipe").Recipe;
+type SkillDraft = import("@/lib/recipe-builder").SkillDraft;
+
+afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));
+
+const post = (url: string, body: unknown) => new Request(`http://localhost:3000${url}`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) });
+
+let photo = "";
+let turntable: Recipe;
+beforeAll(() => {
+ setSetting("demoMode", "auto");
+ setSetting("enhanceProvider", "none");
+ photo = saveFile({ data: encodePng({ width: 64, height: 48, data: Buffer.alloc(64 * 48 * 4, 180) }), contentType: "image/png", source: "upload", name: "lamp.png" }).url;
+ turntable = {
+ fuobeRecipe: 1,
+ params: [
+ { id: "product", label: "Product photo", type: "image", required: true, example: photo },
+ { id: "name", label: "Product name", type: "text", required: true, example: "Lumen desk lamp", max: 200 },
+ ],
+ steps: [
+ { key: "cutout", kind: "generate", label: "Cut out", request: { feature: "skill", modelId: "birefnet-cloud", op: "bg-remove", inputs: { images: ["{{product}}"] } } },
+ { key: "scene", kind: "generate", after: ["cutout"], chain: [{ slot: "images" }], request: { feature: "skill", modelId: "nano-banana-pro", op: "edit", prompt: "{{name}} on a travertine plinth", params: { aspectRatio: "1:1" } } },
+ ],
+ checks: { scene: { kind: "image", count: 1, aspect: "1:1" } },
+ };
+ skills.createSkill({ name: "lamp-scene", title: "Lamp scene", description: "A product on a plinth.", body: "# Lamp scene" });
+ recipes.saveRecipe("lamp-scene", turntable);
+ skills.createSkill({ name: "caption-it", title: "Caption it", description: "Caption a clip.", body: "# Caption it" });
+ recipes.saveRecipe("caption-it", { fuobeRecipe: 1, params: [], steps: [{ key: "captions", kind: "tool", tool: "add_captions", input: { video: photo.replace(".png", ".mp4") } }] });
+});
+
+const draftOf = async (canvas: string) => {
+ const r = await draftRoute.POST(post("/api/assist/skills/draft", { canvas }));
+ expect(r.status).toBe(200);
+ return (await r.json()) as { draft: SkillDraft | null; refusals: { reason: string }[] };
+};
+/** The review screen's starting choices: what starts as Varies. */
+const startChoices = (d: SkillDraft) => ({ varies: Object.fromEntries(d.candidates.filter((c) => c.varies).map((c) => [c.id, true])) });
+
+describe("Open as canvas", () => {
+ it("makes a new canvas with the skill drawn on it", async () => {
+ const r = await canvasesRoute.POST(post("/api/canvases", { skill: "lamp-scene" }));
+ expect(r.status).toBe(201);
+ const c = await r.json();
+ expect(c.name).toBe("Lamp scene");
+ const g = c.pages[0].graph;
+ expect(g.nodes.map((n: { id: string }) => n.id).sort()).toEqual(["input-name", "input-product", "step-cutout", "step-scene"]);
+ // What the board has no field for survives the canvases route's checks.
+ expect(g.nodes.find((n: { id: string }) => n.id === "step-scene").data.skill).toMatchObject({ key: "scene", from: "lamp-scene", check: { kind: "image" } });
+ });
+
+ it("refuses a skill that can't be drawn, saying so", async () => {
+ const r = await canvasesRoute.POST(post("/api/canvases", { skill: "caption-it" }));
+ expect(r.status).toBe(422);
+ expect((await r.json()).error).toMatch(new RegExp(`^${CANT_DRAW}`));
+ expect((await canvasesRoute.POST(post("/api/canvases", { skill: "nope" }))).status).toBe(404);
+ });
+});
+
+describe("Save as skill from a canvas", () => {
+ it("drafts a skill opened as a canvas with its inputs Varies, and saves a swapped model back into it", async () => {
+ 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!.recipe.params).toEqual([]);
+ expect(draft!.candidates.map((x) => [x.id, x.kind, x.varies])).toEqual([
+ ["product", "media", true],
+ ["name", "text", true],
+ ]);
+ // As it starts, the review screen builds the skill it was drawn from.
+ const built = buildRecipe(draft!, startChoices(draft!));
+ expect(built.steps).toEqual(turntable.steps);
+
+ // Swap the scene's model on the board, then save it back.
+ const graph = getCanvas(c.id)!.pages[0].graph;
+ updateCanvas(c.id, { graph: { ...graph, nodes: graph.nodes.map((n) => (n.id === "step-scene" ? { ...n, data: { ...n.data, modelId: "qwen-image-edit-2511-cloud" } } : n)) } });
+ const again = (await draftOf(c.id)).draft!;
+ const recipe = buildRecipe(again, startChoices(again));
+ const saved = await saveRoute.POST(post("/api/assist/skills/draft/save", { name: "lamp-scene", title: "Lamp scene", description: "A product on a plinth.", body: "# Lamp scene", recipe, replace: true }));
+ expect(saved.status).toBe(201);
+ const now = recipes.getRecipe("lamp-scene");
+ expect((now.recipe.steps[1] as { request: { modelId: string } }).request.modelId).toBe("qwen-image-edit-2511-cloud");
+ expect(now.skill.body).toBe("# Lamp scene");
+ expect(now.recipe.verified?.cloud?.plan).toBeTruthy();
+ // A built-in or a skill that's gone isn't replaced.
+ const refused = await saveRoute.POST(post("/api/assist/skills/draft/save", { name: "product-photoshoot", title: "x", description: "x", body: "x", recipe, replace: true }));
+ expect(refused.status).toBe(403);
+ });
+
+ it("drafts a board made on the Canvas with every input Fixed, and a Table's rows for the Many tab; it then runs from its form", async () => {
+ const c = createCanvas({
+ name: "Fox posters",
+ graph: {
+ nodes: [
+ { id: "t", type: "table", position: { x: 0, y: 0 }, data: { columns: ["Animal"], rows: [["fox"], ["owl"]] } },
+ { id: "img", type: "image-input", position: { x: 0, y: 200 }, data: { url: photo } },
+ { id: "m", type: "model", position: { x: 400, y: 0 }, data: { modelId: "nano-banana-pro", op: "edit", prompt: "a {Animal} poster in this style" } },
+ ],
+ edges: [
+ { id: "e1", source: "t", target: "m", sourceHandle: "out", targetHandle: "prompt" },
+ { id: "e2", source: "img", target: "m", sourceHandle: "out", targetHandle: "images" },
+ ],
+ },
+ });
+ const { draft } = await draftOf(c.id);
+ expect(draft!.replaces).toBeUndefined();
+ expect(draft!.name).toBe("fox-posters");
+ expect(draft!.candidates.map((x) => [x.id, x.varies ?? false, x.part ?? false])).toEqual([
+ ["image", false, false],
+ ["animal", true, true],
+ ]);
+ expect(draft!.rows).toEqual([{ animal: "fox" }, { animal: "owl" }]);
+ expect((draft!.recipe.steps[0] as { request: { prompt: string } }).request.prompt).toBe("a fox poster in this style");
+ const recipe = buildRecipe(draft!, startChoices(draft!));
+ expect((recipe.steps[0] as { request: { prompt: string } }).request.prompt).toBe("a {{animal}} poster in this style");
+ const saved = await saveRoute.POST(post("/api/assist/skills/draft/save", { name: draft!.name, title: draft!.title, description: draft!.description, body: "# Fox posters", recipe }));
+ expect(saved.status).toBe(201);
+ expect(recipes.getRecipe("fox-posters").recipe.source).toMatchObject({ from: "canvas", canvas: c.id });
+ // Run from its form, once per row: two runs of one step each, stamped with the skill.
+ const out = await recipes.runRecipe("fox-posters", { rows: draft!.rows });
+ expect(out.runs).toHaveLength(2);
+ const g = gens.getGeneration(out.runs[0].ids[0])!;
+ expect(g.request.prompt).toBe("a fox poster in this style");
+ expect(g.request.skill).toMatchObject({ name: "fox-posters" });
+ });
+
+ it("names a node that can't run", async () => {
+ const c = createCanvas({ name: "Broken", graph: { nodes: [{ id: "m", type: "model", position: { x: 0, y: 0 }, data: { modelId: "kling-3", op: "i2v" } }], edges: [] } });
+ const { draft, refusals } = await draftOf(c.id);
+ expect(draft).toBeNull();
+ expect(refusals[0]).toMatchObject({ id: "m" });
+ expect((await draftRoute.POST(post("/api/assist/skills/draft", { canvas: "nope" }))).status).toBe(404);
+ });
+
+ it("draws a skill made from a canvas the same way back", async () => {
+ const r = recipes.getRecipe("lamp-scene").recipe;
+ const c = await (await canvasesRoute.POST(post("/api/canvases", { skill: "lamp-scene" }))).json();
+ const { draft } = await draftOf(c.id);
+ expect(recipeShape(buildRecipe(draft!, startChoices(draft!)))).toBe(recipeShape({ ...r, checks: r.checks }));
+ });
+});
diff --git a/tests/public-signup-visitors.test.ts b/tests/public-signup-visitors.test.ts
index 1e853a36..9d230583 100644
--- a/tests/public-signup-visitors.test.ts
+++ b/tests/public-signup-visitors.test.ts
@@ -98,7 +98,7 @@ describe("Assist is the owner's", () => {
["POST", "/api/assist/skills"],
["POST", "/api/assist/skills/upload"],
["POST", "/api/assist/skills/draft"],
- // Save as skill from a chat (W3) drafts and names through these two.
+ // Save as skill from a chat (W3), and from a canvas (W5, { canvas }), drafts and names through these two.
["POST", "/api/assist/skills/draft/name"],
["PATCH", "/api/assist/skills/ad-multiplier"],
["POST", "/api/assist/skills/product-photoshoot/run"],
diff --git a/tests/public-signup.test.ts b/tests/public-signup.test.ts
index ad74b5b1..0211f2c6 100644
--- a/tests/public-signup.test.ts
+++ b/tests/public-signup.test.ts
@@ -284,6 +284,7 @@ describe("accounts never see or change the owner's library", () => {
shares: { lists: ["/api/shares"], records: ["/api/shares/s1"], changes: [["POST", "/api/shares"], ["PATCH", "/api/shares/s1"], ["DELETE", "/api/shares/s1"]] },
layers: { lists: ["/api/layers"], records: ["/api/layers/l1"], changes: [["POST", "/api/layers"], ["PATCH", "/api/layers/l1"], ["DELETE", "/api/layers/l1"], ["POST", "/api/layers/l1/versions"]] },
elements: { lists: ["/api/elements"], records: ["/api/elements/e1"], changes: [["POST", "/api/elements"], ["PATCH", "/api/elements/e1"], ["DELETE", "/api/elements/e1"]] },
+ // POST /api/canvases is also Open as canvas ({ skill }, W5): a new canvas in the owner's library.
canvases: { lists: ["/api/canvases"], records: ["/api/canvases/c1"], changes: [["POST", "/api/canvases"], ["PATCH", "/api/canvases/c1"], ["DELETE", "/api/canvases/c1"], ["POST", "/api/canvases/c1/duplicate"]] },
cinema: { lists: ["/api/cinema/projects"], records: ["/api/cinema/projects/p1", "/api/cinema/projects/p1/items"], changes: [["POST", "/api/cinema/projects"], ["PATCH", "/api/cinema/projects/p1"], ["DELETE", "/api/cinema/projects/p1"]] },
storyboards: { lists: [], records: ["/api/storyboards"], changes: [["POST", "/api/storyboards"]] },