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 across studios, as canvases, and suggested from repeated work
Adarsh1ba32b8bf545
diff --git a/bin/lib/commands.mjs b/bin/lib/commands.mjsindex f18ea7ca..056e3cb5 100644--- a/bin/lib/commands.mjs+++ b/bin/lib/commands.mjs@@ -792,10 +792,11 @@ async function skillsRun(ctx, name) {const est = await priceSkill(ctx, view, engine, req.body(fileStandIn));if (!est.runnable) throw new ApiError(estimateProblems(est, req).join("\n") || `/${view.name} can't run with these values`);const runs = est.runs.length;- const asks = !v.yes && !v.json;+ // Only --yes starts a run that costs money without a yes at the prompt; --json alone never spends.+ const asks = !v.yes;const costs = !est.demo && est.total !== 0;if (costs && asks) {- if (!ctx.io.stdinIsTTY) throw new UsageError(`Running ${runs === 1 ? "it" : `these ${runs}`} costs ${costWords(est)}: add --yes to run without asking`);+ if (v.json || !ctx.io.stdinIsTTY) throw new UsageError(`Running ${runs === 1 ? "it" : `these ${runs}`} costs ${costWords(est)}: add --yes to run without asking`);const answer = await ctx.io.ask(runQuestion(est, runs));if (!/^y(es)?$/i.test(answer.trim())) {ctx.note("Nothing was started.");@@ -812,7 +813,7 @@ async function skillsRun(ctx, name) {if (!real.runnable) throw new ApiError(estimateProblems(real, req).join("\n") || `/${view.name} can't run with these files`);if (priceRose(est, real)) {const was = costs ? `, not ${costWords(est)}` : "";- if (!ctx.io.stdinIsTTY) throw new UsageError(`With your files uploaded, running ${runs === 1 ? "it" : `these ${runs}`} costs ${costWords(real)}${was}: add --yes to run without asking. Nothing was started.`);+ if (v.json || !ctx.io.stdinIsTTY) throw new UsageError(`With your files uploaded, running ${runs === 1 ? "it" : `these ${runs}`} costs ${costWords(real)}${was}: add --yes to run without asking. Nothing was started.`);const answer = await ctx.io.ask(`With your files it costs ${costWords(real)}${was}. ${runQuestion(real, runs)}`);if (!/^y(es)?$/i.test(answer.trim())) {ctx.note("Nothing was started.");diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.mdindex 50a36e49..b50966db 100644--- a/docs/ARCHITECTURE.md+++ b/docs/ARCHITECTURE.md@@ -531,6 +531,8 @@ Round 5 part 1 adds no migration (still 23, numbered 0–22, and 43 tables). NewMain's GPU pre-flight and public sign-up added migrations 23 and 24 (above). Round 5 part 2 adds none (still 25, numbered 0–24, and 45 tables), but repairs a data folder that ran PR #15's branch before the owner dropped its accounts packages (`claude/fuobe-parity-4` up to `f7c6d8e`, `claude/fuobe-r5-batch-7` up to `c9cd489`). There, places 23 and 24 are marked done for that branch's own migrations (acc-1's identity tables, acc-2's audit-log trigger), so main's two would be skipped without a word. `forgetDroppedBranchMigrations` (`db.ts`, called in `open()` before the loop) forgets a place when it is marked done, main's work is missing (`gpu_snapshots`; `assets.account_id`) and the dropped package's is there (`users.auth_user_id`; the `audit_log_no_delete` trigger), so the loop runs main's migration. The dropped tables stay, unused, and nothing is deleted; a folder that only ever ran main is untouched (`tests/dropped-branch-migrations.test.ts`). Other new state uses existing places: a filmed path's keys, length and move on its Cinema take (`CinemaTakeInfo.path`); a turnaround step's `consentAt` in `generations.request_json`; DBS's stems and report as a run's outputs; and an exported mix as an upload, put together from its parts in the scratch folder (`mix-<id>.wav.part`; parts nobody finished are removed when the next export starts, after 6 hours). No column gains file URLs, so `ASSET_REFS` and `ASSET_FREE` are unchanged.+Skills W5 to W7 add no numbered migration (W4's `assist_schedules.skill_json` is a numbered migration, in the table above): like the relay, billing and admin tables, their state is made on every start when it's missing (`SKILL_TABLES` in `src/server/db.ts`), so branches that add migrations never clash over a place in the list. `skill_runs` (W7) holds a run of a skill whose steps wait across studios: `id` (also the run's batch), `skill`, `engine`, `status` (running, done, failed), `values_json` (the run's input values) and `state_json` (each step's status, generation ids, the studio page it opened and why it failed, and the steps as filled). `ASSET_REFS` gains `skill_runs.values_json` / `state_json`. W6 keeps its suggestions in the settings row `skills.suggestions` (JSON: the day's sweep, and the chains put off or dismissed) and reads a skill's history from the stamp its runs carry (`request_json` `$.skill`), with no table of its own.+Settings (`src/server/settings.ts`) are typed and validated against allowed values; environment variables give the defaults, and a value saved in Settings wins over them (the password is the exception: `FUOBE_PASSWORD` can't be changed from Settings). Secrets are masked before reaching the browser. `engineMode` is enforced server-side; the client reads it from `/api/status`. Round 4 adds `comfyIsolatedUrl` (`COMFYUI_ISOLATED_URL`, the isolated ComfyUI worker) and `onboarded` (key `onboarding.done`, no environment variable): `GET /api/status` sets it the first time something the engine mode generates with is connected, and putting the Get started guide away sets it too. `/api/status` also returns it, and ComfyUI's RAM as `providers.comfyui.ramBytes`. Round 4 part 2 adds `civitaiKey` (key `civitai.key`, `CIVITAI_API_KEY`, secret: it downloads civitai LoRAs and is never sent to fal or Replicate), and `comfyLorasDir` (`COMFYUI_LORAS_DIR`) is now also where LoRAs are downloaded before a ComfyUI run, so it must be ComfyUI's `models/loras` folder as this machine sees it, writable by Fuobe. Round 4 part 3 adds no setting and no environment variable, but those two matter more: Fuobe DoP's open runs download their preset's LoRAs before the job (the presets' open routes use 84 of the map's 99 files, 98 before round 4 part 4; 36 of the map's files are on civitai) and stop with a message without the folder or, for a civitai file, the key; only a Fuobe Soul look leaves an unreachable civitai LoRA out (see LoRAs). Round 4 part 4 adds no typed setting and no app environment variable: the Models & licences switches are one settings row (`models.access`, read and written by `src/server/model-access.ts`, edited at `/settings/models`); `FUOBE_TRUST_PROXY` now also keys the share-link throttle and `FUOBE_ALLOW_PRIVATE_URLS` also lets a connector URL use plain http beyond localhost; the install script gains `H3_PACK` (default 1), `H3_TOOL_REF`, `H3_RELAY` (default 0) and `H3_RELAY_REF`, and `NC_PACKS` now defaults to 1. The browser keeps the share links it made in localStorage (`fuobe.shareLinks`), since the server can't show a token again. Round 4 part 5 removes `higgsfieldKey` (`HIGGSFIELD_API_KEY`; `HF_KEY` and `HF_API_KEY` + `HF_API_SECRET` aren't read either) and the `higgsfield` value of `cloudProvider` (`FUOBE_CLOUD_PROVIDER` is `auto`, `fal` or `replicate`; a leftover value counts as `auto`, as any value outside the options does, and Settings refuses to save it), and adds no setting or environment variable: `REACH` and `COMFY_WAIT` are constants in the code. The local LLM servers (see Local LLM servers) add `llmProvider` (`FUOBE_LLM_PROVIDER`: auto, ollama, lmstudio, unsloth or custom), `lmstudioUrl`, `lmstudioModel` and `lmstudioToken` (`LMSTUDIO_URL`, `LMSTUDIO_MODEL`, `LMSTUDIO_API_TOKEN` or `LM_API_TOKEN`), `unslothUrl`, `unslothModel` and `unslothKey` (`UNSLOTH_URL`, `UNSLOTH_MODEL`, `UNSLOTH_API_KEY` or `UNSLOTH_STUDIO_AUTH_TOKEN`), `llmUrl`, `llmModel` and `llmKey` (`FUOBE_LLM_URL`, `FUOBE_LLM_MODEL`, `FUOBE_LLM_API_KEY`) and `llmContext` (`FUOBE_LLM_CONTEXT`, default 16384; `parseContext` also takes `16k`, and 0 leaves it to the server). A setting may name several environment variables, and the first one set wins (`envValue`). `enhanceProvider` (Settings → AI helper) takes `local`, and the old `ollama` still means it. Round 5 part 1 adds none either: Settings → Training · AI-Toolkit puts the existing `aiToolkitUrl`, `aiToolkitToken` and `aiToolkitDatasetDir` in the UI (see Training), the photos folder must now be a full path, and on the GPU the LoRA folder is how Fuobe fetches the round's new LoRAs before a run, as it does the others (three of Mixed Media's look LoRAs also need the civitai key). Round 5 part 2 adds no setting and no app environment variable; the install script gains `DBS_WEIGHTS` (default 1, fetch the four DBS files; 0 skips them, and Split soundtrack can't run without them). `withCandidates()` runs code as if typed values were saved (connection tests; see Security). Files live in `data/files/{uploads,outputs}/<date>/<id>.<ext>` (content types include .txt / .srt / .vtt / .json / .glb / .aac, since round 4 .ply / .spz splats, .mkv, .exr and .zip, since round 4 part 3 .ksplat, and since round 4 part 5 .avi; a finished Fuobe Soul picture and the Canvas concatenator's silent WAVs are saved there too) and are served by `/api/files/...` with HTTP range support. `<data dir>/tmp` is a scratch folder on the same file system (`scratchDir()` in `storage.ts`), never served: EXR zips and downloaded result files are written there, then moved into `files/outputs` by `adoptFile`; a partial file is removed on failure. `<data dir>/loras` holds LoRA files downloaded only to mirror them to fal or Replicate, and since round 4 part 4 Fuobe's own copy of every trained Soul ID LoRA (`TRAINED_DIR`), so expect it to grow. `FUOBE_DATA_DIR` moves everything.## UI (`src/components/`, `src/app/(studio)/`)diff --git a/docs/cli.md b/docs/cli.mdindex d7c161a6..facfbacd 100644--- a/docs/cli.md+++ b/docs/cli.md@@ -219,10 +219,10 @@ fuobe skills export weekly-promo --out weekly-promo.zip # SKILL.md and its filworks too. A file path in a cell is read from the table's folder, and each file goes up once. `-p` fillswhat the rows leave empty. A row that doesn't fit is named by its line, and then nothing starts.- `run` prices the whole batch first and asks `Run 20 for $12.40? [y/N]` when it costs money. `--yes`- starts it without asking; so does `--json` (for scripts). Without a terminal to ask on, it stops and- says to add `--yes`. Free runs (your GPU, or a demo) start without asking. Once your files are uploaded- it prices them again (a clip is priced by its length): when that's more, it asks again with the new- price, or stops without a terminal.+ starts it without asking; `--json` alone doesn't (a script adds `--yes`). Without a terminal to ask+ on, it stops and says to add `--yes`. Free runs (your GPU, or a demo) start without asking. Once+ your files are uploaded it prices them again (a clip is priced by its length): when that's more, it+ asks again with the new price, or stops without a terminal.- `--engine open|cloud` picks where it runs, among the engines its steps run on (by default: where itwas checked). A skill not yet checked on that engine gets its free plan check first.- `--wait` and `--out <dir>` wait for the results and save them, as `fuobe generate` does; without them,diff --git a/package.json b/package.jsonindex 4b76cd0c..f909c46c 100644--- a/package.json+++ b/package.json@@ -29,7 +29,8 @@"eval:validate": "node scripts/eval/eval.mjs validate","eval:setup": "node scripts/eval/eval.mjs setup","eval:trash": "node scripts/eval/eval.mjs trash",- "eval:covers": "node scripts/eval/eval.mjs covers"+ "eval:covers": "node scripts/eval/eval.mjs covers",+ "eval:from-skill": "node scripts/eval/from-skill.mjs"},"dependencies": {"@anthropic-ai/sdk": "^0.135.0",diff --git a/scripts/eval/from-skill.mjs b/scripts/eval/from-skill.mjsnew file mode 100644index 00000000..0174a05d--- /dev/null+++ b/scripts/eval/from-skill.mjs@@ -0,0 +1,109 @@+#!/usr/bin/env node+// pnpm eval:from-skill <name> [--out file] [--url …] [--token …]+//+// Writes an evaluation case (scripts/eval/cases/skill-<name>.json) from a saved skill's recipe: its examples become the+// case's inputs, and the case runs the skill through its own routes (POST /api/assist/skills/<name>/run, priced first by+// …/estimate), so `pnpm eval:run --suite skill-<name> --engine open|cloud` regression-tests the skill on a GPU or the+// cloud under the harness's spend cap. The recipe's checks pick the metrics. The skill is read from the Fuobe server the+// harness measures (the fuobe CLI's server and token).+import fs from "node:fs";+import path from "node:path";+import { fileURLToPath } from "node:url";+import { parseArgs } from "node:util";+import { connect } from "./lib/server.mjs";++const HERE = path.dirname(fileURLToPath(import.meta.url));+const MEDIA = { image: "images", video: "video", audio: "audio" };+const METRICS = { image: ["clip", "aesthetic"], video: ["temporal", "clip"], audio: [] };++/** A case input path for an example: a Fuobe file as a link on that server, a link as it is. */+const asInput = (v, server) => (typeof v === "string" && v.startsWith("/api/files/") ? new URL(v, server).href : v);++/**+ * The case for a recipe (pure: the tests call it). Media examples become the case's inputs, and the run's body names+ * them as `{{inputs.…}}`; every other input takes its example (or default).+ * @param {{ name: string, title: string, recipe: { params: any[], steps: any[], checks?: Record<string, any> } }} view+ * @param {string} server the server's address (examples that are Fuobe files become links to it)+ */+export function caseFromSkill(view, server) {+ const { recipe } = view;+ const inputs = {};+ const values = {};+ const missing = [];+ for (const p of recipe.params) {+ const v = p.example ?? p.default;+ const slot = MEDIA[p.type];+ if (slot) {+ if (v === undefined || v === null || v === "") {+ if (p.required) missing.push(p.label);+ continue;+ }+ if (slot === "images") {+ inputs.images = [...(inputs.images ?? []), asInput(v, server)];+ values[p.id] = `{{inputs.images.${inputs.images.length - 1}}}`;+ } else if (!inputs[slot]) {+ inputs[slot] = asInput(v, server);+ values[p.id] = `{{inputs.${slot}}}`;+ } else {+ // A second clip or sound of the same kind: one more of the case's lists (videos, audios).+ const list = slot === "video" ? "videos" : "audios";+ inputs[list] = [...(inputs[list] ?? []), asInput(v, server)];+ values[p.id] = `{{inputs.${list}.${inputs[list].length - 1}}}`;+ }+ } else if (v !== undefined && v !== null && v !== "") values[p.id] = typeof v === "number" ? String(v) : v;+ else if (p.required) missing.push(p.label);+ }+ if (missing.length) throw new Error(`/${view.name} has no example for ${missing.join(", ")}: run it once from its form (Skills → Run…) so it keeps one, then try again`);+ const kinds = Object.values(recipe.checks ?? {}).map((c) => c.kind).filter(Boolean);+ const kind = ["video", "image", "audio"].find((k) => kinds.includes(k)) ?? (recipe.steps.some((s) => s.kind === "tool") ? "video" : "image");+ const generate = recipe.steps.filter((s) => s.kind === "generate");+ const firstModel = generate[0]?.request.modelId ?? "skill";+ const suite = `skill-${view.name}`.toLowerCase().replace(/[^a-z0-9-]+/g, "-").slice(0, 60);+ return {+ $schema: "./case.schema.json",+ suite,+ title: `Skill: ${view.title}`,+ description: `Runs the saved skill /${view.name} with the inputs it was made with, through its own routes, to check that it still makes what it did. Made by pnpm eval:from-skill ${view.name}.`,+ original: "skill",+ kind,+ targets: { open: { models: [firstModel] }, cloud: { models: [firstModel] }, demo: { models: [firstModel] } },+ defaults: { seeds: [1], metrics: METRICS[kind] ?? [], timeoutSeconds: 1800 },+ variants: { default: { description: "The skill as saved" } },+ cases: [+ {+ id: `${suite}/examples`,+ title: `${view.title} with its examples`,+ ...(Object.keys(inputs).length && { inputs }),+ prompts: [{ id: "skill", text: view.title }],+ submit: { route: `/api/assist/skills/${view.name}/run`, body: { values, engine: "{{engine}}" }, result: "all", estimate: `/api/assist/skills/${view.name}/estimate` },+ },+ ],+ };+}++async function main() {+ const { values: v, positionals } = parseArgs({ allowPositionals: true, options: { out: { type: "string" }, url: { type: "string" }, token: { type: "string" } } });+ const name = positionals[0];+ if (!name) {+ process.stderr.write("Usage: pnpm eval:from-skill <name> [--out file]\n");+ return 2;+ }+ const { client, target } = connect({ url: v.url, token: v.token });+ const view = await client.request("GET", `/api/assist/skills/${encodeURIComponent(name)}/recipe`);+ const c = caseFromSkill(view, target.url);+ const out = path.resolve(v.out ?? path.join(HERE, "cases", `${c.suite}.json`));+ fs.writeFileSync(out, `${JSON.stringify(c, null, 2)}\n`);+ process.stdout.write(`Wrote ${path.relative(process.cwd(), out)}. Check it with pnpm eval:validate, then run: pnpm eval:run --suite ${c.suite} --engine open (or cloud, under its spend cap)\n`);+ return 0;+}++// Run directly (not imported by the tests).+if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {+ main().then(+ (code) => (process.exitCode = code),+ (e) => {+ process.stderr.write(`${e.message}\n`);+ process.exitCode = 1;+ },+ );+}diff --git a/scripts/eval/lib/run.mjs b/scripts/eval/lib/run.mjsindex 9a91020f..b0ac0858 100644--- a/scripts/eval/lib/run.mjs+++ b/scripts/eval/lib/run.mjs@@ -93,7 +93,9 @@ async function pool(items, n, fn) {*/export const routeResult = (answer, how) => {const stitch = Array.isArray(answer?.stitches) ? answer.stitches.at(-1) : undefined;- const items = answer?.items ?? (stitch ? (answer.segments ?? []).flatMap((s) => (s.takes ?? []).map((t) => ({ id: t.look }))) : []);+ // A skill's run (POST /api/assist/skills/<name>/run, from pnpm eval:from-skill): every row's generations.+ const runs = Array.isArray(answer?.runs) ? answer.runs.flatMap((r) => (r.ids ?? []).map((id) => ({ id }))) : null;+ const items = answer?.items ?? runs ?? (stitch ? (answer.segments ?? []).flatMap((s) => (s.takes ?? []).map((t) => ({ id: t.look }))) : []);const final = answer?.final ?? (stitch?.final ? { id: stitch.final } : items.at(-1));if (how === "all") return items.length ? items : [final].filter(Boolean);if (how === "last") return [items.at(-1) ?? final].filter(Boolean);diff --git a/src/app/api/assist/skills/[name]/fixes/route.ts b/src/app/api/assist/skills/[name]/fixes/route.tsnew file mode 100644index 00000000..2874e7b3--- /dev/null+++ b/src/app/api/assist/skills/[name]/fixes/route.ts@@ -0,0 +1,28 @@+import { connection } from "next/server";+import { z } from "zod";+import { badBody, recipeFailure } from "@/server/recipe-routes";+import { applyFix, fixCandidates } from "@/server/skill-insights";++/** The steps that need another model (failing, replaced or switched off) and the models that do the same job, priced. */+export async function GET(_request: Request, ctx: RouteContext<"/api/assist/skills/[name]/fixes">) {+ await connection();+ try {+ return Response.json(fixCandidates((await ctx.params).name));+ } catch (e) {+ return recipeFailure(e);+ }+}++const Body = z.object({ step: z.string().min(1).max(40), modelId: z.string().min(1).max(120) });++/** Swap a step's model for the one picked; the skill is checked (plan and a free dry run) before the swap is kept. */+export async function POST(request: Request, ctx: RouteContext<"/api/assist/skills/[name]/fixes">) {+ const parsed = Body.safeParse(await request.json().catch(() => ({})));+ if (!parsed.success) return badBody(parsed.error.issues);+ try {+ const { name } = await ctx.params;+ return Response.json(await applyFix(name, parsed.data.step, parsed.data.modelId));+ } catch (e) {+ return recipeFailure(e);+ }+}diff --git a/src/app/api/assist/skills/[name]/history/route.ts b/src/app/api/assist/skills/[name]/history/route.tsnew file mode 100644index 00000000..a52217cd--- /dev/null+++ b/src/app/api/assist/skills/[name]/history/route.ts@@ -0,0 +1,15 @@+import { connection } from "next/server";+import { getSkill } from "@/server/skills";+import { skillHistory } from "@/server/skill-insights";+import { listSkillRuns } from "@/server/skill-runs";++/**+ * A skill's runs from the stamp on each run's generations: how many, how many worked, the spend, and the last ten; and+ * its newest runs whose steps wait across studios, with each step's progress.+ */+export async function GET(_request: Request, ctx: RouteContext<"/api/assist/skills/[name]/history">) {+ await connection();+ const { name } = await ctx.params;+ if (!getSkill(name)) return Response.json({ error: "No such skill" }, { status: 404 });+ return Response.json({ ...skillHistory(name), waiting: listSkillRuns(name, 5) });+}diff --git a/src/app/api/assist/skills/draft/name/route.ts b/src/app/api/assist/skills/draft/name/route.tsindex 5eab4601..1fa2cd84 100644--- a/src/app/api/assist/skills/draft/name/route.ts+++ b/src/app/api/assist/skills/draft/name/route.ts@@ -1,5 +1,5 @@import { badBody, DraftSource, recipeFailure } from "@/server/recipe-routes";-import { draftFromGenerations, draftFromThread, nameDraft } from "@/server/recipe-builder";+import { draftFromCanvas, draftFromGenerations, draftFromThread, nameDraft } from "@/server/recipe-builder";/*** The optional naming pass for a draft (Claude or Ollama, whichever this install allows): names for its inputs, slots in@@ -10,7 +10,8 @@ export async function POST(request: Request) {const parsed = DraftSource.safeParse(await request.json().catch(() => ({})));if (!parsed.success) return badBody(parsed.error.issues);try {- const { draft, words } = "thread" in parsed.data ? draftFromThread(parsed.data.thread) : { ...draftFromGenerations(parsed.data.generations), words: [] };+ const src = parsed.data;+ const { draft, words } = "thread" in src ? draftFromThread(src.thread) : "canvas" in src ? { ...draftFromCanvas(src.canvas, src.page), words: [] } : { ...draftFromGenerations(src.generations), words: [] };return Response.json({ naming: draft ? await nameDraft(draft, words) : null });} catch (e) {return recipeFailure(e);diff --git a/src/app/api/assist/skills/draft/route.ts b/src/app/api/assist/skills/draft/route.tsindex d4025910..66073d52 100644--- a/src/app/api/assist/skills/draft/route.ts+++ b/src/app/api/assist/skills/draft/route.ts@@ -1,10 +1,11 @@import { badBody, DraftSource, recipeFailure } from "@/server/recipe-routes";-import { draftFromGenerations, draftFromThread } from "@/server/recipe-builder";+import { draftFromCanvas, draftFromGenerations, draftFromThread } from "@/server/recipe-builder";/**- * A skill drafted from results in the Library (W2) or from an Assist chat (W3): the steps behind them rebuilt from- * their requests, every input Fixed, with the inputs that could vary and proposed checks; `refusals` say which picks- * (or which of the chat's steps) couldn't be used and why.+ * A skill drafted from results in the Library (W2), from an Assist chat (W3) or from a canvas (W5): the steps behind them+ * rebuilt from their requests, every input Fixed, with the inputs that could vary and proposed checks; `refusals` say+ * which picks (or which of the chat's steps, or the canvas's nodes) couldn't be used and why. A canvas's Table rows come+ * as `rows`, for the Run form's Many tab.*/export async function POST(request: Request) {const parsed = DraftSource.safeParse(await request.json().catch(() => ({})));@@ -14,6 +15,7 @@ export async function POST(request: Request) {const { draft, refusals } = draftFromThread(parsed.data.thread);return Response.json({ draft, refusals });}+ if ("canvas" in parsed.data) return Response.json(draftFromCanvas(parsed.data.canvas, parsed.data.page));return Response.json(draftFromGenerations(parsed.data.generations));} catch (e) {return recipeFailure(e);diff --git a/src/app/api/skill-suggestions/route.ts b/src/app/api/skill-suggestions/route.tsnew file mode 100644index 00000000..3c50a167--- /dev/null+++ b/src/app/api/skill-suggestions/route.ts@@ -0,0 +1,22 @@+import { connection } from "next/server";+import { z } from "zod";+import { dismissSuggestion, skillSuggestions } from "@/server/skill-insights";++/**+ * Chains the owner made 3 or more times in 14 days that no skill makes yet, offered as skills above the Library (swept at+ * most once a day). Public sign-up: a guest's or an account's answer is empty (the owner's runs stay the owner's).+ */+export async function GET() {+ await connection();+ return Response.json({ items: skillSuggestions() });+}++const Body = z.object({ id: z.string().min(1).max(40), how: z.enum(["later", "never"]) });++/** Not now (hidden for a week) or Don't suggest this (never again). The owner's only. */+export async function POST(request: Request) {+ const parsed = Body.safeParse(await request.json().catch(() => null));+ if (!parsed.success) return Response.json({ error: "Say which suggestion, and later or never" }, { status: 400 });+ dismissSuggestion(parsed.data.id, parsed.data.how);+ return Response.json({ items: skillSuggestions() });+}diff --git a/src/components/assist/hooks.ts b/src/components/assist/hooks.tsindex 9c7a985f..f1300da6 100644--- a/src/components/assist/hooks.ts+++ b/src/components/assist/hooks.ts@@ -244,21 +244,21 @@ 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(","));+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).staleTime: Infinity,gcTime: 0,- queryFn: () => recipeCall<{ draft: SkillDraft | null; refusals: DraftRefusal[] }>("/api/assist/skills/draft", source),+ queryFn: () => recipeCall<{ draft: SkillDraft | null; refusals: DraftRefusal[]; rows?: Record<string, string>[] }>("/api/assist/skills/draft", source),});}diff --git a/src/components/assist/run-skill-dialog.tsx b/src/components/assist/run-skill-dialog.tsxindex 631d3786..f935b435 100644--- a/src/components/assist/run-skill-dialog.tsx+++ b/src/components/assist/run-skill-dialog.tsx@@ -32,20 +32,20 @@ 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 }) {+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} csv={csv} />;return (<div className="space-y-3 p-6"><DialogTitle className="sr-only">Run a skill</DialogTitle>@@ -82,20 +82,21 @@ 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, csv: rowsCsv }: { view: RecipeView; onClose: () => void; examples?: boolean; intro?: string; csv?: string }) {const { recipe, name } = view;const actions = useRecipeActions();const skillActions = useSkillActions();const qc = useQueryClient();const router = useRouter();- const [tab, setTab] = useState<"one" | "many">("one");+ // Rows handed over (a canvas's Table): the Many tab, filled.+ const [tab, setTab] = useState<"one" | "many">(rowsCsv ? "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(rowsCsv ?? "");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);@@ -175,9 +176,17 @@ function Loaded({ view, onClose, examples, intro }: { view: RecipeView; onClose:const href = started[0]?.href ?? "/library";const studio = href.startsWith("/library") ? "Library" : href.startsWith("/video-tools/captions") ? "Captions" : "the studio";const title = failed.length ? `Started ${started.length} of ${r.runs.length} runs` : started.length > 1 ? `Started ${started.length} runs` : "Started the run";+ // A run in stages: its steps start one after another; the toast opens the skill, where each step's progress shows.+ const staged = started.find((x) => x.skillRun);(failed.length ? toast.warning : toast.success)(title, {- description: failed.length ? failed[0].error : r.demo ? "A demo run — no provider connected" : `${view.title}: same steps, new take`,- action: { label: `Open in ${studio}`, onClick: () => router.push(href) },+ description: failed.length+ ? failed[0].error+ : staged?.waiting?.length+ ? `${staged.waiting.join(", ")} start${staged.waiting.length === 1 ? "s" : ""} when the step before is done`+ : r.demo+ ? "A demo run — no provider connected"+ : `${view.title}: same steps, new take`,+ action: staged ? { label: "See its steps", onClick: () => router.push(`/assist/skills?skill=${encodeURIComponent(name)}`) } : { label: `Open in ${studio}`, onClick: () => router.push(href) },});onClose();} catch (e) {diff --git a/src/components/assist/skill-insights.tsx b/src/components/assist/skill-insights.tsxnew file mode 100644index 00000000..61d13709--- /dev/null+++ b/src/components/assist/skill-insights.tsx@@ -0,0 +1,250 @@+"use client";++import { useQuery, useQueryClient } from "@tanstack/react-query";+import { AlertTriangle, ArrowRight, Check, CircleDashed, Loader2, Wrench, X } from "lucide-react";+import Link from "next/link";+import { useState } from "react";+import { toast } from "sonner";+import { Button } from "@/components/ui/button";+import { Skeleton } from "@/components/ui/skeleton";+import { formatCost } from "@/lib/format";+import { refusalShown } from "@/lib/refusals";+import type { FixCandidates, SkillHistory, SkillRunRow } from "@/lib/skill-insights";+import type { SkillRunView } from "@/lib/skill-runs";+import { cn } from "@/lib/utils";+import type { RecipeFailure } from "./hooks";++/**+ * A skill's life after it is saved (packages W6 and W7), in its dialog: its runs (how many, how many worked, what they+ * cost, the last ten, and the steps of a run that waits across studios), and Suggest a fix for a step that keeps+ * failing or whose model was replaced or switched off. The owner's only: a visitor reads the skill, not its runs.+ */++async function read<T>(res: Response): Promise<T> {+ const out = (await res.json().catch(() => ({}))) as T & { error?: string; problems?: string[] };+ if (!res.ok) throw Object.assign(new Error(out.error ?? "Something went wrong. Please try again."), { status: res.status, problems: out.problems });+ return out;+}++export function useSkillHistory(name: string, enabled = true) {+ return useQuery({+ queryKey: ["assist-skill-history", name],+ enabled,+ retry: false,+ queryFn: async () => read<SkillHistory & { waiting?: SkillRunView[] }>(await fetch(`/api/assist/skills/${encodeURIComponent(name)}/history`)),+ // A run that waits across studios moves on its own: look again while one is going.+ refetchInterval: (q) => (q.state.data?.waiting?.some((r) => r.status === "running") || q.state.data?.recent.some((r) => r.status === "running") ? 4000 : false),+ });+}++export function useSkillFixes(name: string, enabled = true) {+ return useQuery({+ queryKey: ["assist-skill-fixes", name],+ enabled,+ retry: false,+ queryFn: async () => read<FixCandidates>(await fetch(`/api/assist/skills/${encodeURIComponent(name)}/fixes`)),+ });+}++const day = (ms: number) => new Date(ms).toLocaleDateString(undefined, { day: "numeric", month: "short", hour: "2-digit", minute: "2-digit" });++const STATUS_WORDS: Record<SkillRunRow["status"], string> = { running: "Running", succeeded: "Done", failed: "Failed", canceled: "Stopped" };++function StatusDot({ status }: { status: SkillRunRow["status"] | "waiting" }) {+ if (status === "succeeded") return <Check className="size-3.5 text-emerald-600 dark:text-emerald-400" aria-hidden />;+ if (status === "failed") return <X className="size-3.5 text-destructive" aria-hidden />;+ if (status === "running") return <Loader2 className="size-3.5 animate-spin text-brand-text" aria-hidden />;+ return <CircleDashed className="size-3.5 text-muted-foreground" aria-hidden />;+}++function Thumb({ o }: { o: SkillRunRow["outputs"][number] }) {+ const cls = "size-10 shrink-0 rounded-md bg-muted object-cover";+ const still = o.kind === "image" ? o.url : o.kind === "video" ? o.poster : undefined;+ // eslint-disable-next-line @next/next/no-img-element+ if (still) return <img src={still} alt="" loading="lazy" className={cls} />;+ if (o.kind === "video") return <video src={o.url} muted playsInline preload="metadata" className={cls} />;+ return <span className={cn(cls, "grid place-items-center text-[10px] text-muted-foreground uppercase")}>{o.kind}</span>;+}++/** A run whose steps wait across studios: "Dub · done → Captions · running → 9:16 cut · waiting". */+export function RunSteps({ run }: { run: SkillRunView }) {+ return (+ <ol className="flex flex-wrap items-center gap-x-1.5 gap-y-1 text-[12px]" aria-label="Steps">+ {run.steps.map((s, i) => (+ <li key={s.key} className="inline-flex min-w-0 items-center gap-1.5">+ {i > 0 && <ArrowRight className="size-3 shrink-0 text-muted-foreground" aria-hidden />}+ <StatusDot status={s.status === "done" ? "succeeded" : s.status === "failed" ? "failed" : s.status === "running" ? "running" : "waiting"} />+ <span className="min-w-0 break-words">+ {s.label} · <span className="text-muted-foreground">{s.status === "done" ? "done" : s.status}</span>+ </span>+ {s.href && (+ <Link href={s.href} className="text-brand-text underline underline-offset-2">+ Open in {s.studio ?? "the studio"}+ </Link>+ )}+ </li>+ ))}+ {run.error && (+ <li role="alert" className="basis-full text-destructive">+ {run.error}+ </li>+ )}+ </ol>+ );+}++/** History: the skill's runs in numbers, then the last ten (status, cost, when, what they made). */+export function SkillHistorySection({ name }: { name: string }) {+ const q = useSkillHistory(name);+ if (q.isError) return null;+ const h = q.data;+ return (+ <section className="mt-4 border-t pt-3" aria-labelledby={`history-${name}`}>+ <p className="text-[12px] font-medium" id={`history-${name}`}>+ History+ </p>+ {!h ? (+ <Skeleton className="mt-2 h-16" />+ ) : !h.runs && !h.waiting?.length ? (+ <p className="mt-1 text-[12px] text-muted-foreground">No runs yet. Run it, and each run shows here with what it cost.</p>+ ) : (+ <>+ <p className="mt-1 text-[12px] text-muted-foreground">+ {h.runs} run{h.runs === 1 ? "" : "s"}+ {h.successRate !== null && ` · ${Math.round(h.successRate * 100)}% worked`}+ {` · ${formatCost(h.spendUsd)} spent`}+ {h.lastRunAt && ` · last ${day(h.lastRunAt)}`}+ {h.favorites > 0 && ` · ${h.favorites} favourite${h.favorites === 1 ? "" : "s"}`}+ </p>+ {!!h.waiting?.length && (+ <ul className="mt-2 space-y-2">+ {h.waiting.map((r) => (+ <li key={r.id} className="rounded-xl border px-3 py-2" data-skill-run={r.id}>+ <p className="mb-1 text-[12px] text-muted-foreground">+ {day(r.createdAt)} · {r.status === "running" ? "Running" : r.status === "failed" ? "Failed" : "Done"}+ </p>+ <RunSteps run={r} />+ </li>+ ))}+ </ul>+ )}+ <ul className="mt-2 divide-y rounded-xl border">+ {h.recent.map((r) => (+ <li key={r.run} className="flex items-center gap-3 px-3 py-2">+ <div className="flex shrink-0 gap-1">{r.outputs.length ? r.outputs.slice(0, 2).map((o) => <Thumb key={o.url} o={o} />) : <span className="size-10 rounded-md bg-muted" />}</div>+ <div className="min-w-0 flex-1 text-[12px]">+ <p className="flex items-center gap-1.5 font-medium">+ <StatusDot status={r.status} /> {STATUS_WORDS[r.status]}+ {r.demo && <span className="font-normal text-muted-foreground">· demo</span>}+ </p>+ <p className="text-muted-foreground">+ {day(r.at)} · {r.costUsd === null ? "price unknown" : formatCost(r.costUsd)} · {r.steps} result{r.steps === 1 ? "" : "s"}+ </p>+ </div>+ <Link href="/library" className="shrink-0 text-[12px] text-brand-text underline underline-offset-2">+ Library+ </Link>+ </li>+ ))}+ </ul>+ </>+ )}+ </section>+ );+}++/**+ * Suggest a fix: the steps that need another model, each with models that do the same job here and their prices. The+ * person picks one; the skill is checked again (free) before the swap is kept. Never swapped by itself.+ */+export function FixPanel({ name, onClose }: { name: string; onClose: () => void }) {+ const q = useSkillFixes(name);+ const qc = useQueryClient();+ const [busy, setBusy] = useState<string | null>(null);+ const pick = async (step: string, modelId: string) => {+ setBusy(`${step}:${modelId}`);+ try {+ const r = await read<{ ok: boolean; problems: string[] }>(+ await fetch(`/api/assist/skills/${encodeURIComponent(name)}/fixes`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ step, modelId }) }),+ );+ if (r.ok) {+ toast.success("Fixed and checked", { description: "The step uses the new model; the skill was priced and run once for free." });+ void qc.invalidateQueries({ queryKey: ["assist-recipe", name] });+ void qc.invalidateQueries({ queryKey: ["assist-skill-fixes", name] });+ onClose();+ } else toast.error("That model doesn't pass the check, so nothing changed", { description: r.problems[0] });+ } catch (e) {+ const f = e as RecipeFailure;+ if (!refusalShown(f)) toast.error(f.message);+ } finally {+ setBusy(null);+ }+ };+ return (+ <div className="mt-3 rounded-xl border bg-background p-3 text-left text-[13px] text-foreground" role="region" aria-label="Suggest a fix">+ <div className="flex items-center justify-between gap-2">+ <p className="font-medium">Suggest a fix</p>+ <Button variant="ghost" size="icon" className="size-7" onClick={onClose} aria-label="Close the fixes">+ <X />+ </Button>+ </div>+ {q.isError ? (+ <p className="mt-1 text-destructive">{(q.error as Error).message}</p>+ ) : !q.data ? (+ <Skeleton className="mt-2 h-16" />+ ) : !q.data.steps.length ? (+ <p className="mt-1 text-muted-foreground">Every step looks fine. Re-check it to price it again.</p>+ ) : (+ <ul className="mt-2 space-y-3">+ {q.data.steps.map((s) => (+ <li key={s.key}>+ <p className="font-medium">+ {s.label} · {s.model}+ </p>+ <p className="text-[12px] text-amber-700 dark:text-amber-300">{s.reasons.join(" · ")}</p>+ {!s.candidates.length ? (+ <p className="mt-1 text-[12px] text-muted-foreground">No other model here does this job. Switch one on in Settings → Models & licences.</p>+ ) : (+ <ul className="mt-1.5 grid gap-1.5 sm:grid-cols-2">+ {s.candidates.map((c) => (+ <li key={c.modelId}>+ <button+ type="button"+ disabled={!!busy || !!c.problem}+ onClick={() => void pick(s.key, c.modelId)}+ className="flex w-full items-center justify-between gap-2 rounded-lg border px-2.5 py-1.5 text-left transition-colors hover:bg-accent disabled:opacity-60"+ >+ <span className="min-w-0">+ <span className="block truncate text-[13px]">{c.name}</span>+ <span className="block text-[11px] text-muted-foreground">{c.problem ?? (c.engine === "open" ? "Your GPU" : "Cloud")}</span>+ </span>+ <span className="shrink-0 text-[12px] tabular-nums">{busy === `${s.key}:${c.modelId}` ? <Loader2 className="size-3.5 animate-spin" /> : formatCost(c.costUsd)}</span>+ </button>+ </li>+ ))}+ </ul>+ )}+ </li>+ ))}+ </ul>+ )}+ </div>+ );+}++/** The amber line a skill gets when a step keeps failing (its re-check line covers replaced and switched-off models). */+export function FailingLine({ fixes, onFix }: { fixes: FixCandidates | undefined; onFix: () => void }) {+ const failing = fixes?.steps.find((s) => s.reasons.some((r) => r.startsWith("It failed")));+ if (!failing) return null;+ return (+ <div className="mt-1 flex flex-wrap items-center gap-x-2 gap-y-1 text-[12px] text-amber-700 dark:text-amber-300">+ <AlertTriangle className="size-3.5 shrink-0" aria-hidden />+ <span className="min-w-0 break-words">+ {failing.label}: {failing.reasons.find((r) => r.startsWith("It failed"))?.toLowerCase()}+ </span>+ <Button variant="outline" size="xs" className="h-6 rounded-full px-2 text-[12px]" onClick={onFix}>+ <Wrench /> Suggest a fix+ </Button>+ </div>+ );+}diff --git a/src/components/assist/skills-view.tsx b/src/components/assist/skills-view.tsxindex 2fd7dc5d..142e355b 100644--- a/src/components/assist/skills-view.tsx+++ b/src/components/assist/skills-view.tsx@@ -1,6 +1,6 @@"use client";-import { AlertTriangle, ChevronDown, Copy, Download, FileUp, Loader2, MessageSquarePlus, Pencil, Play, Plus, Search, ShieldCheck, Trash2, Upload, X } from "lucide-react";+import { AlertTriangle, ChevronDown, Copy, Download, FileUp, Loader2, MessageSquarePlus, Pencil, Play, Plus, Search, ShieldCheck, Trash2, Upload, Wrench, X } from "lucide-react";import Link from "next/link";import { usePathname, useRouter, useSearchParams } from "next/navigation";import { Suspense, useDeferredValue, useId, useRef, useState } from "react";@@ -35,6 +35,7 @@ import { refusalShown, toastError } from "@/lib/refusals";import { radioKeys } from "@/components/studio/radio-keys";import { useRecipe, useRecipeActions, useSkill, useSkillActions, useSkills, type RecipeFailure, type SkillForm } from "./hooks";import { RunSkillDialog } from "./run-skill-dialog";+import { FailingLine, FixPanel, SkillHistorySection, useSkillFixes } from "./skill-insights";import { RailButton } from "./shell";import { SKILL_ICONS, SkillIcon } from "./skill-icon";import { AssistVisitorNote } from "./visitor-note";@@ -283,10 +284,14 @@ function SkillGrid({ list, loading, onOpen, onToggle, empty }: { list: SkillSumm* 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 }) {+function RecipeStatus({ skill, owner }: { skill: Skill; owner: boolean }) {const recipe = useRecipe(skill.name, !!skill.recipe);const actions = useRecipeActions();const [busy, setBusy] = useState(false);+ // Suggest a fix (W6): the owner's own skills, when a step keeps failing, was replaced or was switched off.+ const fixable = owner && skill.source === "user" && !!skill.recipe;+ const fixes = useSkillFixes(skill.name, fixable);+ const [fixing, setFixing] = useState(false);const v = recipe.data;if (!skill.recipe || !v) return null;const recheck = Object.values(v.recheck).flat();@@ -304,16 +309,26 @@ function RecipeStatus({ skill }: { skill: Skill }) {}};const canCheck = skill.source === "user";+ const canFix = fixable && !!fixes.data?.steps.length;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>+ <>+ <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>+ )}+ {canFix && recheck.length > 0 && !fixing && (+ <Button variant="outline" size="xs" className="h-6 rounded-full px-2 text-[12px]" onClick={() => setFixing(true)}>+ <Wrench /> Suggest a fix+ </Button>+ )}+ </div>+ {canFix && !recheck.length && !fixing && <FailingLine fixes={fixes.data} onFix={() => setFixing(true)} />}+ {fixing && <FixPanel name={skill.name} onClose={() => setFixing(false)} />}+ </>);}@@ -343,7 +358,7 @@ function SkillDetail({ name, owner, onClose, onEdit, onRun }: { name: string | n<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} />+ <RecipeStatus skill={s} owner={owner} /><p className="mt-1.5 font-mono text-[11px] text-muted-foreground">/{s.name} · {s.source === "builtin" ? "Built-in" : "Yours"}{s.studio && (@@ -379,6 +394,7 @@ function SkillDetail({ name, owner, onClose, onEdit, onRun }: { name: string | n</ul></div>)}+ {owner && s.recipe && <SkillHistorySection name={s.name} />}</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">diff --git a/src/components/canvas/canvas-editor.tsx b/src/components/canvas/canvas-editor.tsxindex dce9a985..33d72af5 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";@@ -115,6 +115,7 @@ import { NODE_TYPES, type FlowNode } from "./nodes";import { AddMenu, DRAG_TYPE, Palette, PaletteToggle } from "./palette";import { BoardToolbar, PAGE_PANEL_ID, PageTabs, pageTabId, TOOL_KEYS, type DragShape, type PageOps, type Tool } from "./toolbar";import { saveCanvas, useCanvasView, useRunCanvas, type CanvasView } from "./use-canvas";+import { useSkillBuilder } from "@/components/skills/skill-builder-provider";const GRID: [number, number] = [16, 16];const snap = (p: { x: number; y: number }) => ({ x: Math.round(p.x / GRID[0]) * GRID[0], y: Math.round(p.y / GRID[1]) * GRID[1] });@@ -406,6 +407,12 @@ function Editor({ id, initial, view }: { id: string; initial: Canvas; view: Canv},[id, qc, docOf],);+ // ---- Save as skill (W5): the board saved first, so the skill is made from what's on screen.+ const skillBuilder = useSkillBuilder();+ const saveAsSkill = useCallback(async () => {+ await save();+ skillBuilder?.openCanvas(id, latest.current.pageId);+ }, [id, save, skillBuilder]);useEffect(() => {if (rev === 0) return;const t = setTimeout(() => void save(), 700);@@ -1238,12 +1245,14 @@ function Editor({ id, initial, view }: { id: string; initial: Canvas; view: CanvswitchEngine: 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>(() => ({+ saveAsSkill: () => void uiHandlers.current!.saveAsSkill(),run: (targets, force) => uiHandlers.current!.run(targets, force),runSelected: (force) => uiHandlers.current!.runSelection(force),switchEngine: (e) => uiHandlers.current!.switchEngine(e),@@ -1481,6 +1490,8 @@ function Editor({ id, initial, view }: { id: string; initial: Canvas; view: Canv// the board doesn't re-render its menus and tooltips.interface HeaderUi {+ /** The review screen for a skill made from this page of the canvas (W5), once the board is saved. */+ saveAsSkill: () => void;run: (targets?: string[], force?: boolean) => void;runSelected: (force?: boolean) => void;switchEngine: (e: Engine) => void;@@ -1597,6 +1608,10 @@ const EditorHeader = memo(function EditorHeader({<DropdownMenuItem disabled={mode === "open"} onSelect={() => ui.switchEngine("cloud")}><Cloud /> Switch all to cloud</DropdownMenuItem>+ <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.tsxindex 0a84070a..2845229b 100644--- a/src/components/canvas/canvas-list.tsx+++ b/src/components/canvas/canvas-list.tsx@@ -22,6 +22,7 @@ import { timeAgo } from "@/lib/format";import { templateCover } from "@/lib/template-covers";import { cn } from "@/lib/utils";import { toastError } from "@/lib/refusals";+import { SkillCanvases } from "./skill-canvases";import { Schematic, TemplateCard } from "./template-card";import { useCanvasActions, useCanvases } from "./use-canvas";@@ -162,6 +163,7 @@ function ListInner({ templates, intro }: { templates: TemplateCardData[]; intro?const router = useRouter();const params = useSearchParams();const askedTemplates = params.get("tab") === "templates";+ const askedSkills = params.get("tab") === "skills";// A canvas is saved to the studio's library, which is its owner's: a guest or an account can look, not start one.// Until the viewer is known to be the owner, the page is a visitor's: only ready boards with their real cover show.const owner = useIsOwner();@@ -179,6 +181,7 @@ function ListInner({ templates, intro }: { templates: TemplateCardData[]; intro?const [seeAll, setSeeAll] = useState(false);const allTemplates = seeAll || askedTemplates;const gallery = useRef<HTMLElement>(null);+ const skillsRef = useRef<HTMLElement>(null);const access = useModelAccess();const viewing: Viewing = { visitor: !owner, hasCover: (id) => !!templateCover("canvas", id) };@@ -193,6 +196,11 @@ function ListInner({ templates, intro }: { templates: TemplateCardData[]; intro?gallery.current?.scrollIntoView({ block: "start" });}, [askedTemplates, hasBoards]);+ // ?tab=skills: the skills that run by themselves, scrolled to.+ useEffect(() => {+ if (askedSkills && owner && !loadingMine) skillsRef.current?.scrollIntoView({ block: "start" });+ }, [askedSkills, owner, loadingMine]);+const start = async (key: string, body: Parameters<typeof create>[0]) => {setCreating(key);try {@@ -335,6 +343,17 @@ function ListInner({ templates, intro }: { templates: TemplateCardData[]; intro?</>)}+ {/* The studio's skills are its owner's: each one that runs by itself opens as a canvas to change visually. */}+ {owner && !loadingMine && (+ <section id="skills" ref={skillsRef} aria-labelledby="skills-title" className="mt-12 scroll-mt-20">+ <h2 id="skills-title" className="font-heading text-[22px] leading-tight">+ Skills as canvases+ </h2>+ <p className="mt-0.5 text-[13px] text-muted-foreground">Open a skill that runs by itself as a canvas, change a model or a link, then save it back as a skill.</p>+ <SkillCanvases visitor={false} />+ </section>+ )}+<Dialog open={!!renaming} onOpenChange={(o) => !o && setRenaming(null)}><DialogContent className="sm:max-w-sm"><DialogHeader>diff --git a/src/components/canvas/skill-canvases.tsx b/src/components/canvas/skill-canvases.tsxnew file mode 100644index 00000000..66d3bd7d--- /dev/null+++ b/src/components/canvas/skill-canvases.tsx@@ -0,0 +1,103 @@+"use client";++import { useQueries } from "@tanstack/react-query";+import { Info, Loader2, Workflow } from "lucide-react";+import { useRouter } from "next/navigation";+import { useState } from "react";+import { SkillIcon } from "@/components/assist/skill-icon";+import { useSkills } from "@/components/assist/hooks";+import { Button } from "@/components/ui/button";+import { Skeleton } from "@/components/ui/skeleton";+import { recipeToCanvas } from "@/lib/catalog/canvas-recipe";+import type { RecipeView } from "@/lib/recipe";+import { toastError } from "@/lib/refusals";+import { useCanvasActions } from "./use-canvas";++/**+ * Canvas → Skills (package W5): the skills that run by themselves, each drawn as a canvas on request ("Open as canvas"+ * makes a new canvas of its steps, to change a model or a link visually and save it back as a skill). A skill whose steps+ * a canvas can't hold yet says why instead.+ */+export function SkillCanvases({ visitor }: { visitor: boolean }) {+ const skills = useSkills();+ const router = useRouter();+ const { create } = useCanvasActions();+ const [busy, setBusy] = useState<string | null>(null);+ const list = (skills.data ?? []).filter((s) => s.recipe);+ const views = useQueries({+ queries: list.map((s) => ({+ queryKey: ["assist-recipe", s.name],+ retry: false,+ queryFn: async () => {+ const res = await fetch(`/api/assist/skills/${encodeURIComponent(s.name)}/recipe`);+ if (!res.ok) throw new Error(((await res.json().catch(() => ({}))) as { error?: string }).error ?? "This skill can't be read");+ return (await res.json()) as RecipeView;+ },+ })),+ });+ const open = async (view: RecipeView) => {+ setBusy(view.name);+ try {+ const { graph } = recipeToCanvas(view.recipe);+ const c = await create({ name: view.title.slice(0, 80), graph });+ router.push(`/canvas/${c.id}`);+ } catch (e) {+ toastError(e);+ setBusy(null);+ }+ };+ 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-32 rounded-xl" />+ ))}+ </div>+ );+ if (!list.length)+ return (+ <div className="mt-6 rounded-2xl border border-dashed px-5 py-8 text-center">+ <p className="text-[15px] font-medium">No skill runs by itself yet</p>+ <p className="mx-auto mt-1 max-w-md text-[13px] text-muted-foreground">Save a canvas as a skill from its menu, or make one from results in the Library. Each one shows here, ready to open as a canvas.</p>+ </div>+ );+ return (+ <div className="mt-6 grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3" data-skill-canvases>+ {list.map((s, i) => {+ const q = views[i];+ const drawn = q.data ? recipeToCanvas(q.data.recipe) : null;+ return (+ <article key={s.name} className="flex flex-col gap-3 rounded-xl border bg-card p-4">+ <div className="flex items-start gap-3">+ <SkillIcon name={s.name} icon={s.icon} />+ <div className="min-w-0 flex-1">+ <h3 className="text-[14px] font-medium break-words">{s.title}</h3>+ <p className="line-clamp-2 text-[13px] text-muted-foreground">{s.description}</p>+ </div>+ </div>+ {q.isLoading ? (+ <Skeleton className="h-8 w-32" />+ ) : q.isError ? (+ <p className="text-[12px] text-muted-foreground">{(q.error as Error).message}</p>+ ) : drawn?.readOnly ? (+ <p className="flex items-start gap-1.5 text-[12px] text-muted-foreground">+ <Info className="mt-px size-3.5 shrink-0" aria-hidden /> {drawn.readOnly}.+ </p>+ ) : (+ <div className="mt-auto flex flex-wrap items-center gap-2">+ <span className="text-[12px] text-muted-foreground">+ {q.data!.recipe.steps.length} step{q.data!.recipe.steps.length === 1 ? "" : "s"} · {q.data!.recipe.params.length} input{q.data!.recipe.params.length === 1 ? "" : "s"}+ </span>+ {!visitor && (+ <Button size="sm" className="ml-auto rounded-full" onClick={() => void open(q.data!)} disabled={!!busy}>+ {busy === s.name ? <Loader2 className="animate-spin" /> : <Workflow />} Open as canvas+ </Button>+ )}+ </div>+ )}+ </article>+ );+ })}+ </div>+ );+}diff --git a/src/components/library-view.tsx b/src/components/library-view.tsxindex 2038c478..2ae92f06 100644--- a/src/components/library-view.tsx+++ b/src/components/library-view.tsx@@ -7,6 +7,7 @@ import { Suspense, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useimport { toast } from "sonner";import { AssetCard, cardRatio, type CardApi } from "@/components/library/asset-card";import { FilterBar, filterFields, filtersFor, hasFilters, NO_FILTERS, type Filters } from "@/components/library/filters";+import { SkillSuggestions } from "@/components/skills/skill-suggestions";import { FolderDialog, FolderHeader, FolderStrip, MoveMenuItems } from "@/components/library/folders";import { ReviewMenuItems } from "@/components/library/review";import { UploadDeleteProvider } from "@/components/library/upload-delete";@@ -687,6 +688,8 @@ function Inner() {{!uploadsTab && !sharedTab && !missingFolder && (<div className="mb-4 flex flex-wrap items-center justify-between gap-2"><FilterBar value={filters} onChange={setFilters} facets={facets.data} subfolders={!!folder?.folders} scoped={!!folderId || tab.id !== "all" || !!dq} trash={trash} />+ {/* A chain made again and again, offered as a skill (All only; the owner's own runs). */}+ {tab.id === "all" && !folderId && !dq && <SkillSuggestions />}{trash && (<div className="flex items-center gap-3 text-[13px] text-muted-foreground"><span>Items stay here for {TRASH_DAYS} days.</span>diff --git a/src/components/skills/skill-builder-provider.tsx b/src/components/skills/skill-builder-provider.tsxindex 36937499..d6f42b95 100644--- a/src/components/skills/skill-builder-provider.tsx+++ b/src/components/skills/skill-builder-provider.tsx@@ -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 (one of its pages): its model nodes as steps (W5, "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={"thread" in source ? `chat:${source.thread}` : "canvas" in source ? `canvas:${source.canvas}:${source.page ?? ""}` : source.generations.join(",")} source={source} onClose={() => setSource(null)} />}</Ctx.Provider>);}diff --git a/src/components/skills/skill-builder.tsx b/src/components/skills/skill-builder.tsxindex 46b0ad08..45b68e98 100644--- a/src/components/skills/skill-builder.tsx+++ b/src/components/skills/skill-builder.tsx@@ -28,6 +28,9 @@ import { cn } from "@/lib/utils";*/export function SkillBuilder({ source, onClose }: { source: DraftSource; onClose: () => void }) {const [saved, setSaved] = useState<string | null>(null);+ // A canvas's Table rows wait in the Run form's Many tab (W5).+ const rows = useSkillDraft(source).data?.rows;+ const csv = rows?.length ? csvOf(rows) : undefined;return (<><Dialog open={!saved} onOpenChange={(o) => !o && !saved && onClose()}>@@ -35,22 +38,40 @@ 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}+ examples+ csv={csv}+ intro={csv ? "Its table's rows are in Many: run them all, or one with new inputs." : "Try it with new inputs: the form starts with the ones it was made from."}+ onClose={onClose}+ />+ )}</>);}+/** Rows of values as a CSV the Run form's Many tab reads (a header of input ids, then one row per run). */+function csvOf(rows: Record<string, string>[]): string {+ const cols = [...new Set(rows.flatMap((r) => Object.keys(r)))];+ const cell = (v: string) => (/[",\n]/.test(v) ? `"${v.replace(/"/g, '""')}"` : v);+ return [cols.join(","), ...rows.map((r) => cols.map((c) => cell(r[c] ?? "")).join(","))].join("\n");+}+function Loader({ source, onClose, onSaved }: { source: DraftSource; onClose: () => void; onSaved: (name: string) => void }) {const q = useSkillDraft(source);const chat = "thread" in source;- const count = chat ? 0 : source.generations.length;+ const canvas = "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 || canvas ? "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.`}+ : canvas+ ? "From this canvas: each model node is a step, so the skill runs the same steps from a form, Assist, the command line or a schedule."+ : `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 +86,9 @@ 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:" : canvas ? "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 /></>) : (diff --git a/src/components/skills/skill-suggestions.tsx b/src/components/skills/skill-suggestions.tsxnew file mode 100644index 00000000..df41a830--- /dev/null+++ b/src/components/skills/skill-suggestions.tsx@@ -0,0 +1,62 @@+"use client";++import { useQuery, useQueryClient } from "@tanstack/react-query";+import { BookmarkPlus, X } from "lucide-react";+import { useState } from "react";+import { Button } from "@/components/ui/button";+import { useIsVisitor } from "@/lib/api";+import type { SkillSuggestion } from "@/lib/skill-insights";+import { useSkillBuilder } from "./skill-builder-provider";++/**+ * Above the Library's grid (All, package W6): a chain of steps made 3 or more times in two weeks, offered as a skill. Make a+ * skill opens the review screen with the newest run's steps; Not now hides it for a week; Don't suggest this hides it for+ * good. The owner's only: a visitor's Library has none.+ */+export function SkillSuggestions() {+ const visitor = useIsVisitor();+ const builder = useSkillBuilder();+ const qc = useQueryClient();+ const [hidden, setHidden] = useState<string[]>([]);+ const q = useQuery({+ queryKey: ["skill-suggestions"],+ enabled: !visitor,+ retry: false,+ staleTime: 5 * 60_000,+ queryFn: async () => {+ const res = await fetch("/api/skill-suggestions");+ if (!res.ok) return [] as SkillSuggestion[];+ return ((await res.json()) as { items: SkillSuggestion[] }).items;+ },+ });+ const s = (q.data ?? []).find((x) => !hidden.includes(x.id));+ if (visitor || !s || !builder) return null;+ const dismiss = (how: "later" | "never") => {+ setHidden((h) => [...h, s.id]);+ void fetch("/api/skill-suggestions", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ id: s.id, how }) }).then(() => qc.invalidateQueries({ queryKey: ["skill-suggestions"] }));+ };+ return (+ <section aria-label="A skill to save" className="mt-1 flex w-full flex-col gap-3 rounded-2xl border bg-brand-faint/40 px-4 py-3 sm:flex-row sm:items-center" data-skill-suggestion={s.id}>+ <BookmarkPlus className="hidden size-5 shrink-0 text-brand-text sm:block" aria-hidden />+ <div className="min-w-0 flex-1">+ <p className="text-[14px] font-medium break-words">+ You've made “{s.words}” {s.count} times. Save it as a skill?+ </p>+ <p className="text-[12px] text-muted-foreground">+ {s.demo ? "From demo results: check it on your engine once it's saved. " : ""}A skill runs the same steps again with new inputs, priced first.+ </p>+ </div>+ <div className="flex flex-wrap items-center gap-1.5">+ <Button size="sm" onClick={() => builder.open(s.ids)}>+ <BookmarkPlus /> Make a skill+ </Button>+ <Button size="sm" variant="ghost" onClick={() => dismiss("later")}>+ Not now+ </Button>+ <Button size="sm" variant="ghost" onClick={() => dismiss("never")}>+ <X /> Don't suggest this+ </Button>+ </div>+ </section>+ );+}diff --git a/src/instrumentation.ts b/src/instrumentation.tsindex 12cd5ce5..7b095166 100644--- a/src/instrumentation.ts+++ b/src/instrumentation.ts@@ -23,6 +23,9 @@ export async function register() {// Assist's scheduled tasks: a 30 s sweep starts the runs that are due (a run missed while the server was off happens once, a few seconds after boot).const { ensureScheduleRunner } = await import("./server/assist/schedules");ensureScheduleRunner({ soon: true });+ // Skills whose steps wait across studios: each waiting step starts when the step it takes a result from is done.+ const { ensureSkillRunRunner } = await import("./server/skill-runs");+ ensureSkillRunRunner();// Character Swap Studio: takes queued behind the segments they continue from launch (or stop) when those finish.const { ensureSwapStudioRunner } = await import("./server/swap-studio");ensureSwapStudioRunner();diff --git a/src/lib/assist-schedule.ts b/src/lib/assist-schedule.tsindex f9a36764..7f8b134f 100644--- a/src/lib/assist-schedule.ts+++ b/src/lib/assist-schedule.ts@@ -320,10 +320,10 @@ export function withinCap(cap: number | null, spent: number, price: number | nul/*** What a plan would really spend: demo jobs cost nothing and jobs that can't run don't start; null- * when a job that would run for real has no price.+ * when a job that would run for real has no price, or only a guessed one (`estimate`).*/-export function spendOf(jobs: { costUsd: number | null; demo: boolean; error?: string }[]): number | null {+export function spendOf(jobs: { costUsd: number | null; demo: boolean; error?: string; estimate?: boolean }[]): number | null {const real = jobs.filter((j) => !j.demo && !j.error);- if (real.some((j) => j.costUsd === null)) return null;+ if (real.some((j) => j.costUsd === null || j.estimate)) return null;return Math.round(real.reduce((n, j) => n + (j.costUsd ?? 0), 0) * 1000) / 1000;}diff --git a/src/lib/assist.ts b/src/lib/assist.tsindex e1d8851f..70422c01 100644--- a/src/lib/assist.ts+++ b/src/lib/assist.ts@@ -30,6 +30,11 @@ export interface PlannedJob {note?: string;/** One step of a pipeline: it only starts when every step can, so one error blocks the run. */atomic?: boolean;+ /**+ * The price is a guess: the job is priced by its input's length or size, and that input is an earlier step's result,+ * which doesn't exist yet. A spending cap can't count on it (spendOf).+ */+ estimate?: boolean;}/** Whether an approval card's plan can run: something to run, and no pipeline with a broken step. */diff --git a/src/lib/catalog/canvas-recipe.ts b/src/lib/catalog/canvas-recipe.tsnew file mode 100644index 00000000..de491c61--- /dev/null+++ b/src/lib/catalog/canvas-recipe.ts@@ -0,0 +1,272 @@+/**+ * Skills as canvases (package W5): a skill's recipe drawn as a canvas, and a canvas turned into a recipe. Pure and+ * browser-safe (the canvas list draws a skill; the server drafts a skill from a canvas).+ *+ * recipe → canvas: inputs become input nodes (text → a text prompt, image/video/audio → a file node with the example,+ * element → an element node), generate steps become model nodes, and `after` with its chain slots becomes edges. Only+ * when every slot maps to a port: a recipe that uses audio2, audios, model3d or mask, a chain with stem, index or a+ * position, a prompt with more than one input in it, or a studio step can't be drawn yet (a studio step shows as one+ * read-only "Studio step" note).+ *+ * canvas → recipe (the canvas is the demonstration): the request each model node makes, as describeNode builds it, with+ * an input node that came from a skill's input put back as its {{id}}; every other input node's file or words stay as+ * they are (Fixed, until the review screen says they vary). A Table's columns become text inputs and its rows the Many+ * tab's rows (at most 50 × 8, TABLE_LIMITS).+ */+import type { ChainSlot, GenerationRequest } from "./types";+import { describeNode, isGenerator, nodeLabel, TABLE_LIMITS, tableRows, topoOrder, type CanvasEdge, type CanvasGraph, type CanvasNode, type CanvasNodeType, type InputPortId } from "./canvas";+import type { Recipe, RecipeParam, RecipeStep } from "../recipe";++export const CANT_DRAW = "This skill can't be drawn yet";++/** What a node made from a skill's input keeps, so the way back gives the same input. */+type ParamData = RecipeParam;++const INPUT_NODE: Record<RecipeParam["type"], CanvasNodeType | null> = { text: "prompt", image: "image-input", video: "video-input", audio: "audio-input", element: "element", number: null, choice: null };+const SLOT_PORT: Partial<Record<ChainSlot["slot"], InputPortId>> = { images: "images", endImage: "endImage", video: "video", videos: "videos", audio: "audio", voiceAudio: "voice", prompt: "prompt" };+const INPUT_PORT: Record<string, InputPortId> = { images: "images", endImage: "endImage", video: "video", videos: "videos", audio: "audio", voiceAudio: "voice" };+const PLACE = /\{\{\s*([A-Za-z][A-Za-z0-9_]*)\s*\}\}/g;+const EXACT = /^\{\{\s*([A-Za-z][A-Za-z0-9_]*)\s*\}\}$/;++const asList = (a: string | string[] | undefined): string[] => (a === undefined ? [] : Array.isArray(a) ? a : [a]);++/** Why a recipe can't be drawn, or null. */+export function undrawable(recipe: Pick<Recipe, "steps" | "params">): string | null {+ for (const s of recipe.steps) {+ if (s.kind === "tool") continue;+ const r = s.request as GenerationRequest & Record<string, unknown>;+ const inputs = (r.inputs ?? {}) as Record<string, unknown>;+ for (const k of Object.keys(inputs)) if (!INPUT_PORT[k] && inputs[k] !== undefined) return `${CANT_DRAW}: step “${s.key}” takes ${k}, which a canvas has no port for`;+ const chain = (s.chain ?? (r.chain as ChainSlot[] | undefined)) ?? [];+ for (const c of chain) {+ if (!SLOT_PORT[c.slot]) return `${CANT_DRAW}: step “${s.key}” takes ${c.slot} from an earlier step`;+ if (c.stem !== undefined || c.index !== undefined || c.position !== undefined) return `${CANT_DRAW}: step “${s.key}” takes one part of an earlier result`;+ }+ const prompt = typeof r.prompt === "string" ? r.prompt : "";+ if ([...prompt.matchAll(PLACE)].length > 1) return `${CANT_DRAW}: step “${s.key}” puts several inputs into its words`;+ for (const id of [...JSON.stringify(r.params ?? {}).matchAll(PLACE)].map((m) => m[1])) return `${CANT_DRAW}: step “${s.key}” takes a setting from {{${id}}}`;+ if (JSON.stringify(r).includes("{{steps.")) return `${CANT_DRAW}: step “${s.key}” takes a studio step's result`;+ }+ for (const p of recipe.params) if (!INPUT_NODE[p.type]) return `${CANT_DRAW}: “${p.label}” is a ${p.type === "number" ? "number" : "choice"}, which a canvas has no input for`;+ return null;+}++/**+ * A skill's recipe as a canvas: its graph, and when it can't be drawn as it runs, why (the canvas then opens read-only).+ */+export function recipeToCanvas(recipe: Recipe): { graph: CanvasGraph; readOnly?: string } {+ const why = undrawable(recipe);+ const nodes: CanvasNode[] = [];+ const edges: CanvasEdge[] = [];+ const byParam = new Map<string, string>();+ let fixed = 0;+ recipe.params.forEach((p, i) => {+ const type = INPUT_NODE[p.type];+ if (!type) return;+ const id = `in-${p.id}`;+ const v = p.example ?? p.default;+ const data: CanvasNode["data"] = { label: p.label, param: p as ParamData };+ if (type === "prompt") data.text = typeof v === "string" || typeof v === "number" ? String(v) : "";+ else if (type === "element") data.handle = typeof v === "string" ? v.replace(/^@?/, "@") : undefined;+ else if (typeof v === "string") data.url = v;+ nodes.push({ id, type, position: { x: 0, y: i * 220 }, data });+ byParam.set(p.id, id);+ });+ const depth = new Map<string, number>();+ for (const s of recipe.steps) depth.set(s.key, Math.max(0, ...asList(s.kind === "generate" ? s.after : undefined).map((a) => (depth.get(a) ?? 0) + 1)));+ const column = new Map<number, number>();+ const edge = (source: string, target: string, port: InputPortId) => edges.push({ id: `e-${source}-${target}-${port}-${edges.length}`, source, target, sourceHandle: "out", targetHandle: port });+ for (const s of recipe.steps) {+ const d = depth.get(s.key) ?? 0;+ const row = column.get(d) ?? 0;+ column.set(d, row + 1);+ const position = { x: 380 + d * 380, y: row * 260 };+ if (s.kind === "tool") {+ nodes.push({ id: s.key, type: "note", position, data: { label: "Studio step", text: `Studio step: ${s.label ?? s.tool.replace(/_/g, " ")}. It runs in its studio and can't be changed here.` } });+ continue;+ }+ const r = { ...(s.request as GenerationRequest & Record<string, unknown>) };+ const prompt = typeof r.prompt === "string" ? r.prompt : undefined;+ const fromInput = prompt ? [...prompt.matchAll(PLACE)].map((m) => m[1]).find((id) => byParam.has(id)) : undefined;+ const ownPrompt = prompt && fromInput ? (EXACT.test(prompt.trim()) ? "" : prompt.replace(PLACE, "{text}")) : prompt;+ nodes.push({+ id: s.key,+ type: "model",+ position,+ data: {+ label: s.label ?? s.key,+ modelId: String(r.modelId),+ ...(r.op && { op: r.op }),+ ...(r.engine && { engine: r.engine }),+ ...(ownPrompt && { prompt: ownPrompt }),+ ...(r.params && { params: r.params }),+ // What the node was made from: the step's request as the recipe holds it, so drawing it back loses nothing.+ recipeStep: { key: s.key, label: s.label, request: r },+ },+ });+ if (fromInput) edge(byParam.get(fromInput)!, s.key, "prompt");+ for (const [k, v] of Object.entries((r.inputs ?? {}) as Record<string, unknown>)) {+ const port = INPUT_PORT[k];+ if (!port) continue;+ for (const x of Array.isArray(v) ? v : [v]) {+ const m = typeof x === "string" ? EXACT.exec(x) : null;+ if (m && byParam.has(m[1])) edge(byParam.get(m[1])!, s.key, port);+ else if (typeof x === "string") {+ // A file fixed in the step: a file node of its own.+ const id = `file-${s.key}-${fixed++}`;+ nodes.push({ id, type: port === "video" || port === "videos" ? "video-input" : port === "audio" || port === "voice" ? "audio-input" : "image-input", position: { x: position.x - 190, y: position.y + 120 }, data: { url: x } });+ edge(id, s.key, port);+ }+ }+ }+ const chain = (s.chain ?? (r.chain as ChainSlot[] | undefined)) ?? [];+ asList(s.after).forEach((a, i) => edge(a, s.key, SLOT_PORT[chain[i]?.slot ?? "images"] ?? "images"));+ }+ return { graph: { nodes, edges }, ...(why && { readOnly: why }) };+}++/** A column's input id: its words as letters, digits and _ (col_<n> when none are left). */+const columnId = (name: string, i: number, taken: Set<string>) => {+ let id = name.replace(/[^A-Za-z0-9]+/g, "_").replace(/^_+|_+$/g, "").replace(/^(\d)/, "c$1").slice(0, 32) || `col_${i + 1}`;+ if (!/^[A-Za-z]/.test(id)) id = `c_${id}`.slice(0, 32);+ while (taken.has(id)) id = `${id.slice(0, 29)}_${i + 1}`;+ taken.add(id);+ return id;+};++export interface CanvasRecipe {+ recipe: Recipe;+ /** A Table's rows, one run each (the Many tab). */+ rows: Record<string, string>[];+ /** The canvas's generator nodes each step came from. */+ nodes: Record<string, string>;+ /** What a node can't do as a step, by node. */+ refusals: { node: string; label: string; reason: string }[];+}++/**+ * A canvas as a recipe: every generator node a generate step (its request as describeNode builds it), its links to other+ * generator nodes `after` with their chain slots, and the input nodes that came from a skill's inputs put back as+ * {{id}}. `page` names it in the recipe's source.+ */+export function canvasToRecipe(graph: CanvasGraph, page?: { id: string }): CanvasRecipe | { error: string } {+ const refusals: CanvasRecipe["refusals"] = [];+ const params: RecipeParam[] = [];+ const taken = new Set<string>();+ let rows: Record<string, string>[] = [];+ // Inputs from a skill: their node's value becomes the placeholder, so the request is built with it.+ const nodes = graph.nodes.map((n): CanvasNode => {+ const p = n.data.param as ParamData | undefined;+ if (!p || taken.has(p.id)) return n;+ taken.add(p.id);+ params.push(p);+ if (n.type === "prompt") return { ...n, data: { ...n.data, text: `{{${p.id}}}` } };+ if (n.type === "element") return n;+ return { ...n, data: { ...n.data, url: `{{${p.id}}}` } };+ });+ // A Table: one text input per column; the node it feeds reads the row's cells (rowText), so it becomes a text prompt+ // of the columns' inputs, and "{Column}" in a prompt becomes that column's input.+ const tables = nodes.filter((n) => n.type === "table");+ if (tables.length > 1) return { error: "A canvas with more than one table can't be a skill yet" };+ const columnIds = new Map<string, string>();+ const withTables = nodes.map((n) => {+ if (n.type !== "table") return n;+ const cols = (n.data.columns ?? []).slice(0, TABLE_LIMITS.columns);+ cols.forEach((c, i) => {+ const id = columnId(c, i, taken);+ columnIds.set(c, id);+ params.push({ id, label: (c || `Column ${i + 1}`).slice(0, 60), type: "text", required: true });+ });+ rows = tableRows(n)+ .slice(0, TABLE_LIMITS.rows)+ .map((cells) => Object.fromEntries(cols.map((c, i) => [columnIds.get(c)!, cells[i] ?? ""])));+ const first = rows[0] ?? {};+ for (const p of params) if (columnIds.has(p.label) && first[p.id]) p.example = first[p.id];+ return { ...n, type: "prompt" as const, data: { ...n.data, text: cols.map((c) => `{{${columnIds.get(c)}}}`).join(", ") } };+ });+ const prepared: CanvasGraph = {+ ...graph,+ nodes: withTables.map((n) =>+ typeof n.data.prompt === "string" && columnIds.size ? { ...n, data: { ...n.data, prompt: n.data.prompt.replace(/\{([^{}]+)\}/g, (m, c: string) => (columnIds.has(c) ? `{{${columnIds.get(c)}}}` : m)) } } : n,+ ),+ };+ const { cyclic } = topoOrder(prepared);+ if (cyclic.length) return { error: "Some nodes wait for each other in a loop: break the loop first" };+ // The board's own order where the links allow it (a skill drawn and saved back keeps its steps' order).+ const order: string[] = [];+ const placed = new Set<string>();+ while (order.length < prepared.nodes.length) {+ const next = prepared.nodes.find((n) => !placed.has(n.id) && prepared.edges.filter((e) => e.target === n.id).every((e) => placed.has(e.source) || !prepared.nodes.some((x) => x.id === e.source)));+ if (!next) break;+ order.push(next.id);+ placed.add(next.id);+ }+ const byId = new Map(prepared.nodes.map((n) => [n.id, n]));+ const steps: RecipeStep[] = [];+ const stepOf = new Map<string, string>();+ const keys = new Set<string>();+ const keyFor = (n: CanvasNode) => {+ let k = (n.id.replace(/[^A-Za-z0-9_-]+/g, "-").replace(/^[^A-Za-z0-9]+/, "") || "step").slice(0, 36);+ for (let i = 2; keys.has(k); i++) k = `${k.slice(0, 33)}-${i}`;+ keys.add(k);+ return k;+ };+ for (const id of order) {+ const n = byId.get(id);+ if (!n || !isGenerator(n)) continue;+ const label = nodeLabel(n);+ const d = describeNode(prepared, n);+ if (!d.request) {+ refusals.push({ node: n.id, label, reason: d.error ?? "It can't run as it is" });+ continue;+ }+ const missing = d.deps?.find((dep) => !stepOf.has(dep));+ if (missing) {+ refusals.push({ node: n.id, label, reason: `It waits for “${nodeLabel(byId.get(missing) ?? n)}”, which can't be a step` });+ continue;+ }+ const base = (n.data.recipeStep as { label?: string; request?: Record<string, unknown> } | undefined) ?? {};+ if (d.steps?.length) {+ // A node made in several steps (Assemble film): each step, fed by the nodes and steps it takes.+ if (d.steps.some((st) => st.from.some((f) => "row" in f && f.row !== undefined))) {+ refusals.push({ node: n.id, label, reason: "A film of a table's rows can't be a skill yet" });+ continue;+ }+ const own = new Map<string, string>();+ for (const st of d.steps) {+ const key = keyFor({ ...n, id: `${n.id}-${st.key}` });+ own.set(st.key, key);+ const after = st.from.map((f) => ("node" in f ? stepOf.get(f.node)! : own.get(f.step)!));+ const { chain, ...request } = st.request;+ steps.push({ key, kind: "generate", label: st.request.step?.label ?? label, ...(after.length && { after: after.length === 1 ? after[0] : after }), ...(chain?.length && { chain }), request: { ...request, feature: "skill" } as never });+ }+ stepOf.set(n.id, own.get(d.steps.at(-1)!.key)!);+ continue;+ }+ const key = typeof (base as { key?: unknown }).key === "string" && !keys.has((base as { key: string }).key) ? (keys.add((base as { key: string }).key), (base as { key: string }).key) : keyFor(n);+ stepOf.set(n.id, key);+ const { chain, ...built } = d.request;+ // The step as the recipe held it, with what the canvas says now (its model, operation, words, settings, inputs).+ const request = { ...(base.request ?? {}), ...built, feature: "skill" } as Record<string, unknown>;+ if (!built.inputs) delete request.inputs;+ if (!built.prompt) delete request.prompt;+ if (!built.params) delete request.params;+ if (!built.op && !(base.request as { op?: unknown } | undefined)?.op) delete request.op;+ delete request.chain;+ const after = (d.deps ?? []).map((dep) => stepOf.get(dep)!);+ steps.push({+ key,+ kind: "generate",+ ...((base.label ?? (n.data.label as string | undefined)) && { label: String(base.label ?? n.data.label).slice(0, 80) }),+ ...(after.length && { after: after.length === 1 ? after[0] : after }),+ ...(chain?.length && { chain: chain.map((c) => ({ slot: c.slot })) }),+ request: request as never,+ });+ }+ if (!steps.length) return { error: refusals[0]?.reason ? `Nothing on this canvas can be a step: ${refusals[0].reason}` : "Add a model node first: a skill needs a step" };+ // Inputs no step uses (a node left unconnected) stay out.+ const used = JSON.stringify(steps);+ const kept = params.filter((p) => used.includes(`{{${p.id}}}`));+ const recipe: Recipe = { fuobeRecipe: 1, params: kept, steps, ...(page && { source: { from: "canvas", canvas: page.id } }) };+ return { recipe, rows: rows.map((r) => Object.fromEntries(Object.entries(r).filter(([k]) => kept.some((p) => p.id === k)))), nodes: Object.fromEntries([...stepOf.entries()].map(([node, step]) => [step, node])), refusals };+}diff --git a/src/lib/guest-access.ts b/src/lib/guest-access.tsindex a3e3bc49..ca592986 100644--- a/src/lib/guest-access.ts+++ b/src/lib/guest-access.ts@@ -55,6 +55,8 @@ const EMPTY_LISTS = ["/api/assist/projects","/api/assist/schedules","/api/assist/memory",+ // Chains the owner made often enough to offer as skills (the owner's runs).+ "/api/skill-suggestions",];/** The Library's counts with nothing in it (a guest's). */@@ -285,7 +287,7 @@ export const CONNECT_GPU_UPLOAD_OPEN_MESSAGE = "Connect your GPU to add your ownexport const CONNECT_GPU_OR_KEY_MESSAGE = CONNECT_GPU_MESSAGE;/** Install-wide settings, keys and tokens: changes are the owner's (403 for an account). */-const OWNER_WRITES = new Set(["/api/settings", "/api/settings/models", "/api/loras", "/api/llm", "/api/providers/test", "/api/auth/public"]);+const OWNER_WRITES = new Set(["/api/settings", "/api/settings/models", "/api/loras", "/api/llm", "/api/providers/test", "/api/auth/public", "/api/skill-suggestions"]);/*** Owner only, reads included: the password, the API tokens, signing everyone out, the assistant's connectors, the MCP* endpoint and the accounts admin.diff --git a/src/lib/recipe-builder.ts b/src/lib/recipe-builder.tsindex d4ba1e7c..4ac65b8f 100644--- a/src/lib/recipe-builder.ts+++ b/src/lib/recipe-builder.ts@@ -401,7 +401,8 @@ export function buildRecipe(draft: Pick<SkillDraft, "recipe" | "candidates">, ch// The form's order: files first, then elements, words, settings.const rank = (p: RecipeParam) => (isMediaType(p.type) ? 0 : p.type === "element" ? 1 : p.type === "text" ? 2 : 3);params.push(...[...placed, ...slotParams].sort((a, b) => rank(a) - rank(b)));- recipe.params = params;+ // Inputs the draft already has (a skill drawn as a canvas and saved back) come first.+ recipe.params = [...draft.recipe.params, ...params];if (Object.keys(checks).length) recipe.checks = checks;return recipe;}diff --git a/src/lib/recipe.ts b/src/lib/recipe.tsindex 42fdf920..3bacc5b2 100644--- a/src/lib/recipe.ts+++ b/src/lib/recipe.ts@@ -31,6 +31,16 @@ const PARAM_ID = /^[A-Za-z][A-Za-z0-9_]{0,31}$/;const STEP_KEY = /^[A-Za-z0-9][A-Za-z0-9_-]{0,39}$/;/** A placeholder anywhere in a string, and a string that is exactly one. */const PLACEHOLDER = /\{\{\s*([A-Za-z][A-Za-z0-9_]*)\s*\}\}/g;+/**+ * A step reference (recipe version 2): `{{steps.<key>.output}}`, the first output of that earlier step of the kind the+ * field takes. It isn't an input: filling a recipe leaves it for the runner, which puts in the file once the step is done.+ */+const STEP_REF = /\{\{\s*steps\.([A-Za-z0-9][A-Za-z0-9_-]{0,39})\.output\s*\}\}/g;+const STEP_REF_EXACT = /^\{\{\s*steps\.([A-Za-z0-9][A-Za-z0-9_-]{0,39})\.output\s*\}\}$/;+/** `{{steps.<key>.output}}` for a step. */+export const stepRef = (key: string) => `{{steps.${key}.output}}`;+/** The step a value refers to when it is exactly one step reference. */+export const stepRefOf = (v: unknown): string | null => (typeof v === "string" ? (STEP_REF_EXACT.exec(v)?.[1] ?? null) : null);const EXACT = /^\{\{\s*([A-Za-z][A-Za-z0-9_]*)\s*\}\}$/;const DAY = /^\d{4}-\d{2}-\d{2}$/;const ELEMENT = /^@[\p{L}\p{N}_-]{1,40}$/u;@@ -152,8 +162,11 @@ const VerifiedEngineSchema = z.object({});export type VerifiedEngine = z.infer<typeof VerifiedEngineSchema>;+/** The newest recipe version: 2 lets a step take an earlier step's output by reference, and studio steps sit anywhere. */+export const RECIPE_VERSION = 2;+export const RecipeSchema = z.object({- fuobeRecipe: z.literal(1),+ fuobeRecipe: z.union([z.literal(1), z.literal(2)]),params: z.array(ParamSchema).max(RECIPE_LIMITS.params, `at most ${RECIPE_LIMITS.params} inputs`),steps: z.array(StepSchema).min(1, "a recipe needs a step").max(RECIPE_LIMITS.steps, `at most ${RECIPE_LIMITS.steps} steps`),checks: z.record(z.string(), CheckSchema).optional(),@@ -204,12 +217,61 @@ export function placeholders(v: unknown, out = new Set<string>()): Set<string> {const asList = (a: string | string[] | undefined): string[] => (a === undefined ? [] : Array.isArray(a) ? a : [a]);const stepBody = (s: RecipeStep): unknown => (s.kind === "tool" ? s.input : s.request);+/** Every step a value refers to (`{{steps.<key>.output}}`), all the way down. */+export function stepRefs(v: unknown, out = new Set<string>()): Set<string> {+ if (typeof v === "string") for (const m of v.matchAll(STEP_REF)) out.add(m[1]);+ else if (Array.isArray(v)) for (const x of v) stepRefs(x, out);+ else if (v && typeof v === "object") for (const x of Object.values(v)) stepRefs(x, out);+ return out;+}++/** Each step reference in a step with where it sits (the path in its request or input). */+export function stepRefSpots(v: unknown, path: (string | number)[] = [], out: { key: string; path: (string | number)[] }[] = []) {+ if (typeof v === "string") for (const m of v.matchAll(STEP_REF)) out.push({ key: m[1], path });+ else if (Array.isArray(v)) v.forEach((x, i) => stepRefSpots(x, [...path, i], out));+ else if (v && typeof v === "object") for (const [k, x] of Object.entries(v)) stepRefSpots(x, [...path, k], out);+ return out;+}++/** The steps a step waits for: its `after` (a generate step) and the steps it refers to. */+export const waitsFor = (s: RecipeStep): string[] => [...new Set([...(s.kind === "generate" ? asList(s.after) : []), ...stepRefs(stepBody(s))])];++/**+ * Whether a recipe runs in stages (W7): a studio step with other steps, or a step that takes an earlier step's output by+ * reference. Such a run starts each step when the ones it waits for are done (src/server/skill-runs.ts), not as one+ * createPipeline.+ */+export const isStaged = (recipe: Pick<Recipe, "steps">): boolean =>+ (recipe.steps.length > 1 && recipe.steps.some((s) => s.kind === "tool")) || recipe.steps.some((s) => stepRefs(stepBody(s)).size > 0);+/** Steps that wait for nothing later: the only ones whose output count may change (createPipeline's rule). */export function leafKeys(recipe: Pick<Recipe, "steps">): Set<string> {- const fed = new Set(recipe.steps.flatMap((s) => (s.kind === "generate" ? asList(s.after) : [])));+ const fed = new Set(recipe.steps.flatMap(waitsFor));return new Set(recipe.steps.filter((s) => !fed.has(s.key)).map((s) => s.key));}+/**+ * The kind of file a field takes, from where it sits: a request's inputs by their slot, a studio step's input by its+ * name (video, clip, footage; audio, voice, music; image, photo, logo). Undefined when it can't be told.+ */+export function fieldKind(path: (string | number)[]): MediaKind | undefined {+ const names = path.filter((p): p is string => typeof p === "string");+ if (names[0] === "inputs") {+ const slot = names[1];+ if (slot === "images" || slot === "endImage" || slot === "mask") return "image";+ if (slot === "video" || slot === "videos") return "video";+ if (slot === "audio" || slot === "audio2" || slot === "audios" || slot === "voiceAudio") return "audio";+ if (slot === "model3d") return "model3d";+ return undefined;+ }+ if (names[0] === "prompt" || names[0] === "negativePrompt") return "text";+ const key = names.join(" ").toLowerCase();+ if (/video|clip|footage/.test(key)) return "video";+ if (/audio|voice|music|sound/.test(key)) return "audio";+ if (/image|photo|picture|still|frame|logo|product|reference/.test(key)) return "image";+ return undefined;+}+// ---------------------------------------------------------------------------// Values@@ -369,7 +431,11 @@ export interface CompiledStep {chain?: ChainSlot[];}-export type Compiled = { kind: "pipeline"; steps: CompiledStep[]; checks: Record<string, FilledCheck> } | { kind: "tool"; key: string; tool: string; input: Record<string, unknown>; checks: Record<string, FilledCheck> };+export type Compiled =+ | { kind: "pipeline"; steps: CompiledStep[]; checks: Record<string, FilledCheck> }+ | { kind: "tool"; key: string; tool: string; input: Record<string, unknown>; checks: Record<string, FilledCheck> }+ /** A run in stages (W7): each step filled with the values, step references left for the runner. */+ | { kind: "staged"; steps: RecipeStep[]; checks: Record<string, FilledCheck> };export interface CompileOptions {/** The skill's name and this run's id: the server-set stamp on every request. */@@ -387,6 +453,27 @@ export const SKILL_CHECK_FEATURE = "skill-check";/** One run of a recipe: a pipeline of generate steps, or one tool call. Values are checked first (checkValues). */export function compile(recipe: Recipe, values: RecipeValues, o: CompileOptions): Compiled {const { steps, checks } = fill(recipe, values);+ if (isStaged(recipe)) {+ const n = steps.length;+ return {+ kind: "staged",+ checks,+ steps: steps.map((s, i) =>+ s.kind === "tool"+ ? s+ : {+ ...s,+ request: {+ ...s.request,+ batchTitle: o.title.slice(0, 200),+ skill: { name: o.skill, run: o.run },+ ...(s.label && { step: { label: s.label, index: i, of: n } }),+ ...(o.demo && { demo: true, feature: SKILL_CHECK_FEATURE }),+ },+ },+ ),+ };+ }const tool = steps.find((s): s is ToolStep => s.kind === "tool");if (tool) return { kind: "tool", key: tool.key, tool: tool.tool, input: tool.input, checks };const n = steps.length;@@ -416,7 +503,7 @@ export function compile(recipe: Recipe, values: RecipeValues, o: CompileOptions)* a count that varies on a step others wait for, duplicate ids and keys, a tool step that isn't alone, a graph* createPipeline would refuse, and inputs whose default, example or options don't fit their type.*/-export function recipeProblems(recipe: Recipe): string[] {+export function recipeProblems(recipe: Recipe, o: { kinds?: Record<string, MediaKind | undefined> } = {}): string[] {const out: string[] = [];const ids = recipe.params.map((p) => p.id);const keys = recipe.steps.map((s) => s.key);@@ -437,9 +524,38 @@ export function recipeProblems(recipe: Recipe): string[] {}for (const p of recipe.params) if (!used.has(p.id)) out.push(`The input “${p.label}” ({{${p.id}}}) isn't used by any step`);- // One tool step alone (a tool feeding later steps is W7's orchestrator).+ // Version 1: one tool step alone, and no step references. Version 2: each reference names an earlier step that makes+ // the kind of file its field takes.const tools = recipe.steps.filter((s) => s.kind === "tool");- if (tools.length && recipe.steps.length > 1) out.push(`The tool step “${tools[0].key}” must be the recipe's only step (a tool that feeds other steps isn't supported yet)`);+ if (recipe.fuobeRecipe === 1) {+ if (tools.length && recipe.steps.length > 1) out.push(`The tool step “${tools[0].key}” must be the recipe's only step (set "fuobeRecipe": 2 for a studio step that feeds other steps)`);+ for (const s of recipe.steps) if (stepRefs(stepBody(s)).size) out.push(`Step “${s.key}” takes an earlier step's output: that needs "fuobeRecipe": 2`);+ } else {+ // Generate steps joined by `after` start together as one chain: one can't also take another's output by reference.+ const group = new Map(keys.map((k) => [k, k]));+ const root = (k: string): string => (group.get(k) === k ? k : root(group.get(k)!));+ for (const s of recipe.steps) if (s.kind === "generate") for (const a of asList(s.after)) if (group.has(a) && root(a) !== root(s.key)) group.set(root(s.key), root(a));+ const referenced = new Set<string>();+ for (const [i, s] of recipe.steps.entries()) {+ for (const ref of stepRefSpots(stepBody(s))) {+ const at = keys.indexOf(ref.key);+ if (at >= 0 && at < i) referenced.add(ref.key);+ if (at < 0) out.push(`Step “${s.key}” takes the output of “${ref.key}”, which isn't a step`);+ else if (at >= i) out.push(`Step “${s.key}” takes the output of “${ref.key}”, which comes ${at === i ? "from itself" : "later"}: a step can only take an earlier step's output`);+ else if (root(ref.key) === root(s.key)) out.push(`Step “${s.key}” takes the output of “${ref.key}”, which starts with it (they are joined by "after"): take it through "after" and a chain slot, or drop "after"`);+ else {+ const want = fieldKind(ref.path);+ const made = o.kinds?.[ref.key] ?? recipe.checks?.[ref.key]?.kind;+ if (want && made && want !== made && want !== "text") out.push(`Step “${s.key}” takes ${want === "image" ? "an image" : `a ${want}`} from “${ref.key}”, which makes ${made === "image" ? "an image" : `a ${made}`}`);+ }+ }+ if (s.kind === "generate" && asList(s.after).some((a) => recipe.steps.find((x) => x.key === a)?.kind === "tool")) out.push(`Step “${s.key}” waits for the studio step “${asList(s.after).find((a) => recipe.steps.find((x) => x.key === a)?.kind === "tool")}”: take its output with {{steps.<key>.output}} instead`);+ }+ // A dub that waits for its lines to be checked (review, the default) has no video until someone voices it.+ for (const s of recipe.steps) {+ if (s.kind === "tool" && s.tool === "dub_video" && referenced.has(s.key) && (s.input as { review?: unknown }).review !== false) out.push(`Step “${s.key}” dubs for review, so it makes no video for the steps after it: set "review": false to dub in one go`);+ }+ }// The graph, as createPipeline checks it.const keySet = new Set(keys);@@ -450,6 +566,7 @@ export function recipeProblems(recipe: Recipe): string[] {if (a === s.key) out.push(`Step “${s.key}” can't wait for itself`);else if (!keySet.has(a)) out.push(`Step “${s.key}” waits for “${a}”, which isn't a step`);}+ // A step that takes an earlier step's output by reference waits for it; its chain slots are only for `after`.const chain = s.chain ?? (s.request.chain as ChainSlot[] | undefined);if (chain && chain.length !== after.length) out.push(`Step “${s.key}” has ${chain.length} chain slot${chain.length === 1 ? "" : "s"} for ${after.length} earlier step${after.length === 1 ? "" : "s"}`);}@@ -742,9 +859,10 @@ function paramLine(p: RecipeParam): string {/** A step as a line: its model and operation, its words with the inputs as {{id}}, what it waits for. */function stepLine(s: RecipeStep, i: number, keys: string[]): string {- if (s.kind === "tool") return `${i + 1}. \`${s.tool}\` with ${cut(JSON.stringify(s.input), 400)}`;+ const refs = [...stepRefs(stepBody(s))].map((a) => `step ${keys.indexOf(a) + 1}`);+ if (s.kind === "tool") return `${i + 1}. \`${s.tool}\` with ${cut(JSON.stringify(s.input), 400)}${refs.length ? `, from the result of ${refs.join(" and ")}` : ""}`;const r = s.request;- const waits = asList(s.after).map((a) => `step ${keys.indexOf(a) + 1}`);+ const waits = [...new Set([...asList(s.after).map((a) => `step ${keys.indexOf(a) + 1}`), ...refs])];return `${i + 1}. ${s.label ? `${s.label}: ` : ""}\`${r.modelId}\`${r.op ? ` (${r.op})` : ""}${r.prompt ? ` — “${cut(String(r.prompt), 240)}”` : ""}${waits.length ? `, from the result of ${waits.join(" and ")}` : ""}`;}@@ -814,13 +932,21 @@ export const RECIPE_MARKDOWN_MAX = 20_000;*/export function recipeMarkdown(recipe: Recipe, skill?: { name: string }): string {const keys = recipe.steps.map((s) => s.key);- const tool = recipe.steps.find((s): s is ToolStep => s.kind === "tool");- const gen = tool ? null : generateCall(recipe);+ // A run in stages has no one call to show: run_skill (or the steps in order) runs it.+ const staged = isStaged(recipe);+ const tool = staged ? undefined : recipe.steps.find((s): s is ToolStep => s.kind === "tool");+ const gen = tool || staged ? null : generateCall(recipe);const call = tool ? JSON.stringify({ tool: tool.tool, input: tool.input }, null, 2) : gen?.json;const values = Object.fromEntries(recipe.params.map((p) => [p.id, `{{${p.id}}}`]));const build = (withCall: boolean) => {const shown = withCall && !!call;- const how = tool ? `call the studio tool \`${tool.tool}\` the same way` : call ? "make the same `generate` call" : "run the steps with `generate`, in order";+ const how = staged+ ? "run the steps in order, each once the steps it takes a result from are done, putting each earlier result in for {{steps.<key>.output}}"+ : tool+ ? `call the studio tool \`${tool.tool}\` the same way`+ : call+ ? "make the same `generate` call"+ : "run the steps with `generate`, in order";return ["## Run it","",@@ -926,6 +1052,9 @@ export interface RecipeRun {href?: string;/** A tool run that couldn't start after the rows before it had (each tool call stands alone). */error?: string;+ /** A run in stages (W7): its id (its steps' progress in the skill's dialog), and the steps that start later. */+ skillRun?: string;+ waiting?: string[];}export interface EngineCheck {@@ -941,3 +1070,69 @@ export interface VerifyResult {engines: EngineCheck[];view: RecipeView;}++// ---------------------------------------------------------------------------+// Shapes: the same chain made again with other words and files (W6's suggestions)++/** One step of a graph as its shape reads it: its model and operation, and the steps it waits for with their slots. */+export interface ShapeNode {+ id: string;+ modelId: string;+ op?: string;+ /** The steps it waits for, in order (createPipeline's `after`, a run's `depends_on`). */+ after: string[];+ /** The slot each of those fills (images, endImage, video…); images when it isn't said. */+ slots?: string[];+}++/** A shape: a stable key, the steps in order (for the words) and how many steps. */+export interface Shape {+ key: string;+ steps: { modelId: string; op?: string }[];+}++/**+ * The shape of a graph of generate steps: the sorted models and operations, and each link as the two steps it joins and+ * the slot it fills. Prompts, inputs and settings don't count, so the same chain made with other words and files has+ * one shape. Steps come in the order they run (a step after the ones it waits for). Null for a graph that isn't one+ * (a step waits for one that isn't in it, or a loop).+ */+export function shapeOf(nodes: ShapeNode[]): Shape | null {+ if (!nodes.length) return null;+ const byId = new Map(nodes.map((n) => [n.id, n]));+ const label = (n: ShapeNode) => `${n.modelId}:${n.op ?? ""}`;+ // Each step's depth (how many steps run before it), so equal shapes list their steps alike.+ const depth = new Map<string, number>();+ const visit = (n: ShapeNode, seen: Set<string>): number => {+ if (depth.has(n.id)) return depth.get(n.id)!;+ if (seen.has(n.id)) throw new Error("loop");+ seen.add(n.id);+ let d = 0;+ for (const a of n.after) {+ const p = byId.get(a);+ if (!p) throw new Error("missing");+ d = Math.max(d, visit(p, seen) + 1);+ }+ depth.set(n.id, d);+ return d;+ };+ try {+ for (const n of nodes) visit(n, new Set());+ } catch {+ return null;+ }+ const ordered = [...nodes].sort((a, b) => depth.get(a.id)! - depth.get(b.id)! || label(a).localeCompare(label(b)));+ const steps = ordered.map((n) => `${depth.get(n.id)}|${label(n)}`).sort();+ const links = nodes.flatMap((n) => n.after.map((a, i) => `${depth.get(a)}|${label(byId.get(a)!)}>${depth.get(n.id)}|${label(n)}:${n.slots?.[i] ?? "images"}`)).sort();+ return { key: JSON.stringify([steps, links]), steps: ordered.map((n) => ({ modelId: n.modelId, ...(n.op && { op: n.op }) })) };+}++/** A recipe's generate steps as a graph for shapeOf (a recipe with a tool step has no shape). */+export function recipeShapeNodes(recipe: Pick<Recipe, "steps">, modelId: (id: string) => string = (id) => id): ShapeNode[] | null {+ if (recipe.steps.some((s) => s.kind !== "generate")) return null;+ return (recipe.steps as GenerateStep[]).map((s) => {+ const after = asList(s.after);+ const chain = s.chain ?? (s.request.chain as ChainSlot[] | undefined);+ return { id: s.key, modelId: modelId(String(s.request.modelId)), ...(typeof s.request.op === "string" && { op: s.request.op }), after, slots: after.map((_, i) => chain?.[i]?.slot ?? "images") };+ });+}diff --git a/src/lib/skill-insights.ts b/src/lib/skill-insights.tsnew file mode 100644index 00000000..96a38ede--- /dev/null+++ b/src/lib/skill-insights.ts@@ -0,0 +1,62 @@+/**+ * What the skill pages and the Library read about skills in use (package W6, src/server/skill-insights.ts): a chain+ * made often enough to offer as a skill, a skill's run history, and the models that could fix a step. Types only.+ */+import type { Engine, MediaKind } from "./catalog/types";++/** A chain of steps made again and again, offered as a skill. */+export interface SkillSuggestion {+ /** The chain's shape (stable across sweeps): what Not now and Don't suggest this remember. */+ id: string;+ /** "Remove background → Edit → Image to video". */+ words: string;+ /** How many times it was made in the last 14 days. */+ count: number;+ /** The newest run's last steps: Make a skill drafts from them. */+ ids: string[];+ lastAt: number;+ /** Every one was made by the demo provider (no engine connected). */+ demo: boolean;+}++/** One run of a skill, from the stamp its generations carry. */+export interface SkillRunRow {+ run: string;+ batchId: string | null;+ status: "running" | "succeeded" | "failed" | "canceled";+ costUsd: number | null;+ at: number;+ /** How many generations it made. */+ steps: number;+ /** The steps that failed: their model and label. */+ failed: { model: string; error: string | null }[];+ demo: boolean;+ /** Its last few outputs (a still to show). */+ outputs: { url: string; kind: MediaKind; poster?: string }[];+ favorites: number;+}++export interface SkillHistory {+ runs: number;+ /** Of the runs that finished, the share that worked (null: none finished yet). */+ successRate: number | null;+ spendUsd: number;+ lastRunAt: number | null;+ favorites: number;+ /** The newest runs first. */+ recent: SkillRunRow[];+}++/** The steps that could use another model, and the models that do the same job here. */+export interface FixCandidates {+ engine: Engine;+ steps: {+ key: string;+ label: string;+ /** The model it uses now. */+ model: string;+ /** Why it's offered a fix (a model that was replaced or switched off, failures in its last runs). */+ reasons: string[];+ candidates: { modelId: string; name: string; engine: Engine; costUsd: number | null; problem?: string }[];+ }[];+}diff --git a/src/lib/skill-runs.ts b/src/lib/skill-runs.tsnew file mode 100644index 00000000..cbf0a0f2--- /dev/null+++ b/src/lib/skill-runs.ts@@ -0,0 +1,33 @@+/**+ * A run of a skill whose steps wait for each other across studios (package W7, src/server/skill-runs.ts): each step's+ * status, the results it made and the studio page it opened in. Types only.+ */++export type SkillRunStatus = "running" | "done" | "failed";+export type SkillStepStatus = "waiting" | "running" | "done" | "failed";++export interface SkillRunStep {+ key: string;+ /** "Dub", "Captions", "9:16 cut". */+ label: string;+ kind: "generate" | "tool";+ status: SkillStepStatus;+ /** The generations it started. */+ ids: string[];+ /** The studio its job opened in, and the page there. */+ studio?: string;+ href?: string;+ /** Why it failed, or why it didn't start. */+ error?: string;+}++export interface SkillRunView {+ id: string;+ skill: string;+ status: SkillRunStatus;+ createdAt: number;+ updatedAt: number;+ steps: SkillRunStep[];+ /** Which step failed and why. */+ error?: string;+}diff --git a/src/server/assist/context-tools.ts b/src/server/assist/context-tools.tsindex 1dd26165..e84c4e89 100644--- a/src/server/assist/context-tools.ts+++ b/src/server/assist/context-tools.ts@@ -3,6 +3,7 @@ import { z } from "zod";import { guessCategory, MEMORY_CATEGORIES, MEMORY_MAX_CHARS, toCategory, type MemoryCategory } from "@/lib/assist";import { recipeMarkdown } from "@/lib/recipe";import { getSkill, skillFile, skillRecipe } from "../skills";+import { rankSkills } from "../skill-usage";import { canUseSkill, skillsFor } from "./context";import { defineTool } from "./define";import { addMemory, deleteMemory } from "./memory";@@ -19,12 +20,8 @@ const listSkills = defineTool({}),async run({ query }, ctx) {const projectId = ctx.thread?.projectId ?? null;- let list = skillsFor(projectId);- if (query?.trim()) {- const words = query.toLowerCase().split(/\s+/).filter(Boolean);- const scored = list.map((s) => ({ s, n: words.filter((w) => `${s.name} ${s.title} ${s.description} ${s.whenToUse}`.toLowerCase().includes(w)).length }));- if (scored.some((x) => x.n)) list = scored.filter((x) => x.n).sort((a, b) => b.n - a.n).map((x) => x.s);- }+ // By the words, then the skills used most and most lately.+ const list = rankSkills(skillsFor(projectId), { words: query });return {content: JSON.stringify(list.map((s) => {diff --git a/src/server/assist/context.ts b/src/server/assist/context.tsindex 51ddfbe6..10530c7f 100644--- a/src/server/assist/context.ts+++ b/src/server/assist/context.ts@@ -5,6 +5,7 @@ import type { Engine } from "@/lib/catalog/types";import { recipeMarkdown } from "@/lib/recipe";import { db } from "../db";import { engineMode } from "../settings";+import { rankSkills } from "../skill-usage";import { enabledSkills, getSkill, skillRecipe } from "../skills";import { memoriesFor } from "./memory";import { getProject } from "./projects";@@ -151,7 +152,8 @@ export function chatFacts(c: ChatInfo, now = new Date()): ContextFact[] {if (chars > MEMORY_CHARS) break;facts.push({ section: "memory", key: m.id, text: line });}- const available = skillsFor(project?.id ?? null);+ // The skills people run most, and most lately, first: past SKILL_INDEX the rest are left to list_skills.+ const available = rankSkills(skillsFor(project?.id ?? null));for (const s of available.slice(0, SKILL_INDEX)) {// A skill with a recipe runs by itself: said first, so a long description can't cut it off.const runs = s.recipe ? runsByItself(s.name) : "";diff --git a/src/server/assist/skill-tools.ts b/src/server/assist/skill-tools.tsindex 35fea819..e8f7913e 100644--- a/src/server/assist/skill-tools.ts+++ b/src/server/assist/skill-tools.ts@@ -154,9 +154,19 @@ async function runFound(input: RunSkill, ctx: ToolContext, found: { recipe: Recicontent: JSON.stringify({skill: found.name,engine: out.engine,- runs: out.runs.map((r) => ({ started: r.ids, ...(r.batchId && { batch: r.batchId }), ...(r.href && { href: r.href }), ...(r.error && { error: r.error }) })),+ runs: out.runs.map((r) => ({+ started: r.ids,+ ...(r.batchId && { batch: r.batchId }),+ ...(r.href && { href: r.href }),+ ...(r.error && { error: r.error }),+ ...(r.waiting?.length && { waiting: r.waiting }),+ })),...(out.demo && { demo: true }),- note: href ? "The skill's studio job opens at href; its results appear there and in the Library." : "Each run's steps start by themselves as the ones they wait for finish; results appear in the Library.",+ note: out.runs.some((r) => r.waiting?.length)+ ? `Some steps wait for a studio step before them (${[...new Set(out.runs.flatMap((r) => r.waiting ?? []))].join(", ")}): each starts by itself when the step it takes a result from is done. The skill's dialog in Skills shows each step.`+ : href+ ? "The skill's studio job opens at href; its results appear there and in the Library."+ : "Each run's steps start by themselves as the ones they wait for finish; results appear in the Library.",}),items: ids.length ? [{ id: "", role: "generations", ids }] : undefined,};diff --git a/src/server/db.ts b/src/server/db.tsindex 2c02c5ef..bad83975 100644--- a/src/server/db.ts+++ b/src/server/db.ts@@ -795,6 +795,26 @@ export const ADMIN_TABLES = `CREATE TABLE IF NOT EXISTS admin_tokens ();CREATE INDEX IF NOT EXISTS admin_audit_at ON admin_audit(at);`;+/**+ * Skills (src/server/recipes.ts, src/server/skill-runs.ts): a run of a skill whose steps wait for each other across+ * studios keeps each step's state here, so the sweep that starts the waiting steps picks up again after a restart.+ * `values_json`: the run's input values (file links); `state_json`: each step's status, generation ids, studio link and+ * why it failed. Made here rather than as a numbered migration (other branches add those at the same time, and a+ * migration is known by its place in the list). Safe to run on every start.+ */+export const SKILL_TABLES = `CREATE TABLE IF NOT EXISTS skill_runs (+ id TEXT PRIMARY KEY,+ skill TEXT NOT NULL,+ engine TEXT NOT NULL,+ status TEXT NOT NULL,+ values_json TEXT NOT NULL,+ state_json TEXT NOT NULL,+ created_at INTEGER NOT NULL,+ updated_at INTEGER NOT NULL+ );+ CREATE INDEX IF NOT EXISTS skill_runs_skill ON skill_runs(skill, created_at DESC);+ CREATE INDEX IF NOT EXISTS skill_runs_status ON skill_runs(status);`;+/** Columns the optional services added to existing tables: [table, column, type]. */const HOOK_COLUMNS: [string, string, string][] = [// 1: never served to the account (its output check hasn't said "show").@@ -885,6 +905,8 @@ function open(): Database.Database {}// Admin tokens and the admin API's log.db.exec(ADMIN_TABLES);+ // Skills: the runs that wait across studios.+ db.exec(SKILL_TABLES);// A billing hold's rows are found through this index (only rows that have one are in it).try {db.exec("CREATE INDEX IF NOT EXISTS generations_hold ON generations(json_extract(request_json, '$.hold')) WHERE json_extract(request_json, '$.hold') IS NOT NULL");diff --git a/src/server/demo-scope.ts b/src/server/demo-scope.tsnew file mode 100644index 00000000..9c670402--- /dev/null+++ b/src/server/demo-scope.ts@@ -0,0 +1,18 @@+import "server-only";+import { AsyncLocalStorage } from "node:async_hooks";++/**+ * Work done as a demo, whatever its code asks for (package W7): a skill's free dry run of a studio step runs the studio's+ * own module inside runAsDemo, so every generation it creates goes to the demo provider (chooseRoute) and is marked+ * `request.demo`, with no change to the studio's code. Nothing outside the scope is affected.+ */+const scope = new AsyncLocalStorage<true>();++/** Run `fn` (and everything it awaits) as a demo. */+export const runAsDemo = <T>(fn: () => T): T => scope.run(true, fn);++/** Whether this code runs inside runAsDemo. */+export const inDemoScope = (): boolean => scope.getStore() === true;++/** Run `fn` outside any runAsDemo (a process-wide timer created during a dry run mustn't keep its scope). */+export const outsideDemo = <T>(fn: () => T): T => scope.exit(fn);diff --git a/src/server/generations.ts b/src/server/generations.tsindex 4fa7463d..c4ba1cdf 100644--- a/src/server/generations.ts+++ b/src/server/generations.ts@@ -98,6 +98,7 @@ import { accountSend } from "./account-send";import { stamped, stampOf, withRunStamp } from "./run-stamp";import { placeInLine, poolWaitMs, runOnPool } from "./hosted";import { sweepBilling } from "./billing-outbox";+import { inDemoScope } from "./demo-scope";import { moderationConfigured } from "./moderation";import { holdForCheck, sweepOutputChecks } from "./output-checks";import { absolutePath, adoptFile, contentTypeFor, deleteAsset, localHead, readRef, saveFile, scratchDir, scratchOutputFile } from "./storage";@@ -415,6 +416,8 @@ export const ASSET_REFS: AssetRef[] = [{ table: "content_series", cols: ["data_json"], what: "Content Factory series", name: "COALESCE(json_extract(data_json, '$.name'), json_extract(data_json, '$.reference.title'))" },// Assist's scheduled tasks: the files the prompt runs with, and the files a skill task's inputs name.{ table: "assist_schedules", cols: ["attachments_json", "skill_json"], what: "scheduled task", name: "title" },+ // A skill run that waits across studios: its input values and each step's results.+ { table: "skill_runs", cols: ["values_json", "state_json"], what: "skill run", name: "skill" },// Character Swap Studio: the character picture, each clip and its 24 fps copy, masks, anchors, takes and their masters.{ table: "swap_projects", cols: ["data_json"], what: "Character Swap project", name: "name" },// A user skill's bundled text files: its recipe.json names the files a run starts from (an example, a fixed logo).@@ -542,8 +545,9 @@ export function chooseRoute(candidates: ModelRoute[], images = 0, loras: LoraRefconst preferred = getSetting("cloudProvider");const routes = preferred === "auto" ? candidates : [...candidates].sort((a, b) => Number(b.provider === preferred) - Number(a.provider === preferred));const demo = getSetting("demoMode");- // A request marked demo (a skill recipe's free dry run) runs on the demo provider whatever Settings says.- if (demo === "on" || forceDemo) return { route: routes[0], demo: true };+ // A request marked demo (a skill recipe's free dry run) runs on the demo provider whatever Settings says, as does+ // anything a studio starts inside runAsDemo (a skill's dry run of a studio step, src/server/demo-scope.ts).+ if (demo === "on" || forceDemo || inDemoScope()) return { route: routes[0], demo: true };const takes = (r: ModelRoute) => !r.map?.maxImages || images <= r.map.maxImages;// A route that carries every LoRA wins (Replicate's Wan 2.2 takes one per expert, fal's takes a Mix), then one// that makes the length asked; otherwise the first ready one runs and the plan's notes say what it changes.@@ -941,7 +945,9 @@ function stampTenant(asked: GenerationRequest, opts: CreateOptions): GenerationRreturn { ...stamped(asked), account: who, engine: accountEngineMode(who) === "open" ? "open" : asked.engine };}-export function createGenerations(given: GenerationRequest, opts: CreateOptions = {}): Generation[] {+export function createGenerations(sent: GenerationRequest, opts: CreateOptions = {}): Generation[] {+ // Inside a skill's dry run of a studio step every row is a demo row, as the check's own rows are.+ const given: GenerationRequest = inDemoScope() && !sent.demo ? { ...sent, demo: true } : sent;const asked = stampTenant(given, opts);// A retired model or operation (a retry, an old script, a saved project) runs on what replaced it, and says so.const moved = currentRequest(asked);diff --git a/src/server/recipe-builder.ts b/src/server/recipe-builder.tsindex 411121be..7d4d3b10 100644--- a/src/server/recipe-builder.ts+++ b/src/server/recipe-builder.ts@@ -7,7 +7,7 @@ import { dubLanguageFor } from "@/lib/assist-studios";import { isHelperFeature } from "@/lib/library";import { probeMedia } from "@/lib/media-probe";import { videoPoster } from "@/lib/output-actions";-import { isMediaRef, leafKeys, RECIPE_LIMITS, today, type ParamType, type Recipe, type RecipeCheck, type RecipeStep } from "@/lib/recipe";+import { isMediaRef, isStaged, leafKeys, RECIPE_LIMITS, stepRef, today, waitsFor, type ParamType, type Recipe, type RecipeCheck, type RecipeStep } from "@/lib/recipe";import {DEMO_NOTE,isExpansionLabel,@@ -34,6 +34,8 @@ import { declinedByUser, type AssistItem } from "@/lib/assist";import { cardTitle, getTool, planFor } from "./assist/tools";import { getSkill, SkillError } from "./skills";import { absolutePath, readRef } from "./storage";+import { getCanvas } from "./canvas";+import { canvasToRecipe } from "@/lib/catalog/canvas-recipe";/*** Make a skill from results already made (package W2): walk the picked results back through `depends_on` to the@@ -365,10 +367,39 @@ function linkByFile(walk: Walk): void {}}+/**+ * A chat's studio step whose input is another step's result, or a step whose input is a studio step's result (W7): the+ * file becomes a step reference, `{{steps.<key>.output}}`, so a new run feeds the new result on once that step is done.+ * Only to a step made before it. Generate steps joined by their files already wait for each other (linkByFile).+ */+function linkStudios(nodes: Node[], outputsOf: (n: Node) => Set<string>): number {+ let linked = 0;+ for (const n of nodes) {+ const sources = nodes.filter((src) => src !== n && (src.tool || n.tool) && src.gen.createdAt <= n.gen.createdAt);+ if (!sources.length) continue;+ const swap = (v: unknown): unknown => {+ if (typeof v === "string" && isMediaRef(v)) {+ const src = sources.find((s) => outputsOf(s).has(v));+ if (src) {+ linked++;+ return stepRef(src.key);+ }+ return v;+ }+ if (Array.isArray(v)) return v.map(swap);+ if (v && typeof v === "object") return Object.fromEntries(Object.entries(v).map(([k, x]) => [k, swap(x)]));+ return v;+ };+ if (n.step.kind === "tool") n.step = { ...n.step, input: swap(n.step.input) as Record<string, unknown> };+ else n.step = { ...n.step, request: { ...n.step.request, inputs: swap(n.step.request.inputs) as typeof n.step.request.inputs } };+ }+ return linked;+}+/** Steps in an order where each comes after the ones it waits for (Kahn's algorithm, stable). */function ordered(nodes: Node[]): Node[] {const keys = new Set(nodes.map((n) => n.key));- const waits = (n: Node) => (n.step.kind === "generate" ? (Array.isArray(n.step.after) ? n.step.after : n.step.after ? [n.step.after] : []).filter((a) => keys.has(a)) : []);+ const waits = (n: Node) => waitsFor(n.step).filter((a) => keys.has(a));const out: Node[] = [];const done = new Set<string>();while (out.length < nodes.length) {@@ -718,8 +749,8 @@ export const draftFromGenerations = (ids: string[]): DraftResult => buildDraft(i/** Where a draft comes from besides picked results: an Assist chat, its studio calls as they ran, and what it left out. */interface Origin {thread?: string;- /** Studio calls of the chat: each the tool's exact input, and the result that stands for it. */- calls?: { lifted: Lifted; pick: Generation }[];+ /** Studio calls of the chat: each the tool's exact input, the result that stands for it, and every file it made. */+ calls?: { lifted: Lifted; pick: Generation; outputs?: string[] }[];refusals?: DraftRefusal[];notes?: string[];/** Every generation the kept calls started (the recipe's source). */@@ -744,7 +775,7 @@ function toolNode(walk: Walk, lifted: Lifted, g: Generation): Node {function buildDraft(ids: string[], o: Origin = {}): DraftResult {const refusals: DraftRefusal[] = [...(o.refusals ?? [])];const walk = new Walk();- const tools: { node: Node; pick: Generation }[] = (o.calls ?? []).map((c) => ({ node: toolNode(walk, c.lifted, c.pick), pick: c.pick }));+ const tools: { node: Node; pick: Generation; outputs?: string[] }[] = (o.calls ?? []).map((c) => ({ node: toolNode(walk, c.lifted, c.pick), pick: c.pick, outputs: c.outputs }));const generated: Generation[] = [];const unique = [...new Set(ids)].slice(0, 200);for (const id of unique) {@@ -790,23 +821,27 @@ function buildDraft(ids: string[], o: Origin = {}): DraftResult {refusals.push({ id, title, reason: e.message });}}- // Version 1 runs a graph of generate steps or one studio tool, not both (a tool feeding later steps is W7).- if (tools.length && (walk.nodes.size || tools.length > 1)) {+ // From results in the Library, a skill runs a graph of generate steps or one studio tool, not both. From a chat (W7),+ // its studio calls are steps too, and a result one passes to another becomes a step reference (linkStudios).+ if (!o.thread && tools.length && (walk.nodes.size || tools.length > 1)) {const keep = walk.nodes.size ? [] : tools.slice(0, 1);for (const t of tools.filter((x) => !keep.includes(x))) {refusals.push({ id: t.pick.id, title: cut(t.pick.request.title || t.pick.request.prompt || t.node.label, 80), reason: walk.nodes.size ? "A studio step can't be in a skill with other steps yet: make a skill from it on its own" : "One studio step per skill for now: make a skill from each" });}tools.splice(0, tools.length, ...keep);}- if (tools.length) walk.nodes.set(tools[0].node.key, tools[0].node);+ for (const t of tools) walk.nodes.set(t.node.key, t.node);linkByFile(walk);+ const outputs = new Map(tools.map((t) => [t.node.key, new Set(t.outputs ?? t.pick.outputs.map((x) => x.url))]));+ const linked = o.thread ? linkStudios([...walk.nodes.values()], (n) => outputs.get(n.key) ?? new Set(n.rows.flatMap((id) => getGeneration(id, { includeDeleted: true })?.outputs.map((x) => x.url) ?? []))) : 0;const nodes = ordered([...walk.nodes.values()]);if (!nodes.length) return { draft: null, refusals };if (nodes.length > RECIPE_LIMITS.steps) return { draft: null, refusals: [...refusals, { id: ids[0], title: "These results", reason: `They take ${nodes.length} steps; a skill has at most ${RECIPE_LIMITS.steps}` }] };// Steps in an order where every step comes after the ones it waits for (the walk added dependencies first).const steps = nodes.map((n) => n.step);- const recipe: Recipe = { fuobeRecipe: 1, params: [], steps };+ // Studio steps among other steps, or a step that takes a studio step's result: recipe version 2 (it runs in stages).+ const recipe: Recipe = { fuobeRecipe: linked || isStaged({ steps }) ? 2 : 1, params: [], steps };const leaves = leafKeys(recipe);const checks: Record<string, RecipeCheck> = {};for (const n of nodes) if (leaves.has(n.key) && n.step.kind === "generate") checks[n.key] = proposeCheck(n);@@ -859,8 +894,6 @@ function buildDraft(ids: string[], o: Origin = {}): DraftResult {// ---------------------------------------------------------------------------// A skill from an Assist chat (W3)-/** Why a chat's step can't join the others: a studio step's result feeding another step, or the other way round (W7). */-export const STUDIO_WAIT = "Skills can't wait for a studio step yet: make a skill from each step on its own";/** Tools whose started generations are drafted as plain results (a run_skill pipeline is one too). */const GENERATE_TOOLS = new Set(["generate", "run_skill"]);@@ -1057,16 +1090,9 @@ export function draftFromThread(threadId: string): ThreadDraft {}const kept = calls.filter((c) => keptSet.has(c));const replaced = calls.length - kept.length;- // A studio step's result feeding a later step, or a step's result feeding a studio step: refused (W7).- const joined: typeof kept = [];- for (const c of kept) {- const from = joined.filter((d) => [...d.outputs].some((u) => c.inputs.has(u)));- if (from.length && (c.studio || from.some((d) => d.studio))) {- refusals.push({ id: c.gens[0].id, title: cut(cardTitle(c.name, c.input), 80), reason: STUDIO_WAIT });- continue;- }- joined.push(c);- }+ // A studio step's result feeding a later step, or a step's result feeding a studio step, becomes a step reference+ // in the recipe (W7): the run starts each step when the one it takes a result from is done.+ const joined: typeof kept = kept;const notes: string[] = [];if (replaced) notes.push(replaced === 1 ? "An earlier try of a step was left out: the skill keeps the last one" : `${replaced} earlier tries of steps were left out: the skill keeps the last of each`);if (declined || failed) notes.push(`Left out: ${[declined && `${declined} plan${declined === 1 ? "" : "s"} you declined`, failed && `${failed} that didn't run`].filter(Boolean).join(" and ")}`);@@ -1086,7 +1112,7 @@ export function draftFromThread(threadId: string): ThreadDraft {continue;}const pick = c.gens.findLast((g) => g.status === "succeeded");- if (pick) studioCalls.push({ lifted: chatLift(c, c.use), pick });+ if (pick) studioCalls.push({ lifted: chatLift(c, c.use), pick, outputs: [...c.outputs] });}const result = buildDraft(ids, { thread: threadId, calls: studioCalls, refusals, notes, generations: joined.flatMap((c) => c.gens.map((g) => g.id)) });return { ...result, words };@@ -1154,3 +1180,54 @@ export async function nameDraft(draft: SkillDraft, asked: string[] = []): Promisconst text = await llmText(NAMING_SYSTEM, `${images.length ? "The pictures are the results the person kept.\n" : ""}The record:\n${JSON.stringify(record, null, 2)}`, images);return parseNaming(text, draft);}++// ---------------------------------------------------------------------------+// A skill from a canvas (W5)++/**+ * The draft of a skill from a canvas (the canvas is the demonstration): each model node a generate step as describeNode+ * builds its request (canvasToRecipe), the files and words of its input nodes Fixed until the review screen says they+ * vary, and a Table's columns as inputs with its rows for the Many tab. A node that can't be a step is a refusal.+ */+export function draftFromCanvas(id: string, pageId?: string): DraftResult & { rows: Record<string, string>[] } {+ const c = getCanvas(id);+ if (!c) throw new SkillError("No such canvas", 404);+ // One page of the canvas: the one asked for, else the first.+ const page = c.pages.find((p) => p.id === pageId) ?? c.pages[0];+ if (!page) return { draft: null, refusals: [{ id, title: c.name, reason: "This canvas is empty" }], rows: [] };+ const out = canvasToRecipe(page.graph, { id });+ if ("error" in out) return { draft: null, refusals: [{ id, title: c.name, reason: out.error }], rows: [] };+ const recipe: Recipe = { ...out.recipe, source: { from: "canvas", canvas: id, at: today() } };+ const nodes: Node[] = recipe.steps.map((s) => {+ const m = s.kind === "generate" ? getModel(s.request.modelId) : undefined;+ return { key: s.key, gen: { kind: m?.kind ?? "image", outputs: [], createdAt: c.updatedAt } as unknown as Generation, rows: [], step: s, label: s.label ?? m?.name ?? s.key, modelName: m?.name ?? s.key, notes: [] };+ });+ const leaves = leafKeys(recipe);+ // Words that already hold an input (a skill drawn as a canvas) stay as they are: the input varies, not the words.+ const found = candidates(nodes, leaves).filter((x) => !(x.kind === "text" && String(x.example).includes("{{")));+ const flow = nodes.map((n) => n.label).join(" → ");+ const models = [...new Set(nodes.map((n) => n.modelName))];+ const title = cut(c.name || "Canvas", 80);+ const draft: SkillDraft = {+ recipe,+ steps: nodes.map((n) => ({+ key: n.key,+ kind: "generate",+ label: n.label,+ modelName: n.modelName,+ generation: "",+ waits: (n.step.kind === "generate" ? (Array.isArray(n.step.after) ? n.step.after : n.step.after ? [n.step.after] : []) : []).map((a) => nodes.find((x) => x.key === a)?.label ?? a),+ leaf: leaves.has(n.key),+ notes: [],+ })),+ candidates: found,+ name: freeName(title),+ title,+ description: cut(`${nodes.length === 1 ? flow : `${nodes.length} steps: ${flow}`}, with ${models.join(", ")}. Made from the canvas “${title}” and run again with new inputs.`, 1000),+ whenToUse: cut(`When you want what the canvas “${title}” makes, with new inputs.`, 1000),+ demo: false,+ notes: out.rows.length ? [`Its table's ${out.rows.length} row${out.rows.length === 1 ? "" : "s"} wait in the Many tab of the Run form once it's saved`] : [],+ llm: llmTextBackend(),+ };+ return { draft, refusals: out.refusals.map((r) => ({ id: r.node, title: r.label, reason: r.reason })), rows: out.rows };+}diff --git a/src/server/recipe-routes.ts b/src/server/recipe-routes.tsindex 1d924d4f..e7c19827 100644--- a/src/server/recipe-routes.ts+++ b/src/server/recipe-routes.ts@@ -19,8 +19,9 @@ export function recipeFailure(e: unknown): Response {export const badBody = (issues: z.core.$ZodIssue[]) => Response.json({ error: issues.map((i) => `${i.path.join(".") || "body"}: ${i.message}`).join("; ") }, { status: 400 });-/** What a skill is drafted from: results picked in the Library (W2), or an Assist chat whose plans ran (W3). */+/** What a skill is drafted from: results picked in the Library (W2), an Assist chat whose plans ran (W3), or a canvas (W5). */export const DraftSource = z.union([z.object({ generations: z.array(z.string().min(1).max(40)).min(1).max(200) }),z.object({ thread: z.string().min(1).max(40) }),+ z.object({ canvas: z.string().min(1).max(40), page: z.string().max(40).optional() }),]);diff --git a/src/server/recipes.ts b/src/server/recipes.tsindex 22f521fa..b3171336 100644--- a/src/server/recipes.ts+++ b/src/server/recipes.ts@@ -7,13 +7,18 @@ import { planRunnable, totalCost, type PlannedJob } from "@/lib/assist";import { getModel } from "@/lib/catalog";import { dualEngine } from "@/lib/catalog/engines";import { currentModelId, replacedBy } from "@/lib/catalog/replaced";-import type { Engine, Generation, GenerationRequest, MediaKind } from "@/lib/catalog/types";+import type { ChainSlot, Engine, Generation, GenerationRequest, MediaKind } from "@/lib/catalog/types";import { probeMedia, type MediaInfo } from "@/lib/media-probe";import {checkOutputs,checkValues,compile,exampleValues,+ fieldKind,+ stepRefs,+ type CompiledStep,+ type GenerateStep,+ type RecipeStep,isMediaRef,isMediaType,parseRecipe,@@ -48,6 +53,8 @@ import { isOffered, modelLicence } from "./model-access";import { GenerationRequestSchema } from "./request-schema";import { engineMode } from "./settings";import { createSkill, deleteSkill, getSkill, setSkillFile, skillFile, SkillError } from "./skills";+import { beginSkillRun, stagedDryRun } from "./skill-runs";+import { runAsDemo } from "./demo-scope";import { absolutePath, readRef, saveFile } from "./storage";/**@@ -109,9 +116,27 @@ function serverProblems(recipe: Recipe): string[] {return out;}+/** What a studio tool's step makes, for a later step that takes its result (W7). */+const TOOL_KINDS: Record<string, MediaKind> = {+ dub_video: "video",+ add_captions: "video",+ restore_video: "video",+ restyle_footage: "video",+ faceless_episode: "video",+ blockout_film: "video",+ katana: "video",+ split_layers: "image",+ create_ads: "image",+};++/** What each step makes (its model's kind, or its studio's), so a step reference is checked against its field. */+function stepKinds(recipe: Recipe): Record<string, MediaKind | undefined> {+ return Object.fromEntries(recipe.steps.map((s) => [s.key, s.kind === "tool" ? TOOL_KINDS[s.tool] : getModel(currentModelId(s.request.modelId))?.kind]));+}+/** Everything that keeps a recipe from being saved: its shape (recipeProblems), then the catalog and the API's limits. */export function allProblems(recipe: Recipe): string[] {- const own = recipeProblems(recipe);+ const own = recipeProblems(recipe, { kinds: stepKinds(recipe) });return own.length ? own : serverProblems(recipe);}@@ -163,6 +188,37 @@ function noEngine(recipe: Recipe): string {// ---------------------------------------------------------------------------// Compiling one run+/** One generate step as the API takes it (shape and limits checked), an Original put on the run's engine. */+export function apiStep(s: CompiledStep, engine: Engine): CompiledStep {+ const { skill: stamp, demo, batchTitle, step, chain, ...asked } = s.request;+ const parsed = GenerationRequestSchema.safeParse(asked);+ if (!parsed.success) throw new SkillError(`Step “${s.key}”: ${parsed.error.issues.map((i) => `${i.path.join(".")}: ${i.message}`).join("; ")}`, 422);+ const req = parsed.data as GenerationRequest;+ const m = getModel(currentModelId(req.modelId));+ const slots = s.chain ?? chain;+ return {+ ...s,+ ...(slots && { chain: slots }),+ request: { ...req, ...(m && dualEngine(m) && !req.engine && { engine }), batchTitle, skill: stamp, ...(step && { step }), ...(demo && { demo }) },+ };+}++/**+ * A run in stages with a stand-in for each step reference (W7): a file of the kind its field takes (a link to price+ * with; a real small file when the run will read it, `files`), or a few words in a prompt. What a check and a price use.+ */+export function withStandIns<T>(v: T, files = false, path: (string | number)[] = []): T {+ if (typeof v === "string") {+ if (!stepRefs(v).size) return v;+ const kind = fieldKind(path);+ if (kind === "image" || kind === "video" || kind === "audio") return (files ? standIn(kind) : PRICE_STAND_IN[kind]) as T;+ return v.replace(/\{\{\s*steps\.[^}]+\}\}/g, "the earlier step's words") as T;+ }+ if (Array.isArray(v)) return v.map((x, i) => withStandIns(x, files, [...path, i])) as T;+ if (v && typeof v === "object") return Object.fromEntries(Object.entries(v).map(([k, x]) => [k, withStandIns(x, files, [...path, k])])) as T;+ return v;+}+/** Validate and compile one run: each filled request as the API takes it, an Original put on the run's engine. */function compileRun(skill: { name: string; title: string }, recipe: Recipe, values: RecipeValues, engine: Engine, o: { run: string; demo?: boolean }): Compiled {const c = compile(recipe, values, { skill: skill.name, run: o.run, title: skill.title, demo: o.demo });@@ -171,22 +227,30 @@ function compileRun(skill: { name: string; title: string }, recipe: Recipe, valuif (error) throw new SkillError(`Step “${c.key}”: ${error.replace(/^Invalid input: /, "")}`, 422);return c;}- return {- ...c,- steps: c.steps.map((s) => {- const { skill: stamp, demo, batchTitle, step, chain, ...asked } = s.request;- const parsed = GenerationRequestSchema.safeParse(asked);- if (!parsed.success) throw new SkillError(`Step “${s.key}”: ${parsed.error.issues.map((i) => `${i.path.join(".")}: ${i.message}`).join("; ")}`, 422);- const req = parsed.data as GenerationRequest;- const m = getModel(currentModelId(req.modelId));- const slots = s.chain ?? chain;- return {- ...s,- ...(slots && { chain: slots }),- request: { ...req, ...(m && dualEngine(m) && !req.engine && { engine }), batchTitle, skill: stamp, ...(step && { step }), ...(demo && { demo }) },- };- }),- };+ if (c.kind === "staged") {+ // Each step is checked with stand-ins for the results it waits for; the run keeps the references.+ for (const s of c.steps) {+ if (s.kind === "tool") {+ const error = validateInput(s.tool, withStandIns(s.input));+ if (error) throw new SkillError(`Step “${s.key}”: ${error.replace(/^Invalid input: /, "")}`, 422);+ } else apiStep({ key: s.key, request: withStandIns(s.request) as GenerationRequest, ...(s.chain && { chain: s.chain as ChainSlot[] }) }, engine);+ }+ return c;+ }+ return { ...c, steps: c.steps.map((s) => apiStep(s, engine)) };+}++/**+ * A run in stages as parts that start on their own (W7): each studio step alone, and generate steps joined by `after`+ * as one createPipeline. A part waits for the steps its members take results from.+ */+export function stagedParts(steps: RecipeStep[]): { id: string; keys: string[]; waits: string[] }[] {+ const parent = new Map(steps.map((s) => [s.key, s.key]));+ const root = (k: string): string => (parent.get(k) === k ? k : root(parent.get(k)!));+ for (const s of steps) if (s.kind === "generate") for (const a of typeof s.after === "string" ? [s.after] : (s.after ?? [])) if (parent.has(a)) parent.set(root(s.key), root(a));+ const parts = new Map<string, string[]>();+ for (const s of steps) parts.set(root(s.key), [...(parts.get(root(s.key)) ?? []), s.key]);+ return [...parts.entries()].map(([id, keys]) => ({ id, keys, waits: [...new Set(steps.filter((s) => keys.includes(s.key)).flatMap((s) => [...stepRefs(s.kind === "tool" ? s.input : s.request)]))].filter((k) => !keys.includes(k)) }));}interface RunPlan {@@ -204,8 +268,44 @@ interface RunPlan {*/export const onlyConnect = (errors: string[]): boolean => errors.length > 0 && errors.every((e) => /^Connect\b/.test(e));+/** Units priced by the input's length or size (a step reference's stand-in has neither, so its price is a guess). */+const SIZED_UNITS = new Set(["second", "minute", "megapixel"]);++/** A job of a part that waits for earlier results, marked `estimate` when its price depends on those results' length or size. */+function guessed(j: PlannedJob, fixedLength: boolean): PlannedJob {+ const unit = getModel(j.modelId)?.pricing?.unit;+ if (!unit || !SIZED_UNITS.has(unit) || (fixedLength && unit !== "megapixel")) return j;+ return { ...j, estimate: true };+}+/** Price one compiled run the way it would start (planSteps / planFor), with what stops it. */function planRun(c: Compiled, engine: Engine): RunPlan {+ if (c.kind === "staged") {+ // Each part priced on its own, with stand-ins for the results it waits for; studio steps open in their studios.+ const jobs: PlannedJob[] = [];+ const errors: string[] = [];+ let place: RecipePlace | undefined;+ let connect = true;+ for (const part of stagedParts(c.steps)) {+ const members = c.steps.filter((s) => part.keys.includes(s.key));+ const tool = members.find((s) => s.kind === "tool");+ if (tool && tool.kind === "tool") {+ const sub = planRun({ kind: "tool", key: tool.key, tool: tool.tool, input: withStandIns(tool.input), checks: {} }, engine);+ jobs.push(...sub.jobs.map((j) => ({ ...(part.waits.length ? guessed(j, false) : j), note: tool.label ?? j.note })));+ errors.push(...sub.errors);+ connect &&= !sub.errors.length || onlyConnect(sub.errors);+ place ??= sub.place;+ continue;+ }+ const sub = planRun({ kind: "pipeline", checks: {}, steps: members.map((s) => apiStep({ key: s.key, request: withStandIns((s as GenerateStep).request) as GenerationRequest, ...((s as GenerateStep).after !== undefined && { after: (s as GenerateStep).after }), ...((s as GenerateStep).chain && { chain: (s as GenerateStep).chain as ChainSlot[] }) }, engine)) }, engine);+ // A step that sets its own length (params.duration) is priced for it; one that takes it from an earlier result is a guess.+ const fixed = (i: number) => (members[i] as GenerateStep | undefined)?.request.params?.duration !== undefined;+ jobs.push(...(part.waits.length ? sub.jobs.map((j, i) => guessed(j, fixed(i))) : sub.jobs));+ errors.push(...sub.errors);+ connect &&= !sub.errors.length || !!sub.connectOnly;+ }+ return { jobs, total: totalCost(jobs), errors: [...new Set(errors)], ...(place && { place }), connectOnly: errors.length > 0 && connect };+ }if (c.kind === "tool") {const p = planFor(c.tool, c.input, { engine });const errors = [...(p.error ? [p.error] : []), ...p.jobs.filter((j) => j.error).map((j) => `${j.note ?? j.modelName}: ${j.error}`)];@@ -220,7 +320,9 @@ function planRun(c: Compiled, engine: Engine): RunPlan {/** The run with every request on the demo provider: valid and priced the same whether or not a provider is connected. */function asDemo(c: Compiled): Compiled {- return c.kind === "tool" ? c : { ...c, steps: c.steps.map((s) => ({ ...s, request: { ...s.request, demo: true } })) };+ if (c.kind === "tool") return c;+ if (c.kind === "staged") return { ...c, steps: c.steps.map((s) => (s.kind === "generate" ? { ...s, request: { ...s.request, demo: true } } : s)) };+ return { ...c, steps: c.steps.map((s) => ({ ...s, request: { ...s.request, demo: true } })) };}/**@@ -231,10 +333,26 @@ function asDemo(c: Compiled): Compiled {function planCheck(c: Compiled, engine: Engine): RunPlan & { notes: string[] } {const plan = planRun(c, engine);if (!plan.errors.length || c.kind === "tool" || !plan.connectOnly) return { ...plan, notes: [] };- const demo = planRun(asDemo(c), engine);+ // A run in stages: its studio steps are planned as demos too (runAsDemo), as its dry run runs them.+ const demo = c.kind === "staged" ? runAsDemo(() => planRun(asDemo(c), engine)) : planRun(asDemo(c), engine);return demo.errors.length ? { ...plan, notes: [] } : { ...demo, notes: [...new Set(plan.jobs.flatMap((j) => (j.error ? [j.error] : [])))] };}+/**+ * Each generate step of a recipe priced on an engine with the check's values (the examples, or stand-ins): its model,+ * operation, kind and price, as a run would plan it. Null for a tool recipe or one that doesn't compile.+ */+export function stepPlans(recipe: Recipe, engine: Engine): { key: string; job: PlannedJob }[] | null {+ try {+ const c = compileRun({ name: "check", title: "Check" }, recipe, valuesForCheck(recipe), engine, { run: "check" });+ if (c.kind !== "pipeline") return null;+ const plan = planCheck(c, engine);+ return c.steps.map((s, i) => ({ key: s.key, job: plan.jobs[i] }));+ } catch {+ return null;+ }+}+/*** sha256 of what a run uses: each step's model, operation, route (the first one on, as the demo provider would name it,* so connecting a key doesn't count as a change) and price table.@@ -244,10 +362,19 @@ function planHash(compiled: Compiled, engine: Engine): string {const parts =c.kind === "tool"? planFor(c.tool, c.input, { engine }).jobs.map((j) => [j.modelId, j.op, getModel(j.modelId)?.pricing ?? null])- : c.steps.map((s) => {- const p = previewChained({ ...s.request, ...(s.chain && { chain: s.chain }) }, asList(s.after).length);- return [p.model.id, p.op, p.route.provider, p.route.endpoint, p.model.pricing ?? null];- });+ : c.kind === "staged"+ ? c.steps.map((s) =>+ s.kind === "tool"+ ? [s.tool, ...planFor(s.tool, withStandIns(s.input), { engine }).jobs.map((j) => [j.modelId, j.op, getModel(j.modelId)?.pricing ?? null])]+ : (() => {+ const p = previewChained({ ...(withStandIns(s.request) as GenerationRequest), ...(s.chain && { chain: s.chain as ChainSlot[] }) }, asList(s.after).length);+ return [p.model.id, p.op, p.route.provider, p.route.endpoint, p.model.pricing ?? null];+ })(),+ )+ : c.steps.map((s) => {+ const p = previewChained({ ...s.request, ...(s.chain && { chain: s.chain }) }, asList(s.after).length);+ return [p.model.id, p.op, p.route.provider, p.route.endpoint, p.model.pricing ?? null];+ });return `sha256:${crypto.createHash("sha256").update(JSON.stringify(parts)).digest("hex")}`;}@@ -259,7 +386,7 @@ declare global {}/** A small real file of a kind, saved once as a hidden (derived) asset: the dry run's providers read their inputs. */-function standIn(kind: "image" | "video" | "audio"): string {+export function standIn(kind: "image" | "video" | "audio"): string {const cache = (globalThis.__fuobeStandIns ??= new Map());const known = cache.get(kind);if (known && fs.existsSync(absolutePath(decodeURIComponent(known.slice("/api/files/".length))))) return known;@@ -504,10 +631,21 @@ export async function runRecipe(name: string, input: RunInput, asked?: Engine):const c = compileRun(skill, recipe, r.values!, engine, { run });const plan = planRun(c, engine);if (plan.errors.length) throw new RecipeError(plan.errors.map((e) => `${rows.length > 1 ? `Row ${r.line}: ` : ""}${e}`));- return { run, c };+ return { run, c, values: r.values! };});const runs: RecipeRun[] = [];let demo = true;+ if (compiled[0].c.kind === "staged") {+ // A run in stages: each row's steps start as the ones they wait for finish (src/server/skill-runs.ts).+ for (const { run, c, values } of compiled) {+ if (c.kind !== "staged") continue;+ const started = await beginSkillRun({ id: run, skill: skill.name, title: skill.title, engine, values, steps: c.steps });+ demo &&= started.ids.every((id) => getGeneration(id)?.provider === "mock");+ runs.push({ batchId: run, ids: started.ids, ...(started.href && { href: started.href }), skillRun: run, waiting: started.waiting, ...(started.error && { error: started.error }) });+ }+ if (!runs.some((r) => !r.error)) throw new SkillError(runs[0]?.error ?? "Nothing could start", 422);+ return { engine, runs, demo };+ }if (compiled[0].c.kind === "tool") {for (const { run, c } of compiled) {if (c.kind !== "tool") continue;@@ -591,6 +729,9 @@ const REAL_RUN_MS = 15 * 60_000;/** The free dry run: one run on the demo provider, its rows hidden (skill-check) and moved to the Trash at the end. */async function dryRun(skill: { name: string; title: string }, recipe: Recipe, engine: Engine): Promise<NonNullable<EngineCheck["dryRun"]>> {const c = compileRun(skill, recipe, valuesForCheck(recipe, true), engine, { run: nanoid(10), demo: true });+ // A run in stages: its studio steps run as demos (runAsDemo), each when the steps before are done; then every record a+ // studio made for it (a dub session, a Layers project…) is deleted and its rows go to the Trash.+ if (c.kind === "staged") return stagedDryRun(skill, c.steps, engine, valuesForCheck(recipe, true), DRY_RUN_MS);// A studio step would make a record the user sees (a demo dub, a Layers project): its plan is its check in W1.if (c.kind === "tool") return { ok: true, problems: [], skipped: `A studio step (${c.tool}) is checked by its plan only` };const p = createPipeline(c.steps, { batchId: nanoid(10) });@@ -667,6 +808,8 @@ async function realRun(skill: { name: string; title: string }, recipe: Recipe, econst helpers: string[] = [];let made: Generation[];let byKey: Record<string, string> = {};+ // A run in stages is checked by its plan and its dry run; a real test of one isn't offered yet.+ if (c.kind === "staged") return { ok: true, problems: [], notes: ["A real test of a skill whose steps wait across studios isn't offered yet: its plan and its dry run check it"], demo: false };if (c.kind === "tool") {const out = await executeTool(c.tool, c.input, { engine });if (out.isError) return { ok: false, problems: [typeof out.content === "string" ? out.content : "The tool couldn't start"], notes, demo: false };diff --git a/src/server/skill-insights.ts b/src/server/skill-insights.tsnew file mode 100644index 00000000..0a59cd6d--- /dev/null+++ b/src/server/skill-insights.ts@@ -0,0 +1,318 @@+import "server-only";+import crypto from "node:crypto";+import { getModel, modelsFor } from "@/lib/catalog";+import { dualEngine } from "@/lib/catalog/engines";+import { currentModelId, replacedBy } from "@/lib/catalog/replaced";+import { OPERATION_LABELS, type ChainSlot, type Engine, type GenerationRequest, type MediaKind, type Operation } from "@/lib/catalog/types";+import { isHelperFeature } from "@/lib/library";+import { RECIPE_LIMITS, recipeShapeNodes, shapeOf, type Recipe, type ShapeNode } from "@/lib/recipe";+import type { FixCandidates, SkillHistory, SkillRunRow, SkillSuggestion } from "@/lib/skill-insights";+import { db } from "./db";+import { offeredModels, isOffered } from "./model-access";+import { getRecipe, needsRecheck, recipeEngines, saveRecipe, stepPlans, verifyRecipe } from "./recipes";+import { listSkills, skillRecipe, SkillError } from "./skills";++/**+ * Skills that notice repeated work and stay healthy (package W6, docs/research/work2skill-7.md):+ * - suggestions: the same chain of steps made 3 or more times in 14 days, with other words and files, offered as a+ * skill (an online induction: the Library's runs are the demonstrations). Read from the owner's own runs only.+ * - history: each skill's runs, from the stamp every run of a skill carries (`request.skill`), with no table of its own.+ * - fixes: a step that keeps failing, was replaced, or was switched off gets models that do the same job, priced; the+ * person picks one, and the skill is checked again before it is saved. Nothing is swapped by itself.+ * - usage: how often and how lately each skill ran, so Assist ranks the skills people use.+ */++// ---------------------------------------------------------------------------+// The owner's runs (an account's never count: they stay out of the owner's lists)++/** Rows the owner made, not in the Trash. */+const OWNER = "json_valid(request_json) AND json_extract(request_json, '$.account') IS NULL AND NOT EXISTS (SELECT 1 FROM generation_trash t WHERE t.generation_id = generations.id)";++interface RunRow {+ id: string;+ batch_id: string | null;+ depends_on: string | null;+ request_json: string;+ feature: string;+ provider: string;+ model_id: string;+ op: string;+ status: string;+ cost_usd: number | null;+ favorite: number;+ created_at: number;+ outputs_json: string;+}++const depIds = (v: string | null): string[] => (!v ? [] : v.startsWith("[") ? (JSON.parse(v) as string[]) : [v]);++// ---------------------------------------------------------------------------+// Usage and history+++/** A run's status from its rows: going while any is, failed when any failed, else done. */+function runStatus(rows: Pick<RunRow, "status">[]): SkillRunRow["status"] {+ if (rows.some((r) => r.status === "queued" || r.status === "running")) return "running";+ if (rows.some((r) => r.status === "failed")) return "failed";+ if (rows.every((r) => r.status === "canceled")) return "canceled";+ return "succeeded";+}++/** A skill's runs: how many, how many worked, what they cost, when it last ran, its favourites and the last `limit`. */+export function skillHistory(name: string, limit = 10): SkillHistory {+ const rows = db()+ .prepare(`SELECT * FROM generations WHERE ${OWNER} AND json_extract(request_json, '$.skill.name') = ? AND feature != 'skill-check' AND COALESCE(json_extract(request_json, '$.skill.run'), '') NOT LIKE 'check-%' ORDER BY created_at DESC LIMIT 5000`)+ .all(name) as RunRow[];+ const runs = new Map<string, RunRow[]>();+ for (const r of rows) {+ const req = JSON.parse(r.request_json) as GenerationRequest & { skill?: { run?: string } };+ const key = req.skill?.run ?? r.batch_id ?? r.id;+ runs.set(key, [...(runs.get(key) ?? []), r]);+ }+ const list: SkillRunRow[] = [...runs.entries()].map(([run, rs]) => {+ const outputs = rs.flatMap((r) => (JSON.parse(r.outputs_json) as { url: string; kind: MediaKind; poster?: string }[]).map((o) => ({ url: o.url, kind: o.kind, ...(o.poster && { poster: o.poster }) })));+ const costs = rs.map((r) => r.cost_usd);+ return {+ run,+ batchId: rs.find((r) => r.batch_id)?.batch_id ?? null,+ status: runStatus(rs),+ costUsd: costs.every((c) => c === null) ? null : Math.round(costs.reduce<number>((s, c) => s + (c ?? 0), 0) * 1000) / 1000,+ at: Math.min(...rs.map((r) => r.created_at)),+ steps: rs.length,+ failed: [...rs].sort((x, y) => x.created_at - y.created_at).filter((r) => r.status === "failed").map((r) => ({ model: r.model_id, error: (JSON.parse(r.request_json) as { step?: { label?: string } }).step?.label ?? null })),+ demo: rs.every((r) => r.provider === "mock"),+ outputs: outputs.slice(-4),+ favorites: rs.filter((r) => r.favorite).length,+ };+ });+ list.sort((a, b) => b.at - a.at);+ const finished = list.filter((r) => r.status !== "running");+ const ok = finished.filter((r) => r.status === "succeeded").length;+ const spent = list.reduce((s, r) => s + (r.costUsd ?? 0), 0);+ return {+ runs: list.length,+ successRate: finished.length ? ok / finished.length : null,+ spendUsd: Math.round(spent * 100) / 100,+ lastRunAt: list[0]?.at ?? null,+ favorites: list.reduce((s, r) => s + r.favorites, 0),+ recent: list.slice(0, limit),+ };+}++// ---------------------------------------------------------------------------+// Suggestions++const KEY = "skills.suggestions";+const WINDOW_MS = 14 * 86_400_000;+const SWEEP_MS = 86_400_000;+const LATER_MS = 7 * 86_400_000;+/** The fewest times a chain must have been made to be suggested. */+export const SUGGEST_AFTER = 3;++interface Stored {+ sweptAt?: number;+ /** The last sweep's suggestions, each with its shape's key. */+ list?: (SkillSuggestion & { key?: string })[];+ /** Shapes never to suggest again. */+ dismissed?: string[];+ /** Shapes not to suggest before a time ("Not now"). */+ later?: Record<string, number>;+}++function readStored(): Stored {+ const row = db().prepare("SELECT value FROM settings WHERE key = ?").get(KEY) as { value: string } | undefined;+ try {+ return row ? (JSON.parse(row.value) as Stored) : {};+ } catch {+ return {};+ }+}++function writeStored(s: Stored): void {+ db().prepare("INSERT INTO settings (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(KEY, JSON.stringify(s));+}++/** A shape's id: short and stable. */+const shapeId = (key: string) => crypto.createHash("sha256").update(key).digest("hex").slice(0, 16);++/** "Remove background → Edit → Image to video": a chain in words, by what each step does. */+function chainWords(steps: { modelId: string; op?: string }[]): string {+ return steps.map((s) => (s.op && OPERATION_LABELS[s.op as Operation]) || getModel(s.modelId)?.name || s.modelId).join(" → ");+}++/** The shape of a run's rows (one batch): its generate steps and their links. Null when it isn't a chain. */+function rowsShape(rows: RunRow[]): ReturnType<typeof shapeOf> {+ const ids = new Set(rows.map((r) => r.id));+ const nodes: ShapeNode[] = rows.map((r) => {+ const req = JSON.parse(r.request_json) as GenerationRequest;+ const after = depIds(r.depends_on).filter((d) => ids.has(d));+ const chain = req.chain as ChainSlot[] | undefined;+ return { id: r.id, modelId: currentModelId(req.modelId ?? r.model_id), ...(req.op && { op: req.op }), after, slots: after.map((_, i) => chain?.[i]?.slot ?? "images") };+ });+ // Only a chain: at least one step waits for another, and not more steps than a skill takes.+ if (!nodes.some((n) => n.after.length) || nodes.length > RECIPE_LIMITS.steps) return null;+ return shapeOf(nodes);+}++/** The shapes of the saved skills' recipes: a chain a skill already makes isn't suggested. */+function savedShapes(): Set<string> {+ const out = new Set<string>();+ for (const s of listSkills()) {+ if (!s.recipe) continue;+ const recipe = skillRecipe(s.name);+ const nodes = recipe && recipeShapeNodes(recipe, currentModelId);+ const shape = nodes && shapeOf(nodes);+ if (shape) out.add(shape.key);+ }+ return out;+}++/**+ * Group the owner's runs of the last 14 days by shape and keep each chain made SUGGEST_AFTER times or more that no saved+ * skill makes. Helper rows, a skill's own runs and the evaluation harness's runs don't count.+ */+export function sweepSuggestions(now = Date.now()): SkillSuggestion[] {+ const rows = db()+ .prepare(`SELECT * FROM generations WHERE ${OWNER} AND created_at >= ? AND status = 'succeeded' AND batch_id IS NOT NULL AND json_extract(request_json, '$.skill') IS NULL ORDER BY created_at DESC LIMIT 20000`)+ .all(now - WINDOW_MS) as RunRow[];+ const batches = new Map<string, RunRow[]>();+ for (const r of rows) {+ if (isHelperFeature(r.feature) || r.feature === "upload") continue;+ batches.set(r.batch_id!, [...(batches.get(r.batch_id!) ?? []), r]);+ }+ const groups = new Map<string, { shape: NonNullable<ReturnType<typeof shapeOf>>; batches: { rows: RunRow[]; at: number }[] }>();+ for (const rs of batches.values()) {+ const shape = rowsShape(rs);+ if (!shape) continue;+ const g = groups.get(shape.key) ?? { shape, batches: [] };+ g.batches.push({ rows: rs, at: Math.max(...rs.map((r) => r.created_at)) });+ groups.set(shape.key, g);+ }+ const saved = savedShapes();+ const out: (SkillSuggestion & { key: string })[] = [];+ for (const [key, g] of groups) {+ if (g.batches.length < SUGGEST_AFTER || saved.has(key)) continue;+ g.batches.sort((a, b) => b.at - a.at);+ const newest = g.batches[0].rows;+ // The newest run's last steps: the review screen walks back from them to the whole chain.+ const fed = new Set(newest.flatMap((r) => depIds(r.depends_on)));+ out.push({+ key,+ id: shapeId(key),+ words: chainWords(g.shape.steps),+ count: g.batches.length,+ ids: newest.filter((r) => !fed.has(r.id)).map((r) => r.id),+ lastAt: g.batches[0].at,+ demo: g.batches.every((b) => b.rows.every((r) => r.provider === "mock")),+ });+ }+ return out.sort((a, b) => b.count - a.count || b.lastAt - a.lastAt).slice(0, 5);+}++/**+ * The suggestions to show now: swept at most once a day (when the Library opens), less the ones put off or dismissed.+ * `force` sweeps again (after a skill is saved, or a test).+ */+export function skillSuggestions(o: { now?: number; force?: boolean } = {}): SkillSuggestion[] {+ const now = o.now ?? Date.now();+ let stored = readStored();+ if (o.force || !stored.sweptAt || now - stored.sweptAt >= SWEEP_MS || now < stored.sweptAt) {+ stored = { ...stored, sweptAt: now, list: sweepSuggestions(now) };+ writeStored(stored);+ }+ const dismissed = new Set(stored.dismissed ?? []);+ const later = stored.later ?? {};+ // A chain a skill now makes is left out at once, without waiting for the next sweep.+ const saved = (stored.list ?? []).length ? savedShapes() : new Set<string>();+ return (stored.list ?? []).filter((s) => !dismissed.has(s.id) && !((later[s.id] ?? 0) > now) && !(s.key && saved.has(s.key))).map((s) => ({ id: s.id, words: s.words, count: s.count, ids: s.ids, lastAt: s.lastAt, demo: s.demo }));+}++/** "Not now" (hidden for a week) or "Don't suggest this" (never again). */+export function dismissSuggestion(id: string, how: "later" | "never", now = Date.now()): void {+ const s = readStored();+ if (how === "never") s.dismissed = [...new Set([...(s.dismissed ?? []), id])].slice(-500);+ else s.later = { ...Object.fromEntries(Object.entries(s.later ?? {}).filter(([, until]) => until > now)), [id]: now + LATER_MS };+ writeStored(s);+}+++// ---------------------------------------------------------------------------+// Fixes++/** How many of the last runs a step may fail in before it is offered a fix. */+const FAILS = { of: 5, at: 2 } as const;++/**+ * The steps that need a fix, each with models that do the same job (the same operation and kind, switched on here),+ * priced on the skill's engine: a step that failed in 2 of the last 5 runs, a model Fuobe replaced, or one switched off in+ * Settings → Models & licences. Nothing changes until the person picks one (applyFix).+ */+export function fixCandidates(name: string): FixCandidates {+ const { recipe } = getRecipe(name);+ const engines = recipeEngines(recipe);+ const engine: Engine = engines.find((e) => !!recipe.verified?.[e]?.plan) ?? engines[0] ?? "cloud";+ const plans = stepPlans(recipe, engine) ?? [];+ const recent = skillHistory(name, FAILS.of).recent.filter((r) => r.status !== "running");+ const steps: FixCandidates["steps"] = [];+ for (const s of recipe.steps) {+ if (s.kind !== "generate") continue;+ const asked = s.request.modelId;+ const id = currentModelId(asked);+ const m = getModel(id);+ const reasons: string[] = [];+ const moved = replacedBy(asked);+ if (moved) reasons.push(`${moved.was} was replaced by ${getModel(moved.id)?.name ?? moved.id}`);+ if (m && !isOffered(id, dualEngine(m) ? engine : undefined)) reasons.push(`${m.name} is switched off in Settings → Models & licences`);+ const fails = recent.filter((r) => r.failed.some((f) => f.model === id || f.model === asked)).length;+ if (fails >= FAILS.at) reasons.push(`It failed in ${fails} of the last ${recent.length} runs`);+ if (!reasons.length) continue;+ const plan = plans.find((p) => p.key === s.key)?.job;+ const op = (s.request.op as Operation | undefined) ?? (plan && plan.op !== "storyboard" && plan.op !== "memory" ? plan.op : undefined);+ const kind = m?.kind ?? plan?.kind;+ const pool = op && kind ? offeredModels(modelsFor({ kind, ops: [op], engine: "all" })) : [];+ const candidates = pool+ .filter((c) => c.id !== id && c.id !== asked && (!m || c.engine === m.engine || dualEngine(c)))+ .slice(0, 12)+ .map((c) => {+ const swapped: Recipe = { ...recipe, steps: recipe.steps.map((x) => (x.key === s.key && x.kind === "generate" ? { ...x, request: { ...x.request, modelId: c.id } } : x)) };+ const priced = stepPlans(swapped, engine);+ const job = priced?.find((p) => p.key === s.key)?.job;+ return { modelId: c.id, name: c.name, engine: c.engine, costUsd: job && !job.error ? job.costUsd : null, ...(job?.error && { problem: job.error }) };+ })+ .sort((a, b) => Number(!!a.problem) - Number(!!b.problem) || (a.costUsd ?? Infinity) - (b.costUsd ?? Infinity));+ steps.push({ key: s.key, label: s.label ?? (op ? OPERATION_LABELS[op] : s.key), model: m?.name ?? asked, reasons, candidates });+ }+ return { engine, steps };+}++/**+ * Swap one step's model for the one picked, then check the recipe (the plan, and a free dry run) before it is kept: a+ * swap whose plan fails isn't saved, and the recipe stays as it was.+ */+export async function applyFix(name: string, step: string, modelId: string): Promise<{ ok: boolean; problems: string[] }> {+ const { skill, recipe } = getRecipe(name);+ if (skill.source === "builtin") throw new SkillError("Built-in skills can't be changed — Duplicate it first, then change your copy", 403);+ const target = recipe.steps.find((s) => s.key === step);+ if (!target || target.kind !== "generate") throw new SkillError(`The skill has no step “${step}”`, 404);+ const offered = fixCandidates(name).steps.find((s) => s.key === step)?.candidates.some((c) => c.modelId === modelId);+ if (!offered) throw new SkillError("Pick one of the models offered for that step", 422);+ const next: Recipe = { ...recipe, steps: recipe.steps.map((s) => (s.key === step && s.kind === "generate" ? { ...s, request: { ...s.request, modelId } } : s)) };+ saveRecipe(name, next);+ const check = await verifyRecipe(name, "demo");+ // Any engine's failed check undoes the swap (an engine still marked ready from before doesn't keep it).+ if (!check.ok) {+ saveRecipe(name, recipe, { keepVerified: true });+ return { ok: false, problems: check.engines.flatMap((e) => [...e.plan.errors, ...(e.dryRun?.problems ?? [])]) };+ }+ return { ok: true, problems: [] };+}++/** Whether a skill has a step to fix now (its re-check line offers Suggest a fix). */+export const needsFix = (name: string): boolean => {+ try {+ const { recipe } = getRecipe(name);+ return Object.keys(needsRecheck(recipe)).length > 0 || fixCandidates(name).steps.length > 0;+ } catch {+ return false;+ }+};diff --git a/src/server/skill-runs.ts b/src/server/skill-runs.tsnew file mode 100644index 00000000..9e00f040--- /dev/null+++ b/src/server/skill-runs.ts@@ -0,0 +1,396 @@+import "server-only";+import type { Engine, Generation, GenerationRequest, MediaKind } from "@/lib/catalog/types";+import { fieldKind, stepRefOf, stepRefs, type RecipeStep, type RecipeValues } from "@/lib/recipe";+import type { SkillRunStatus, SkillRunStep, SkillRunView } from "@/lib/skill-runs";+import { executeTool } from "./assist/tools";+import { createPipeline } from "./chains";+import { db } from "./db";+import { outsideDemo, runAsDemo } from "./demo-scope";+import { ASSET_REFS, getGeneration, stampRequests } from "./generations";+import { trashGenerations } from "./library";+import { apiStep, stagedParts, standIn } from "./recipes";++/**+ * Skills whose steps wait for each other across studios (package W7): "dub, then captions, then a 9:16 cut". A run is a+ * `skill_runs` row: every step whose inputs exist starts at once (generate steps joined by `after` as one createPipeline,+ * a studio step through its Assist tool, keeping the studio's page), and a sweep starts each waiting step when the steps+ * it takes results from are done, putting the first output of the kind its field takes in for `{{steps.<key>.output}}`.+ * A failure fails the steps after it and says which step and why. The state lives in the database, so a restart picks+ * up where it was.+ */++interface StepState extends SkillRunStep {+ /** The part it starts with (stagedParts). */+ part: string;+ /** The generation whose output later steps take. */+ final?: string;+}++interface State {+ title: string;+ /** The steps as filled with the run's values, references kept. */+ plan: RecipeStep[];+ steps: StepState[];+ error?: string;+ /** A skill's dry run (its rows go to the Trash at the end; never shown in its history). */+ check?: boolean;+}++interface Row {+ id: string;+ skill: string;+ engine: Engine;+ status: SkillRunStatus;+ values_json: string;+ state_json: string;+ created_at: number;+ updated_at: number;+}++const TERMINAL = new Set(["succeeded", "failed", "canceled"]);+const SWEEP_MS = 10_000;++const load = (id: string): (Row & { state: State }) | null => {+ const r = db().prepare("SELECT * FROM skill_runs WHERE id = ?").get(id) as Row | undefined;+ return r ? { ...r, state: JSON.parse(r.state_json) as State } : null;+};++function save(id: string, status: SkillRunStatus, state: State): void {+ db().prepare("UPDATE skill_runs SET status = ?, state_json = ?, updated_at = ? WHERE id = ?").run(status, JSON.stringify(state), Date.now(), id);+}++const words = (s: Pick<StepState, "label">) => `“${s.label}”`;++/** The first output of a kind a generation made (text: its words; a field whose kind can't be told: its first output, a file or words). */+function outputOf(g: Generation, kind: MediaKind | undefined): string | undefined {+ if (kind === "text") return g.outputs.find((o) => typeof o.text === "string")?.text;+ if (kind) return g.outputs.find((o) => o.kind === kind)?.url;+ const first = g.outputs[0];+ return first?.url || (typeof first?.text === "string" ? first.text : undefined);+}++/** A value with each step reference put in: the referenced step's output of the kind its field takes. */+function resolve(v: unknown, outputs: (key: string, kind: MediaKind | undefined) => string, path: (string | number)[] = []): unknown {+ if (typeof v === "string") {+ if (!stepRefs(v).size) return v;+ const exact = stepRefOf(v);+ if (exact) return outputs(exact, fieldKind(path));+ return v.replace(/\{\{\s*steps\.([A-Za-z0-9][A-Za-z0-9_-]{0,39})\.output\s*\}\}/g, (_, k: string) => outputs(k, "text"));+ }+ if (Array.isArray(v)) return v.map((x, i) => resolve(x, outputs, [...path, i]));+ if (v && typeof v === "object") return Object.fromEntries(Object.entries(v).map(([k, x]) => [k, resolve(x, outputs, [...path, k])]));+ return v;+}++/** Start one part: its generate steps as one createPipeline, or its studio step through its tool. */+async function startPart(run: Row & { state: State }, partId: string): Promise<void> {+ const { state } = run;+ const members = state.steps.filter((s) => s.part === partId);+ const outputs = (key: string, kind: MediaKind | undefined): string => {+ const from = state.steps.find((s) => s.key === key);+ const g = from?.final ? getGeneration(from.final, { includeDeleted: true }) : null;+ const out = g && outputOf(g, kind);+ if (!out) throw new Error(`${words(from ?? { label: key })} made no ${kind ?? "result"} for the next step`);+ return out;+ };+ const fail = (error: string) => {+ for (const m of members) Object.assign(m, { status: "failed", error });+ };+ try {+ const plan = state.plan.filter((s) => members.some((m) => m.key === s.key));+ const tool = plan.find((s) => s.kind === "tool");+ if (tool && tool.kind === "tool") {+ const input = resolve(tool.input, outputs) as Record<string, unknown>;+ const out = await executeTool(tool.tool, input, { engine: run.engine });+ const text = typeof out.content === "string" ? out.content : "";+ if (out.isError) return fail(text.replace(/^\{"error":"(.*)"\}$/, "$1") || "The studio couldn't start it");+ let body: { href?: string; studio?: string; results?: string[] } = {};+ try {+ body = JSON.parse(text) as typeof body;+ } catch {+ body = {};+ }+ const ids = (out.items ?? []).flatMap((i) => (i.role === "generations" ? i.ids : []));+ const studio = (out.items ?? []).find((i) => i.role === "tool" && "studio" in i && i.studio) as { studio?: string } | undefined;+ // The run's stamp and the skill's title on everything the studio started.+ stampRequests(ids, () => ({ skill: { name: run.skill, run: run.id }, batchTitle: state.title.slice(0, 200) }));+ const m = members[0];+ Object.assign(m, { status: ids.length ? "running" : "failed", ids, final: body.results?.[0] ?? ids[0], ...(body.href && { href: body.href }), ...((studio?.studio ?? body.studio) && { studio: studio?.studio ?? body.studio }), ...(!ids.length && { error: "The studio started nothing" }) });+ return;+ }+ const steps = plan.map((s) => {+ if (s.kind !== "generate") throw new Error("A part mixes studio and generate steps");+ return apiStep({ key: s.key, request: resolve(s.request, outputs) as GenerationRequest, ...(s.after !== undefined && { after: s.after }), ...(s.chain && { chain: s.chain as never }) }, run.engine);+ });+ const p = createPipeline(steps, { batchId: run.id });+ for (const m of members) {+ const g = p.byKey[m.key];+ Object.assign(m, { status: "running", ids: g ? [g.id] : [], final: g?.id });+ }+ } catch (e) {+ fail((e as Error).message);+ }+}++/** Whether a step's work is over: the step's generations (and the rest of their batches, for a studio) are finished. */+function settled(s: StepState): { done: boolean; ok: boolean; error?: string } {+ if (!s.ids.length) return { done: true, ok: false, error: s.error ?? "It started nothing" };+ const gens = s.ids.map((id) => getGeneration(id, { includeDeleted: true })).filter((g): g is Generation => !!g);+ // A studio's later steps share its first steps' batch: wait for the whole batch.+ const batches = [...new Set(gens.map((g) => g.batchId).filter((b): b is string => !!b))];+ const more =+ s.kind === "tool" && batches.length+ ? (db().prepare(`SELECT id, status FROM generations WHERE batch_id IN (${batches.map(() => "?").join(", ")})`).all(...batches) as { id: string; status: string }[])+ : [];+ if (gens.some((g) => !TERMINAL.has(g.status)) || more.some((r) => !TERMINAL.has(r.status))) return { done: false, ok: false };+ const final = s.final ? getGeneration(s.final, { includeDeleted: true }) : gens.at(-1);+ if (final?.status === "succeeded") return { done: true, ok: true };+ const bad = final ?? gens.find((g) => g.status !== "succeeded");+ return { done: true, ok: false, error: bad?.error ?? (bad?.status === "canceled" ? "It was stopped" : "It didn't finish") };+}++/**+ * Move a run on: finish the steps whose work is over, fail the steps after a failure (with which step and why), and+ * start each part whose waits are all done. Returns the run's status.+ */+export async function advanceSkillRun(id: string): Promise<SkillRunStatus | null> {+ // One move at a time per run: a studio step's tool takes a moment, and a sweep meanwhile mustn't start it again.+ const busy = (globalThis.__fuobeSkillRunsBusy ??= new Set<string>());+ if (busy.has(id)) return load(id)?.status ?? null;+ busy.add(id);+ try {+ return await advance(id);+ } finally {+ busy.delete(id);+ }+}++async function advance(id: string): Promise<SkillRunStatus | null> {+ const run = load(id);+ if (!run) return null;+ if (run.status !== "running") return run.status;+ const { state } = run;+ for (const s of state.steps) {+ if (s.status !== "running") continue;+ const r = settled(s);+ if (!r.done) continue;+ s.status = r.ok ? "done" : "failed";+ if (!r.ok) s.error = r.error;+ }+ const parts = stagedParts(state.plan);+ const statusOf = (key: string) => state.steps.find((s) => s.key === key)?.status;+ // A step after a failed one fails too, saying which step failed (and so on down the chain).+ for (let moved = true; moved; ) {+ moved = false;+ for (const part of parts) {+ const members = state.steps.filter((s) => s.part === part.id && s.status === "waiting");+ if (!members.length) continue;+ const broken = part.waits.find((k) => statusOf(k) === "failed");+ if (!broken) continue;+ const from = state.steps.find((s) => s.key === broken)!;+ // The step that failed first is named all the way down the chain.+ const error = from.error?.endsWith("so this didn't start") ? from.error : `${words(from)} failed, so this didn't start`;+ for (const m of members) Object.assign(m, { status: "failed", error });+ moved = true;+ }+ }+ for (const part of parts) {+ const waiting = state.steps.filter((s) => s.part === part.id);+ if (!waiting.every((s) => s.status === "waiting") || !part.waits.every((k) => statusOf(k) === "done")) continue;+ // A dry run's steps always run as demos, whoever moves it on (never real studio work on real keys or a GPU).+ if (state.check) await runAsDemo(() => startPart(run, part.id));+ else await startPart(run, part.id);+ }+ const failed = state.steps.find((s) => s.status === "failed" && !/didn't start$/.test(s.error ?? ""));+ if (failed && !state.error) state.error = `${words(failed)} failed${failed.error ? `: ${failed.error}` : ""}`;+ const going = state.steps.some((s) => s.status === "running" || (s.status === "waiting" && !failed));+ const status: SkillRunStatus = going ? "running" : state.steps.every((s) => s.status === "done") ? "done" : "failed";+ save(id, status, state);+ return status;+}++export interface StartedRun {+ /** The generations started now. */+ ids: string[];+ /** The first studio page a step opened in. */+ href?: string;+ /** The labels of the steps that start later. */+ waiting: string[];+ /** Why nothing could start. */+ error?: string;+}++const labelOf = (s: RecipeStep, i: number) => s.label ?? (s.kind === "tool" ? s.tool.replace(/_/g, " ") : `Step ${i + 1}`);++/**+ * Start a run in stages: a `skill_runs` row with every step waiting, then every part with nothing to wait for. The sweep+ * starts the rest. `check`: a skill's dry run (kept out of its history).+ */+export function startSkillRun(o: { id: string; skill: string; title: string; engine: Engine; values: RecipeValues; steps: RecipeStep[]; check?: boolean }): { done: Promise<SkillRunStatus | null> } {+ const parts = stagedParts(o.steps);+ const partOf = new Map(parts.flatMap((p) => p.keys.map((k) => [k, p.id] as const)));+ const state: State = {+ title: o.title,+ plan: o.steps,+ steps: o.steps.map((s, i) => ({ key: s.key, label: labelOf(s, i), kind: s.kind, status: "waiting", ids: [], part: partOf.get(s.key)! })),+ ...(o.check && { check: true }),+ };+ const now = Date.now();+ db()+ .prepare("INSERT INTO skill_runs (id, skill, engine, status, values_json, state_json, created_at, updated_at) VALUES (?, ?, ?, 'running', ?, ?, ?, ?)")+ .run(o.id, o.skill, o.engine, JSON.stringify(o.values), JSON.stringify(state), now, now);+ ensureSkillRunRunner();+ // The first parts start now (a studio step's tool may take a moment).+ return { done: advanceSkillRun(o.id) };+}++/** Start a run and wait for its first parts to have started (a studio step's tool is asynchronous). */+export async function beginSkillRun(o: Parameters<typeof startSkillRun>[0]): Promise<StartedRun> {+ const started = startSkillRun(o);+ await started.done;+ const r = load(o.id)!;+ const steps = r.state.steps;+ const error = steps.every((s) => s.status === "failed") ? (r.state.error ?? steps[0]?.error) : undefined;+ return { ids: steps.flatMap((s) => s.ids), href: steps.find((s) => s.href)?.href, waiting: steps.filter((s) => s.status === "waiting").map((s) => s.label), ...(error && { error }) };+}++/** A run as the skill's dialog shows it. */+const toView = (r: Row & { state: State }): SkillRunView => ({+ id: r.id,+ skill: r.skill,+ status: r.status,+ createdAt: r.created_at,+ updatedAt: r.updated_at,+ steps: r.state.steps.map((s) => ({ key: s.key, label: s.label, kind: s.kind, status: s.status, ids: s.ids, ...(s.studio && { studio: s.studio }), ...(s.href && { href: s.href }), ...(s.error && { error: s.error }) })),+ ...(r.state.error && { error: r.state.error }),+});++export function getSkillRun(id: string): SkillRunView | null {+ const r = load(id);+ return r && !r.state.check ? toView(r) : null;+}++/** A skill's newest runs in stages (dry runs left out). */+export function listSkillRuns(skill: string, limit = 5): SkillRunView[] {+ const rows = db().prepare("SELECT * FROM skill_runs WHERE skill = ? ORDER BY created_at DESC LIMIT ?").all(skill, limit * 3) as Row[];+ return rows+ .map((r) => ({ ...r, state: JSON.parse(r.state_json) as State }))+ .filter((r) => !r.state.check)+ .slice(0, limit)+ .map(toView);+}++// ---------------------------------------------------------------------------+// The sweep++/**+ * Move every run that is still going (also after a restart: the state is in the database). A dry run's row is left out:+ * only its own loop (inside runAsDemo) moves it, and its row is removed when that loop ends.+ */+export async function sweepSkillRuns(): Promise<void> {+ const ids = (db().prepare("SELECT id FROM skill_runs WHERE status = 'running' AND id NOT LIKE 'check-%' ORDER BY created_at LIMIT 200").all() as { id: string }[]).map((r) => r.id);+ for (const id of ids) {+ try {+ await advanceSkillRun(id);+ } catch (e) {+ console.warn(`[fuobe] skill run ${id}: ${(e as Error).message}`);+ }+ }+}++declare global {+ var __fuobeSkillRuns: { tick: () => void; timer: NodeJS.Timeout } | undefined;+ var __fuobeSkillRunsBusy: Set<string> | undefined;+}++const tick = () => void sweepSkillRuns().catch((e: Error) => console.warn(`[fuobe] skill run sweep failed: ${e.message}`));++/** Start the sweep (once per process: at boot, and when a run in stages starts). */+export function ensureSkillRunRunner(): void {+ const cur = globalThis.__fuobeSkillRuns;+ if (cur) {+ cur.tick = tick;+ return;+ }+ // Made outside any dry run's demo scope, so the sweep never runs a real step as a demo.+ const state = { tick, timer: outsideDemo(() => setInterval(() => globalThis.__fuobeSkillRuns?.tick(), SWEEP_MS)) };+ state.timer.unref?.();+ globalThis.__fuobeSkillRuns = state;+}++// ---------------------------------------------------------------------------+// The dry run of a run in stages++/** Tables whose rows a studio makes (a dub session, a Layers project…): the ones ASSET_REFS keys by their own id. */+const STUDIO_TABLES = () => ASSET_REFS.filter((r) => !r.key && !["generations", "assist_threads", "assist_schedules", "skills", "skill_runs", "canvases"].includes(r.table));++function snapshot(): Map<string, Set<string>> {+ const out = new Map<string, Set<string>>();+ for (const r of STUDIO_TABLES()) {+ try {+ out.set(r.table, new Set((db().prepare(`SELECT id FROM ${r.table}`).all() as { id: string }[]).map((x) => String(x.id))));+ } catch {+ // A table this install doesn't have.+ }+ }+ return out;+}++/**+ * Delete what a studio made for a dry run: rows that weren't there before it and that name one of its files or results+ * (a stand-in input, a generation it started). Anything else made meanwhile stays.+ */+function deleteStudioRecords(before: Map<string, Set<string>>, marks: string[]): number {+ let n = 0;+ for (const r of STUDIO_TABLES()) {+ const had = before.get(r.table);+ if (!had) continue;+ try {+ const rows = db().prepare(`SELECT id, ${r.cols.map((c) => `COALESCE(${c}, '')`).join(" || ' ' || ")} AS text FROM ${r.table}`).all() as { id: string; text: string }[];+ for (const row of rows) {+ if (had.has(String(row.id)) || !marks.some((m) => row.text.includes(m))) continue;+ n += db().prepare(`DELETE FROM ${r.table} WHERE id = ?`).run(row.id).changes;+ }+ } catch {+ // A table or column this install doesn't have.+ }+ }+ return n;+}++/**+ * The free dry run of a run in stages: every step on the demo provider (studio steps inside runAsDemo, so their own code+ * runs as a demo), each started when the steps before it are done, at most `ms`. Then the studio records it made are+ * deleted, its rows go to the Trash and the run's row is removed.+ */+export async function stagedDryRun(skill: { name: string; title: string }, steps: RecipeStep[], engine: Engine, values: RecipeValues, ms: number): Promise<{ ok: boolean; problems: string[]; skipped?: string }> {+ const id = `check-${Math.random().toString(36).slice(2, 12)}`;+ const before = snapshot();+ const marks = [...new Set([standIn("image"), standIn("video"), standIn("audio"), ...Object.values(values).filter((v): v is string => typeof v === "string" && v.startsWith("/api/files/"))])];+ const made = new Set<string>();+ try {+ return await runAsDemo(async () => {+ await startSkillRun({ id, skill: skill.name, title: skill.title, engine, values, steps, check: true }).done;+ const until = Date.now() + ms;+ for (;;) {+ const status = await advanceSkillRun(id);+ const r = load(id);+ for (const s of r?.state.steps ?? []) for (const g of s.ids) made.add(g);+ if (status !== "running") {+ const problems = (r?.state.steps ?? []).filter((s) => s.status === "failed").map((s) => `Step “${s.key}”: ${s.error ?? "it failed"}`);+ return { ok: status === "done", problems };+ }+ if (Date.now() > until) return { ok: false, problems: ["The dry run took too long"] };+ await new Promise((res) => setTimeout(res, 300));+ }+ });+ } finally {+ // Every row of the runs it started (a studio's later steps share their batch), then the studio's records.+ const batches = made.size ? (db().prepare(`SELECT DISTINCT batch_id FROM generations WHERE id IN (${[...made].map(() => "?").join(", ")}) AND batch_id IS NOT NULL`).all(...made) as { batch_id: string }[]).map((b) => b.batch_id) : [];+ const all = batches.length ? (db().prepare(`SELECT id FROM generations WHERE batch_id IN (${batches.map(() => "?").join(", ")})`).all(...batches) as { id: string }[]).map((g) => g.id) : [];+ const ids = [...new Set([...made, ...all])];+ deleteStudioRecords(before, [...marks, ...ids]);+ if (ids.length) trashGenerations(ids);+ db().prepare("DELETE FROM skill_runs WHERE id = ?").run(id);+ }+}diff --git a/src/server/skill-usage.ts b/src/server/skill-usage.tsnew file mode 100644index 00000000..4fe62946--- /dev/null+++ b/src/server/skill-usage.ts@@ -0,0 +1,42 @@+import "server-only";+import { db } from "./db";++/**+ * How often and how lately each skill ran (package W6): its stamped generations (`request.skill`) grouped by run, the+ * owner's own and not in the Trash. Assist ranks skills by it, so the ones people use stay in its context.+ */+export function skillUsage(): Map<string, { runs: number; last: number }> {+ try {+ const rows = db()+ .prepare(+ `SELECT json_extract(request_json, '$.skill.name') AS name, COUNT(DISTINCT COALESCE(json_extract(request_json, '$.skill.run'), batch_id, id)) AS runs, MAX(created_at) AS last+ FROM generations WHERE json_valid(request_json) AND json_extract(request_json, '$.skill.name') IS NOT NULL AND json_extract(request_json, '$.account') IS NULL+ AND feature != 'skill-check' AND COALESCE(json_extract(request_json, '$.skill.run'), '') NOT LIKE 'check-%' AND NOT EXISTS (SELECT 1 FROM generation_trash t WHERE t.generation_id = generations.id)+ GROUP BY name`,+ )+ .all() as { name: string; runs: number; last: number }[];+ return new Map(rows.map((r) => [r.name, { runs: r.runs, last: r.last }]));+ } catch {+ return new Map();+ }+}++const RECENT_MS = 30 * 86_400_000;++/**+ * Skills in the order Assist offers them: those matching more of the words first (when there are words), then those used+ * in the last 30 days, then by how often and how lately they ran; the rest keep their order. A skill that matches none of+ * the words is left out when some match.+ */+export function rankSkills<T extends { name: string; title: string; description: string; whenToUse?: string }>(list: T[], o: { words?: string; usage?: Map<string, { runs: number; last: number }>; now?: number } = {}): T[] {+ const usage = o.usage ?? skillUsage();+ const now = o.now ?? Date.now();+ const words = (o.words ?? "").toLowerCase().split(/\s+/).filter(Boolean);+ const scored = list.map((s, i) => {+ const hay = `${s.name} ${s.title} ${s.description} ${s.whenToUse ?? ""}`.toLowerCase();+ const u = usage.get(s.name);+ return { s, i, match: words.filter((w) => hay.includes(w)).length, recent: u && now - u.last < RECENT_MS ? 1 : 0, runs: u?.runs ?? 0, last: u?.last ?? 0 };+ });+ const kept = words.length && scored.some((x) => x.match) ? scored.filter((x) => x.match) : scored;+ return kept.sort((a, b) => b.match - a.match || b.recent - a.recent || b.runs - a.runs || b.last - a.last || a.i - b.i).map((x) => x.s);+}diff --git a/tests/assist-schedule.test.ts b/tests/assist-schedule.test.tsindex 78443396..7ccc9beb 100644--- a/tests/assist-schedule.test.ts+++ b/tests/assist-schedule.test.ts@@ -157,6 +157,8 @@ describe("what a scheduled run may start on its own", () => {expect(spendOf([{ costUsd: 0.15, demo: true }])).toBe(0);expect(spendOf([{ costUsd: 0.15, demo: false }, { costUsd: 0.5, demo: false }])).toBe(0.65);expect(spendOf([{ costUsd: null, demo: false }])).toBeNull();+ // A price guessed before an earlier step's result exists can't count against a cap.+ expect(spendOf([{ costUsd: 0.5, demo: false, estimate: true }])).toBeNull();expect(spendOf([{ costUsd: null, demo: false, error: "no input" }, { costUsd: 1, demo: false }])).toBe(1);});});diff --git a/tests/assist-skill-tools.test.ts b/tests/assist-skill-tools.test.tsindex 544da9c0..b61a523c 100644--- a/tests/assist-skill-tools.test.ts+++ b/tests/assist-skill-tools.test.ts@@ -212,7 +212,7 @@ describe("draftFromThread", () => {expect(draft!.notes.join(" ")).toMatch(/An earlier try of a step was left out/);});- it("refuses a generate result passed into a studio call, as the studio call really answered", async () => {+ it("makes a generate result passed into a studio call a step reference (a recipe that runs in stages), as the studio call really answered", async () => {// A clip made in the chat, then captioned in the chat: both calls run through the agent, approved on their cards.const t = await chatRun("open", [{ id: "toolu_clip", name: "generate", input: { summary: "Clip", jobs: [{ model_id: "kling-3", op: "i2v", prompt: "the lamp turns", images: [photo], duration: 5 }] } },@@ -221,8 +221,13 @@ describe("draftFromThread", () => {await chatRun("open", [{ id: "toolu_caps", name: "add_captions", input: { video: made.outputs[0].url, translate_to: "Spanish" } }], t);await settle(threadIds(t));const { draft, refusals } = builder.draftFromThread(t);- expect(refusals).toEqual([{ id: expect.any(String), title: "Captions in Spanish", reason: builder.STUDIO_WAIT }]);- expect(draft!.recipe.steps.map((s) => s.kind)).toEqual(["generate"]);+ expect(refusals).toEqual([]);+ expect(draft!.recipe.fuobeRecipe).toBe(2);+ const [clipStep, caps] = draft!.recipe.steps;+ expect([clipStep.kind, caps.kind]).toEqual(["generate", "tool"]);+ expect(caps.kind === "tool" && caps.input).toEqual({ video: `{{steps.${clipStep.key}.output}}`, translate_to: "Spanish" });+ // The clip's file isn't an input any more: the next run feeds the new clip on.+ expect(draft!.candidates.some((c) => c.example === made.outputs[0].url)).toBe(false);});/** Each studio tool as it really answers (a studio that opened, Katana's final cut), run through the agent in demo mode. */diff --git a/tests/canvas-recipe.test.ts b/tests/canvas-recipe.test.tsnew file mode 100644index 00000000..328712ba--- /dev/null+++ b/tests/canvas-recipe.test.ts@@ -0,0 +1,110 @@+import { describe, expect, it } from "vitest";+import { canvasToRecipe, CANT_DRAW, recipeToCanvas } from "@/lib/catalog/canvas-recipe";+import type { CanvasGraph } from "@/lib/catalog/canvas";+import { RecipeSchema, recipeProblems, type Recipe } from "@/lib/recipe";++/** Skills W5: a skill's recipe drawn as a canvas and back, and a canvas (with a Table) turned into a skill's recipe. */++const photo = "/api/files/uploads/2026-11-01/lamp.png";++/** A portrait from words, then a clip from it, then a clip from a photo of the product: drawable as it is. */+const drawable = (): Recipe =>+ RecipeSchema.parse({+ fuobeRecipe: 1,+ params: [+ { id: "subject", label: "Subject", type: "text", required: true, example: "a ceramicist at her wheel" },+ { id: "product", label: "Product photo", type: "image", required: true, example: photo },+ ],+ steps: [+ { key: "portrait", label: "Portrait", kind: "generate", request: { feature: "skill", modelId: "nano-banana-pro", op: "t2i", prompt: "{{subject}}, editorial portrait", params: { aspectRatio: "4:5" } } },+ { key: "clip", label: "Clip", kind: "generate", after: "portrait", chain: [{ slot: "images" }], request: { feature: "skill", modelId: "kling-3", op: "i2v", prompt: "she looks up and smiles", params: { duration: 5 } } },+ { key: "still", label: "Product still", kind: "generate", request: { feature: "skill", modelId: "nano-banana-pro", op: "edit", prompt: "on a travertine plinth", inputs: { images: ["{{product}}"] } } },+ ],+ });++describe("a recipe as a canvas", () => {+ it("draws inputs as input nodes and steps as model nodes, with an edge per link, and comes back the same", () => {+ const recipe = drawable();+ const { graph, readOnly } = recipeToCanvas(recipe);+ expect(readOnly).toBeUndefined();+ expect(graph.nodes.map((n) => [n.id, n.type])).toEqual([+ ["in-subject", "prompt"],+ ["in-product", "image-input"],+ ["portrait", "model"],+ ["clip", "model"],+ ["still", "model"],+ ]);+ expect(graph.edges.map((e) => [e.source, e.target, e.targetHandle])).toEqual([+ ["in-subject", "portrait", "prompt"],+ ["portrait", "clip", "images"],+ ["in-product", "still", "images"],+ ]);+ // The input node shows the example; the model node's own words keep where the input goes.+ expect(graph.nodes[0].data.text).toBe("a ceramicist at her wheel");+ expect(graph.nodes[2].data.prompt).toBe("{text}, editorial portrait");+ const back = canvasToRecipe(graph);+ expect("error" in back).toBe(false);+ if ("error" in back) return;+ expect(back.refusals).toEqual([]);+ expect(back.recipe.params).toEqual(recipe.params);+ expect(back.recipe.steps).toEqual(recipe.steps);+ expect(recipeProblems(back.recipe)).toEqual([]);+ });++ it("takes a model swapped on the canvas back into the step", () => {+ const { graph } = recipeToCanvas(drawable());+ const node = graph.nodes.find((n) => n.id === "still")!;+ node.data.modelId = "seedream-5-pro";+ const back = canvasToRecipe(graph);+ if ("error" in back) throw new Error(back.error);+ expect(back.recipe.steps.find((s) => s.key === "still")).toMatchObject({ request: { modelId: "seedream-5-pro", inputs: { images: ["{{product}}"] } } });+ });++ it("opens read-only what it can't draw: a slot with no port, part of a result, several inputs in one prompt, a studio step", () => {+ const base = drawable();+ const audio2 = { ...base, steps: [{ ...base.steps[0], request: { ...(base.steps[0] as { request: object }).request, inputs: { audio2: photo } } }] } as Recipe;+ expect(recipeToCanvas(audio2).readOnly).toMatch(new RegExp(`^${CANT_DRAW}: step “portrait” takes audio2`));+ const position = { ...base, steps: [base.steps[0], { ...base.steps[1], chain: [{ slot: "images", position: "first" }] }] } as Recipe;+ expect(recipeToCanvas(position).readOnly).toMatch(/takes one part of an earlier result/);+ const words = { ...base, steps: [{ ...base.steps[0], request: { ...(base.steps[0] as { request: object }).request, prompt: "{{subject}} with {{product}}" } }] } as Recipe;+ expect(recipeToCanvas(words).readOnly).toMatch(/several inputs into its words/);+ const tool = RecipeSchema.parse({ fuobeRecipe: 1, params: [{ id: "video", label: "Video", type: "video", required: true }], steps: [{ key: "captions", kind: "tool", tool: "add_captions", input: { video: "{{video}}" } }] });+ const drawn = recipeToCanvas(tool);+ expect(drawn.graph.nodes.find((n) => n.id === "captions")).toMatchObject({ type: "note", data: { label: "Studio step" } });+ });+});++describe("a canvas as a recipe", () => {+ it("makes each model node a step, keeps files and words fixed, and a Table's columns inputs with its rows as runs", () => {+ const graph: CanvasGraph = {+ nodes: [+ { id: "t1", type: "table", position: { x: 0, y: 0 }, data: { columns: ["Product", "Colour"], rows: [["lamp", "red"], ["vase", "blue"], ["", ""]] } },+ { id: "img", type: "image-input", position: { x: 0, y: 300 }, data: { url: photo } },+ { id: "m1", type: "model", position: { x: 400, y: 0 }, data: { modelId: "nano-banana-pro", op: "edit", prompt: "a {Colour} {Product} on a plinth" } },+ { id: "note", type: "note", position: { x: 0, y: 600 }, data: { text: "not run" } },+ ],+ edges: [+ { id: "e1", source: "t1", target: "m1", sourceHandle: "out", targetHandle: "prompt" },+ { id: "e2", source: "img", target: "m1", sourceHandle: "out", targetHandle: "images" },+ ],+ };+ const out = canvasToRecipe(graph, { id: "cv1" });+ if ("error" in out) throw new Error(out.error);+ expect(out.recipe.params.map((p) => [p.id, p.type, p.example])).toEqual([+ ["Product", "text", "lamp"],+ ["Colour", "text", "red"],+ ]);+ expect(out.recipe.steps).toEqual([{ key: "m1", kind: "generate", request: expect.objectContaining({ feature: "skill", modelId: "nano-banana-pro", op: "edit", inputs: { images: [photo] } }) }]);+ expect((out.recipe.steps[0] as { request: { prompt: string } }).request.prompt).toContain("a {{Colour}} {{Product}} on a plinth");+ expect(out.rows).toEqual([+ { Product: "lamp", Colour: "red" },+ { Product: "vase", Colour: "blue" },+ ]);+ expect(out.recipe.source).toMatchObject({ from: "canvas", canvas: "cv1" });+ expect(out.nodes).toEqual({ m1: "m1" });+ });++ it("says why a canvas with nothing to run can't be a skill", () => {+ expect(canvasToRecipe({ nodes: [{ id: "p", type: "prompt", position: { x: 0, y: 0 }, data: { text: "hi" } }], edges: [] })).toEqual({ error: "Add a model node first: a skill needs a step" });+ });+});diff --git a/tests/cli-run.test.ts b/tests/cli-run.test.tsindex 7eb61cb6..cc0ea35b 100644--- a/tests/cli-run.test.ts+++ b/tests/cli-run.test.ts@@ -471,12 +471,18 @@ describe("fuobe skills: a skill that runs by itself", () => {expect(posts("run")[0].json).toEqual({ values: { product: "/api/files/uploads/2026-10-22/up1.png", name: "Lumen" }, engine: "cloud" });});- it("--rows: one run per row, -p fills the empty cells, files beside the table go up once, and --json skips the question", async () => {+ it("--rows: one run per row, -p fills the empty cells, files beside the table go up once, and --json --yes skips the question", async () => {const dir = path.join(tmp, "products");fs.mkdirSync(dir, { recursive: true });fs.writeFileSync(path.join(dir, "lamp.png"), PNG);fs.writeFileSync(path.join(dir, "rows.csv"), "Product photo,Product name,Notes\nlamp.png,\"Lumen, desk\",first\n\nlamp.png,,second\n");- const r = await run(["skills", "run", "weekly-promo", "--rows", "products/rows.csv", "-p", "name=Halo", "--json"]);+ // --json alone never starts a run that costs money.+ const unasked = await run(["skills", "run", "weekly-promo", "--rows", "products/rows.csv", "-p", "name=Halo", "--json"]);+ expect(unasked.code).toBe(2);+ expect(unasked.stderr).toMatch(/add --yes to run without asking/);+ expect(posts("run")).toHaveLength(0);+ seen = [];+ const r = await run(["skills", "run", "weekly-promo", "--rows", "products/rows.csv", "-p", "name=Halo", "--json", "--yes"]);expect(r.code).toBe(0);expect(JSON.parse(r.stdout).runs).toHaveLength(2);expect(r.stderr).toContain("“Notes” isn't an input of /weekly-promo, so that column is left out.");diff --git a/tests/e2e/skills-w5-w7.mjs b/tests/e2e/skills-w5-w7.mjsnew file mode 100644index 00000000..29a2faab--- /dev/null+++ b/tests/e2e/skills-w5-w7.mjs@@ -0,0 +1,230 @@+// Skills W5 to W7 in a real browser (demo mode: no keys, ComfyUI unreachable), at 1440 and 390 px, light and dark:+// - W5: Canvas → Skills as canvases lists a skill that runs by itself and opens it as a canvas; the canvas menu has Save as skill…,+// which opens the review screen with the canvas's steps.+// - W6: three runs of the same chain offer it as a skill above the Library (Make a skill, Not now, Don't suggest this),+// and a skill's dialog shows its History.+// - W7: a skill whose steps wait across studios shows each step's progress in its dialog.+// A visitor (public sign-up) sees no suggestion, no history and no skills on the Canvas page. Nothing scrolls sideways.+// (A scheduled task that runs a skill, W4, has its own check: tests/e2e/schedule-skill.mjs.)+// Usage: node tests/e2e/skills-w5-w7.mjs [appUrl] [--shots <dir>] (app running with FUOBE_DEMO_MODE=on). Exits 1 on a failed check.+// E2E_OWNER_PASSWORD: the studio's password, when it has one (the owner's checks sign in with it, and the guest's+// checks run too: start the app with FUOBE_PASSWORD and FUOBE_PUBLIC_SIGNUP=1).+import fs from "node:fs";+import path from "node:path";+import { launch, openRoute, root } from "./_browser.mjs";++const argv = process.argv.slice(2);+const app = (argv.find((a) => !a.startsWith("--") && argv[argv.indexOf(a) - 1] !== "--shots") ?? "http://localhost:3000").replace(/\/$/, "");+const shots = argv.includes("--shots") ? argv[argv.indexOf("--shots") + 1] : undefined;+if (shots) fs.mkdirSync(shots, { recursive: true });++const failures = [];+const check = (label, ok, extra = "") => {+ console.log(`${ok ? "ok " : "FAIL"} ${label.padEnd(80)}${extra ? ` ${extra}` : ""}`);+ if (!ok) failures.push(label);+};+const PASSWORD = process.env.E2E_OWNER_PASSWORD;+let ownerCookie = "";+if (PASSWORD) {+ const res = await fetch(`${app}/api/auth/login`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ password: PASSWORD }) });+ ownerCookie = res.headers.getSetCookie().map((c) => c.split(";")[0]).join("; ");+ if (!res.ok || !ownerCookie) throw new Error(`couldn't sign in as the owner: ${res.status}`);+}+/** The owner's requests (signed in when the studio has a password). */+const ownerFetch = (url, init = {}) => fetch(url, { ...init, headers: { ...init.headers, ...(ownerCookie && { cookie: ownerCookie }) } });+const send = (method, route, body) => ownerFetch(app + route, { method, headers: { "content-type": "application/json" }, body: body === undefined ? undefined : JSON.stringify(body) });+const json = async (method, route, body) => {+ const r = await send(method, route, body);+ return { ok: r.ok, status: r.status, body: await r.json().catch(() => null) };+};++async function upload(file, type, name) {+ const form = new FormData();+ form.append("file", new Blob([fs.readFileSync(path.join(root, file))], { type }), name);+ const res = await ownerFetch(`${app}/api/uploads`, { method: "POST", body: form });+ if (!res.ok) throw new Error(`upload failed: ${res.status}`);+ return (await res.json()).url;+}++async function settled(ids, ms = 120_000) {+ const until = Date.now() + ms;+ while (Date.now() < until) {+ const all = await Promise.all(ids.map(async (id) => (await (await ownerFetch(`${app}/api/generations/${id}`)).json()).status));+ if (all.every((s) => ["succeeded", "failed", "canceled"].includes(s))) return true;+ await new Promise((r) => setTimeout(r, 1000));+ }+ return false;+}++// ---------------------------------------------------------------------------+// Seed++const photo = await upload("public/samples/grade-sample.jpg", "image/jpeg", "lamp.jpg");+const clip = await upload("public/samples/demo-landscape.mp4", "video/mp4", "talk.mp4");+const POSTER = "e2e-w4-poster";+const SHORT = "e2e-w7-short";+for (const n of [POSTER, SHORT]) await send("DELETE", `/api/assist/skills/${n}`);+await send("POST", "/api/assist/skills", { name: POSTER, title: "E2E Poster", description: "A product poster from a product photo.", body: "# Poster" });+const put = await json("PUT", `/api/assist/skills/${POSTER}/recipe`, {+ fuobeRecipe: 1,+ params: [+ { id: "product", label: "Product photo", type: "image", required: true, example: photo },+ { id: "name", label: "Product name", type: "text", required: true, example: "Lumen desk lamp", max: 200 },+ ],+ steps: [+ { key: "cutout", kind: "generate", label: "Cut-out", request: { feature: "skill", modelId: "birefnet-cloud", op: "bg-remove", inputs: { images: ["{{product}}"] } } },+ { key: "scene", kind: "generate", label: "Poster", after: "cutout", chain: [{ slot: "images" }], request: { feature: "skill", modelId: "nano-banana-pro", op: "edit", prompt: "{{name}} on a travertine plinth" } },+ ],+});+check("seed: a recipe skill saves", put.ok, put.ok ? "" : JSON.stringify(put.body));+await json("POST", `/api/assist/skills/${POSTER}/verify`, { level: "plan" });+const run = await json("POST", `/api/assist/skills/${POSTER}/run`, { values: { product: photo, name: "Halo lamp" }, engine: "cloud" });+check("seed: the skill runs once (its History)", run.ok, run.ok ? "" : JSON.stringify(run.body));+if (run.ok) await settled(run.body.runs[0].ids);++await send("POST", "/api/assist/skills", { name: SHORT, title: "E2E Spanish short", description: "Dub, caption and cut a clip.", body: "# Short" });+const staged = await json("PUT", `/api/assist/skills/${SHORT}/recipe`, {+ fuobeRecipe: 2,+ params: [{ id: "clip", label: "Clip", type: "video", required: true, example: clip }],+ steps: [+ { key: "dub", label: "Dub", kind: "tool", tool: "dub_video", input: { video: "{{clip}}", languages: ["Spanish"], lipsync: false, review: false } },+ { key: "captions", label: "Captions", kind: "tool", tool: "add_captions", input: { video: "{{steps.dub.output}}" } },+ { key: "cut", label: "9:16 cut", kind: "generate", request: { feature: "skill", modelId: "scale-video", op: "reframe", inputs: { video: "{{steps.captions.output}}" }, params: { aspectRatio: "9:16" } } },+ ],+});+check("seed: a skill that waits across studios saves", staged.ok, staged.ok ? "" : JSON.stringify(staged.body));+await json("POST", `/api/assist/skills/${SHORT}/verify`, { level: "plan", engine: "cloud" });+const stagedRun = await json("POST", `/api/assist/skills/${SHORT}/run`, { values: { clip }, engine: "cloud" });+check("seed: it starts the dub and waits with the rest", stagedRun.ok && stagedRun.body.runs[0].waiting?.length === 2, JSON.stringify(stagedRun.body?.runs?.[0]?.waiting ?? stagedRun.body));++// Three runs of the same chain (cut-out → still → clip) through MCP's generate, with other words each time.+for (const w of ["a lamp", "a vase", "a chair"]) {+ const r = await json("POST", "/api/mcp", {+ jsonrpc: "2.0",+ id: 1,+ method: "tools/call",+ params: {+ name: "generate",+ arguments: {+ summary: `Turntable of ${w}`,+ jobs: [+ { model_id: "birefnet-cloud", op: "bg-remove", prompt: "", images: [photo] },+ { model_id: "nano-banana-pro", op: "edit", prompt: `${w} on a plinth`, after: 0 },+ { model_id: "kling-3", op: "i2v", prompt: `${w} turning`, after: 1, duration: 5 },+ ],+ engine: "cloud",+ },+ },+ });+ const text = r.body?.result?.content?.[0]?.text ?? "";+ const ids = [...text.matchAll(/"([\w-]{12})"/g)].map((m) => m[1]);+ check(`seed: a chain for ${w} starts`, r.ok && ids.length > 0, r.ok ? "" : JSON.stringify(r.body));+ if (ids.length) await settled([...new Set(ids)]);+}++// ---------------------------------------------------------------------------+// The browser++const seen = (locator, ms = 20_000) =>+ locator+ .first()+ .waitFor({ state: "visible", timeout: ms })+ .then(() => true)+ .catch(() => false);+const noSideScroll = (page) => page.evaluate(() => document.documentElement.scrollWidth <= document.documentElement.clientWidth);+const shot = (page, name) => shots && page.screenshot({ path: path.join(shots, `${name}.png`) });++const browser = await launch();+try {+ for (const scheme of ["light", "dark"]) {+ for (const [width, height] of [+ [1440, 900],+ [390, 844],+ ]) {+ const tag = `${width}-${scheme}`;+ const phone = width < 600;+ const ctx = await browser.newContext({ viewport: { width, height }, colorScheme: scheme, ...(phone && { isMobile: true, hasTouch: true }) });+ if (PASSWORD) await ctx.request.post(`${app}/api/auth/login`, { data: { password: PASSWORD } });+ const page = await ctx.newPage();++ // W6 + W7: the skill's History, and the run that waits across studios.+ await openRoute(page, `${app}/assist/skills?skill=${POSTER}`);+ check(`${tag} history: the skill's runs show in its dialog`, await seen(page.getByRole("dialog").getByText(/\b\d+ runs?\b/)));+ await shot(page, `history-${tag}`);+ await openRoute(page, `${app}/assist/skills?skill=${SHORT}`);+ check(`${tag} runs in stages: each step's progress shows`, await seen(page.getByRole("dialog").locator("[data-skill-run]")));+ check(`${tag} runs in stages: the steps are named`, await seen(page.getByRole("dialog").getByText(/Captions ·/)));+ check(`${tag} history: nothing scrolls sideways`, await noSideScroll(page));+ await shot(page, `run-steps-${tag}`);++ // W6: the suggestion above the Library.+ await openRoute(page, `${app}/library`);+ const card = page.locator("[data-skill-suggestion]");+ check(`${tag} library: a chain made 3 times is offered as a skill`, await seen(card, 30_000));+ check(`${tag} library: Make a skill, Not now and Don't suggest this`, (await card.getByRole("button").count()) === 3);+ check(`${tag} library: nothing scrolls sideways`, await noSideScroll(page));+ await shot(page, `suggestion-${tag}`);+ await card.getByRole("button", { name: /Make a skill/ }).click();+ check(`${tag} library: Make a skill opens the review screen`, await seen(page.getByRole("dialog").getByText("Make a skill")));+ await page.keyboard.press("Escape");++ // W5: Canvas → Skills as canvases, Open as canvas, then Save as skill… from its menu.+ await openRoute(page, `${app}/canvas?tab=skills`);+ check(`${tag} canvas: Skills as canvases lists the skill`, await seen(page.locator("[data-skill-canvases]").getByText("E2E Poster")));+ check(`${tag} canvas: a skill a canvas can't hold says why`, await seen(page.getByText(/This skill can't be drawn yet/)));+ check(`${tag} canvas: nothing scrolls sideways`, await noSideScroll(page));+ await shot(page, `canvas-skills-${tag}`);+ if (!phone) {+ await page.locator("article", { hasText: "E2E Poster" }).getByRole("button", { name: /Open as canvas/ }).click();+ await page.waitForURL(/\/canvas\/[\w-]+$/, { timeout: 30_000 });+ check(`${tag} canvas: Open as canvas draws its steps`, await seen(page.getByText("Poster").first()));+ await page.getByRole("button", { name: "More run options" }).click();+ await page.getByRole("menuitem", { name: /Save as skill/ }).click();+ check(`${tag} canvas: Save as skill… opens the review screen`, await seen(page.getByRole("dialog").getByText(/From this canvas/)));+ await shot(page, `canvas-save-skill-${tag}`);+ await page.keyboard.press("Escape");+ }+ await ctx.close();+ }+ }++ // A visitor under public sign-up: the owner's suggestions, history and run steps stay the owner's.+ if (PASSWORD) {+ const guest = await fetch(`${app}/api/skill-suggestions`).then((r) => r.json());+ check("guest: no skill suggestions", Array.isArray(guest.items) && guest.items.length === 0, JSON.stringify(guest));+ const history = await fetch(`${app}/api/assist/skills/${POSTER}/history`);+ check("guest: a skill's history is refused", !history.ok, String(history.status));+ const dismiss = await fetch(`${app}/api/skill-suggestions`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ id: "x", how: "never" }) });+ check("guest: dismissing a suggestion is refused", !dismiss.ok, String(dismiss.status));+ for (const scheme of ["light", "dark"]) {+ for (const [width, height] of [+ [1440, 900],+ [390, 844],+ ]) {+ const tag = `guest-${width}-${scheme}`;+ const phone = width < 600;+ const ctx = await browser.newContext({ viewport: { width, height }, colorScheme: scheme, ...(phone && { isMobile: true, hasTouch: true }) });+ const page = await ctx.newPage();+ await openRoute(page, `${app}/library`, { settleMs: 2500 });+ check(`${tag} library: no skill suggestion`, (await page.locator("[data-skill-suggestion]").count()) === 0);+ check(`${tag} library: nothing scrolls sideways`, await noSideScroll(page));+ await shot(page, `guest-library-${tag}`);+ await openRoute(page, `${app}/canvas?tab=skills`, { settleMs: 2500 });+ check(`${tag} canvas: the page opens`, await seen(page.locator("main").first()));+ check(`${tag} canvas: no skills for a visitor`, (await page.locator("[data-skill-canvases], #skills").count()) === 0);+ check(`${tag} canvas: no Open as canvas for a visitor`, (await page.getByRole("button", { name: /Open as canvas/ }).count()) === 0);+ check(`${tag} canvas: nothing scrolls sideways`, await noSideScroll(page));+ await shot(page, `guest-canvas-skills-${tag}`);+ await ctx.close();+ }+ }+ }+} finally {+ await browser.close();+}++// Leave the studio as it was found.+for (const n of [POSTER, SHORT]) await send("DELETE", `/api/assist/skills/${n}`);++console.log(failures.length ? `\n${failures.length} failed` : "\nall passed");+process.exit(failures.length ? 1 : 0);diff --git a/tests/public-signup-visitors.test.ts b/tests/public-signup-visitors.test.tsindex 1e853a36..1a292269 100644--- a/tests/public-signup-visitors.test.ts+++ b/tests/public-signup-visitors.test.ts@@ -102,6 +102,9 @@ describe("Assist is the owner's", () => {["POST", "/api/assist/skills/draft/name"],["PATCH", "/api/assist/skills/ad-multiplier"],["POST", "/api/assist/skills/product-photoshoot/run"],+ // A skill's Suggest a fix (W6) and a schedule that runs a skill (W4).+ ["POST", "/api/assist/skills/product-photoshoot/fixes"],+ ["PATCH", "/api/assist/schedules/s1"],["POST", "/api/assist/memory"],["POST", "/api/assist/memory/import"],["POST", "/api/assist/projects"],@@ -213,3 +216,20 @@ describe("an account's own Library", () => {expect((await bulk({ action: "pin", ids: ["owner-1"] })).status).toBe(401);});});++describe("skills in use (W6, W7) are the owner's", () => {+ it("gives a guest and an account no suggestions, and refuses the rest of a skill's runs", async () => {+ for (const cookie of [undefined, account, gpuAccount]) {+ const who = cookie ? "account" : "guest";+ const list = proxy(req("/api/skill-suggestions", { cookie }));+ expect(list.status, who).toBe(200);+ expect(await list.json(), who).toEqual({ items: [] });+ // Dismissing one changes the owner's settings.+ expect(passed(proxy(req("/api/skill-suggestions", { method: "POST", cookie }))), who).toBe(false);+ // A skill's run history, its fixes and its steps' progress are the owner's runs.+ for (const p of ["/api/assist/skills/product-photoshoot/history", "/api/assist/skills/product-photoshoot/fixes"]) expect(passed(proxy(req(p, { cookie }))), `${p} ${who}`).toBe(false);+ }+ for (const p of ["/api/skill-suggestions", "/api/assist/skills/product-photoshoot/history", "/api/assist/skills/product-photoshoot/fixes"]) expect(passed(proxy(req(p, { cookie: owner }))), p).toBe(true);+ expect(passed(proxy(req("/api/skill-suggestions", { method: "POST", cookie: owner })))).toBe(true);+ });+});diff --git a/tests/recipe.test.ts b/tests/recipe.test.tsindex 48d80383..d9621bd4 100644--- a/tests/recipe.test.ts+++ b/tests/recipe.test.ts@@ -68,7 +68,7 @@ describe("the recipe format", () => {it("refuses what isn't a recipe: a version, caps, an empty graph, bad JSON", () => {expect(parseRecipe("{")).toEqual({ ok: false, error: "recipe.json isn't valid JSON" });- expect(parseRecipe(JSON.stringify({ ...lamp(), fuobeRecipe: 2 }))).toMatchObject({ ok: false, error: expect.stringContaining("fuobeRecipe") });+ expect(parseRecipe(JSON.stringify({ ...lamp(), fuobeRecipe: 3 }))).toMatchObject({ ok: false, error: expect.stringContaining("fuobeRecipe") });expect(parseRecipe(JSON.stringify({ ...lamp(), steps: [] }))).toMatchObject({ ok: false, error: expect.stringContaining("a recipe needs a step") });const many = Array.from({ length: RECIPE_LIMITS.params + 1 }, (_, i) => ({ id: `p${i}`, label: `P ${i}`, type: "text" }));expect(parseRecipe(JSON.stringify({ ...lamp(), params: many }))).toMatchObject({ ok: false, error: expect.stringContaining("at most 12 inputs") });diff --git a/tests/recipes.test.ts b/tests/recipes.test.tsindex 768f6e43..89128acd 100644--- a/tests/recipes.test.ts+++ b/tests/recipes.test.ts@@ -466,3 +466,95 @@ describe("the recipe routes", () => {expect((await recipeRoute.GET(new Request("http://x"), ctx("nope"))).status).toBe(404);});});++describe("a skill in use (W6)", () => {+ const insights = () => import("@/server/skill-insights");+ const usage = () => import("@/server/skill-usage");+ const mark = (ids: string[], status: string, error: string | null = null) =>+ db()+ .prepare(`UPDATE generations SET status = ?, error = ?, cost_usd = 0.5 WHERE id IN (${ids.map(() => "?").join(", ")})`)+ .run(status, error, ...ids);++ it("keeps a history of its runs from the stamp each run carries", async () => {+ makeSkill("history-lamp", lamp());+ await recipes.verifyRecipe("history-lamp", "plan", "cloud");+ const a = await recipes.runRecipe("history-lamp", { values: { product: photo, name: "Halo" } }, "cloud");+ const b = await recipes.runRecipe("history-lamp", { values: { product: photo, name: "Arc" } }, "cloud");+ mark(a.runs[0].ids, "succeeded");+ mark(b.runs[0].ids.slice(0, 1), "succeeded");+ mark(b.runs[0].ids.slice(1), "failed", "The provider said no");+ const h = (await insights()).skillHistory("history-lamp");+ expect(h).toMatchObject({ runs: 2, successRate: 0.5, spendUsd: 3, favorites: 0 });+ expect(h.recent.map((r) => [r.run, r.status, r.steps])).toEqual([+ [b.runs[0].batchId, "failed", 3],+ [a.runs[0].batchId, "succeeded", 3],+ ]);+ expect(h.recent[0].failed.map((f) => f.model)).toEqual(["nano-banana-pro", "kling-3"]);+ // Through its route.+ const route = await import("@/app/api/assist/skills/[name]/history/route");+ const res = await route.GET(new Request("http://x"), { params: Promise.resolve({ name: "history-lamp" }) } as never);+ expect(await res.json()).toMatchObject({ runs: 2, waiting: [] });+ });++ it("suggests a fix for a step that failed in 2 of its last 5 runs: models with the same operation and kind, switched on", async () => {+ makeSkill("fix-lamp", lamp());+ await recipes.verifyRecipe("fix-lamp", "plan", "cloud");+ for (const name of ["One", "Two"]) {+ const r = await recipes.runRecipe("fix-lamp", { values: { product: photo, name } }, "cloud");+ mark(r.runs[0].ids.slice(0, 1), "succeeded");+ mark(r.runs[0].ids.slice(1, 2), "failed", "Timed out");+ mark(r.runs[0].ids.slice(2), "canceled");+ }+ const fixes = (await insights()).fixCandidates("fix-lamp");+ expect(fixes.steps.map((s) => s.key)).toEqual(["scene"]);+ const scene = fixes.steps[0];+ expect(scene.reasons).toEqual(["It failed in 2 of the last 2 runs"]);+ expect(scene.candidates.length).toBeGreaterThan(1);+ const { getModel } = await import("@/lib/catalog");+ const { isOffered } = await import("@/server/model-access");+ for (const c of scene.candidates) {+ const m = getModel(c.modelId)!;+ expect(m.kind, c.modelId).toBe("image");+ expect(m.routes.map((x) => x.op), c.modelId).toContain("edit");+ expect(isOffered(c.modelId), c.modelId).toBe(true);+ expect(c.modelId).not.toBe("nano-banana-pro");+ }+ // A model switched off isn't offered.+ const off = scene.candidates[0].modelId;+ changeAccess([{ kind: "model", id: off, on: false }]);+ try {+ expect((await insights()).fixCandidates("fix-lamp").steps[0].candidates.map((c) => c.modelId)).not.toContain(off);+ } finally {+ changeAccess([{ kind: "model", id: off, on: true }]);+ }+ // Picking one swaps the step and checks the skill again; anything not offered is refused.+ const pick = scene.candidates.find((c) => !c.problem)!;+ await expect((await insights()).applyFix("fix-lamp", "scene", "kling-3")).rejects.toThrow(/Pick one of the models offered/);+ const done = await (await insights()).applyFix("fix-lamp", "scene", pick.modelId);+ expect(done).toEqual({ ok: true, problems: [] });+ const now = recipes.recipeView("fix-lamp");+ expect(now.recipe.steps[1]).toMatchObject({ request: { modelId: pick.modelId } });+ expect(now.recipe.verified?.cloud?.dryRun).toBe(today());+ });++ it("ranks the skills Assist offers by the words, then by how often and how lately they ran", async () => {+ const { rankSkills } = await usage();+ const list = [+ { name: "a", title: "Alpha", description: "posters" },+ { name: "b", title: "Beta", description: "product posters" },+ { name: "c", title: "Gamma", description: "videos" },+ ];+ const now = Date.now();+ const used = new Map([+ ["c", { runs: 5, last: now - 86_400_000 }],+ ["a", { runs: 1, last: now - 40 * 86_400_000 }],+ ]);+ expect(rankSkills(list, { usage: used, now }).map((s) => s.name)).toEqual(["c", "a", "b"]);+ expect(rankSkills(list, { words: "product posters", usage: used, now }).map((s) => s.name)).toEqual(["b", "a"]);+ // From the stamps: the skill that ran comes first.+ const real = (await usage()).skillUsage();+ expect(real.get("history-lamp")?.runs).toBe(2);+ const ranked = rankSkills(skills.enabledSkills()).map((s) => s.name);+ expect(ranked.indexOf("history-lamp")).toBeLessThan(ranked.indexOf("product-photoshoot"));+ });+});diff --git a/tests/skill-runs.test.ts b/tests/skill-runs.test.tsnew file mode 100644index 00000000..a32d47a5--- /dev/null+++ b/tests/skill-runs.test.ts@@ -0,0 +1,272 @@+import fs from "node:fs";+import os from "node:os";+import path from "node:path";+import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";++vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));+vi.setConfig({ testTimeout: 180_000 });++/**+ * Skills W7: a skill whose steps wait across studios ("dub, then captions, then a 9:16 cut") runs as a skill_runs row:+ * each step starts when the step it takes a result from is done, a failure fails the steps after it with the reason,+ * the state survives a restart, and the free dry run deletes the studio records it made.+ */++const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-skill-runs-"));+process.env.FUOBE_DATA_DIR = dir;+process.env.COMFYUI_URL = "http://127.0.0.1:9";+process.env.OLLAMA_URL = "http://127.0.0.1:9";++const { setSetting } = await import("@/server/settings");+const recipes = await import("@/server/recipes");+const runs = await import("@/server/skill-runs");+const skills = await import("@/server/skills");+const gens = await import("@/server/generations");+const { db } = await import("@/server/db");+const { saveFile } = await import("@/server/storage");+const { recipeProblems, parseRecipe, isStaged } = await import("@/lib/recipe");+const { runAsDemo, inDemoScope, outsideDemo } = await import("@/server/demo-scope");+const { spendOf } = await import("@/lib/assist-schedule");+const tools = await import("@/server/assist/tools");++afterAll(() => {+ try {+ fs.rmSync(dir, { recursive: true, force: true });+ } catch {+ // Windows keeps the open database.+ }+});++let clip = "";+beforeAll(() => {+ setSetting("demoMode", "auto");+ setSetting("enhanceProvider", "none");+ clip = saveFile({ data: fs.readFileSync(path.join(__dirname, "fixtures/shorts-12s.mp4")), contentType: "video/mp4", source: "upload", name: "talk.mp4" }).url;+});++async function settle(ids: string[], ms = 90_000) {+ const until = Date.now() + ms;+ for (;;) {+ const all = ids.map((id) => gens.getGeneration(id, { includeDeleted: true })!);+ if (all.every((g) => ["succeeded", "failed", "canceled"].includes(g.status))) return all;+ if (Date.now() > until) throw new Error(`timed out: ${all.map((g) => `${g.id} ${g.status} ${g.message}`).join(", ")}`);+ await new Promise((r) => setTimeout(r, 300));+ }+}++/** Sweep until the run stops going, letting the generation runner finish each step's work. */+async function finish(id: string, ms = 150_000) {+ const until = Date.now() + ms;+ for (;;) {+ const status = await runs.advanceSkillRun(id);+ if (status !== "running") return status;+ const ids = runs.getSkillRun(id)!.steps.filter((s) => s.status === "running").flatMap((s) => s.ids);+ if (ids.length) await settle(ids);+ if (Date.now() > until) throw new Error("the run didn't finish");+ }+}++/** Dub (a studio), then captions on the dub (a studio), then a 9:16 cut of the captioned clip (a model). */+const spanishShort = () => ({+ fuobeRecipe: 2,+ params: [{ id: "clip", label: "Clip", type: "video", required: true, example: clip }],+ steps: [+ { key: "dub", label: "Dub", kind: "tool", tool: "dub_video", input: { video: "{{clip}}", languages: ["Spanish"], lipsync: false, review: false } },+ { key: "captions", label: "Captions", kind: "tool", tool: "add_captions", input: { video: "{{steps.dub.output}}" } },+ { key: "cut", label: "9:16 cut", kind: "generate", request: { feature: "skill", modelId: "scale-video", op: "reframe", inputs: { video: "{{steps.captions.output}}" }, params: { aspectRatio: "9:16" } } },+ ],+});++function shortSkill(name = "spanish-short") {+ if (skills.getSkill(name)) return name;+ skills.createSkill({ name, title: "Spanish short", description: "Dub, caption and cut a clip for a Spanish short.", body: "# Spanish short" });+ recipes.saveRecipe(name, spanishShort());+ return name;+}++describe("the recipe format, version 2", () => {+ it("takes an earlier step's output by reference, checked against the step order and the kind it makes", () => {+ const parsed = parseRecipe(JSON.stringify(spanishShort()));+ expect(parsed.ok).toBe(true);+ const recipe = parsed.ok ? parsed.recipe : null!;+ expect(isStaged(recipe)).toBe(true);+ expect(recipeProblems(recipe)).toEqual([]);+ // A reference to a later step, to no step, and a kind that doesn't fit.+ const later = { ...recipe, steps: [recipe.steps[1], recipe.steps[0], recipe.steps[2]] };+ expect(recipeProblems(later)).toContain("Step “captions” takes the output of “dub”, which comes later: a step can only take an earlier step's output");+ const none = { ...recipe, steps: [recipe.steps[0], { ...recipe.steps[1], input: { video: "{{steps.nope.output}}" } }] } as typeof recipe;+ expect(recipeProblems(none)).toContain("Step “captions” takes the output of “nope”, which isn't a step");+ expect(recipeProblems(recipe, { kinds: { dub: "audio" } })).toContain("Step “captions” takes a video from “dub”, which makes a audio");+ // A dub for review makes no video until someone voices it: a later step can't take its result.+ const reviewed = { ...recipe, steps: recipe.steps.map((s) => (s.kind === "tool" && s.tool === "dub_video" ? { ...s, input: { ...s.input, review: true } } : s)) };+ expect(recipeProblems(reviewed)).toContain("Step “dub” dubs for review, so it makes no video for the steps after it: set \"review\": false to dub in one go");+ const unset = { ...recipe, steps: recipe.steps.map((s) => (s.kind === "tool" && s.tool === "dub_video" ? { ...s, input: { video: "{{clip}}", languages: ["Spanish"] } } : s)) };+ expect(recipeProblems(unset).some((p) => p.startsWith("Step “dub” dubs for review"))).toBe(true);+ // A step joined to another by `after` can't also take its output by reference (they start together).+ const cut = (key: string, video: string, after?: string) => ({ key, kind: "generate" as const, ...(after && { after }), request: { feature: "skill", modelId: "scale-video", op: "reframe", inputs: { video }, params: { aspectRatio: "9:16" } } });+ const joined = { ...recipe, steps: [recipe.steps[0], cut("a", "{{steps.dub.output}}"), cut("b", "{{steps.a.output}}", "a")] } as typeof recipe;+ expect(recipeProblems(joined)).toContain('Step “b” takes the output of “a”, which starts with it (they are joined by "after"): take it through "after" and a chain slot, or drop "after"');+ // Version 1 says what it needs.+ expect(recipeProblems({ ...recipe, fuobeRecipe: 1 })).toEqual(expect.arrayContaining([expect.stringMatching(/needs "fuobeRecipe": 2/)]));+ // On the server, the catalog says what each step makes.+ expect(recipes.allProblems(recipe)).toEqual([]);+ });++ it("is priced step by step, with stand-in files for the results steps wait for", () => {+ const name = shortSkill();+ const est = recipes.estimateRecipe(name, { values: { clip } }, "cloud");+ expect(est.errors).toEqual([]);+ expect(est.runs[0].errors).toEqual([]);+ expect(est.jobs.at(-1)).toMatchObject({ modelId: "scale-video", op: "reframe" });+ expect(est.runnable).toBe(true);+ // A step priced by the length of an earlier step's result is a guess: a spending cap holds it for a yes.+ const guessed = est.jobs.filter((j) => j.estimate);+ expect(guessed.length).toBeGreaterThan(0);+ expect(guessed.every((j) => j.note !== "Dub")).toBe(true);+ expect(spendOf(est.jobs.map((j) => ({ ...j, demo: false })))).toBeNull();+ });+});++describe("a run in stages", () => {+ it("starts the dub, waits, then starts the captions and the cut, each from the step before", async () => {+ const name = shortSkill();+ await recipes.verifyRecipe(name, "plan", "cloud");+ const out = await recipes.runRecipe(name, { values: { clip } }, "cloud");+ const run = out.runs[0];+ expect(run.skillRun).toBeTruthy();+ expect(run.waiting).toEqual(["Captions", "9:16 cut"]);+ expect(run.ids.length).toBeGreaterThan(0);+ const first = runs.getSkillRun(run.skillRun!)!;+ expect(first.steps.map((s) => [s.key, s.status])).toEqual([+ ["dub", "running"],+ ["captions", "waiting"],+ ["cut", "waiting"],+ ]);+ expect(first.steps[0].studio).toBeTruthy();+ // Every row it started carries the run's stamp.+ expect(gens.getGeneration(run.ids[0])!.request.skill).toEqual({ name, run: run.skillRun });+ expect(await finish(run.skillRun!)).toBe("done");+ const done = runs.getSkillRun(run.skillRun!)!;+ expect(done.steps.map((s) => s.status)).toEqual(["done", "done", "done"]);+ // The cut took the captioned clip, which took the dub.+ const cut = gens.getGeneration(done.steps[2].ids[0])!;+ const captions = gens.getGeneration(done.steps[1].ids.at(-1)!, { includeDeleted: true })!;+ expect(cut.request.inputs?.video).toMatch(/^\/api\/files\//);+ expect(captions.request.inputs?.video ?? JSON.stringify(captions.request)).not.toContain("{{steps.");+ expect(cut.request.inputs?.video).not.toBe(clip);+ expect(runs.listSkillRuns(name)[0]).toMatchObject({ id: run.skillRun, status: "done" });+ });++ it("a failed dub fails the steps after it, saying which step and why", async () => {+ const name = shortSkill();+ const out = await recipes.runRecipe(name, { values: { clip } }, "cloud");+ const id = out.runs[0].skillRun!;+ const dub = runs.getSkillRun(id)!.steps[0];+ // The dub's work fails (as a provider would fail it).+ const batches = db().prepare(`SELECT DISTINCT batch_id FROM generations WHERE id IN (${dub.ids.map(() => "?").join(", ")})`).all(...dub.ids) as { batch_id: string | null }[];+ db()+ .prepare(`UPDATE generations SET status = 'failed', error = 'No speech found in the clip' WHERE id IN (${dub.ids.map(() => "?").join(", ")}) OR batch_id IN (${batches.map(() => "?").join(", ") || "''"})`)+ .run(...dub.ids, ...batches.map((b) => b.batch_id));+ expect(await runs.advanceSkillRun(id)).toBe("failed");+ const r = runs.getSkillRun(id)!;+ expect(r.steps.map((s) => s.status)).toEqual(["failed", "failed", "failed"]);+ expect(r.error).toMatch(/^“Dub” failed/);+ expect(r.steps[1].error).toBe("“Dub” failed, so this didn't start");+ expect(r.steps[2].error).toBe("“Dub” failed, so this didn't start");+ });++ it("keeps its state in the database: a restart's sweep carries on", async () => {+ const name = shortSkill();+ await recipes.verifyRecipe(name, "plan", "cloud");+ const out = await recipes.runRecipe(name, { values: { clip } }, "cloud");+ const id = out.runs[0].skillRun!;+ await settle(runs.getSkillRun(id)!.steps[0].ids);+ // A restart: the database is opened again and the runner is gone.+ globalThis.__fuobeDb?.close();+ globalThis.__fuobeDb = undefined;+ // Opening the database clears the in-process demo setting ("auto"): set it again, as a test does.+ setSetting("demoMode", "auto");+ const timer = globalThis.__fuobeSkillRuns?.timer;+ if (timer) clearInterval(timer);+ globalThis.__fuobeSkillRuns = undefined;+ await runs.sweepSkillRuns();+ expect(runs.getSkillRun(id)!.steps.map((s) => s.status)).toEqual(["done", "running", "waiting"]);+ expect(await finish(id)).toBe("done");+ });+});++describe("checks of a run in stages", () => {+ it("the dry run runs the studios as demos, then deletes what they made", async () => {+ const name = shortSkill("spanish-short-check");+ const count = (t: string) => (db().prepare(`SELECT COUNT(*) AS n FROM ${t}`).get() as { n: number }).n;+ const before = { dub: count("dub_sessions"), runs: count("skill_runs") };+ const v = await recipes.verifyRecipe(name, "demo", "cloud");+ expect(v.engines[0].plan.errors).toEqual([]);+ expect(v.engines[0].dryRun).toMatchObject({ ok: true, problems: [] });+ expect(v.view.recipe.verified?.cloud?.dryRun).toBeTruthy();+ expect({ dub: count("dub_sessions"), runs: count("skill_runs") }).toEqual(before);+ // Its rows are in the Trash, and none shows in the skill's history.+ expect(runs.listSkillRuns(name)).toEqual([]);+ const left = db().prepare("SELECT id, feature, model_id, status, batch_id FROM generations g WHERE json_extract(request_json, '$.skill.name') = ? AND NOT EXISTS (SELECT 1 FROM generation_trash t WHERE t.generation_id = g.id)").all(name);+ expect(left).toEqual([]);+ });++ it("a dry run's steps run as demos whoever moves it on, and the sweep leaves it alone", async () => {+ const id = "check-sweep";+ const steps = JSON.parse(JSON.stringify(spanishShort().steps).replaceAll("{{clip}}", clip));+ const state = () => JSON.parse((db().prepare("SELECT state_json FROM skill_runs WHERE id = ?").get(id) as { state_json: string }).state_json) as { steps: { status: string; ids: string[] }[] };+ // Started and moved on outside any demo scope, as a sweep would.+ expect(inDemoScope()).toBe(false);+ await runs.startSkillRun({ id, skill: "spanish-short-sweep", title: "Sweep", engine: "cloud", values: { clip }, steps, check: true }).done;+ const dub = state().steps[0];+ expect(dub.status).toBe("running");+ await settle(dub.ids);+ const batchOf = (ids: string[]) => (db().prepare(`SELECT DISTINCT batch_id FROM generations WHERE id IN (${ids.map(() => "?").join(", ")}) AND batch_id IS NOT NULL`).all(...ids) as { batch_id: string }[]).map((b) => b.batch_id);+ await settle((db().prepare(`SELECT id FROM generations WHERE batch_id IN (${batchOf(dub.ids).map(() => "?").join(", ") || "''"})`).all(...batchOf(dub.ids)) as { id: string }[]).map((g) => g.id));+ // The sweep skips a dry run: the steps after the dub still wait.+ await runs.sweepSkillRuns();+ expect(state().steps.map((s) => s.status)).toEqual(["running", "waiting", "waiting"]);+ const until = Date.now() + 150_000;+ for (;;) {+ const status = await runs.advanceSkillRun(id);+ if (status !== "running") {+ expect(status).toBe("done");+ break;+ }+ const going = state().steps.filter((s) => s.status === "running").flatMap((s) => s.ids);+ if (going.length) await settle(going);+ if (Date.now() > until) throw new Error("the dry run didn't finish");+ }+ // Every row it made, the studios' later steps too, is a demo on the demo provider.+ const ids = state().steps.flatMap((s) => s.ids);+ const batches = batchOf(ids);+ const rows = db().prepare(`SELECT id, provider, request_json FROM generations WHERE id IN (${ids.map(() => "?").join(", ")}) OR batch_id IN (${batches.map(() => "?").join(", ") || "''"})`).all(...ids, ...batches) as { provider: string; request_json: string }[];+ expect(rows.length).toBeGreaterThan(2);+ for (const r of rows) expect({ provider: r.provider, demo: (JSON.parse(r.request_json) as { demo?: boolean }).demo }).toEqual({ provider: "mock", demo: true });+ db().prepare("DELETE FROM skill_runs WHERE id = ?").run(id);+ });++ it("the sweep's timer never keeps the demo scope it was first made in", async () => {+ expect(runAsDemo(() => outsideDemo(() => inDemoScope()))).toBe(false);+ const cur = globalThis.__fuobeSkillRuns;+ if (cur) clearInterval(cur.timer);+ globalThis.__fuobeSkillRuns = undefined;+ runAsDemo(() => runs.ensureSkillRunRunner());+ const seen = await new Promise<boolean>((res) => {+ globalThis.__fuobeSkillRuns!.tick = () => res(inDemoScope());+ });+ expect(seen).toBe(false);+ runs.ensureSkillRunRunner();+ });++ it("runAsDemo puts everything a studio starts on the demo provider", async () => {+ expect(inDemoScope()).toBe(false);+ const out = await runAsDemo(async () => {+ expect(inDemoScope()).toBe(true);+ return tools.executeTool("add_captions", { video: clip }, { engine: "cloud" });+ });+ const ids = (out.items ?? []).flatMap((i) => (i.role === "generations" ? i.ids : []));+ expect(ids.length).toBeGreaterThan(0);+ for (const id of ids) expect(gens.getGeneration(id)).toMatchObject({ provider: "mock", request: expect.objectContaining({ demo: true }) });+ });+});diff --git a/tests/skill-suggest.test.ts b/tests/skill-suggest.test.tsnew file mode 100644index 00000000..04f280ce--- /dev/null+++ b/tests/skill-suggest.test.ts@@ -0,0 +1,166 @@+import fs from "node:fs";+import os from "node:os";+import path from "node:path";+import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";++vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));+vi.setConfig({ testTimeout: 60_000 });++/**+ * Skills W6: Fuobe notices a chain of steps made again and again (the same models, operations and links, whatever the+ * words and files) and offers to save it as a skill, at most once a day, until it's saved or dismissed.+ */++const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-skill-suggest-"));+process.env.FUOBE_DATA_DIR = dir;+process.env.COMFYUI_URL = "http://127.0.0.1:9";+process.env.OLLAMA_URL = "http://127.0.0.1:9";++const { setSetting } = await import("@/server/settings");+const { createPipeline } = await import("@/server/chains");+const insights = await import("@/server/skill-insights");+const skills = await import("@/server/skills");+const recipes = await import("@/server/recipes");+const { db } = await import("@/server/db");+const { saveFile } = await import("@/server/storage");+const { encodePng } = await import("@/server/png");+const { shapeOf, recipeShapeNodes } = await import("@/lib/recipe");+const route = await import("@/app/api/skill-suggestions/route");++afterAll(() => {+ try {+ fs.rmSync(dir, { recursive: true, force: true });+ } catch {+ // Windows keeps the open database.+ }+});++let photo = "";+beforeAll(() => {+ setSetting("demoMode", "auto");+ photo = saveFile({ data: encodePng({ width: 32, height: 32, data: Buffer.alloc(32 * 32 * 4, 150) }), contentType: "image/png", source: "upload", name: "p.png" }).url;+});++/** Cut-out → scene → turntable, with its own words and photo each time; its rows marked done (the sweep reads those). */+function turntable(words: string, o: { feature?: string; at?: number } = {}) {+ const feature = o.feature ?? "image";+ const p = createPipeline([+ { key: "cut", request: { feature, modelId: "birefnet-cloud", op: "bg-remove", inputs: { images: [photo] } } },+ { key: "scene", after: "cut", chain: [{ slot: "images", position: "first" }], request: { feature, modelId: "nano-banana-pro", op: "edit", prompt: `${words} on a plinth` } },+ { key: "spin", after: "scene", chain: [{ slot: "images" }], request: { feature, modelId: "kling-3", op: "i2v", prompt: `${words} turning`, params: { duration: 5 } } },+ ]);+ const ids = p.items.map((g) => g.id);+ db()+ .prepare(`UPDATE generations SET status = 'succeeded', outputs_json = '[]', created_at = COALESCE(?, created_at) WHERE id IN (${ids.map(() => "?").join(", ")})`)+ .run(o.at ?? null, ...ids);+ return p;+}++const clear = () => db().exec("DELETE FROM generations; DELETE FROM settings WHERE key = 'skills.suggestions'");++describe("the shape of a chain", () => {+ it("is the same for the same chain with other words and files, and differs with another model or link", () => {+ const a = shapeOf([+ { id: "1", modelId: "birefnet-cloud", op: "bg-remove", after: [] },+ { id: "2", modelId: "nano-banana-pro", op: "edit", after: ["1"], slots: ["images"] },+ ]);+ const b = shapeOf([+ { id: "x", modelId: "nano-banana-pro", op: "edit", after: ["y"] },+ { id: "y", modelId: "birefnet-cloud", op: "bg-remove", after: [] },+ ]);+ expect(a!.key).toBe(b!.key);+ expect(a!.steps.map((s) => s.modelId)).toEqual(["birefnet-cloud", "nano-banana-pro"]);+ const other = shapeOf([+ { id: "1", modelId: "birefnet-cloud", op: "bg-remove", after: [] },+ { id: "2", modelId: "nano-banana-pro", op: "edit", after: ["1"], slots: ["endImage"] },+ ]);+ expect(other!.key).not.toBe(a!.key);+ expect(shapeOf([{ id: "1", modelId: "m", after: ["2"] }])).toBeNull();+ });++ it("of a recipe matches the runs it makes", () => {+ const p = turntable("a lamp");+ const recipe = {+ steps: [+ { key: "a", kind: "generate" as const, request: { feature: "skill", modelId: "birefnet-cloud", op: "bg-remove" as const } },+ { key: "b", kind: "generate" as const, after: "a", chain: [{ slot: "images" as const, position: "first" as const }], request: { feature: "skill", modelId: "nano-banana-pro", op: "edit" as const } },+ { key: "c", kind: "generate" as const, after: "b", chain: [{ slot: "images" as const }], request: { feature: "skill", modelId: "kling-3", op: "i2v" as const } },+ ],+ };+ const deps = (id: string) => {+ const v = (db().prepare("SELECT depends_on FROM generations WHERE id = ?").get(id) as { depends_on: string | null }).depends_on;+ return !v ? [] : v.startsWith("[") ? (JSON.parse(v) as string[]) : [v];+ };+ const fromRuns = shapeOf(p.items.map((g) => ({ id: g.id, modelId: g.modelId, op: g.request.op, after: deps(g.id), slots: deps(g.id).map((_, i) => g.request.chain?.[i]?.slot ?? "images") })));+ expect(fromRuns!.key).toBe(shapeOf(recipeShapeNodes(recipe)!)!.key);+ clear();+ });+});++describe("suggestions", () => {+ it("offer a chain made 3 times in 14 days, with the newest run's last step to draft from", async () => {+ clear();+ turntable("a lamp");+ turntable("a vase");+ expect(insights.skillSuggestions({ force: true })).toEqual([]);+ const newest = turntable("a chair");+ const [s] = insights.skillSuggestions({ force: true });+ expect(s).toMatchObject({ words: "Background removal → Image edit → Image to video", count: 3, demo: true, ids: [newest.byKey.spin.id] });+ // Through the route, as the Library reads it.+ expect(((await (await route.GET()).json()) as { items: unknown[] }).items).toEqual([s]);+ });++ it("leave out older runs, helper rows and the evaluation harness's runs", () => {+ clear();+ turntable("a lamp", { at: Date.now() - 20 * 86_400_000 });+ turntable("a vase", { feature: "eval" });+ turntable("a cup", { feature: "mixed-media-preview" });+ turntable("a chair");+ turntable("a desk");+ expect(insights.skillSuggestions({ force: true })).toEqual([]);+ });++ it("are swept at most once a day", () => {+ clear();+ const now = Date.now();+ for (const w of ["a", "b", "c"]) turntable(w);+ expect(insights.skillSuggestions({ now })).toHaveLength(1);+ // Nothing is left, but the day's sweep stands until tomorrow.+ db().exec("DELETE FROM generations");+ expect(insights.skillSuggestions({ now: now + 3_600_000 })).toHaveLength(1);+ expect(insights.skillSuggestions({ now: now + 25 * 3_600_000 })).toEqual([]);+ });++ it("Not now hides one for a week; Don't suggest this for good", async () => {+ clear();+ for (const w of ["a", "b", "c"]) turntable(w);+ const now = Date.now();+ const [s] = insights.skillSuggestions({ now, force: true });+ insights.dismissSuggestion(s.id, "later", now);+ expect(insights.skillSuggestions({ now })).toEqual([]);+ expect(insights.skillSuggestions({ now: now + 8 * 86_400_000 }).map((x) => x.id)).toEqual([s.id]);+ const res = await route.POST(new Request("http://x/api/skill-suggestions", { method: "POST", body: JSON.stringify({ id: s.id, how: "never" }) }));+ expect(res.status).toBe(200);+ expect(insights.skillSuggestions({ now: now + 30 * 86_400_000, force: true })).toEqual([]);+ expect((await route.POST(new Request("http://x", { method: "POST", body: "{}" }))).status).toBe(400);+ });++ it("aren't offered for a chain a saved skill already makes", () => {+ clear();+ for (const w of ["a", "b", "c"]) turntable(w);+ expect(insights.skillSuggestions({ force: true })).toHaveLength(1);+ skills.createSkill({ name: "my-turntable", title: "My turntable", description: "x", body: "x" });+ recipes.saveRecipe("my-turntable", {+ fuobeRecipe: 1,+ params: [{ id: "product", label: "Product", type: "image", required: true, example: photo }],+ steps: [+ { key: "cut", kind: "generate", request: { feature: "skill", modelId: "birefnet-cloud", op: "bg-remove", inputs: { images: ["{{product}}"] } } },+ { key: "scene", kind: "generate", after: "cut", chain: [{ slot: "images", position: "first" }], request: { feature: "skill", modelId: "nano-banana-pro", op: "edit", prompt: "on a plinth" } },+ { key: "spin", kind: "generate", after: "scene", chain: [{ slot: "images" }], request: { feature: "skill", modelId: "kling-3", op: "i2v", prompt: "turning", params: { duration: 5 } } },+ ],+ });+ // At once, without waiting for the next day's sweep.+ expect(insights.skillSuggestions()).toEqual([]);+ expect(insights.skillSuggestions({ force: true })).toEqual([]);+ });+});