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.
TypeScript ai-videocomfyuicreative-toolsgenerative-aiideogramimage-generationimage-to-3dimage-to-videoltx-videominimax-h3nextjsopen-sourceopen-weightsqwen-imagetext-to-imagevideo-generationwan
Skills W1: Run… a skill from the Skills page, one run or many, priced before it starts
Claude6a3fa87790ee
diff --git a/src/components/assist/hooks.ts b/src/components/assist/hooks.tsindex 2d4e5e92..1524f153 100644--- a/src/components/assist/hooks.ts+++ b/src/components/assist/hooks.ts@@ -20,6 +20,7 @@ import type {import type { ConnectorView } from "@/lib/assist-connectors";import type { ScheduleRule, ScheduleView } from "@/lib/assist-schedule";import type { Engine, Generation } from "@/lib/catalog/types";+import type { RecipeEstimate, RecipeRun, RecipeView, VerifyResult } from "@/lib/recipe";/** A rule as the dialog sends it: the server sets when "every N hours" starts counting. */export type ScheduleRuleInput = ScheduleRule extends infer R ? (R extends { kind: "hours" } ? Omit<R, "from"> : R) : never;@@ -176,6 +177,52 @@ export function useSkillActions() {};}+// ---------------------------------------------------------------------------+// Skills that run by themselves (recipe.json, src/lib/recipe.ts)++/** A refusal from the recipe routes: the reason, and every problem of a recipe that can't run as it is. */+export type RecipeFailure = Error & { status?: number; problems?: string[] };++async function recipeCall<T>(url: string, body: unknown): Promise<T> {+ const res = await fetch(url, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) });+ const out = (await res.json().catch(() => ({}))) as T & { error?: string; problems?: string[] };+ if (!res.ok) throw Object.assign(new Error(out.error ?? `Request failed (${res.status})`), { status: res.status, problems: out.problems }) as RecipeFailure;+ return out;+}++/** A skill's recipe with where it runs and what was checked; null when the skill has none. */+export function useRecipe(name: string | null, enabled = true) {+ return useHydrationSafe(+ useQuery({+ queryKey: ["assist-recipe", name],+ enabled: !!name && enabled,+ retry: false,+ queryFn: async () => json<RecipeView>(await fetch(`/api/assist/skills/${name}/recipe`)),+ }),+ );+}++export interface RecipeBody {+ values?: Record<string, unknown>;+ csv?: string;+ engine?: Engine;+}++export function useRecipeActions() {+ const qc = useQueryClient();+ return {+ estimate: (name: string, body: RecipeBody) => recipeCall<RecipeEstimate>(`/api/assist/skills/${name}/estimate`, body),+ run: (name: string, body: RecipeBody) => recipeCall<{ engine: Engine; runs: RecipeRun[]; demo: boolean }>(`/api/assist/skills/${name}/run`, body),+ /** Check it (plan + the free dry run by default); the skill's status is refreshed with the result. */+ verify: async (name: string, body: { level?: "plan" | "demo" | "real"; engine?: Engine; confirm?: boolean } = {}) => {+ const r = await recipeCall<VerifyResult>(`/api/assist/skills/${name}/verify`, { level: "demo", ...body });+ qc.setQueryData(["assist-recipe", name], r.view);+ void qc.invalidateQueries({ queryKey: ["assist-skills"] });+ return r;+ },+ };+}+// ---------------------------------------------------------------------------// Memorydiff --git a/src/components/assist/plan-jobs.tsx b/src/components/assist/plan-jobs.tsxnew file mode 100644index 00000000..d4b4f10d--- /dev/null+++ b/src/components/assist/plan-jobs.tsx@@ -0,0 +1,72 @@+"use client";++import { AudioLines, Box, Brain, CircleAlert, Clapperboard, FileText, ImageIcon, Video } from "lucide-react";+import { useState } from "react";+import type { PlannedJob } from "@/lib/assist";+import { OPERATION_LABELS, type MediaKind, type Operation } from "@/lib/catalog/types";+import { formatCost } from "@/lib/format";+import { cn } from "@/lib/utils";++const KIND_ICON: Record<MediaKind | "storyboard" | "memory", typeof ImageIcon> = { image: ImageIcon, video: Video, audio: AudioLines, text: FileText, model3d: Box, storyboard: Clapperboard, memory: Brain };++/** One job's price on a plan: Free, Demo, a price, or a dash when it can't run. */+export function jobPrice(j: PlannedJob): string {+ if (j.error) return "—";+ if (j.op === "memory") return "";+ if (j.demo) return "Demo";+ if (j.costUsd === 0) return "Free";+ return j.costUsd === null ? "Price varies" : formatCost(j.costUsd);+}++function jobLine(j: PlannedJob): string {+ if (j.op === "storyboard") return `Storyboard · ${j.count} frames`;+ if (j.op === "memory") return j.note ?? "Memory";+ const op = OPERATION_LABELS[j.op as Operation] ?? j.op;+ return [j.note && j.note !== op ? j.note : op, j.count > 1 ? `${j.count} takes` : ""].filter(Boolean).join(" · ");+}++/**+ * The jobs of a plan, priced, each with what stops it: Assist's approval card and a skill's "What runs". Long plans+ * (a dub, a faceless episode) fold after `fold` steps.+ */+export function PlanJobs({ jobs, fold = 6, className }: { jobs: PlannedJob[]; fold?: number; className?: string }) {+ const [all, setAll] = useState(false);+ const shown = all ? jobs : jobs.slice(0, fold);+ return (+ <>+ <ul className={cn("divide-y", className)}>+ {shown.map((j, i) => {+ const Icon = KIND_ICON[j.op === "storyboard" ? "storyboard" : j.op === "memory" ? "memory" : j.kind];+ return (+ <li key={i} className="flex gap-3 px-4 py-3">+ <span className="mt-0.5 grid size-8 shrink-0 place-items-center rounded-lg bg-secondary">+ <Icon className="size-4" />+ </span>+ <div className="min-w-0 flex-1">+ <p className="text-[13px] font-medium break-words">+ {j.modelName}+ <span className="font-normal text-muted-foreground">+ {" · "}+ {jobLine(j)}+ </span>+ </p>+ <p className={cn("mt-0.5 text-[13px] break-words", j.op === "memory" ? "text-foreground" : "line-clamp-2 text-muted-foreground")}>{j.prompt}</p>+ {j.error && (+ <p className="mt-1 flex items-start gap-1 text-[12px] text-destructive">+ <CircleAlert className="mt-0.5 size-3 shrink-0" /> {j.error}+ </p>+ )}+ </div>+ <span className="shrink-0 font-mono text-[12px] text-muted-foreground">{jobPrice(j)}</span>+ </li>+ );+ })}+ </ul>+ {jobs.length > fold && (+ <button type="button" onClick={() => setAll((v) => !v)} className="w-full border-t px-4 py-2 text-left text-[12px] font-medium text-brand-text hover:bg-accent">+ {all ? "Show fewer steps" : `Show all ${jobs.length} steps`}+ </button>+ )}+ </>+ );+}diff --git a/src/components/assist/run-skill-dialog.tsx b/src/components/assist/run-skill-dialog.tsxnew file mode 100644index 00000000..09a79e28--- /dev/null+++ b/src/components/assist/run-skill-dialog.tsx@@ -0,0 +1,570 @@+"use client";++import { keepPreviousData, useQuery } from "@tanstack/react-query";+import { AlertTriangle, ChevronDown, Cloud, Cpu, FileUp, Info, Loader2, Minus, Play, Plus, ShieldCheck, X } from "lucide-react";+import Link from "next/link";+import { useRouter } from "next/navigation";+import { useEffect, useId, useMemo, useRef, useState } from "react";+import { toast } from "sonner";+import { Button } from "@/components/ui/button";+import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible";+import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";+import { Input } from "@/components/ui/input";+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";+import { Skeleton } from "@/components/ui/skeleton";+import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs";+import { Textarea } from "@/components/ui/textarea";+import { EngineSwitch } from "@/components/studio/engine-switch";+import { MediaSlot, type SlotValue } from "@/components/studio/media-slot";+import { radioKeys, radioTab } from "@/components/studio/radio-keys";+import { useElements } from "@/lib/api";+import type { Engine } from "@/lib/catalog/types";+import { formatCost } from "@/lib/format";+import { checkValues, isMediaType, parseRows, RECIPE_LIMITS, type RecipeEstimate, type RecipeParam, type RecipeView } from "@/lib/recipe";+import { cn } from "@/lib/utils";+import { useRecipe, useRecipeActions, type RecipeFailure } from "./hooks";+import { PlanJobs } from "./plan-jobs";+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 }: { name: string | null; onClose: () => void }) {+ 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} />}+ </DialogContent>+ </Dialog>+ );+}++function RunForm({ name, onClose }: { name: string; onClose: () => void }) {+ const view = useRecipe(name);+ if (view.data) return <Loaded view={view.data} onClose={onClose} />;+ return (+ <div className="space-y-3 p-6">+ <DialogTitle className="sr-only">Run a skill</DialogTitle>+ {view.isError ? (+ <>+ <p className="text-[14px] text-muted-foreground">{(view.error as Error).message}</p>+ <Button variant="outline" size="sm" onClick={onClose}>+ Close+ </Button>+ </>+ ) : (+ <Skeleton className="h-56" />+ )}+ </div>+ );+}++function useDebounced<T>(value: T, ms: number): T {+ const [v, setV] = useState(value);+ useEffect(() => {+ const t = setTimeout(() => setV(value), ms);+ return () => clearTimeout(t);+ }, [value, ms]);+ return v;+}++/** "$0.62 on Cloud", "Free on your GPU", "$12.40 for 20 runs", "Demo — no provider connected". */+function priceLine(e: RecipeEstimate | undefined, runs: number): string {+ if (!e) return "";+ if (e.demo) return `Demo — no provider connected, free${runs > 1 ? ` · ${runs} runs` : ""}`;+ if (e.total === null) return "Some prices vary";+ const where = e.engine === "open" ? "on your GPU" : "on Cloud";+ if (e.total === 0) return runs > 1 ? `Free · ${runs} runs ${where}` : `Free ${where}`;+ return runs > 1 ? `${formatCost(e.total)} for ${runs} runs ${where}` : `${formatCost(e.total)} ${where}`;+}++function Loaded({ view, onClose }: { view: RecipeView; onClose: () => void }) {+ const { recipe, name } = view;+ const actions = useRecipeActions();+ const router = useRouter();+ const [tab, setTab] = useState<"one" | "many">("one");+ const [values, setValues] = useState<Record<string, string | number | undefined>>(() => Object.fromEntries(recipe.params.map((p) => [p.id, p.default])));+ const [slots, setSlots] = useState<Record<string, SlotValue | null>>({});+ const [csv, setCsv] = useState("");+ const [engine, setEngine] = useState<Engine>(view.ready[0] ?? view.engines[0] ?? "cloud");+ const [tried, setTried] = useState(false);+ const [busy, setBusy] = useState<"run" | "check" | null>(null);+ const [problems, setProblems] = useState<string[]>([]);+ const [open, setOpen] = useState(false);++ const ready = view.ready.includes(engine);+ const uploading = Object.values(slots).some((s) => s?.uploading);+ const form = useMemo(() => ({ ...values, ...Object.fromEntries(Object.entries(slots).map(([k, s]) => [k, s && !s.uploading ? s.ref : undefined])) }), [values, slots]);+ const checked = useMemo(() => checkValues(recipe, form), [recipe, form]);+ const rows = useMemo(() => (tab === "many" && csv.trim() ? parseRows(csv, recipe) : null), [tab, csv, recipe]);+ const rowsOk = !!rows && !rows.errors.length && rows.rows.length > 0 && rows.rows.every((r) => !r.errors.length);+ const runs = tab === "many" ? (rows?.rows.length ?? 0) : 1;+ const body = tab === "one" ? { values: checked.values ?? form, engine } : { csv, engine };+ const key = useDebounced(JSON.stringify(body), 400);+ const canPrice = ready && !uploading && (tab === "one" ? !!checked.values : rowsOk);+ const estimate = useQuery({+ queryKey: ["assist-recipe-estimate", name, key],+ enabled: canPrice,+ retry: false,+ placeholderData: keepPreviousData,+ queryFn: () => actions.estimate(name, JSON.parse(key)),+ });+ const est = canPrice ? estimate.data : undefined;+ const estError = canPrice && estimate.error ? (estimate.error as Error).message : (est?.errors[0] ?? est?.runs.flatMap((r) => r.errors)[0]);+ const runnable = canPrice && !!est?.runnable && !estimate.isFetching;+ const recheck = view.recheck[engine];++ const check = async () => {+ setBusy("check");+ setProblems([]);+ try {+ const r = await actions.verify(name);+ const passed = r.engines.filter((e) => e.plan.ok && (e.dryRun?.ok ?? true)).map((e) => (e.engine === "cloud" ? "Cloud" : "your GPU"));+ if (r.ok) toast.success(`Checked — it runs on ${passed.join(" and ")}`, { description: "Priced, and run once on the demo provider for free." });+ else {+ const why = r.engines.flatMap((e) => [...e.plan.errors, ...(e.dryRun?.problems ?? [])]);+ setProblems(why);+ toast.error(passed.length ? `It runs on ${passed.join(" and ")} only` : "The check didn't pass", { description: why[0] });+ }+ const next = r.view.ready;+ if (next.length && !next.includes(engine)) setEngine(next[0]);+ } catch (e) {+ const f = e as RecipeFailure;+ setProblems(f.problems ?? [f.message]);+ toast.error(f.message);+ } finally {+ setBusy(null);+ }+ };++ const run = async () => {+ setTried(true);+ if (!runnable) return;+ setBusy("run");+ try {+ const r = await actions.run(name, body);+ const href = r.runs[0]?.href ?? "/library";+ const studio = href.startsWith("/library") ? "Library" : href.startsWith("/video-tools/captions") ? "Captions" : "the studio";+ toast.success(r.runs.length > 1 ? `Started ${r.runs.length} runs` : "Started the run", {+ description: r.demo ? "A demo run — no provider connected" : `${view.title}: same steps, new take`,+ action: { label: `Open in ${studio}`, onClick: () => router.push(href) },+ });+ onClose();+ } catch (e) {+ const f = e as RecipeFailure;+ setProblems(f.problems ?? [f.message]);+ toast.error(f.message);+ } finally {+ setBusy(null);+ }+ };++ const price = !ready ? "" : estError ? "" : estimate.isFetching && !est ? "Pricing…" : priceLine(est, runs);+ return (+ <>+ <DialogHeader className="flex-row items-start gap-3 border-b px-5 pt-5 pb-4 text-left">+ <SkillIcon name={name} size="lg" />+ <div className="min-w-0 flex-1 pr-6">+ <DialogTitle className="font-heading text-[24px] leading-tight font-normal">Run {view.title}</DialogTitle>+ <DialogDescription className="mt-1">Same steps, new inputs. Priced before anything starts; no chat needed.</DialogDescription>+ </div>+ </DialogHeader>+ <div className="min-h-0 flex-1 space-y-4 overflow-y-auto px-5 py-4">+ {view.why ? (+ <Notice tone="warn">{view.why}</Notice>+ ) : !view.ready.length ? (+ <div className="flex flex-col gap-3 rounded-xl bg-muted/60 px-4 py-3 sm:flex-row sm:items-center">+ <ShieldCheck className="size-5 shrink-0 text-brand-text" />+ <p className="min-w-0 flex-1 text-[13px]">+ <span className="font-medium">Check it once first — it's free.</span> <span className="text-muted-foreground">Fuobe prices every step and runs it on the demo provider, so you know it works before you spend anything.</span>+ </p>+ <Button size="sm" onClick={() => void check()} disabled={busy !== null}>+ {busy === "check" ? <Loader2 className="animate-spin" /> : <ShieldCheck />} Check it (free)+ </Button>+ </div>+ ) : recheck?.length ? (+ <Notice tone="warn" action={<Button size="sm" variant="outline" onClick={() => void check()} disabled={busy !== null}>{busy === "check" ? <Loader2 className="animate-spin" /> : null} Re-check</Button>}>+ Needs a re-check: {recheck[0]}+ </Notice>+ ) : null}+ {problems.length > 0 && (+ <div role="alert" className="space-y-1 rounded-xl bg-destructive/10 px-3 py-2 text-[13px] text-destructive">+ {problems.slice(0, 6).map((p, i) => (+ <p key={i} className="flex items-start gap-2 break-words">+ <X className="mt-0.5 size-3.5 shrink-0" /> {p}+ </p>+ ))}+ </div>+ )}+ <div className="flex flex-wrap items-center justify-between gap-2">+ <Tabs value={tab} onValueChange={(v) => setTab(v as typeof tab)}>+ <TabsList>+ <TabsTrigger value="one" className="px-3">+ One+ </TabsTrigger>+ <TabsTrigger value="many" className="px-3">+ Many+ </TabsTrigger>+ </TabsList>+ </Tabs>+ {view.ready.length > 1 ? (+ <EngineSwitch value={engine} onChange={setEngine} size="sm" compact={false} />+ ) : (+ view.engines.length > 0 && (+ <span className="inline-flex h-8 items-center gap-1.5 rounded-full bg-muted px-3 text-[12px] font-medium text-muted-foreground">+ {(view.ready[0] ?? view.engines[0]) === "open" ? <Cpu className="size-3.5" /> : <Cloud className="size-3.5" />}+ {(view.ready[0] ?? view.engines[0]) === "open" ? "Runs on your GPU · open source" : "Runs in the cloud"}+ </span>+ )+ )}+ </div>+ {tab === "one" ? (+ <div className="space-y-4">+ {recipe.params.length === 0 && <p className="text-[13px] text-muted-foreground">This skill takes no inputs: it runs the same steps each time.</p>}+ {recipe.params.map((p) => (+ <Field+ key={p.id}+ p={p}+ value={values[p.id]}+ onChange={(v) => setValues((x) => ({ ...x, [p.id]: v }))}+ slot={slots[p.id] ?? null}+ onSlot={(v) => setSlots((x) => ({ ...x, [p.id]: v }))}+ error={tried ? checked.errors[p.id] : undefined}+ />+ ))}+ </div>+ ) : (+ <Many recipeParams={recipe.params} csv={csv} setCsv={setCsv} parsed={rows} name={name} />+ )}+ {ready && (est?.jobs.length ?? 0) > 0 && (+ <Collapsible open={open} onOpenChange={setOpen} className="overflow-hidden rounded-xl border">+ <CollapsibleTrigger className="flex w-full items-center gap-2 px-4 py-2.5 text-left text-[13px] font-medium hover:bg-accent">+ What runs+ <span className="font-normal text-muted-foreground">+ · {est!.jobs.length} step{est!.jobs.length === 1 ? "" : "s"}+ {runs > 1 ? ` × ${runs} runs` : ""}+ </span>+ <ChevronDown className={cn("ml-auto size-4 text-muted-foreground transition-transform", open && "rotate-180")} />+ </CollapsibleTrigger>+ <CollapsibleContent className="border-t">+ <PlanJobs jobs={est!.jobs} />+ {(est?.place?.studio || est?.place?.fallback || view.models.some((m) => m.engine === engine)) && (+ <div className="space-y-1 border-t px-4 py-2.5 text-[12px] text-muted-foreground">+ {est?.place?.studio && <p>Opens in {est.place.studio}, where you can keep working on it.</p>}+ {est?.place?.fallback && <p>{est.place.fallback}.</p>}+ {view.models.filter((m) => m.engine === engine).length > 0 && (+ <p>+ Licences (for your information):{" "}+ {view.models+ .filter((m) => m.engine === engine)+ .map((m) => `${m.name} — ${m.licence}`)+ .join("; ")}+ . Turn models on or off in{" "}+ <Link href="/settings/models" className="underline underline-offset-2">+ Models & licences+ </Link>+ .+ </p>+ )}+ </div>+ )}+ </CollapsibleContent>+ </Collapsible>+ )}+ </div>+ <DialogFooter className="mx-0 mb-0 flex-col gap-2 border-t px-5 py-3 sm:flex-row sm:items-center sm:justify-between">+ <p className={cn("min-w-0 text-[13px] break-words", estError ? "text-destructive" : "text-muted-foreground")} aria-live="polite">+ {!ready ? "Check it first to see the price" : estError ?? (canPrice ? price : tab === "one" ? (tried ? Object.values(checked.errors)[0] : "Fill in the inputs to see the price") : rows ? (rows.errors[0] ?? "Fix the rows marked below") : "Paste rows to see the total")}+ </p>+ <div className="flex shrink-0 gap-1.5 max-sm:w-full">+ <Button variant="ghost" size="sm" onClick={onClose} className="max-sm:flex-1">+ Cancel+ </Button>+ <Button size="sm" onClick={() => void run()} disabled={busy !== null || !ready || (tried && !runnable)} className="max-sm:flex-[2]">+ {busy === "run" ? <Loader2 className="animate-spin" /> : <Play />}+ {runs > 1 ? `Run ${runs}` : "Run"}+ {runnable && est && !est.demo && est.total ? ` · ${formatCost(est.total)}` : ""}+ </Button>+ </div>+ </DialogFooter>+ </>+ );+}++function Notice({ tone, children, action }: { tone: "warn" | "info"; children: React.ReactNode; action?: React.ReactNode }) {+ return (+ <div+ className={cn(+ "flex flex-col gap-2 rounded-xl px-3 py-2.5 text-[13px] sm:flex-row sm:items-center",+ tone === "warn" ? "bg-amber-500/10 text-amber-800 dark:text-amber-300" : "bg-muted text-muted-foreground",+ )}+ >+ <p className="flex min-w-0 flex-1 items-start gap-2 break-words">+ {tone === "warn" ? <AlertTriangle className="mt-0.5 size-3.5 shrink-0" /> : <Info className="mt-0.5 size-3.5 shrink-0" />}+ <span>{children}</span>+ </p>+ {action}+ </div>+ );+}++/** One input of the form, by its type. */+function Field({+ p,+ value,+ onChange,+ slot,+ onSlot,+ error,+}: {+ p: RecipeParam;+ value: string | number | undefined;+ onChange: (v: string | number | undefined) => void;+ slot: SlotValue | null;+ onSlot: (v: SlotValue | null) => void;+ error?: string;+}) {+ const id = useId();+ const label = (+ <label htmlFor={id} className="text-sm font-medium">+ {p.label}+ {p.required && p.default === undefined ? "" : <span className="font-normal text-muted-foreground"> · optional</span>}+ </label>+ );+ const hint = p.hint && <p className="text-[12px] text-muted-foreground">{p.hint}</p>;+ const err = error && (+ <p role="alert" className="text-[12px] text-destructive">+ {error}+ </p>+ );+ if (isMediaType(p.type)) {+ return (+ <div className="flex items-center gap-3" id={id}>+ <MediaSlot label={p.label} kind={p.type} value={slot} onChange={onSlot} required={p.required} size="lg" />+ <div className="min-w-0 flex-1 space-y-0.5">+ <p className="text-sm font-medium">{p.label}</p>+ <p className="text-[12px] text-muted-foreground">{p.hint ?? `Upload ${p.type === "image" ? "a picture" : p.type === "video" ? "a clip" : "a sound file"}, or pick one from your Library.`}</p>+ {err}+ </div>+ </div>+ );+ }+ const example = typeof p.example === "string" || typeof p.example === "number" ? String(p.example) : undefined;+ if (p.type === "text") {+ const long = (p.max ?? RECIPE_LIMITS.text) > 120;+ return (+ <div className="space-y-1.5">+ {label}+ {long ? (+ <Textarea id={id} rows={3} value={value === undefined ? "" : String(value)} maxLength={p.max ?? RECIPE_LIMITS.text} placeholder={example} onChange={(e) => onChange(e.target.value)} aria-invalid={!!error} />+ ) : (+ <Input id={id} value={value === undefined ? "" : String(value)} maxLength={p.max} placeholder={example} onChange={(e) => onChange(e.target.value)} aria-invalid={!!error} />+ )}+ {hint}+ {err}+ </div>+ );+ }+ if (p.type === "number") {+ const n = typeof value === "number" ? value : Number(value ?? p.min ?? 0);+ const step = p.step ?? 1;+ const clamp = (x: number) => Math.min(p.max ?? Infinity, Math.max(p.min ?? -Infinity, x));+ return (+ <div className="space-y-1.5">+ {label}+ <div className="flex w-fit items-center gap-1 rounded-full bg-muted p-0.5">+ <Button type="button" variant="ghost" size="icon" className="size-8 rounded-full" aria-label={`Fewer: ${p.label}`} disabled={p.min !== undefined && n <= p.min} onClick={() => onChange(clamp(n - step))}>+ <Minus />+ </Button>+ <Input+ id={id}+ inputMode="decimal"+ value={value === undefined ? "" : String(value)}+ placeholder={example}+ onChange={(e) => onChange(e.target.value === "" ? undefined : Number.isNaN(Number(e.target.value)) ? e.target.value : Number(e.target.value))}+ className="h-8 w-16 border-0 bg-transparent text-center tabular-nums shadow-none"+ aria-invalid={!!error}+ />+ <Button type="button" variant="ghost" size="icon" className="size-8 rounded-full" aria-label={`More: ${p.label}`} disabled={p.max !== undefined && n >= p.max} onClick={() => onChange(clamp(n + step))}>+ <Plus />+ </Button>+ </div>+ {hint}+ {err}+ </div>+ );+ }+ if (p.type === "choice") {+ const options = p.options ?? [];+ return (+ <div className="space-y-1.5">+ <p className="text-sm font-medium" id={id}>+ {p.label}+ </p>+ <div role="radiogroup" aria-labelledby={id} onKeyDown={radioKeys} className="flex max-w-full flex-wrap gap-1 rounded-2xl bg-muted p-0.5">+ {options.map((o) => (+ <button+ key={o}+ type="button"+ role="radio"+ aria-checked={value === o}+ tabIndex={radioTab(value === o || (value === undefined && o === options[0]))}+ onClick={() => onChange(o)}+ className={cn("h-8 rounded-full px-3 text-[13px] font-medium text-muted-foreground transition-colors", value === o && "bg-background text-foreground shadow-soft")}+ >+ {o}+ </button>+ ))}+ </div>+ {hint}+ {err}+ </div>+ );+ }+ return <ElementField id={id} label={label} p={p} value={value} onChange={onChange} hint={hint} err={err} />;+}++/** An @element input: the saved elements, as the composer's @ mentions list them. */+function ElementField({ id, label, p, value, onChange, hint, err }: { id: string; label: React.ReactNode; p: RecipeParam; value: string | number | undefined; onChange: (v: string | undefined) => void; hint: React.ReactNode; err: React.ReactNode }) {+ const elements = useElements();+ const list = (elements.data ?? []).filter((e) => e.kind !== "voice");+ const current = typeof value === "string" ? value.replace(/^@/, "") : undefined;+ return (+ <div className="space-y-1.5">+ {label}+ {list.length ? (+ <Select value={current} onValueChange={(v) => onChange(`@${v}`)}>+ <SelectTrigger id={id} className="w-full max-w-xs">+ <SelectValue placeholder={p.example ? String(p.example) : "Pick an element"} />+ </SelectTrigger>+ <SelectContent>+ {list.map((e) => (+ <SelectItem key={e.id} value={e.handle}>+ @{e.handle} <span className="text-muted-foreground">· {e.name}</span>+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ ) : (+ <p className="text-[13px] text-muted-foreground">+ {elements.isLoading ? "Loading your elements…" : "No elements yet. "}+ {!elements.isLoading && (+ <Link href="/elements?new=1" className="text-brand-text underline underline-offset-2">+ Save a character, place or product+ </Link>+ )}+ </p>+ )}+ {hint}+ {err}+ </div>+ );+}++/** Many runs: a pasted or uploaded CSV (or a spreadsheet's paste), checked row by row. */+function Many({ recipeParams, csv, setCsv, parsed, name }: { recipeParams: RecipeParam[]; csv: string; setCsv: (v: string) => void; parsed: ReturnType<typeof parseRows> | null; name: string }) {+ const file = useRef<HTMLInputElement>(null);+ const id = useId();+ const quote = (s: string) => (/[",\n]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s);+ const template = [recipeParams.map((p) => quote(p.label)).join(","), recipeParams.map((p) => quote(p.example !== undefined && p.example !== null ? String(p.example) : p.default !== undefined ? String(p.default) : "")).join(",")].join("\n");+ const labelOf = (col: string | null) => recipeParams.find((p) => p.id === col)?.label;+ return (+ <div className="space-y-3">+ <div className="space-y-1.5">+ <label htmlFor={id} className="text-sm font-medium">+ Rows to run+ </label>+ <p className="text-[12px] text-muted-foreground">+ One run per row, up to {RECIPE_LIMITS.rows}. The first row names the inputs ({recipeParams.map((p) => p.label).join(", ")}); paste from a spreadsheet or a CSV file. Files are links: /api/files/… from your Library, or https://….+ </p>+ <Textarea id={id} rows={5} value={csv} onChange={(e) => setCsv(e.target.value)} placeholder={template} className="font-mono text-[12px] leading-relaxed" spellCheck={false} />+ <div className="flex flex-wrap gap-1.5">+ <input+ ref={file}+ type="file"+ accept=".csv,.tsv,.txt,text/csv,text/plain"+ hidden+ onChange={async (e) => {+ const f = e.target.files?.[0];+ e.target.value = "";+ if (f) setCsv(await f.text());+ }}+ />+ <Button type="button" variant="outline" size="sm" onClick={() => file.current?.click()}>+ <FileUp /> Upload CSV+ </Button>+ <Button type="button" variant="ghost" size="sm" asChild>+ <a href={`data:text/csv;charset=utf-8,${encodeURIComponent(`${template}\n`)}`} download={`${name}-rows.csv`}>+ Template+ </a>+ </Button>+ </div>+ </div>+ {parsed && (+ <div className="space-y-2">+ {parsed.errors.map((e, i) => (+ <p key={i} role="alert" className="flex items-start gap-2 rounded-xl bg-destructive/10 px-3 py-2 text-[13px] text-destructive">+ <X className="mt-0.5 size-3.5 shrink-0" /> {e}+ </p>+ ))}+ {parsed.notes.map((n, i) => (+ <p key={i} className="text-[12px] text-muted-foreground">+ {n}+ </p>+ ))}+ {parsed.rows.length > 0 && (+ <div className="max-h-72 overflow-auto rounded-xl border">+ <table className="w-full min-w-max text-left text-[12px]">+ <thead className="sticky top-0 bg-muted">+ <tr>+ <th className="px-2 py-1.5 font-medium text-muted-foreground">#</th>+ {parsed.header.map((h, i) => (+ <th key={i} className={cn("px-2 py-1.5 font-medium", !parsed.columns[i] && "text-muted-foreground line-through")}>+ {labelOf(parsed.columns[i]) ?? h}+ </th>+ ))}+ </tr>+ </thead>+ <tbody className="divide-y">+ {parsed.rows.map((r) => (+ <RowLine key={r.line} line={r.line} cells={r.cells} errors={r.errors} width={parsed.header.length} />+ ))}+ </tbody>+ </table>+ </div>+ )}+ {parsed.rows.length > 0 && (+ <p className="text-[12px] text-muted-foreground">+ {parsed.rows.length} run{parsed.rows.length === 1 ? "" : "s"}+ {parsed.rows.some((r) => r.errors.length) ? ` · ${parsed.rows.filter((r) => r.errors.length).length} to fix` : " · all fine"}+ </p>+ )}+ </div>+ )}+ </div>+ );+}++function RowLine({ line, cells, errors, width }: { line: number; cells: string[]; errors: string[]; width: number }) {+ return (+ <>+ <tr className={cn(errors.length && "bg-destructive/5")}>+ <td className="px-2 py-1.5 text-muted-foreground tabular-nums">{line}</td>+ {Array.from({ length: width }, (_, i) => (+ <td key={i} className="max-w-[14rem] truncate px-2 py-1.5" title={cells[i]}>+ {cells[i] ?? ""}+ </td>+ ))}+ </tr>+ {errors.length > 0 && (+ <tr className="bg-destructive/5">+ <td />+ <td colSpan={width} className="px-2 pb-1.5 text-destructive">+ {errors.join(" · ")}+ </td>+ </tr>+ )}+ </>+ );+}diff --git a/src/components/assist/skills-view.tsx b/src/components/assist/skills-view.tsxindex 0f7b988f..cf40acfe 100644--- a/src/components/assist/skills-view.tsx+++ b/src/components/assist/skills-view.tsx@@ -1,6 +1,6 @@"use client";-import { Copy, Download, FileUp, Loader2, MessageSquarePlus, Pencil, Plus, Search, Trash2, Upload, X } from "lucide-react";+import { AlertTriangle, ChevronDown, Copy, Download, FileUp, Loader2, MessageSquarePlus, Pencil, Play, Plus, Search, ShieldCheck, Trash2, Upload, X } from "lucide-react";import Link from "next/link";import { usePathname, useRouter, useSearchParams } from "next/navigation";import { Suspense, useDeferredValue, useId, useRef, useState } from "react";@@ -19,6 +19,7 @@ import {} from "@/components/ui/alert-dialog";import { Button } from "@/components/ui/button";import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";+import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";import { Empty, EmptyContent, EmptyDescription, EmptyHeader, EmptyTitle } from "@/components/ui/empty";import { Input } from "@/components/ui/input";import { Label } from "@/components/ui/label";@@ -30,7 +31,8 @@ import { Textarea } from "@/components/ui/textarea";import { SKILL_LIMITS, SKILL_NAME_RE, skillSlug, type Skill, type SkillSummary } from "@/lib/assist";import { cn } from "@/lib/utils";import { radioKeys } from "@/components/studio/radio-keys";-import { useSkill, useSkillActions, useSkills, type SkillForm } from "./hooks";+import { useRecipe, useRecipeActions, useSkill, useSkillActions, useSkills, type RecipeFailure, type SkillForm } from "./hooks";+import { RunSkillDialog } from "./run-skill-dialog";import { RailButton } from "./shell";import { SKILL_ICONS, SkillIcon } from "./skill-icon";@@ -53,6 +55,8 @@ function Skills() {const pathname = usePathname();const params = useSearchParams();const viewing = params.get("skill");+ // ?run=<name>: the skill's Run form (a deep link, ⌘K's "Run …", the skill's Run… button).+ const running = params.get("run");const [tab, setTab] = useState<"builtin" | "user">("builtin");const [query, setQuery] = useState("");const q = useDeferredValue(query.trim().toLowerCase());@@ -66,6 +70,12 @@ function Skills() {const own = all.filter((s) => s.source === "user");const filter = (list: SkillSummary[]) => (q ? list.filter((s) => `${s.name} ${s.title} ${s.description} ${s.whenToUse} ${(s.tags ?? []).join(" ")}`.toLowerCase().includes(q)) : list);const open = (name: string | null) => router.replace(name ? `${pathname}?skill=${name}` : pathname, { scroll: false });+ // The Run form opened from a skill's dialog goes back to it when it closes.+ const runFrom = useRef<string | null>(null);+ const run = (name: string, from: string | null = null) => {+ runFrom.current = from;+ router.replace(`${pathname}?run=${name}`, { scroll: false });+ };const upload = async (f: File, replace = false) => {setUploading(true);@@ -164,7 +174,15 @@ function Skills() {</TabsContent></Tabs></div>- <SkillDetail name={viewing} onClose={() => open(null)} onEdit={(s) => (open(null), setEditing(s))} />+ <SkillDetail name={viewing} onClose={() => open(null)} onEdit={(s) => (open(null), setEditing(s))} onRun={(name) => run(name, name)} />+ <RunSkillDialog+ name={running}+ onClose={() => {+ const back = runFrom.current;+ runFrom.current = null;+ open(back);+ }}+ /><SkillEditorskill={editing}onClose={() => setEditing(null)}@@ -227,14 +245,65 @@ function SkillGrid({ list, loading, onOpen, onToggle, empty }: { list: SkillSumm<Switch size="sm" checked={s.enabled} onCheckedChange={(v) => onToggle(s, v)} aria-label={`${s.enabled ? "Switch off" : "Switch on"} ${s.title}`} className="relative z-10" /></div><p className="mt-3 line-clamp-3 text-[13px] text-muted-foreground">{s.description}</p>- {s.files.length > 0 && <p className="mt-auto pt-3 text-[11px] text-muted-foreground">+ {s.files.length} file{s.files.length > 1 ? "s" : ""}</p>}+ {(s.recipe || s.files.length > 0) && (+ <div className="mt-auto flex flex-wrap items-center gap-2 pt-3 text-[11px] text-muted-foreground">+ {s.recipe && (+ <span className="inline-flex h-5 items-center gap-1 rounded-full bg-brand-faint px-2 font-medium text-brand-text">+ <Play className="size-3" aria-hidden /> Runs by itself+ </span>+ )}+ {s.files.length > 0 && (+ <span>+ + {s.files.length} file{s.files.length > 1 ? "s" : ""}+ </span>+ )}+ </div>+ )}</li>))}</ul>);}-function SkillDetail({ name, onClose, onEdit }: { name: string | null; onClose: () => void; onEdit: (s: Skill) => void }) {+/**+ * Under a recipe skill's description: where it was checked ("Checked 29 Oct · Cloud ✓ · GPU not checked"), or in amber+ * why it needs a re-check, with Re-check (the plan and the free dry run).+ */+function RecipeStatus({ skill }: { skill: Skill }) {+ const recipe = useRecipe(skill.name, !!skill.recipe);+ const actions = useRecipeActions();+ const [busy, setBusy] = useState(false);+ const v = recipe.data;+ if (!skill.recipe || !v) return null;+ const recheck = Object.values(v.recheck).flat();+ const recheckNow = async () => {+ setBusy(true);+ try {+ const r = await actions.verify(skill.name);+ if (r.ok) toast.success("Checked — it still runs", { description: "Priced, and run once on the demo provider for free." });+ else toast.error("The check didn't pass", { description: r.engines.flatMap((e) => [...e.plan.errors, ...(e.dryRun?.problems ?? [])])[0] });+ } catch (e) {+ const f = e as RecipeFailure;+ toast.error(f.message, { description: f.problems?.slice(1).join("; ") || undefined });+ } finally {+ setBusy(false);+ }+ };+ const canCheck = skill.source === "user";+ return (+ <div className={cn("mt-2 flex flex-wrap items-center gap-x-2 gap-y-1 text-[12px]", recheck.length || v.why ? "text-amber-700 dark:text-amber-300" : "text-muted-foreground")}>+ {recheck.length || v.why ? <AlertTriangle className="size-3.5 shrink-0" aria-hidden /> : <ShieldCheck className="size-3.5 shrink-0" aria-hidden />}+ <span className="min-w-0 break-words">{v.why ?? (recheck.length ? `Needs a re-check: ${recheck[0]}` : v.line)}</span>+ {canCheck && !v.why && (recheck.length > 0 || !v.ready.length) && (+ <Button variant="outline" size="xs" className="h-6 rounded-full px-2 text-[12px]" onClick={() => void recheckNow()} disabled={busy}>+ {busy && <Loader2 className="animate-spin" />} {v.ready.length ? "Re-check" : "Check it (free)"}+ </Button>+ )}+ </div>+ );+}++function SkillDetail({ name, onClose, onEdit, onRun }: { name: string | null; onClose: () => void; onEdit: (s: Skill) => void; onRun: (name: string) => void }) {const skill = useSkill(name);const actions = useSkillActions();const router = useRouter();@@ -255,6 +324,7 @@ function SkillDetail({ name, onClose, onEdit }: { name: string | null; onClose:<div className="min-w-0 flex-1"><DialogTitle className="font-heading text-[24px] leading-tight font-normal">{s.title}</DialogTitle><DialogDescription className="mt-1">{s.description}</DialogDescription>+ <RecipeStatus skill={s} /><p className="mt-1.5 font-mono text-[11px] text-muted-foreground">/{s.name} · {s.source === "builtin" ? "Built-in" : "Yours"}{s.studio && (@@ -293,11 +363,33 @@ function SkillDetail({ name, onClose, onEdit }: { name: string | null; onClose:</div><DialogFooter className="mx-0 mb-0 flex-row flex-wrap items-center gap-2 border-t px-5 py-3 sm:justify-between"><div className="flex flex-wrap gap-1.5">- <Button variant="ghost" size="sm" asChild>- <a href={`/api/assist/skills/${s.name}/download`} download>- <Download /> SKILL.md- </a>- </Button>+ {s.files.length > 0 ? (+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <Button variant="ghost" size="sm">+ <Download /> Download <ChevronDown className="opacity-60" />+ </Button>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="start">+ <DropdownMenuItem asChild>+ <a href={`/api/assist/skills/${s.name}/download`} download>+ SKILL.md+ </a>+ </DropdownMenuItem>+ <DropdownMenuItem asChild>+ <a href={`/api/assist/skills/${s.name}/download?format=zip`} download>+ Skill with its files (.zip)+ </a>+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ ) : (+ <Button variant="ghost" size="sm" asChild>+ <a href={`/api/assist/skills/${s.name}/download`} download>+ <Download /> SKILL.md+ </a>+ </Button>+ )}<Buttonvariant="ghost"size="sm"@@ -324,9 +416,20 @@ function SkillDetail({ name, onClose, onEdit }: { name: string | null; onClose:</>)}</div>- <Button size="sm" onClick={() => router.push(`/assist?skill=${s.name}`)} disabled={!s.enabled}>- <MessageSquarePlus /> Use in a new chat- </Button>+ {s.recipe ? (+ <div className="flex flex-wrap gap-1.5">+ <Button variant="ghost" size="sm" onClick={() => router.push(`/assist?skill=${s.name}`)} disabled={!s.enabled}>+ <MessageSquarePlus /> Use in a new chat+ </Button>+ <Button size="sm" onClick={() => onRun(s.name)} disabled={!s.enabled}>+ <Play /> Run…+ </Button>+ </div>+ ) : (+ <Button size="sm" onClick={() => router.push(`/assist?skill=${s.name}`)} disabled={!s.enabled}>+ <MessageSquarePlus /> Use in a new chat+ </Button>+ )}</DialogFooter><AlertDialog open={confirm} onOpenChange={setConfirm}><AlertDialogContent>diff --git a/src/components/assist/transcript.tsx b/src/components/assist/transcript.tsxindex 019a61e7..3229de9c 100644--- a/src/components/assist/transcript.tsx+++ b/src/components/assist/transcript.tsx@@ -1,20 +1,19 @@"use client";-import { AppWindow, ArrowUpRight, AudioLines, Box, Brain, Captions, Check, CircleAlert, Clapperboard, Film, FileText, ImageIcon, Info, Languages, Layers, Loader2, Megaphone, Plug, Scissors, Search, Sparkles, Video } from "lucide-react";+import { AppWindow, ArrowUpRight, Brain, Captions, Check, CircleAlert, Clapperboard, Film, ImageIcon, Info, Languages, Layers, Loader2, Megaphone, Plug, Scissors, Search, Sparkles } from "lucide-react";import Link from "next/link";import { useState } from "react";import { toast } from "sonner";import { Button } from "@/components/ui/button";import { FailedTile, MediaThumb, PendingTile, tileRatio } from "@/components/studio/feed";import { useCreateGeneration } from "@/lib/api";-import { planRunnable, type AssistItem, type AssistThread, type PlannedJob, type SkillSummary } from "@/lib/assist";-import { OPERATION_LABELS, type Generation, type MediaKind, type Operation } from "@/lib/catalog/types";+import { planRunnable, type AssistItem, type AssistThread, type SkillSummary } from "@/lib/assist";+import type { Generation } from "@/lib/catalog/types";import { formatCost } from "@/lib/format";import { cn } from "@/lib/utils";+import { PlanJobs } from "./plan-jobs";import { SkillIcon } from "./skill-icon";-const KIND_ICON: Record<MediaKind | "storyboard" | "memory", typeof ImageIcon> = { image: ImageIcon, video: Video, audio: AudioLines, text: FileText, model3d: Box, storyboard: Clapperboard, memory: Brain };-/** Paragraphs, "- " bullets and **bold** — the little markdown the assistant uses. */export function Prose({ text }: { text: string }) {const inline = (s: string) => s.split(/(\*\*[^*]+\*\*)/g).map((p, i) => (p.startsWith("**") && p.endsWith("**") ? <strong key={i}>{p.slice(2, -2)}</strong> : p));@@ -41,21 +40,6 @@ export function Prose({ text }: { text: string }) {);}-function jobPrice(j: PlannedJob): string {- if (j.error) return "—";- if (j.op === "memory") return "";- if (j.demo) return "Demo";- if (j.costUsd === 0) return "Free";- return j.costUsd === null ? "Price varies" : formatCost(j.costUsd);-}--function jobLine(j: PlannedJob): string {- if (j.op === "storyboard") return `Storyboard · ${j.count} frames`;- if (j.op === "memory") return j.note ?? "Memory";- const op = OPERATION_LABELS[j.op as Operation] ?? j.op;- return [j.note && j.note !== op ? j.note : op, j.count > 1 ? `${j.count} takes` : ""].filter(Boolean).join(" · ");-}-export function ApprovalCard({ item, live, onAnswer }: { item: Extract<AssistItem, { role: "approval" }>; live: boolean; onAnswer: (ok: boolean) => Promise<void> }) {const [busy, setBusy] = useState<boolean | null>(null);const runnable = planRunnable(item.jobs);@@ -82,9 +66,6 @@ export function ApprovalCard({ item, live, onAnswer }: { item: Extract<AssistItesetBusy(null);}};- // Long studio plans (a dub, a faceless episode) fold after six steps.- const [all, setAll] = useState(false);- const shown = all ? item.jobs : item.jobs.slice(0, 6);return (<div className={cn("animate-fade-up overflow-hidden rounded-2xl border bg-background shadow-soft", item.status !== "pending" && "opacity-80")}><div className="flex items-center gap-2 border-b bg-muted/40 px-4 py-2.5">@@ -97,34 +78,7 @@ export function ApprovalCard({ item, live, onAnswer }: { item: Extract<AssistIte)}{item.status === "declined" && <span className="text-[12px] text-muted-foreground">Skipped</span>}</div>- <ul className="divide-y">- {shown.map((j, i) => {- const Icon = KIND_ICON[j.op === "storyboard" ? "storyboard" : j.op === "memory" ? "memory" : j.kind];- return (- <li key={i} className="flex gap-3 px-4 py-3">- <span className="mt-0.5 grid size-8 shrink-0 place-items-center rounded-lg bg-secondary">- <Icon className="size-4" />- </span>- <div className="min-w-0 flex-1">- <p className="text-[13px] font-medium break-words">- {j.modelName}- <span className="font-normal text-muted-foreground">- {" · "}- {jobLine(j)}- </span>- </p>- <p className={cn("mt-0.5 text-[13px] break-words", j.op === "memory" ? "text-foreground" : "line-clamp-2 text-muted-foreground")}>{j.prompt}</p>- {j.error && (- <p className="mt-1 flex items-start gap-1 text-[12px] text-destructive">- <CircleAlert className="mt-0.5 size-3 shrink-0" /> {j.error}- </p>- )}- </div>- <span className="shrink-0 font-mono text-[12px] text-muted-foreground">{jobPrice(j)}</span>- </li>- );- })}- </ul>+ <PlanJobs jobs={item.jobs} />{!!(item.opens?.length || item.notes?.length) && (<div className="space-y-1 border-t px-4 py-2.5 text-[12px] text-muted-foreground">{item.opens?.length ? (@@ -139,11 +93,6 @@ export function ApprovalCard({ item, live, onAnswer }: { item: Extract<AssistIte))}</div>)}- {item.jobs.length > 6 && (- <button onClick={() => setAll((v) => !v)} className="w-full border-t px-4 py-2 text-left text-[12px] font-medium text-brand-text hover:bg-accent">- {all ? "Show fewer steps" : `Show all ${item.jobs.length} steps`}- </button>- )}<div className="flex flex-wrap items-center gap-2 border-t px-4 py-2.5"><p className="text-[12px] text-muted-foreground">{total}</p>{live && item.status === "pending" && (diff --git a/src/components/command-palette.tsx b/src/components/command-palette.tsxindex 3788bbdf..ff7eb11d 100644--- a/src/components/command-palette.tsx+++ b/src/components/command-palette.tsx@@ -1,9 +1,10 @@"use client";import { useQuery } from "@tanstack/react-query";-import { Bell, Clapperboard, Cpu, Film, KeyRound, Layers, LayoutGrid, Loader2, Plug, Plus, Scale, Server, Settings2, ShieldCheck, Sparkles, Wand2, type LucideIcon } from "lucide-react";+import { Bell, Clapperboard, Cpu, Film, KeyRound, Layers, LayoutGrid, Loader2, Play, Plug, Plus, Scale, Server, Settings2, ShieldCheck, Sparkles, Wand2, type LucideIcon } from "lucide-react";import { useRouter } from "next/navigation";import { createContext, lazy, Suspense, useCallback, useContext, useEffect, useMemo, useRef, useState } from "react";+import { useSkills } from "@/components/assist/hooks";import { NAV } from "@/components/nav-items";import { MediaThumb } from "@/components/studio/result-media";import { CommandDialog, CommandEmpty, CommandGroup, CommandItem, CommandList } from "@/components/ui/command";@@ -11,7 +12,7 @@ import { Kbd } from "@/components/ui/kbd";import { Command as CommandPrimitive } from "cmdk";import { useEngineMode, useGenerations, useModelAccess } from "@/lib/api";import type { Generation } from "@/lib/catalog/types";-import { indexEntries, KIND_LABELS, rankPalette, type PaletteEntry, type PaletteIndex, type PaletteKind } from "@/lib/command-search";+import { indexEntries, KIND_LABELS, rankPalette, skillEntries, type PaletteEntry, type PaletteIndex, type PaletteKind } from "@/lib/command-search";import { useModKey } from "@/lib/keys";import { userTitle } from "@/lib/library";import { cn } from "@/lib/utils";@@ -80,7 +81,7 @@ const SETTING_ENTRIES: (PaletteEntry & { icon: LucideIcon })[] = SETTINGS.map((s// Icons as elements made once (a component picked during render would remount on every keystroke).const iconEl = (Icon: LucideIcon) => <Icon className="text-muted-foreground" />;const ICONS = new Map<string, React.ReactNode>([...PAGES, ...SETTING_ENTRIES].map((e) => [e.key, iconEl(e.icon)]));-const KIND_ICONS: Partial<Record<PaletteKind, React.ReactNode>> = { app: iconEl(LayoutGrid), motion: iconEl(Film), effect: iconEl(Wand2), model: iconEl(Clapperboard) };+const KIND_ICONS: Partial<Record<PaletteKind, React.ReactNode>> = { app: iconEl(LayoutGrid), motion: iconEl(Film), effect: iconEl(Wand2), model: iconEl(Clapperboard), skill: iconEl(Play) };function useDebounced<T>(value: T, ms: number): T {const [v, setV] = useState(value);@@ -150,7 +151,12 @@ function PaletteBody({ onPick, onOpenRecent, onClose }: { onPick: (e: PaletteEntstaleTime: Infinity,});const recent = useGenerations({ q: dq || undefined, limit: 5, statuses: ["succeeded"] }, { keepPrevious: true });- const entries = useMemo(() => [...PAGES, ...SETTING_ENTRIES, ...(index.data ? indexEntries(index.data, mode, access) : [])], [index.data, mode, access]);+ // Skills that run by themselves: "Run <skill>…" opens its Run form.+ const skills = useSkills();+ const entries = useMemo(+ () => [...PAGES, ...SETTING_ENTRIES, ...skillEntries(skills.data ?? []), ...(index.data ? indexEntries(index.data, mode, access) : [])],+ [index.data, mode, access, skills.data],+ );const groups = useMemo(() => rankPalette(entries, query), [entries, query]);const recentItems = (recent.data ?? []).filter((g) => g.outputs[0]);const searching = !!query.trim();diff --git a/src/lib/command-search.ts b/src/lib/command-search.tsindex eacf5a7d..ca02dfd0 100644--- a/src/lib/command-search.ts+++ b/src/lib/command-search.ts@@ -4,7 +4,7 @@*/import { offered, type AccessSummary } from "./model-access";-export type PaletteKind = "page" | "setting" | "app" | "motion" | "effect" | "model" | "recent";+export type PaletteKind = "page" | "setting" | "skill" | "app" | "motion" | "effect" | "model" | "recent";export interface PaletteEntry {/** Unique in the palette. */@@ -22,6 +22,7 @@ export interface PaletteEntry {export const KIND_LABELS: Record<PaletteKind, string> = {page: "Go to",setting: "Settings",+ skill: "Run a skill",app: "Apps",motion: "Camera motions",effect: "Effects",@@ -117,7 +118,7 @@ export interface PaletteGroup {}/** How many matches each group shows. */-export const GROUP_LIMIT: Record<PaletteKind, number> = { page: 6, setting: 4, app: 5, motion: 4, effect: 4, model: 5, recent: 5 };+export const GROUP_LIMIT: Record<PaletteKind, number> = { page: 6, setting: 4, skill: 4, app: 5, motion: 4, effect: 4, model: 5, recent: 5 };/** Matches far weaker than the best one are noise next to it ("lip" finds Lipsync, not "virality predictor"). */const KEEP_FROM_BEST = 0.35;@@ -208,3 +209,10 @@ export function indexEntries(index: PaletteIndex, mode: "both" | "cloud" | "open}),];}++/** Skills that run by themselves (a recipe), switched on: "Run Lamp turntable…", opening its Run form. */+export function skillEntries(skills: { name: string; title: string; description: string; recipe?: boolean; enabled: boolean }[]): PaletteEntry[] {+ return skills+ .filter((s) => s.recipe && s.enabled)+ .map((s) => ({ key: `skill:${s.name}`, kind: "skill" as const, label: `Run ${s.title}…`, hint: "Skill", href: `/assist/skills?run=${s.name}`, keywords: `${s.name} ${s.description} skill run` }));+}diff --git a/src/lib/recipe.ts b/src/lib/recipe.tsindex d537f7fa..d8cb0115 100644--- a/src/lib/recipe.ts+++ b/src/lib/recipe.ts@@ -13,6 +13,7 @@* (src/server/recipes.ts). Nothing here reads the catalog: the server checks models, prices and engines.*/import { z } from "zod";+import type { PlannedJob } from "./assist";import type { ChainSlot, GenerationRequest, MediaKind, OutputFile } from "./catalog/types";import type { MediaInfo } from "./media-probe";@@ -802,3 +803,69 @@ export function verifiedLine(recipe: Pick<Recipe, "verified">, engines: RecipeEnconst parts = engines.map((e) => (v[e]?.dryRun ? `${ENGINE_WORDS[e]} ✓` : v[e]?.plan ? `${ENGINE_WORDS[e]} priced` : `${ENGINE_WORDS[e]} not checked`));return [`Checked ${shortDay(last)}`, ...parts].join(" · ");}++// ---------------------------------------------------------------------------+// What the recipe routes answer (src/server/recipes.ts)++/** Where a studio tool's run opens (its studio and page), or why it runs in the Library. */+export interface RecipePlace {+ studio?: string;+ href?: string;+ fallback?: string;+}++export interface RecipeView {+ name: string;+ title: string;+ builtin: boolean;+ recipe: Recipe;+ /** Engines its steps allow on this install. */+ engines: RecipeEngine[];+ /** Engines it may run on now: its plan check passed there. */+ ready: RecipeEngine[];+ /** Why it needs a re-check, per engine checked before. */+ recheck: Partial<Record<RecipeEngine, string[]>>;+ /** "Checked 29 Oct · Cloud ✓ · GPU not checked". */+ line: string;+ /** Why it runs nowhere on this install. */+ why?: string;+ /** Each step's model and its licence on each engine, as information. */+ models: { engine: RecipeEngine; name: string; licence: string }[];+}++export interface RecipeEstimate {+ engine: RecipeEngine;+ /** One entry per row: its jobs priced, and what stops it. */+ runs: { line: number; jobs: PlannedJob[]; total: number | null; errors: string[] }[];+ /** The first run's jobs ("What runs"). */+ jobs: PlannedJob[];+ /** Every run together (null: a price that varies). */+ total: number | null;+ /** Every job would run on the demo provider. */+ demo: boolean;+ runnable: boolean;+ /** What stops every run (no column for an input, too many rows, a recipe that runs nowhere). */+ errors: string[];+ place?: RecipePlace;+}++export interface RecipeRun {+ /** The run's batch (a pipeline's rows share it), its generations, and the studio page a tool run opens in. */+ batchId?: string;+ ids: string[];+ href?: string;+}++export interface EngineCheck {+ engine: RecipeEngine;+ /** `notes`: what stops a real run on this install that isn't the recipe's fault (a provider to connect). */+ plan: { ok: boolean; total: number | null; demo: boolean; errors: string[]; notes: string[] };+ dryRun?: { ok: boolean; problems: string[]; skipped?: string };+ real?: { ok: boolean; problems: string[]; notes: string[]; demo: boolean };+}++export interface VerifyResult {+ ok: boolean;+ engines: EngineCheck[];+ view: RecipeView;+}diff --git a/src/server/recipes.ts b/src/server/recipes.tsindex 5b3936d8..2153dcdb 100644--- a/src/server/recipes.ts+++ b/src/server/recipes.ts@@ -29,12 +29,17 @@ import {type FilledCheck,type Recipe,type RecipeValues,+ type EngineCheck,+ type RecipePlace,+ type RecipeEstimate,+ type RecipeRun,+ type RecipeView,type VerifiedEngine,+ type VerifyResult,} from "@/lib/recipe";import type { Skill } from "@/lib/assist";import { planSteps } from "./assist/studio-tools";import { executeTool, getTool, planFor, validateInput } from "./assist/tools";-import type { JobPlace } from "./assist/define";import { createPipeline } from "./chains";import { llmText, llmTextBackend } from "./enhance";import { cancelGeneration, createGenerations, currentRequest, getGeneration, previewChained } from "./generations";@@ -188,7 +193,7 @@ interface RunPlan {jobs: PlannedJob[];total: number | null;errors: string[];- place?: JobPlace;+ place?: RecipePlace;}/** Price one compiled run the way it would start (planSteps / planFor), with what stops it. */@@ -310,25 +315,6 @@ function valuesForCheck(recipe: Recipe, files = false): RecipeValues {// ---------------------------------------------------------------------------// What a page shows-export interface RecipeView {- name: string;- title: string;- builtin: boolean;- recipe: Recipe;- /** Engines its steps allow on this install. */- engines: Engine[];- /** Engines it may run on now: its plan check passed there. */- ready: Engine[];- /** Why it needs a re-check, per engine checked before. */- recheck: Partial<Record<Engine, string[]>>;- /** "Checked 29 Oct · Cloud ✓ · GPU not checked". */- line: string;- /** Why it runs nowhere on this install. */- why?: string;- /** Each step's model and its licence on each engine, as information. */- models: { engine: Engine; name: string; licence: string }[];-}-export function recipeView(name: string): RecipeView {const { skill, recipe } = getRecipe(name);const engines = recipeEngines(recipe);@@ -435,28 +421,12 @@ function engineFor(recipe: Recipe, asked: Engine | undefined): Engine {// ---------------------------------------------------------------------------// Estimate and run-export interface RecipeEstimate {- engine: Engine;- /** One entry per row: its jobs priced, and what stops it. */- runs: { line: number; jobs: PlannedJob[]; total: number | null; errors: string[] }[];- /** The first run's jobs ("What runs"). */- jobs: PlannedJob[];- /** Every run together (null: a price that varies). */- total: number | null;- /** Every job would run on the demo provider. */- demo: boolean;- runnable: boolean;- /** What stops every run (no column for an input, too many rows, a recipe that runs nowhere). */- errors: string[];- place?: JobPlace;-}-/** Price one run or many (rows priced together, with a total) on an engine, without starting anything. */export function estimateRecipe(name: string, input: RunInput, asked?: Engine): RecipeEstimate {const { skill, recipe } = getRecipe(name);const engine = engineFor(recipe, asked);const { rows, errors } = rowsOf(recipe, input);- let place: JobPlace | undefined;+ let place: RecipePlace | undefined;const runs = rows.map((r) => {if (!r.values) return { line: r.line, jobs: [], total: null, errors: r.errors };try {@@ -482,13 +452,6 @@ export function estimateRecipe(name: string, input: RunInput, asked?: Engine): R};}-export interface RecipeRun {- /** The run's batch (a pipeline's rows share it), its generations, and the studio page a tool run opens in. */- batchId?: string;- ids: string[];- href?: string;-}-/*** Run a recipe once or once per row on an engine whose plan check passed. Every row is validated and priced first:* one bad row starts nothing. A pipeline is one createPipeline per row; a tool recipe one executeTool call per row.@@ -554,14 +517,6 @@ export async function runRecipe(name: string, input: RunInput, asked?: Engine):export type VerifyLevel = "plan" | "demo" | "real";-export interface EngineCheck {- engine: Engine;- /** `notes`: what stops a real run on this install that isn't the recipe's fault (a provider to connect). */- plan: { ok: boolean; total: number | null; demo: boolean; errors: string[]; notes: string[] };- dryRun?: { ok: boolean; problems: string[]; skipped?: string };- real?: { ok: boolean; problems: string[]; notes: string[]; demo: boolean };-}-const TERMINAL = new Set(["succeeded", "failed", "canceled"]);/** Wait for generations to finish (the runner moves them), at most `ms`; cancels what's left when time runs out. */@@ -701,12 +656,6 @@ async function realRun(skill: Skill, recipe: Recipe, engine: Engine): Promise<Noreturn { ok: !problems.length, problems, notes, demo };}-export interface VerifyResult {- ok: boolean;- engines: EngineCheck[];- view: RecipeView;-}-/*** Check a recipe and write what passed into its `verified`:* - `plan`: compile with the examples (a stand-in file for a media input with none) and price it on each engine itsdiff --git a/tests/command-palette.test.ts b/tests/command-palette.test.tsindex ea1856e6..12dac347 100644--- a/tests/command-palette.test.ts+++ b/tests/command-palette.test.ts@@ -3,7 +3,7 @@ import path from "node:path";import { describe, expect, it } from "vitest";import { NAV } from "@/components/nav-items";import { APPS, EFFECTS, getModel, MODELS, MOTIONS } from "@/lib/catalog";-import { entryScore, indexEntries, normalize, rankPalette, wordScore, type PaletteEntry } from "@/lib/command-search";+import { entryScore, indexEntries, normalize, rankPalette, skillEntries, wordScore, type PaletteEntry } from "@/lib/command-search";import { modelHref, paletteIndex } from "@/lib/palette-index";import { modelSearchText, toModelRow } from "@/lib/model-rows";import { hubModePaths, studioRoutes } from "./e2e/_routes.mjs";@@ -82,11 +82,22 @@ describe("palette ranking", () => {it("orders groups by their best match and caps each group", () => {const groups = rankPalette(ALL, "zoom");- for (const g of groups) expect(g.entries.length).toBeLessThanOrEqual({ page: 6, setting: 4, app: 5, motion: 4, effect: 4, model: 5, recent: 5 }[g.kind]);+ for (const g of groups) expect(g.entries.length).toBeLessThanOrEqual({ page: 6, setting: 4, skill: 4, app: 5, motion: 4, effect: 4, model: 5, recent: 5 }[g.kind]);const best = groups.map((g) => entryScore("zoom", g.entries[0]));expect(best).toEqual([...best].sort((a, b) => b - a));});+ it("lists “Run <skill>…” for skills that run by themselves, and finds them", () => {+ const skills = [+ { name: "lamp-turntable", title: "Lamp turntable", description: "A turntable from a product photo.", recipe: true, enabled: true },+ { name: "off", title: "Switched off", description: "x", recipe: true, enabled: false },+ { name: "playbook", title: "Playbook only", description: "x", enabled: true },+ ];+ const entries = skillEntries(skills);+ expect(entries).toEqual([expect.objectContaining({ kind: "skill", label: "Run Lamp turntable…", href: "/assist/skills?run=lamp-turntable" })]);+ expect(rankPalette([...ALL, ...entries], "turntable").find((g) => g.kind === "skill")?.entries.map((e) => e.label)).toEqual(["Run Lamp turntable…"]);+ });+it("matches nothing on an empty query (the palette shows its own start list)", () => {expect(rankPalette(ALL, "")).toEqual([]);expect(rankPalette(ALL, " ")).toEqual([]);