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 Skills tab opens recipe skills as canvases, and the run menu saves a canvas as a skill

Claude98ab25bea47a
diff --git a/src/components/assist/hooks.ts b/src/components/assist/hooks.ts
index 9c7a985f..3d356df7 100644
--- a/src/components/assist/hooks.ts
+++ b/src/components/assist/hooks.ts
@@ -244,15 +244,15 @@ export interface DraftCheckResult {
}
/** What a skill is drafted from: results picked in the Library (W2), or an Assist chat whose plans ran (W3). */
-export type DraftSource = { generations: string[] } | { thread: string };
+export type DraftSource = { generations: string[] } | { thread: string } | { canvas: string; page?: string };
-const sourceKey = (s: DraftSource) => ("thread" in s ? `chat:${s.thread}` : s.generations.join(","));
+export const sourceKey = (s: DraftSource) => ("thread" in s ? `chat:${s.thread}` : "canvas" in s ? `canvas:${s.canvas}:${s.page ?? ""}` : s.generations.join(","));
/** The draft of a skill from picked results or a chat: its steps rebuilt, every input Fixed, and what it couldn't use. */
export function useSkillDraft(source: DraftSource) {
return useQuery({
queryKey: ["skill-draft", sourceKey(source)],
- enabled: "thread" in source || source.generations.length > 0,
+ enabled: !("generations" in source) || source.generations.length > 0,
retry: false,
// Read once while the review is open, and dropped when it closes: opened again, it is drafted again (a name saved
// since is taken, a result trashed since is gone).
@@ -269,7 +269,7 @@ export function useDraftActions() {
check: (recipe: unknown, level: "plan" | "demo", title?: string) => recipeCall<DraftCheckResult>("/api/assist/skills/draft/check", { recipe, level, title }),
/** The optional naming pass (null: no LLM, or its answer didn't fit). */
name: async (source: DraftSource) => (await recipeCall<{ naming: Naming | null }>("/api/assist/skills/draft/name", source)).naming,
- save: async (body: { name: string; title: string; description: string; whenToUse?: string; body: string; recipe: unknown }) => {
+ save: async (body: { name: string; title: string; description: string; whenToUse?: string; body: string; recipe: unknown; replace?: boolean }) => {
const view = await recipeCall<RecipeView>("/api/assist/skills/draft/save", body);
qc.setQueryData(["assist-recipe", view.name], view);
qc.removeQueries({ queryKey: ["skill-draft"] });
diff --git a/src/components/assist/run-skill-dialog.tsx b/src/components/assist/run-skill-dialog.tsx
index 073a9aa9..95ba8ea0 100644
--- a/src/components/assist/run-skill-dialog.tsx
+++ b/src/components/assist/run-skill-dialog.tsx
@@ -32,20 +32,21 @@ import { SkillIcon } from "./skill-icon";
* Run a skill with new inputs (package W1): a form made from its recipe's inputs, priced live before it runs, one
* run or many from a pasted CSV, on an engine where the recipe was checked. No LLM: the server compiles the recipe.
*/
-export function RunSkillDialog({ name, onClose, examples, intro }: { name: string | null; onClose: () => void; examples?: boolean; intro?: string }) {
+/** `csv`: the Many tab starts with these rows (a canvas's Table, saved as a skill). */
+export function RunSkillDialog({ name, onClose, examples, intro, csv }: { name: string | null; onClose: () => void; examples?: boolean; intro?: string; csv?: string }) {
return (
<Dialog open={!!name} onOpenChange={(o) => !o && onClose()}>
<DialogContent className="flex max-h-[min(94svh,900px)] flex-col gap-0 overflow-hidden p-0 max-sm:h-svh max-sm:max-h-svh max-sm:max-w-full max-sm:rounded-none max-sm:ring-0 sm:max-w-[680px]">
- {name && <RunForm key={name} name={name} onClose={onClose} examples={examples} intro={intro} />}
+ {name && <RunForm key={name} name={name} onClose={onClose} examples={examples} intro={intro} csv={csv} />}
</DialogContent>
</Dialog>
);
}
/** `examples`: the form starts filled with the values the skill was made from (a skill just made: "Try it with new inputs"). */
-function RunForm({ name, onClose, examples, intro }: { name: string; onClose: () => void; examples?: boolean; intro?: string }) {
+function RunForm({ name, onClose, examples, intro, csv }: { name: string; onClose: () => void; examples?: boolean; intro?: string; csv?: string }) {
const view = useRecipe(name);
- if (view.data) return <Loaded view={view.data} onClose={onClose} examples={examples} intro={intro} />;
+ if (view.data) return <Loaded view={view.data} onClose={onClose} examples={examples} intro={intro} startCsv={csv} />;
return (
<div className="space-y-3 p-6">
<DialogTitle className="sr-only">Run a skill</DialogTitle>
@@ -82,20 +83,20 @@ function priceLine(e: RecipeEstimate | undefined, runs: number): string {
return runs > 1 ? `${formatCost(e.total)} for ${runs} runs ${where}` : `${formatCost(e.total)} ${where}`;
}
-function Loaded({ view, onClose, examples, intro }: { view: RecipeView; onClose: () => void; examples?: boolean; intro?: string }) {
+function Loaded({ view, onClose, examples, intro, startCsv }: { view: RecipeView; onClose: () => void; examples?: boolean; intro?: string; startCsv?: string }) {
const { recipe, name } = view;
const actions = useRecipeActions();
const skillActions = useSkillActions();
const qc = useQueryClient();
const router = useRouter();
- const [tab, setTab] = useState<"one" | "many">("one");
+ const [tab, setTab] = useState<"one" | "many">(startCsv ? "many" : "one");
const [values, setValues] = useState<Record<string, string | number | undefined>>(() =>
Object.fromEntries(recipe.params.map((p) => [p.id, examples && !isMediaType(p.type) && p.example !== undefined && p.example !== null ? p.example : p.default])),
);
const [slots, setSlots] = useState<Record<string, SlotValue | null>>(() =>
examples ? Object.fromEntries(recipe.params.flatMap((p) => (isMediaType(p.type) && typeof p.example === "string" && p.example ? [[p.id, { ref: p.example, preview: p.example, kind: p.type }]] : []))) : {},
);
- const [csv, setCsv] = useState("");
+ const [csv, setCsv] = useState(startCsv ?? "");
const [engine, setEngine] = useState<Engine>(view.ready[0] ?? view.engines[0] ?? "cloud");
const [tried, setTried] = useState(false);
const [busy, setBusy] = useState<"run" | "check" | "on" | null>(null);
diff --git a/src/components/canvas/canvas-editor.tsx b/src/components/canvas/canvas-editor.tsx
index 506616f3..dd873cdd 100644
--- a/src/components/canvas/canvas-editor.tsx
+++ b/src/components/canvas/canvas-editor.tsx
@@ -26,7 +26,7 @@ import {
type OnNodeDrag,
type Viewport,
} from "@xyflow/react";
-import { ChevronDown, ChevronLeft, Check, Cloud, Cpu, LayoutGrid, List, Loader2, Play, RotateCcw, Sparkles, TriangleAlert } from "lucide-react";
+import { BookmarkPlus, ChevronDown, ChevronLeft, Check, Cloud, Cpu, LayoutGrid, List, Loader2, Play, RotateCcw, Sparkles, TriangleAlert } from "lucide-react";
import Link from "next/link";
import { useTheme } from "next-themes";
import { memo, useCallback, useDeferredValue, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
@@ -42,7 +42,8 @@ import { EngineSwitch } from "@/components/studio/engine-switch";
import { fileToSlot } from "@/components/studio/media-slot";
import { Viewer } from "@/components/studio/viewer";
import { useIsMobile } from "@/hooks/use-mobile";
-import { useElements, useEngine, useStatus, type EngineMode } from "@/lib/api";
+import { useSkillBuilder } from "@/components/skills/skill-builder-provider";
+import { useElements, useEngine, useIsVisitor, useStatus, type EngineMode } from "@/lib/api";
import { getModel } from "@/lib/catalog";
import { stemLabel, type StemId } from "@/lib/av/split";
import { dualEngine, onEngine, runsOn } from "@/lib/catalog/engines";
@@ -1238,6 +1239,14 @@ function Editor({ id, initial, view }: { id: string; initial: Canvas; view: Canv
.filter(Boolean)
.join(" · ");
+ // ---- Save as skill (W5): the board as it stands is saved first, then drafted on the server
+ const skillBuilder = useSkillBuilder();
+ const visitor = useIsVisitor();
+ const saveAsSkill = async () => {
+ await save();
+ skillBuilder?.openCanvas(id, latest.current.pageId);
+ };
+
// ---- what the header and the palette call: stable, so they skip the re-render a keystroke causes
const uiHandlers = useRef<{
run: typeof run;
@@ -1245,9 +1254,10 @@ function Editor({ id, initial, view }: { id: string; initial: Canvas; view: Canv
switchEngine: typeof switchEngine;
rename: typeof rename;
addAtCenter: typeof addAtCenter;
+ saveAsSkill: typeof saveAsSkill;
} | null>(null);
useLayoutEffect(() => {
- uiHandlers.current = { run, runSelection, switchEngine, rename, addAtCenter };
+ uiHandlers.current = { run, runSelection, switchEngine, rename, addAtCenter, saveAsSkill };
});
const ui = useMemo<HeaderUi>(
() => ({
@@ -1256,6 +1266,7 @@ function Editor({ id, initial, view }: { id: string; initial: Canvas; view: Canv
switchEngine: (e) => uiHandlers.current!.switchEngine(e),
rename: (v) => void uiHandlers.current!.rename(v),
addAtCenter: (p) => uiHandlers.current!.addAtCenter(p),
+ saveAsSkill: () => void uiHandlers.current!.saveAsSkill(),
}),
[],
);
@@ -1279,6 +1290,7 @@ function Editor({ id, initial, view }: { id: string; initial: Canvas; view: Canv
selectedCount={isMobile ? 0 : selected.length}
running={runM.isPending}
canRun={generators.length > 0}
+ canSaveSkill={!!skillBuilder && !visitor}
mode={mode}
ui={ui}
/>
@@ -1493,6 +1505,7 @@ interface HeaderUi {
switchEngine: (e: Engine) => void;
rename: (name: string) => void;
addAtCenter: (p: PaletteItem) => void;
+ saveAsSkill: () => void;
}
const EditorHeader = memo(function EditorHeader({
@@ -1506,6 +1519,7 @@ const EditorHeader = memo(function EditorHeader({
selectedCount,
running,
canRun,
+ canSaveSkill,
mode,
ui,
}: {
@@ -1519,6 +1533,7 @@ const EditorHeader = memo(function EditorHeader({
selectedCount: number;
running: boolean;
canRun: boolean;
+ canSaveSkill: boolean;
mode: EngineMode;
ui: HeaderUi;
}) {
@@ -1605,6 +1620,14 @@ const EditorHeader = memo(function EditorHeader({
<DropdownMenuItem disabled={mode === "open"} onSelect={() => ui.switchEngine("cloud")}>
<Cloud /> Switch all to cloud
</DropdownMenuItem>
+ {canSaveSkill && (
+ <>
+ <DropdownMenuSeparator />
+ <DropdownMenuItem onSelect={() => ui.saveAsSkill()}>
+ <BookmarkPlus /> Save as skill…
+ </DropdownMenuItem>
+ </>
+ )}
</DropdownMenuContent>
</DropdownMenu>
</div>
diff --git a/src/components/canvas/canvas-list.tsx b/src/components/canvas/canvas-list.tsx
index a52d36de..43fe59c2 100644
--- a/src/components/canvas/canvas-list.tsx
+++ b/src/components/canvas/canvas-list.tsx
@@ -1,6 +1,6 @@
"use client";
-import { Cloud, Copy, Cpu, Loader2, MoreHorizontal, Pencil, Plus, Search, Trash2, Workflow } from "lucide-react";
+import { BookOpen, Cloud, Copy, Cpu, Loader2, MoreHorizontal, Pencil, Plus, Search, Trash2, Workflow } from "lucide-react";
import Link from "next/link";
import { useRouter, useSearchParams } from "next/navigation";
import { Suspense, useState } from "react";
@@ -26,6 +26,8 @@ import { cn } from "@/lib/utils";
import { toastError } from "@/lib/refusals";
import { NodeIcon } from "./canvas-context";
import { useCanvasActions, useCanvases } from "./use-canvas";
+import { useRecipe, useSkills } from "@/components/assist/hooks";
+import type { SkillSummary } from "@/lib/assist";
const BOX = { w: 280, h: 150 };
@@ -211,7 +213,7 @@ export function TemplateCard({ t, engine, onUse, busy }: { t: TemplateCardData;
function ListInner({ templates }: { templates: TemplateCardData[] }) {
const router = useRouter();
const params = useSearchParams();
- const tab = params.get("tab") === "templates" ? "templates" : "mine";
+ const tab = params.get("tab") === "templates" ? "templates" : params.get("tab") === "skills" ? "skills" : "mine";
const canvases = useCanvases();
const { create, rename, remove } = useCanvasActions();
const [engine, setEngine] = useEngine();
@@ -224,7 +226,7 @@ function ListInner({ templates }: { templates: TemplateCardData[] }) {
const visitor = useIsVisitor();
const items = (canvases.data ?? []).filter((c) => !q || c.name.toLowerCase().includes(q.toLowerCase()));
- const setTab = (t: "mine" | "templates") => router.replace(t === "templates" ? "/canvas?tab=templates" : "/canvas", { scroll: false });
+ const setTab = (t: "mine" | "templates" | "skills") => router.replace(t === "mine" ? "/canvas" : `/canvas?tab=${t}`, { scroll: false });
const start = async (key: string, body: Parameters<typeof create>[0]) => {
setCreating(key);
@@ -254,11 +256,12 @@ function ListInner({ templates }: { templates: TemplateCardData[] }) {
</div>
<div className="mt-6 flex flex-wrap items-center gap-3">
- <div className="inline-grid h-9 grid-cols-2 rounded-full bg-muted p-0.5 text-[13px] font-medium" role="tablist" aria-label="Canvases or templates">
+ <div className="inline-grid h-9 grid-cols-3 rounded-full bg-muted p-0.5 text-[13px] font-medium" role="tablist" aria-label="Canvases, templates or skills">
{(
[
["mine", "Your canvases"],
["templates", "Templates"],
+ ["skills", "Skills"],
] as const
).map(([k, label]) => (
<button key={k} role="tab" aria-selected={tab === k} onClick={() => setTab(k)} className={cn("rounded-full px-3.5 transition-colors", tab === k ? "bg-background text-foreground shadow-soft" : "text-muted-foreground hover:text-foreground")}>
@@ -271,7 +274,7 @@ function ListInner({ templates }: { templates: TemplateCardData[] }) {
<Search className="pointer-events-none absolute top-1/2 left-3 size-4 -translate-y-1/2 text-muted-foreground" />
<Input value={q} onChange={(e) => setQ(e.target.value)} placeholder="Search canvases" aria-label="Search canvases" className="h-9 rounded-full pl-9" />
</div>
- ) : (
+ ) : tab === "skills" ? null : (
<div className="ml-auto flex items-center gap-2 text-[13px] text-muted-foreground">
<span className="hidden sm:inline">Variant</span>
<EngineSwitch value={engine} onChange={setEngine} size="sm" />
@@ -326,6 +329,8 @@ function ListInner({ templates }: { templates: TemplateCardData[] }) {
</EmptyContent>
</Empty>
)
+ ) : tab === "skills" ? (
+ <SkillsTab visitor={visitor} busy={creating} onOpen={(name) => void start(`skill:${name}`, { skill: name })} />
) : (
<div className="mt-6 space-y-10">
{[...new Set(templates.map((t) => t.group ?? ""))].map((group) => (
@@ -403,6 +408,79 @@ function ListInner({ templates }: { templates: TemplateCardData[] }) {
);
}
+/** Recipe skills (W5): each that can be drawn opens as a new canvas; one that runs a studio step shows as a note. */
+function SkillsTab({ visitor, busy, onOpen }: { visitor: boolean; busy: string | null; onOpen: (name: string) => void }) {
+ const skills = useSkills();
+ const list = (skills.data ?? []).filter((s) => s.recipe);
+ if (skills.isLoading)
+ return (
+ <div className="mt-6 grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3">
+ {Array.from({ length: 3 }, (_, i) => (
+ <Skeleton key={i} className="h-40 rounded-xl" />
+ ))}
+ </div>
+ );
+ if (!list.length)
+ return (
+ <Empty className="mt-6 border">
+ <EmptyHeader>
+ <EmptyMedia variant="icon">
+ <BookOpen />
+ </EmptyMedia>
+ <EmptyTitle className="text-[22px]">No skills that run by themselves yet</EmptyTitle>
+ <EmptyDescription>Make one from results you like in the Library, or save a canvas as a skill from its run menu: it then opens here as a canvas.</EmptyDescription>
+ </EmptyHeader>
+ </Empty>
+ );
+ return (
+ <div className="mt-6 space-y-3">
+ <p className="text-[13px] text-muted-foreground">Open a skill as a new canvas to see its steps and swap a model, then use Save as skill to put it back.</p>
+ <div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3">
+ {list.map((s) => (
+ <SkillCard key={s.name} s={s} visitor={visitor} busy={busy === `skill:${s.name}`} onOpen={() => onOpen(s.name)} />
+ ))}
+ </div>
+ </div>
+ );
+}
+
+function SkillCard({ s, visitor, busy, onOpen }: { s: SkillSummary; visitor: boolean; busy: boolean; onOpen: () => void }) {
+ const view = useRecipe(s.name);
+ const drawn = view.data?.canvas;
+ const steps = view.data?.recipe.steps.length;
+ return (
+ <article className="flex min-w-0 flex-col gap-2 rounded-xl border bg-card p-3.5">
+ <div className="min-w-0">
+ <h3 className="truncate text-[14px] font-medium">{s.title || s.name}</h3>
+ <p className="font-mono text-[12px] text-muted-foreground">/{s.name}</p>
+ </div>
+ {s.description && <p className="line-clamp-2 text-[13px] text-muted-foreground">{s.description}</p>}
+ {!view.data ? (
+ view.isError ? null : <Skeleton className="h-8 w-32 rounded-full" />
+ ) : drawn && !drawn.ok ? (
+ drawn.studio ? (
+ <p className="rounded-lg bg-muted/60 px-3 py-2 text-[12px] text-muted-foreground">
+ <span className="font-medium text-foreground">Studio step</span> · runs {drawn.studio} as one step, so it isn&apos;t drawn as nodes. Run it from Skills.
+ </p>
+ ) : (
+ <p className="rounded-lg bg-muted/60 px-3 py-2 text-[12px] text-muted-foreground">
+ <span className="font-medium text-foreground">This skill can&apos;t be drawn yet</span> · {drawn.detail}.
+ </p>
+ )
+ ) : (
+ <div className="mt-auto flex flex-wrap items-center gap-2">
+ {!visitor && (
+ <Button size="sm" className="w-fit rounded-full" onClick={onOpen} disabled={busy}>
+ {busy ? <Loader2 className="animate-spin" /> : <Workflow />} Open as canvas
+ </Button>
+ )}
+ {steps !== undefined && <span className="text-[12px] text-muted-foreground">{steps === 1 ? "1 step" : `${steps} steps`}</span>}
+ </div>
+ )}
+ </article>
+ );
+}
+
export function CanvasList({ templates }: { templates: TemplateCardData[] }) {
return (
<Suspense fallback={null}>
diff --git a/src/components/canvas/use-canvas.ts b/src/components/canvas/use-canvas.ts
index 4651ab15..ea53ffad 100644
--- a/src/components/canvas/use-canvas.ts
+++ b/src/components/canvas/use-canvas.ts
@@ -52,7 +52,7 @@ export function useCanvasActions() {
const qc = useQueryClient();
const refresh = () => void qc.invalidateQueries({ queryKey: ["canvases"], exact: true });
return {
- create: async (body: { name?: string; templateId?: string; engine?: Engine; graph?: CanvasGraph }) => {
+ create: async (body: { name?: string; templateId?: string; engine?: Engine; graph?: CanvasGraph; skill?: string }) => {
const c = await json<Canvas>(await send("/api/canvases", "POST", body));
refresh();
return c;
diff --git a/src/components/skills/skill-builder-provider.tsx b/src/components/skills/skill-builder-provider.tsx
index 36937499..6fe5de4c 100644
--- a/src/components/skills/skill-builder-provider.tsx
+++ b/src/components/skills/skill-builder-provider.tsx
@@ -2,7 +2,7 @@
import dynamic from "next/dynamic";
import { createContext, useCallback, useContext, useMemo, useState } from "react";
-import type { DraftSource } from "@/components/assist/hooks";
+import { sourceKey, type DraftSource } from "@/components/assist/hooks";
/**
* "Make a skill" from anywhere under the studio layout (the result ⋯ menu in the Library, the feeds and the viewer; the
@@ -13,6 +13,8 @@ interface SkillBuilderApi {
open: (ids: string[]) => void;
/** Draft a skill from an Assist chat: the plans that ran in it (W3, "Save as skill"). */
openChat: (thread: string) => void;
+ /** Draft a skill from a canvas page, saved first (W5, the canvas's "Save as skill"). */
+ openCanvas: (canvas: string, page?: string) => void;
}
const Ctx = createContext<SkillBuilderApi | null>(null);
@@ -27,11 +29,12 @@ export function SkillBuilderProvider({ children }: { children: React.ReactNode }
// After a menu has closed and handed focus back, so the dialog keeps it.
const open = useCallback((list: string[]) => void setTimeout(() => list.length && setSource({ generations: [...new Set(list)] }), 0), []);
const openChat = useCallback((thread: string) => void setTimeout(() => setSource({ thread }), 0), []);
- const api = useMemo(() => ({ open, openChat }), [open, openChat]);
+ const openCanvas = useCallback((canvas: string, page?: string) => void setTimeout(() => setSource({ canvas, ...(page && { page }) }), 0), []);
+ const api = useMemo(() => ({ open, openChat, openCanvas }), [open, openChat, openCanvas]);
return (
<Ctx.Provider value={api}>
{children}
- {source && <SkillBuilder key={"thread" in source ? `chat:${source.thread}` : source.generations.join(",")} source={source} onClose={() => setSource(null)} />}
+ {source && <SkillBuilder key={sourceKey(source)} source={source} onClose={() => setSource(null)} />}
</Ctx.Provider>
);
}
diff --git a/src/components/skills/skill-builder.tsx b/src/components/skills/skill-builder.tsx
index 46b0ad08..6a62a4f2 100644
--- a/src/components/skills/skill-builder.tsx
+++ b/src/components/skills/skill-builder.tsx
@@ -16,7 +16,7 @@ import { Textarea } from "@/components/ui/textarea";
import { SKILL_LIMITS, SKILL_NAME_RE } from "@/lib/assist";
import { formatCost } from "@/lib/format";
import { isMediaType, recipeProblems, RECIPE_LIMITS, type ParamType } from "@/lib/recipe";
-import { buildRecipe, paramIdFrom, skillBody, slugify, type DraftCandidate, type DraftRefusal, type DraftStep, type Naming, type SkillDraft, type Slot } from "@/lib/recipe-builder";
+import { buildRecipe, paramIdFrom, rowsCsv, skillBody, slugify, type DraftCandidate, type DraftRefusal, type DraftStep, type Naming, type SkillDraft, type Slot } from "@/lib/recipe-builder";
import { refusalShown } from "@/lib/refusals";
import { cn } from "@/lib/utils";
@@ -27,7 +27,7 @@ import { cn } from "@/lib/utils";
* A tall dialog on a desktop, the whole screen on a phone.
*/
export function SkillBuilder({ source, onClose }: { source: DraftSource; onClose: () => void }) {
- const [saved, setSaved] = useState<string | null>(null);
+ const [saved, setSaved] = useState<{ name: string; csv?: string } | null>(null);
return (
<>
<Dialog open={!saved} onOpenChange={(o) => !o && !saved && onClose()}>
@@ -35,22 +35,35 @@ export function SkillBuilder({ source, onClose }: { source: DraftSource; onClose
<Loader source={source} onClose={onClose} onSaved={setSaved} />
</DialogContent>
</Dialog>
- {saved && <RunSkillDialog name={saved} examples intro="Try it with new inputs: the form starts with the ones it was made from." onClose={onClose} />}
+ {saved && (
+ <RunSkillDialog
+ name={saved.name}
+ examples
+ csv={saved.csv}
+ intro={saved.csv ? "Run it for the table's rows, or switch to One for a single run." : "Try it with new inputs: the form starts with the ones it was made from."}
+ onClose={onClose}
+ />
+ )}
</>
);
}
-function Loader({ source, onClose, onSaved }: { source: DraftSource; onClose: () => void; onSaved: (name: string) => void }) {
+type Saved = { name: string; csv?: string };
+
+function Loader({ source, onClose, onSaved }: { source: DraftSource; onClose: () => void; onSaved: (saved: Saved) => void }) {
const q = useSkillDraft(source);
const chat = "thread" in source;
- const count = chat ? 0 : source.generations.length;
+ const board = "canvas" in source;
+ const count = "generations" in source ? source.generations.length : 0;
const header = (
<DialogHeader className="border-b px-5 pt-5 pb-4 text-left">
- <DialogTitle className="font-heading text-[24px] leading-tight font-normal">{chat ? "Save as skill" : "Make a skill"}</DialogTitle>
+ <DialogTitle className="font-heading text-[24px] leading-tight font-normal">{chat || board ? "Save as skill" : "Make a skill"}</DialogTitle>
<DialogDescription>
{chat
? "From this chat: Fuobe rebuilds the steps from the plans that ran, so next time it runs them again with new inputs."
- : `From ${count === 1 ? "this result" : `${count} results`}: Fuobe rebuilds the steps from what you made, so nothing has to be recorded.`}
+ : board
+ ? "From this canvas: its nodes become the steps and its inputs the form, so it runs from Skills, Assist, the CLI and schedules."
+ : `From ${count === 1 ? "this result" : `${count} results`}: Fuobe rebuilds the steps from what you made, so nothing has to be recorded.`}
</DialogDescription>
</DialogHeader>
);
@@ -65,7 +78,7 @@ function Loader({ source, onClose, onSaved }: { source: DraftSource; onClose: ()
</p>
) : q.data ? (
<>
- <p className="text-[14px]">{chat ? "This chat can't become a skill yet:" : q.data.refusals.length === 1 ? "This result can't become a skill yet:" : "None of these results can become a skill yet:"}</p>
+ <p className="text-[14px]">{chat ? "This chat can't become a skill yet:" : board ? "This canvas can't become a skill yet:" : q.data.refusals.length === 1 ? "This result can't become a skill yet:" : "None of these results can become a skill yet:"}</p>
<Refusals list={q.data.refusals} open />
</>
) : (
@@ -97,9 +110,11 @@ interface CheckState {
const ENGINE_WORD = { cloud: "Cloud", open: "your GPU" } as const;
-function Review({ draft, refusals, source, onClose, onSaved, header }: { draft: SkillDraft; refusals: DraftRefusal[]; source: DraftSource; onClose: () => void; onSaved: (name: string) => void; header: React.ReactNode }) {
+function Review({ draft, refusals, source, onClose, onSaved, header }: { draft: SkillDraft; refusals: DraftRefusal[]; source: DraftSource; onClose: () => void; onSaved: (saved: Saved) => void; header: React.ReactNode }) {
const actions = useDraftActions();
- const [varies, setVaries] = useState<Record<string, boolean>>({});
+ // Fixed unless it varied in the skill a canvas was drawn from, or is a Table's column (W5).
+ const [varies, setVaries] = useState<Record<string, boolean>>(() => Object.fromEntries(draft.candidates.filter((c) => c.varies).map((c) => [c.id, true])));
+ const [replace, setReplace] = useState(!!draft.replaces);
const [labels, setLabels] = useState<Record<string, string>>({});
const [pids, setPids] = useState<Record<string, string>>({});
const [required, setRequired] = useState<Record<string, boolean>>({});
@@ -119,11 +134,11 @@ function Review({ draft, refusals, source, onClose, onSaved, header }: { draft:
const own = useMemo(() => {
const out = recipeProblems(recipe);
if (recipe.params.length > RECIPE_LIMITS.params) out.unshift(`A skill takes at most ${RECIPE_LIMITS.params} inputs: switch some back to Fixed`);
- if (!SKILL_NAME_RE.test(name)) out.unshift("The name is lowercase letters, digits and single hyphens (e.g. lamp-turntable)");
+ if (!replace && !SKILL_NAME_RE.test(name)) out.unshift("The name is lowercase letters, digits and single hyphens (e.g. lamp-turntable)");
if (!title.trim()) out.unshift("Give the skill a title");
if (!description.trim()) out.unshift("Give the skill a description");
return out;
- }, [recipe, name, title, description]);
+ }, [recipe, name, title, description, replace]);
const body = customBody ?? skillBody(recipe, draft, { title: title.trim() || draft.title, description: description.trim() || draft.description, name });
const current = check?.key === key ? check : null;
const planOk = !!current?.plan?.ok || (current?.plan?.ready.length ?? 0) > 0;
@@ -159,9 +174,10 @@ function Review({ draft, refusals, source, onClose, onSaved, header }: { draft:
if (!planOk || own.length) return;
setBusy("save");
try {
- const view = await actions.save({ name, title: title.trim(), description: description.trim(), whenToUse: whenToUse.trim() || undefined, body, recipe });
- toast.success(`Saved /${view.name}`, { description: "It's in Skills → My skills. Try it with new inputs now." });
- onSaved(view.name);
+ const into = replace && draft.replaces ? draft.replaces.name : name;
+ const view = await actions.save({ name: into, title: title.trim(), description: description.trim(), whenToUse: whenToUse.trim() || undefined, body, recipe, ...(replace && { replace: true }) });
+ toast.success(replace ? `Saved back into /${view.name}` : `Saved /${view.name}`, { description: replace ? "Its steps are the canvas's now; its SKILL.md is as it was." : "It's in Skills → My skills. Try it with new inputs now." });
+ onSaved({ name: view.name, ...(draft.rows?.length && { csv: rowsCsv(draft.rows, recipe.params, { ids: pids }) }) });
} catch (e) {
const f = e as Error & { problems?: string[] };
if (refusalShown(f)) return;
@@ -282,6 +298,15 @@ function Review({ draft, refusals, source, onClose, onSaved, header }: { draft:
<h3 id="sb-about" className="text-sm font-medium">
About this skill
</h3>
+ {draft.replaces && (
+ <label className="flex items-start gap-2 rounded-xl bg-muted/60 px-3 py-2.5 text-[13px]">
+ <Checkbox checked={replace} onCheckedChange={(v) => setReplace(v === true)} className="mt-0.5" />
+ <span className="min-w-0">
+ <span className="font-medium">Save back into /{draft.replaces.name}</span>
+ <span className="block text-[12px] text-muted-foreground">Its steps and inputs become the canvas&apos;s; its title and SKILL.md stay as they are. Untick to save a new skill.</span>
+ </span>
+ </label>
+ )}
<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)} />
@@ -296,7 +321,8 @@ function Review({ draft, refusals, source, onClose, onSaved, header }: { draft:
onChange={(e) => setName(e.target.value.toLowerCase().replace(/[^a-z0-9-]/g, "-"))}
onBlur={() => setName((n) => slugify(n) || draft.name)}
className="h-9 min-w-0 flex-1 bg-transparent px-1 text-[14px] outline-none"
- aria-invalid={!SKILL_NAME_RE.test(name)}
+ aria-invalid={!replace && !SKILL_NAME_RE.test(name)}
+ disabled={replace}
/>
</div>
</Field>
@@ -344,7 +370,7 @@ function Review({ draft, refusals, source, onClose, onSaved, header }: { draft:
{busy === "check" ? <Loader2 className="animate-spin" /> : <ShieldCheck />} {current?.plan ? "Check again" : "Check it"}
</Button>
<Button size="sm" onClick={() => void save()} disabled={busy !== null || !planOk || own.length > 0} className="max-sm:flex-[1.4]">
- {busy === "save" ? <Loader2 className="animate-spin" /> : <Check />} Save skill
+ {busy === "save" ? <Loader2 className="animate-spin" /> : <Check />} {replace ? "Save back" : "Save skill"}
</Button>
</div>
</div>
@@ -635,7 +661,7 @@ function Words({ c, varies, slots, setSlots, takenIds }: { c: DraftCandidate; va
setTyping(false);
};
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">The whole prompt is an input. Was: “{text}”</p>;
+ 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>;
}
return (
<div className="mt-2 space-y-2">
diff --git a/src/lib/recipe-builder.ts b/src/lib/recipe-builder.ts
index ef6e870d..c8083e6b 100644
--- a/src/lib/recipe-builder.ts
+++ b/src/lib/recipe-builder.ts
@@ -480,6 +480,21 @@ export function fixedDraft(recipe: Recipe, varies: string[] = []): Pick<SkillDra
return { recipe: fixed, candidates };
}
+/**
+ * A canvas's Table rows (by candidate id) as the Run form's Many tab CSV: a header of the input ids the recipe asks for
+ * (a column switched back to Fixed is left out), one quoted line per row.
+ */
+export function rowsCsv(rows: Record<string, string>[], params: Pick<RecipeParam, "id">[], choices: Pick<BuilderChoices, "ids"> = {}): string {
+ const asked = new Set(params.map((p) => p.id));
+ const cols = Object.keys(rows[0] ?? {}).flatMap((cand) => {
+ const id = choices.ids?.[cand]?.trim() || cand;
+ return asked.has(id) ? [{ cand, id }] : [];
+ });
+ if (!cols.length) return "";
+ const cell = (v: string) => (/[",\n\r]/.test(v) ? `"${v.replace(/"/g, '""')}"` : v);
+ return [cols.map((c) => c.id).join(","), ...rows.map((r) => cols.map((c) => cell(r[c.cand] ?? "")).join(","))].join("\n");
+}
+
// ---------------------------------------------------------------------------
// SKILL.md
diff --git a/src/lib/recipe.ts b/src/lib/recipe.ts
index 42fdf920..9c061115 100644
--- a/src/lib/recipe.ts
+++ b/src/lib/recipe.ts
@@ -901,6 +901,8 @@ export interface RecipeView {
why?: string;
/** Each step's model and its licence on each engine, as information. */
models: { engine: RecipeEngine; name: string; licence: string }[];
+ /** Whether it opens as a canvas (W5), or why not; a skill that runs one studio step names the studio. */
+ canvas?: { ok: true } | { ok: false; detail: string; studio?: string };
}
export interface RecipeEstimate {
diff --git a/src/server/recipes.ts b/src/server/recipes.ts
index 6f0b6bdd..4f474dec 100644
--- a/src/server/recipes.ts
+++ b/src/server/recipes.ts
@@ -1,4 +1,6 @@
import "server-only";
+import { recipeToCanvas } from "@/lib/catalog/canvas";
+import { studioForTool } from "@/lib/recipe-builder";
import crypto from "node:crypto";
import fs from "node:fs";
import path from "node:path";
@@ -351,6 +353,10 @@ export function recipeView(name: string): RecipeView {
line: verifiedLine(recipe, engines),
...(!engines.length && { why: noEngine(recipe) }),
models: [...new Map(models.map((x) => [`${x.engine}:${x.name}`, x])).values()],
+ canvas: (() => {
+ const d = recipeToCanvas(recipe);
+ return d.ok ? { ok: true as const } : { ok: false as const, detail: d.detail, ...(d.studio && { studio: studioForTool(d.studio) ?? d.studio }) };
+ })(),
};
}
diff --git a/tests/canvas-skills.test.ts b/tests/canvas-skills.test.ts
index 3f7fe449..e1e4341c 100644
--- a/tests/canvas-skills.test.ts
+++ b/tests/canvas-skills.test.ts
@@ -81,6 +81,9 @@ describe("Open as canvas", () => {
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);
+ // The Skills tab reads the same answer from the skill's recipe view.
+ expect(recipes.recipeView("caption-it").canvas).toMatchObject({ ok: false, studio: "Captions" });
+ expect(recipes.recipeView("lamp-scene").canvas).toEqual({ ok: true });
});
});