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: a skill can span studios, each step starting by itself when the one it takes from finishes
Claude658586c1812a
diff --git a/src/app/api/assist/skills/[name]/runs/route.ts b/src/app/api/assist/skills/[name]/runs/route.tsnew file mode 100644index 00000000..940792c2--- /dev/null+++ b/src/app/api/assist/skills/[name]/runs/route.ts@@ -0,0 +1,14 @@+import { connection } from "next/server";+import { listSkillRuns } from "@/server/skill-runs";+import { getSkill } from "@/server/skills";++/**+ * A skill's newest runs that span studios (recipe version 2), each step with its status and its studio's page: the+ * progress the skill's dialog shows. The owner's: a guest's or an account's read is refused by the proxy.+ */+export async function GET(_request: Request, ctx: RouteContext<"/api/assist/skills/[name]/runs">) {+ await connection();+ const { name } = await ctx.params;+ if (!getSkill(name)) return Response.json({ error: "No such skill" }, { status: 404 });+ return Response.json({ items: listSkillRuns(name) });+}diff --git a/src/lib/recipe.ts b/src/lib/recipe.tsindex 42fdf920..9a55876c 100644--- a/src/lib/recipe.ts+++ b/src/lib/recipe.ts@@ -6,8 +6,14 @@* A recipe has typed inputs (`params`) and either a graph of generate steps (one `createPipeline`) or one call of a* gated Assist tool (`dub_video`, `add_captions`…). A string that is exactly `"{{id}}"` takes the input with its type;* `{{id}}` inside a longer string inserts its text. Unknown or unused placeholders are refused when the recipe is- * saved (`recipeProblems`), never at run time. Step outputs travel only through `after` and `chain`, exactly as- * createPipeline takes them.+ * saved (`recipeProblems`), never at run time. Within a graph of generate steps, outputs travel through `after` and+ * `chain`, exactly as createPipeline takes them.+ *+ * Version 2 (package W7, skills that span studios) adds `{{steps.<key>.output}}`: a whole field of a step's input that+ * takes an earlier step's first output of the kind the field takes, so tool steps can sit anywhere in the order ("dub,+ * then captions, then a 9:16 cut"). Such a recipe runs in parts (`compile` → `staged`): each graph of generate steps+ * joined by `after` is one createPipeline, each tool step one call, and a part starts once the steps it takes from have+ * finished (src/server/skill-runs.ts). Version 1 files load and run as before.** Pure and browser-safe: the Run form validates a row and parses a CSV with it, the server compiles the requests* (src/server/recipes.ts). Nothing here reads the catalog: the server checks models, prices and engines.@@ -33,6 +39,9 @@ const STEP_KEY = /^[A-Za-z0-9][A-Za-z0-9_-]{0,39}$/;const PLACEHOLDER = /\{\{\s*([A-Za-z][A-Za-z0-9_]*)\s*\}\}/g;const EXACT = /^\{\{\s*([A-Za-z][A-Za-z0-9_]*)\s*\}\}$/;const DAY = /^\d{4}-\d{2}-\d{2}$/;+/** A step reference (version 2): a whole field taking an earlier step's output. */+const STEP_REF = /^\{\{\s*steps\.([A-Za-z0-9][A-Za-z0-9_-]{0,39})\.output\s*\}\}$/;+const ANY_STEP_REF = /\{\{\s*steps\./;const ELEMENT = /^@[\p{L}\p{N}_-]{1,40}$/u;/** A media input: a file saved in Fuobe or a public http(s) link (read through remote-fetch.ts). */@@ -152,8 +161,11 @@ const VerifiedEngineSchema = z.object({});export type VerifiedEngine = z.infer<typeof VerifiedEngineSchema>;+/** The newest recipe format: version 2 has step references ({{steps.<key>.output}}); version 1 files still load. */+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(),@@ -210,6 +222,155 @@ export function leafKeys(recipe: Pick<Recipe, "steps">): Set<string> {return new Set(recipe.steps.filter((s) => !fed.has(s.key)).map((s) => s.key));}+// ---------------------------------------------------------------------------+// Step references (version 2)++/** The text that puts an earlier step's output in a field: `{{steps.<key>.output}}`. */+export const stepRef = (key: string): string => `{{steps.${key}.output}}`;++/** The step a whole-field reference names, or null. */+export const refKey = (v: unknown): string | null => (typeof v === "string" ? (STEP_REF.exec(v)?.[1] ?? null) : null);++export interface StepRefAt {+ key: string;+ path: (string | number)[];+}++/** Every step reference in a value, with its path; `loose` collects strings that mention one without being one. */+export function stepRefs(v: unknown, path: (string | number)[] = [], out: StepRefAt[] = [], loose?: (string | number)[][]): StepRefAt[] {+ if (typeof v === "string") {+ const key = refKey(v);+ if (key) out.push({ key, path });+ else if (loose && ANY_STEP_REF.test(v)) loose.push(path);+ } else if (Array.isArray(v)) v.forEach((x, i) => stepRefs(x, [...path, i], out, loose));+ else if (v && typeof v === "object") for (const [k, x] of Object.entries(v)) stepRefs(x, [...path, k], out, loose);+ return out;+}++/** What each studio tool makes, for a later step that takes its output (its first output of the field's kind). */+export const TOOL_MAKES: Record<string, MediaKind> = {+ dub_video: "video",+ add_captions: "video",+ restyle_footage: "video",+ restore_video: "video",+ remove_person: "video",+ blockout_film: "video",+ fly_around: "video",+ faceless_episode: "video",+ katana: "video",+ split_layers: "image",+ create_ads: "image",+ create_storyboard: "image",+};++/**+ * The kind of file a field takes, from its name (a request's `inputs.images`, a tool's `video`): null when the name+ * doesn't say, and the step's first file of any kind fills it.+ */+export function fieldKind(path: (string | number)[], tool?: string): "image" | "video" | "audio" | null {+ const key = [...path].reverse().find((p): p is string => typeof p === "string") ?? "";+ // Katana's reference is the edit to copy (a clip); elsewhere a reference is a picture.+ if (key === "reference" && tool === "katana") return "video";+ if (/^(video|videos|footage|clip|clips)$/i.test(key)) return "video";+ if (/^(audio|audios|audio2|voiceAudio|voice_sample|music|sound)$/i.test(key)) return "audio";+ if (/^(image|images|endImage|end_image|photos?|product_image|first_frame|depth|references?|logo|mask)$/i.test(key)) return "image";+ return null;+}++/** Whether a recipe runs in parts (version 2): a step reference anywhere, or a tool step beside other steps. */+export function isStaged(recipe: Pick<Recipe, "steps">): boolean {+ return recipe.steps.some((s) => stepRefs(stepBody(s)).length > 0) || (recipe.steps.some((s) => s.kind === "tool") && recipe.steps.length > 1);+}++/**+ * The parts a staged recipe runs in: each graph of generate steps joined by `after` (one createPipeline), each tool step+ * alone, in the order of their first step; `needs` are the steps whose outputs a part takes ({{steps.<key>.output}}).+ */+export function recipeParts(recipe: Pick<Recipe, "steps">): { keys: string[]; needs: string[] }[] {+ const keys = recipe.steps.map((s) => s.key);+ const group = new Map(keys.map((k) => [k, k]));+ const root = (k: string): string => {+ let r = k;+ while (group.get(r) !== r) r = group.get(r)!;+ return r;+ };+ for (const s of recipe.steps) {+ if (s.kind !== "generate") continue;+ for (const a of asList(s.after)) {+ const other = recipe.steps.find((t) => t.key === a);+ if (other?.kind === "generate") group.set(root(a), root(s.key));+ }+ }+ const parts = new Map<string, { keys: string[]; needs: string[] }>();+ for (const s of recipe.steps) {+ const r = root(s.key);+ const part = parts.get(r) ?? { keys: [], needs: [] };+ part.keys.push(s.key);+ for (const ref of stepRefs(stepBody(s))) if (!part.needs.includes(ref.key)) part.needs.push(ref.key);+ parts.set(r, part);+ }+ return [...parts.values()];+}++/** Why a step's reference can't be filled as written (version 2), or null. `makes` names what a generate step makes. */+function refProblems(recipe: Recipe, makes?: (s: GenerateStep) => MediaKind | undefined): string[] {+ const out: string[] = [];+ const v1 = recipe.fuobeRecipe === 1;+ recipe.steps.forEach((s, i) => {+ const loose: (string | number)[][] = [];+ const refs = stepRefs(stepBody(s), [], [], loose);+ if (loose.length) out.push(`Step “${s.key}”: a step's output fills a whole field ({{steps.<key>.output}} alone, not inside other words)`);+ if (refs.length && v1) out.push(`Step “${s.key}” takes another step's output: that needs "fuobeRecipe": 2`);+ for (const r of refs) {+ const j = recipe.steps.findIndex((t) => t.key === r.key);+ if (j < 0) {+ out.push(`Step “${s.key}” uses {{steps.${r.key}.output}}, but there's no step “${r.key}”`);+ continue;+ }+ if (j >= i) {+ out.push(`Step “${s.key}” uses the output of “${r.key}”, which comes ${j === i ? "from itself" : "after it"}: a step takes only from earlier steps`);+ continue;+ }+ const from = recipe.steps[j];+ const wants = fieldKind(r.path, s.kind === "tool" ? s.tool : undefined);+ const made = from.kind === "tool" ? TOOL_MAKES[from.tool] : (recipe.checks?.[from.key]?.kind ?? makes?.(from));+ if (wants && made && made !== wants) out.push(`Step “${s.key}” takes ${wants === "image" ? "an image" : `a${wants === "audio" ? "n" : ""} ${wants}`} from “${r.key}”, which makes ${made === "image" ? "an image" : made === "audio" ? "audio" : `a ${made}`}`);+ if (from.kind === "tool" && from.tool === "dub_video" && from.input.review !== false) {+ out.push(`“${r.key}” waits for you to review its lines in Translate & dub before it makes a video: set "review": false so “${s.key}” can take it`);+ }+ }+ if (s.kind === "generate") {+ for (const a of asList(s.after)) {+ if (recipe.steps.find((t) => t.key === a)?.kind === "tool") out.push(`Step “${s.key}” waits for the studio step “${a}”: put {{steps.${a}.output}} in its input instead`);+ }+ }+ });+ // A part that takes from a step in its own pipeline, or parts that wait for each other.+ if (!out.length) {+ const parts = recipeParts(recipe);+ const partOf = new Map(parts.flatMap((p, i) => p.keys.map((k) => [k, i] as const)));+ for (const p of parts) {+ const own = p.needs.find((k) => p.keys.includes(k));+ if (own) out.push(`“${own}” runs in the same pipeline as the step that takes its output: chain them with "after" instead`);+ }+ if (!out.length) {+ const done = new Set<number>();+ let moved = true;+ while (moved) {+ moved = false;+ parts.forEach((p, i) => {+ if (done.has(i) || p.needs.some((k) => !done.has(partOf.get(k)!))) return;+ done.add(i);+ moved = true;+ });+ }+ const stuck = parts.flatMap((p, i) => (done.has(i) ? [] : p.keys));+ if (stuck.length) out.push(`These steps wait for each other in a loop: ${stuck.map((k) => `“${k}”`).join(", ")}`);+ }+ }+ return out;+}+// ---------------------------------------------------------------------------// Values@@ -369,7 +530,14 @@ 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> };+/** One part of a staged run: a pipeline of generate steps, or one tool call; `needs` are the steps it takes from. */+export type CompiledPart = ({ kind: "pipeline"; steps: CompiledStep[] } | { kind: "tool"; key: string; tool: string; input: Record<string, unknown>; label?: string }) & { needs: string[] };++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> }+ /** Version 2: parts that start as the steps they take from finish ({{steps.<key>.output}} still in their inputs). */+ | { kind: "staged"; parts: CompiledPart[]; checks: Record<string, FilledCheck> };export interface CompileOptions {/** The skill's name and this run's id: the server-set stamp on every request. */@@ -387,25 +555,49 @@ 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);+ const n = steps.length;+ const generate = (s: GenerateStep): CompiledStep => ({+ key: s.key,+ request: {+ ...s.request,+ batchTitle: o.title.slice(0, 200),+ skill: { name: o.skill, run: o.run },+ ...(s.label && { step: { label: s.label, index: steps.indexOf(s), of: n } }),+ ...(o.demo && { demo: true, feature: SKILL_CHECK_FEATURE }),+ },+ ...(s.after !== undefined && { after: s.after }),+ ...(s.chain && { chain: s.chain as ChainSlot[] }),+ });+ if (isStaged(recipe)) {+ const byKey = new Map(steps.map((s) => [s.key, s]));+ const parts = recipeParts(recipe).map((p): CompiledPart => {+ const first = byKey.get(p.keys[0])!;+ if (first.kind === "tool") return { kind: "tool", key: first.key, tool: first.tool, input: first.input, ...(first.label && { label: first.label }), needs: p.needs };+ return { kind: "pipeline", steps: p.keys.map((k) => generate(byKey.get(k) as GenerateStep)), needs: p.needs };+ });+ return { kind: "staged", parts, checks };+ }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;- return {- kind: "pipeline",- checks,- steps: (steps as GenerateStep[]).map((s, i) => ({- key: s.key,- 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 }),- },- ...(s.after !== undefined && { after: s.after }),- ...(s.chain && { chain: s.chain as ChainSlot[] }),- })),- };+ return { kind: "pipeline", checks, steps: (steps as GenerateStep[]).map(generate) };+}++/**+ * A part's input with each step reference filled: `pick(key, kind)` gives that step's first output of the kind the+ * field takes (null: any kind); a reference it can't fill throws, naming the step and what was missing.+ */+export function fillRefs<T>(v: T, pick: (key: string, kind: "image" | "video" | "audio" | null) => string | undefined, tool?: string, path: (string | number)[] = []): T {+ if (typeof v === "string") {+ const key = refKey(v);+ if (!key) return v;+ const kind = fieldKind(path, tool);+ const url = pick(key, kind);+ if (!url) throw new Error(`“${key}” made no ${kind ?? "file"} for the next step`);+ return url as T;+ }+ if (Array.isArray(v)) return v.map((x, i) => fillRefs(x, pick, tool, [...path, i])) as T;+ if (v && typeof v === "object") return Object.fromEntries(Object.entries(v).map(([k, x]) => [k, fillRefs(x, pick, tool, [...path, k])])) as T;+ return v;}// ---------------------------------------------------------------------------@@ -416,7 +608,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: { makes?: (s: GenerateStep) => MediaKind | undefined } = {}): string[] {const out: string[] = [];const ids = recipe.params.map((p) => p.id);const keys = recipe.steps.map((s) => s.key);@@ -437,9 +629,10 @@ 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. Version 2: tool steps anywhere, and every step reference fits (refProblems).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 && tools.length && recipe.steps.length > 1) out.push(`The tool step “${tools[0].key}” must be the recipe's only step in a version 1 recipe (set "fuobeRecipe": 2 to run it with other steps)`);+ out.push(...refProblems(recipe, o.makes));// The graph, as createPipeline checks it.const keySet = new Set(keys);@@ -814,13 +1007,20 @@ 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);+ 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 (`generate` or the studio tool each names), waiting for each step's result and passing it on where a step says {{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,8 +1126,40 @@ 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 skill that spans studios (version 2): its run's id (its progress in the skill's dialog), and the steps that wait. */+ run?: string;+ waiting?: string[];}+/** One step of a skill run that spans studios, as its progress shows it (src/server/skill-runs.ts). */+export interface SkillRunStep {+ key: string;+ label: string;+ /** The studio a tool step runs in ("Translate & dub"), when it opened one. */+ studio?: string;+ status: "waiting" | "running" | "done" | "failed";+ ids: string[];+ /** The studio's page for this step's job, when it gave one. */+ href?: string;+ error?: string;+}++export interface SkillRunView {+ id: string;+ skill: string;+ engine: RecipeEngine;+ status: "running" | "done" | "failed";+ /** Which step failed and why. */+ error?: string;+ demo?: boolean;+ steps: SkillRunStep[];+ createdAt: number;+ updatedAt: number;+}++/** "Dub · done → Captions · running → 9:16 cut · waiting". */+export const runLine = (steps: Pick<SkillRunStep, "label" | "status">[]): string => steps.map((s) => `${s.label} · ${s.status}`).join(" → ");+export interface EngineCheck {engine: RecipeEngine;/** `notes`: what stops a real run on this install that isn't the recipe's fault (a provider to connect). */diff --git a/src/server/db.ts b/src/server/db.tsindex e6975faa..d50870b5 100644--- a/src/server/db.ts+++ b/src/server/db.ts@@ -612,6 +612,19 @@ export const MIGRATIONS: string[] = [// skill's name, one set of its inputs as text (a file is its /api/files/… URL) and the file inputs that take the// newest upload of their kind when the run starts. NULL: a request, as before.`ALTER TABLE assist_schedules ADD COLUMN skill_json TEXT;`,+ // originals (o/w2s-w7): a run of a skill that spans studios (Skills W7): its values, and each step's status, generation+ // ids and studio page as the runner moves it on (src/server/skill-runs.ts), so a run survives a restart.+ `CREATE TABLE IF NOT EXISTS skill_runs (+ id TEXT PRIMARY KEY,+ skill 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);+ CREATE INDEX IF NOT EXISTS skill_runs_status ON skill_runs (status);`,];/**diff --git a/src/server/demo-scope.ts b/src/server/demo-scope.tsnew file mode 100644index 00000000..fd34b07c--- /dev/null+++ b/src/server/demo-scope.ts@@ -0,0 +1,20 @@+import "server-only";+import { AsyncLocalStorage } from "node:async_hooks";++/**+ * A studio's dry run (skills that span studios, package W7): work done inside `runAsDemo` runs on the demo provider+ * whatever Settings → Demo mode says, so a studio module (a dub, a Layers project, captions) can be checked for free+ * with no change to its code. `chooseRoute` returns the demo route inside the scope, and every generation created in+ * it is stamped `request.demo`, so its waiting steps stay demos when the runner starts them later, outside the scope.+ */+const scope = new AsyncLocalStorage<{ demo: true }>();++/** Run `fn` (and everything it starts and awaits) on the demo provider. */+export function runAsDemo<T>(fn: () => T): T {+ return scope.run({ demo: true }, fn);+}++/** Whether this work runs inside runAsDemo. */+export function inDemoScope(): boolean {+ return scope.getStore()?.demo === true;+}diff --git a/src/server/generations.ts b/src/server/generations.tsindex 27d0bf69..00251f9b 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 } from "./storage";@@ -419,6 +420,8 @@ export const ASSET_REFS: AssetRef[] = [{ 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).{ table: "skills", cols: ["files_json"], what: "skill", key: "name", name: "title" },+ // A skill run that spans studios: the files its inputs name, and each step's results and studio page.+ { table: "skill_runs", cols: ["values_json", "state_json"], what: "skill run", name: "skill" },];/**@@ -541,7 +544,7 @@ export function chooseRoute(candidates: ModelRoute[], images = 0, loras: LoraRefconst 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 };+ 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.@@ -961,7 +964,8 @@ function stampTenant(asked: GenerationRequest, opts: CreateOptions): GenerationR}export function createGenerations(given: GenerationRequest, opts: CreateOptions = {}): Generation[] {- const asked = stampTenant(given, opts);+ // A studio's dry run (src/server/demo-scope.ts): its rows say so, so their waiting steps stay demos too.+ const asked = stampTenant(inDemoScope() && !given.demo ? { ...given, demo: true } : 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);const original = moved.request;diff --git a/src/server/recipes.ts b/src/server/recipes.tsindex 22f521fa..d6ff052c 100644--- a/src/server/recipes.ts+++ b/src/server/recipes.ts@@ -14,6 +14,7 @@ import {checkValues,compile,exampleValues,+ fillRefs,isMediaRef,isMediaType,parseRecipe,@@ -26,6 +27,8 @@ import {today,verifiedLine,type Compiled,+ type CompiledPart,+ type CompiledStep,type FilledCheck,type Recipe,type RecipeValues,@@ -42,12 +45,14 @@ import { planSteps } from "./assist/studio-tools";import { executeTool, getTool, planFor, validateInput } from "./assist/tools";import { createPipeline } from "./chains";import { llmSeesImages, llmText } from "./enhance";-import { cancelGeneration, createGenerations, currentRequest, getGeneration, previewChained, stampRequests } from "./generations";+import { cancelGeneration, createGenerations, currentRequest, getGeneration, outputKind, previewChained, stampRequests } from "./generations";import { trashGenerations } from "./library";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 { runAsDemo } from "./demo-scope";+import { advanceSkillRun, discardSkillRun, skillRunGenerations, startSkillRun, stopSkillRun } from "./skill-runs";import { absolutePath, readRef, saveFile } from "./storage";/**@@ -86,6 +91,18 @@ export function getRecipe(name: string): { skill: Skill; recipe: Recipe } {return { skill, recipe: parsed.recipe };}+/** What a generate step makes (its model and operation), for a later step that takes its output. */+function stepMakes(s: Extract<Recipe["steps"][number], { kind: "generate" }>): MediaKind | undefined {+ const m = getModel(currentModelId(s.request.modelId));+ if (!m) return undefined;+ const op = s.request.op ?? m.routes[0]?.op;+ try {+ return op ? outputKind(op as Generation["op"], m) : m.kind;+ } catch {+ return m.kind;+ }+}+/** Tools a recipe may call: the gated ones that make something (not remember, which changes what Assist knows). */const runnableTool = (name: string) => !!getTool(name)?.gated && name !== "remember" && name !== "run_skill";@@ -111,7 +128,7 @@ function serverProblems(recipe: Recipe): string[] {/** 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, { makes: stepMakes });return own.length ? own : serverProblems(recipe);}@@ -167,25 +184,46 @@ function noEngine(recipe: Recipe): string {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 });if (c.kind === "tool") {- const error = validateInput(c.tool, c.input);- if (error) throw new SkillError(`Step “${c.key}”: ${error.replace(/^Invalid input: /, "")}`, 422);+ checkTool(c.key, c.tool, c.input);return c;}+ if (c.kind === "staged") {+ // Each part checked with a stand-in file where it takes an earlier step's output; it keeps the reference to fill.+ const parts = c.parts.map((p): CompiledPart => {+ if (p.kind === "tool") {+ checkTool(p.key, p.tool, fillRefs(p.input, (_, kind) => PRICE_STAND_IN[kind ?? "image"], p.tool));+ return p;+ }+ return { ...p, steps: p.steps.map((s) => ({ ...checkedStep({ ...s, request: fillRefs(s.request, (_, kind) => PRICE_STAND_IN[kind ?? "image"]) }, engine), request: withEngine(s.request, engine) })) };+ });+ return { ...c, parts };+ }+ return { ...c, steps: c.steps.map((s) => checkedStep(s, engine)) };+}++/** A tool step's input as its tool takes it, or the step's refusal. */+function checkTool(key: string, tool: string, input: Record<string, unknown>): void {+ const error = validateInput(tool, input);+ if (error) throw new SkillError(`Step “${key}”: ${error.replace(/^Invalid input: /, "")}`, 422);+}++/** An Original's request put on the run's engine (a model of one engine stays on its own). */+function withEngine(r: GenerationRequest, engine: Engine): GenerationRequest {+ const m = getModel(currentModelId(r.modelId));+ return m && dualEngine(m) && !r.engine ? { ...r, engine } : r;+}++/** A generate step's request as the API takes it, an Original put on the run's engine; else the step's refusal. */+function checkedStep(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 slots = s.chain ?? chain;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 }) },- };- }),+ ...s,+ ...(slots && { chain: slots }),+ request: { ...withEngine(req, engine), batchTitle, skill: stamp, ...(step && { step }), ...(demo && { demo }) },};}@@ -206,10 +244,11 @@ export const onlyConnect = (errors: string[]): boolean => errors.length > 0 && e/** 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") return planStaged(c.parts, engine);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}`)];- return { jobs: p.jobs, total: p.total, errors, place: { ...(p.studio && { studio: p.studio }), ...(p.href && { href: p.href }), ...(p.fallback && { fallback: p.fallback }) } };+ return { jobs: p.jobs, total: p.total, errors, place: { ...(p.studio && { studio: p.studio }), ...(p.href && { href: p.href }), ...(p.fallback && { fallback: p.fallback }) }, connectOnly: onlyConnect(errors.map((e) => e.replace(/^[^:]*: (?=Connect\b)/, ""))) };}const jobs = planSteps("run_skill", c.steps);const failed = jobs.filter((j) => j.error);@@ -218,9 +257,43 @@ function planRun(c: Compiled, engine: Engine): RunPlan {return { jobs, total: totalCost(jobs), errors, connectOnly: failed.length === errors.length && onlyConnect(failed.map((j) => j.error!)) };}+/**+ * A stand-in for an earlier step's output, to price a part with before that step has run: a studio that keeps a clip's+ * length (a dub, captions, a restyle) is priced on the clip it takes; anything else on a stand-in link.+ */+function refStandIn(parts: CompiledPart[], key: string, kind: "image" | "video" | "audio" | null, depth = 0): string {+ const fallback = PRICE_STAND_IN[kind ?? "image"];+ const from = parts.find((p) => p.kind === "tool" && p.key === key);+ if (!from || from.kind !== "tool" || depth > RECIPE_LIMITS.steps || (kind && kind !== "video")) return fallback;+ const src = from.input.video ?? from.input.footage;+ if (typeof src !== "string") return fallback;+ const ref = /^\{\{\s*steps\.([\w-]+)\.output\s*\}\}$/.exec(src)?.[1];+ return ref ? refStandIn(parts, ref, "video", depth + 1) : src;+}++/** A staged run priced part by part, each with stand-ins where it takes an earlier step's output. */+function planStaged(parts: CompiledPart[], engine: Engine): RunPlan {+ const jobs: PlannedJob[] = [];+ const errors: string[] = [];+ let place: RecipePlace | undefined;+ let connectOnly = true;+ for (const p of parts) {+ const fill = <T,>(v: T, tool?: string) => fillRefs(v, (key, kind) => refStandIn(parts, key, kind), tool);+ const one = p.kind === "tool" ? planRun({ kind: "tool", key: p.key, tool: p.tool, input: fill(p.input, p.tool), checks: {} }, engine) : planRun({ kind: "pipeline", steps: p.steps.map((s) => ({ ...s, request: fill(s.request) })), checks: {} }, engine);+ jobs.push(...one.jobs);+ errors.push(...one.errors.filter((e) => e !== "Nothing to run"));+ if (one.errors.length && !one.connectOnly) connectOnly = false;+ if (p.kind === "tool" && one.place?.studio) place ??= one.place;+ }+ if (!errors.length && !jobs.length) errors.push("Nothing to run");+ return { jobs, total: totalCost(jobs), errors, ...(place && { place }), connectOnly: errors.length > 0 && connectOnly };+}+/** 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 } })) };+ const demo = (s: CompiledStep) => ({ ...s, request: { ...s.request, demo: true } });+ if (c.kind === "staged") return { ...c, parts: c.parts.map((p) => (p.kind === "tool" ? p : { ...p, steps: p.steps.map(demo) })) };+ return c.kind === "tool" ? c : { ...c, steps: c.steps.map(demo) };}/**@@ -230,8 +303,9 @@ 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);+ if (!plan.errors.length || !plan.connectOnly) return { ...plan, notes: [] };+ // A studio step plans inside runAsDemo, as its dry run runs (src/server/demo-scope.ts).+ const demo = runAsDemo(() => planRun(asDemo(c), engine));return demo.errors.length ? { ...plan, notes: [] } : { ...demo, notes: [...new Set(plan.jobs.flatMap((j) => (j.error ? [j.error] : [])))] };}@@ -241,13 +315,19 @@ function planCheck(c: Compiled, engine: Engine): RunPlan & { notes: string[] } {*/function planHash(compiled: Compiled, engine: Engine): string {const c = asDemo(compiled);+ const tool = (name: string, input: Record<string, unknown>) => planFor(name, input, { engine }).jobs.map((j) => [j.modelId, j.op, getModel(j.modelId)?.pricing ?? null]);+ const steps = (list: CompiledStep[]) =>+ list.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];+ });+ const stand = <T,>(v: T, name?: string) => fillRefs(v, (_, kind) => PRICE_STAND_IN[kind ?? "image"], name);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.parts.map((p) => (p.kind === "tool" ? tool(p.tool, stand(p.input, p.tool)) : steps(p.steps.map((s) => ({ ...s, request: stand(s.request) })))))+ : c.kind === "tool"+ ? tool(c.tool, c.input)+ : steps(c.steps);return `sha256:${crypto.createHash("sha256").update(JSON.stringify(parts)).digest("hex")}`;}@@ -504,10 +584,30 @@ 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 skill that spans studios: each row a skill run, its first parts started now and the rest as their steps finish.+ for (const { run, c, values } of compiled) {+ if (c.kind !== "staged") continue;+ const v = await startSkillRun(skill, recipe, c.parts, engine, values, { id: run });+ const ids = v.steps.flatMap((x) => x.ids);+ const started = v.steps.filter((x) => x.status !== "waiting" && !x.error);+ if (v.status === "failed" && !started.length && compiled.length === 1) throw new SkillError(v.error ?? "Nothing could start", 422);+ demo &&= ids.every((id) => getGeneration(id)?.provider === "mock");+ runs.push({+ run: v.id,+ batchId: v.id,+ ids,+ href: v.steps.find((x) => x.href)?.href ?? `/assist/skills?skill=${encodeURIComponent(name)}`,+ waiting: v.steps.filter((x) => x.status === "waiting").map((x) => x.label),+ ...(v.status === "failed" && { error: v.error ?? "It failed" }),+ });+ }+ return { engine, runs, demo };+ }if (compiled[0].c.kind === "tool") {for (const { run, c } of compiled) {if (c.kind !== "tool") continue;@@ -590,9 +690,10 @@ 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 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 values = valuesForCheck(recipe, true);+ const c = compileRun(skill, recipe, values, engine, { run: nanoid(10), demo: true });+ // A studio step runs as a demo too (runAsDemo), and the records it opened are deleted after (W7).+ if (c.kind === "tool" || c.kind === "staged") return studioDryRun(skill, recipe, c, engine, values);const p = createPipeline(c.steps, { batchId: nanoid(10) });const ids = p.items.map((g) => g.id);try {@@ -614,6 +715,50 @@ async function dryRun(skill: { name: string; title: string }, recipe: Recipe, en}}+/** A tool recipe, or one that spans studios, as the parts of a skill run. */+const partsOf = (c: Extract<Compiled, { kind: "tool" | "staged" }>): CompiledPart[] => (c.kind === "staged" ? c.parts : [{ kind: "tool", key: c.key, tool: c.tool, input: c.input, needs: [] }]);++/** Move a skill run on until it ends, at most `ms`; what's left is stopped. */+async function finishRun(id: string, ms: number) {+ const until = Date.now() + ms;+ let v = await advanceSkillRun(id);+ while (v?.status === "running" && Date.now() < until) {+ await new Promise((r) => setTimeout(r, 300));+ v = await advanceSkillRun(id);+ }+ if (v?.status === "running") {+ for (const g of skillRunGenerations(id)) if (!TERMINAL.has(getGeneration(g, { includeDeleted: true })?.status ?? "failed")) await cancelGeneration(g);+ stopSkillRun(id, "It took too long, so it was stopped");+ v = await advanceSkillRun(id);+ }+ return v!;+}++/**+ * The free dry run of a recipe with studio steps: one skill run with every part on the demo provider (studio modules+ * inside runAsDemo, unchanged), then what it made goes to the Trash and the studio records it opened are deleted.+ */+async function studioDryRun(skill: { name: string; title: string }, recipe: Recipe, c: Extract<Compiled, { kind: "tool" | "staged" }>, engine: Engine, values: RecipeValues): Promise<NonNullable<EngineCheck["dryRun"]>> {+ const run = await startSkillRun(skill, recipe, partsOf(c), engine, values, { check: true });+ try {+ const v = await finishRun(run.id, DRY_RUN_MS);+ const problems: string[] = [];+ for (const s of v.steps) {+ if (s.status === "failed") {+ problems.push(`Step “${s.key}” ${s.error?.startsWith("Didn't start") ? `didn't start (${s.error.replace(/^Didn't start: /, "")})` : `failed${s.error ? `: ${s.error}` : ""}`}`);+ continue;+ }+ const kind = c.checks[s.key]?.kind;+ if (!kind) continue;+ const outputs = s.ids.flatMap((id) => getGeneration(id, { includeDeleted: true })?.outputs ?? []);+ if (!outputs.some((o) => o.kind === kind)) problems.push(`Step “${s.key}” made no ${kind}`);+ }+ return { ok: !problems.length, problems };+ } finally {+ await discardSkillRun(run.id);+ }+}+/** A stored output's header facts (duration, size, sound), or null when it can't be read. */async function infoOf(url: string, kind: MediaKind): Promise<MediaInfo | null> {if (kind !== "video" && kind !== "audio") return null;@@ -667,7 +812,12 @@ async function realRun(skill: { name: string; title: string }, recipe: Recipe, econst helpers: string[] = [];let made: Generation[];let byKey: Record<string, string> = {};- if (c.kind === "tool") {+ if (c.kind === "staged") {+ const run = await startSkillRun(skill, recipe, c.parts, engine, valuesForCheck(recipe, true));+ const v = await finishRun(run.id, REAL_RUN_MS);+ made = skillRunGenerations(run.id).map((id) => getGeneration(id, { includeDeleted: true })).filter((g): g is Generation => !!g);+ byKey = Object.fromEntries(v.steps.flatMap((s) => (s.ids.length ? [[s.key, s.ids[0]]] : [])));+ } else 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 };const ids = (out.items ?? []).flatMap((i) => (i.role === "generations" ? i.ids : []));diff --git a/src/server/skill-runs.ts b/src/server/skill-runs.tsnew file mode 100644index 00000000..540bd6c4--- /dev/null+++ b/src/server/skill-runs.ts@@ -0,0 +1,377 @@+import "server-only";+import { nanoid } from "nanoid";+import { getModel } from "@/lib/catalog";+import { currentModelId } from "@/lib/catalog/replaced";+import type { Engine, Generation, MediaKind } from "@/lib/catalog/types";+import { fillRefs, type CompiledPart, type Recipe, type RecipeValues, type SkillRunStep, type SkillRunView } from "@/lib/recipe";+import { studioForTool } from "@/lib/recipe-builder";+import { executeTool } from "./assist/tools";+import { createPipeline } from "./chains";+import { db } from "./db";+import { runAsDemo } from "./demo-scope";+import { deleteDubSession } from "./dub";+import { deleteEpisode } from "./faceless";+import { getGeneration, stampRequests } from "./generations";+import { deleteKatana } from "./katana";+import { deleteProject } from "./layers";+import { trashGenerations } from "./library";+import { deleteSession } from "./shorts";++/**+ * Runs of skills that span studios (recipe version 2, package W7): a studio step that feeds later steps, and a generate+ * step that feeds a studio step ("dub, then captions, then a 9:16 cut"). createPipeline can't hold such a run as one+ * graph (a studio tool runs through its own module and opens as a StudioRun), so a run is kept in `skill_runs`: its+ * values, and each part's status, generation ids and studio page. A part (a graph of generate steps, one+ * createPipeline; or one tool call, executeTool) starts once the steps it takes from have succeeded, with their first+ * output of the kind each field takes in place of `{{steps.<key>.output}}`. `advanceSkillRun` moves a run on; a sweep+ * started with the generation runner (src/instrumentation.ts) advances every running run, so a run survives a restart.+ * A failure fails the parts that wait for it and says which step failed and why.+ */++type Status = SkillRunStep["status"];++interface PartState {+ part: CompiledPart;+ status: Status;+ /** Every generation the part made (a pipeline's rows; the generations the tool's result names). */+ ids: string[];+ /** A pipeline part's step keys → their generation. */+ byKey?: Record<string, string>;+ href?: string;+ studio?: string;+ error?: string;+ /** The step of a pipeline part that failed (else the part's first). */+ failed?: string;+ /** What the studio made besides generations (a dub, a Layers project…): a dry run deletes them at the end. */+ records?: string[];+}++interface RunState {+ engine: Engine;+ /** The skill's title (the Library stack's name). */+ title: string;+ /** Each step's label, in the recipe's order. */+ labels: { key: string; label: string }[];+ parts: PartState[];+ /** A dry run: every part on the demo provider (tool steps inside runAsDemo), hidden from the skill's runs. */+ check?: boolean;+ error?: string;+}++interface Row {+ id: string;+ skill: string;+ status: SkillRunView["status"];+ values_json: string;+ state_json: string;+ created_at: number;+ updated_at: number;+}++const TERMINAL = new Set(["succeeded", "failed", "canceled"]);++/** A step's name in a run's progress: its label, else its studio ("Translate & dub") or its model's name. */+export function stepLabel(s: Recipe["steps"][number]): string {+ if (s.label) return s.label;+ if (s.kind === "tool") return studioForTool(s.tool) ?? s.tool.replace(/_/g, " ");+ return getModel(currentModelId(s.request.modelId))?.name ?? s.key;+}++const keysOf = (p: CompiledPart): string[] => (p.kind === "tool" ? [p.key] : p.steps.map((s) => s.key));++function load(id: string): { row: Row; state: RunState } | null {+ const row = db().prepare("SELECT * FROM skill_runs WHERE id = ?").get(id) as Row | undefined;+ return row ? { row, state: JSON.parse(row.state_json) as RunState } : null;+}++function save(id: string, state: RunState, status: SkillRunView["status"]): void {+ db().prepare("UPDATE skill_runs SET state_json = ?, status = ?, updated_at = ? WHERE id = ?").run(JSON.stringify(state), status, Date.now(), id);+}++/** The run as its progress shows it: each step in the recipe's order with its part's status, results and studio page. */+function view(row: Row, state: RunState): SkillRunView {+ const steps: SkillRunStep[] = state.labels.map(({ key, label }) => {+ const p = state.parts.find((x) => keysOf(x.part).includes(key));+ if (!p) return { key, label, status: "waiting", ids: [] };+ if (p.part.kind === "tool") return { key, label, status: p.status, ids: p.ids, ...(p.studio && { studio: p.studio }), ...(p.href && { href: p.href }), ...(p.error && { error: p.error }) };+ // A pipeline's steps each go by their own generation once it has started.+ const g = p.byKey?.[key] ? getGeneration(p.byKey[key], { includeDeleted: true }) : null;+ const status: Status = !g ? (p.status === "failed" ? "failed" : "waiting") : g.status === "succeeded" ? "done" : g.status === "failed" || g.status === "canceled" ? "failed" : g.status === "queued" && g.message?.startsWith("Waits") ? "waiting" : "running";+ const error = status === "failed" ? (g?.error ?? p.error) : undefined;+ return { key, label, status, ids: g ? [g.id] : [], ...(error && { error }) };+ });+ return {+ id: row.id,+ skill: row.skill,+ engine: state.engine,+ status: row.status,+ ...(state.error && { error: state.error }),+ ...(state.check && { demo: true }),+ steps,+ createdAt: row.created_at,+ updatedAt: row.updated_at,+ };+}++/** The label of a step by its key. */+const labelOf = (state: RunState, key: string) => state.labels.find((l) => l.key === key)?.label ?? key;++/** The generations behind a step's output: its own row in a pipeline, every result of a tool. */+function made(state: RunState, key: string): Generation[] {+ const p = state.parts.find((x) => keysOf(x.part).includes(key));+ if (!p) return [];+ const ids = p.part.kind === "tool" ? p.ids : p.byKey?.[key] ? [p.byKey[key]] : [];+ return ids.map((id) => getGeneration(id, { includeDeleted: true })).filter((g): g is Generation => !!g && g.status === "succeeded");+}++/** A step's first output of a kind (any image, video or audio when the field doesn't say). */+function outputOf(state: RunState, key: string, kind: "image" | "video" | "audio" | null): string | undefined {+ const media: MediaKind[] = kind ? [kind] : ["video", "image", "audio"];+ for (const g of made(state, key)) {+ const o = g.outputs.find((x) => media.includes(x.kind) && !!x.url);+ if (o) return o.url;+ }+ return undefined;+}++/** The ids of a studio's records named in its result, for a dry run to delete (dub, Layers, Shorts, Faceless, Katana). */+function recordsOf(content: string, href: string | undefined): string[] {+ const out: string[] = [];+ try {+ const body = JSON.parse(content) as { dub?: unknown; katana?: unknown; job?: unknown };+ if (typeof body.dub === "string") out.push(`dub:${body.dub}`);+ } catch {+ // Plain text: only its page says what it made.+ }+ const path = href?.split("?")[0] ?? "";+ const m = /^\/(layers|shorts)\/([\w-]+)$/.exec(path) ?? /^\/(faceless)\/[\w-]+\/([\w-]+)$/.exec(path);+ if (m) out.push(`${m[1]}:${m[2]}`);+ return out;+}++/** Delete the records a dry run's studios made (the user never asked for them), and Katana jobs naming its results. */+async function deleteRecords(state: RunState): Promise<void> {+ const ids = state.parts.flatMap((p) => p.ids);+ for (const rec of state.parts.flatMap((p) => p.records ?? [])) {+ const [kind, id] = [rec.slice(0, rec.indexOf(":")), rec.slice(rec.indexOf(":") + 1)];+ try {+ if (kind === "dub") deleteDubSession(id);+ else if (kind === "layers") deleteProject(id);+ else if (kind === "shorts") deleteSession(id);+ else if (kind === "faceless") await deleteEpisode(id);+ } catch {+ // Gone already.+ }+ }+ for (const id of ids) {+ const rows = db().prepare("SELECT id FROM katana_jobs WHERE instr(data_json, ?) > 0").all(JSON.stringify(id)) as { id: string }[];+ for (const r of rows) deleteKatana(r.id);+ }+}++/** Every row a run's generations share a batch with (a studio's own steps: a transcript before its captions). */+function withBatchMates(ids: string[]): string[] {+ if (!ids.length) return [];+ const marks = ids.map(() => "?").join(", ");+ const rows = db()+ .prepare(`SELECT id FROM generations WHERE id IN (${marks}) OR batch_id IN (SELECT batch_id FROM generations WHERE id IN (${marks}) AND batch_id IS NOT NULL)`)+ .all(...ids, ...ids) as { id: string }[];+ return [...new Set([...ids, ...rows.map((r) => r.id)])];+}++/** Start one part: its references filled from the steps it takes from, then createPipeline or the tool. */+async function startPart(runId: string, skill: string, state: RunState, p: PartState): Promise<void> {+ const pick = (key: string, kind: "image" | "video" | "audio" | null) => outputOf(state, key, kind);+ try {+ if (p.part.kind === "pipeline") {+ const steps = p.part.steps.map((s) => ({ ...s, request: fillRefs(s.request, pick) }));+ const made = createPipeline(steps, { batchId: runId });+ p.ids = made.items.map((g) => g.id);+ p.byKey = Object.fromEntries(Object.entries(made.byKey).map(([k, g]) => [k, g.id]));+ p.status = "running";+ return;+ }+ const tool = p.part.tool;+ const input = fillRefs(p.part.input, pick, tool);+ const out = state.check ? await runAsDemo(() => executeTool(tool, input, { engine: state.engine })) : await executeTool(tool, input, { engine: state.engine });+ const text = typeof out.content === "string" ? out.content : "";+ if (out.isError) throw new Error(text.replace(/^\{"error":"(.*)"\}$/, "$1") || "The studio couldn't start");+ const card = (out.items ?? []).flatMap((i) => (i.role === "tool" && i.href ? [i] : []))[0];+ p.ids = [...new Set((out.items ?? []).flatMap((i) => (i.role === "generations" ? i.ids : [])))];+ p.href = card?.href && card.href !== "/library" ? card.href : undefined;+ p.studio = card?.studio;+ if (state.check) p.records = recordsOf(text, card?.href);+ // The studio's own rows carry the run's stamp and the skill's title, as a pipeline's do.+ stampRequests(p.ids, () => ({ skill: { name: skill, run: runId }, batchTitle: state.title.slice(0, 200) }));+ p.status = p.ids.length ? "running" : "done";+ } catch (e) {+ p.status = "failed";+ p.error = (e as Error).message;+ }+}++/** A running part's status from its generations: failed when one failed (with its reason), done when all succeeded. */+function settle(state: RunState, p: PartState): void {+ const gens = p.ids.map((id) => getGeneration(id, { includeDeleted: true }));+ const failed = gens.find((g) => !g || g.status === "failed" || g.status === "canceled");+ if (failed !== undefined) {+ p.status = "failed";+ p.failed = p.part.kind === "pipeline" ? Object.entries(p.byKey ?? {}).find(([, id]) => id === failed?.id)?.[0] : undefined;+ p.error = !failed ? "its result was deleted" : failed.status === "canceled" ? "it was stopped" : (failed.error ?? "it failed");+ return;+ }+ if (gens.every((g) => g && TERMINAL.has(g.status))) p.status = "done";+}++const runLocks = new Set<string>();++/**+ * Move a run on: settle its running parts, fail what waits for a failure, start each waiting part whose steps have+ * finished, and save it. Returns the run as its progress shows it (null: no such run).+ */+export async function advanceSkillRun(id: string): Promise<SkillRunView | null> {+ if (runLocks.has(id)) {+ const found = load(id);+ return found ? view(found.row, found.state) : null;+ }+ runLocks.add(id);+ try {+ const found = load(id);+ if (!found) return null;+ const { row, state } = found;+ if (row.status !== "running") return view(row, state);+ for (let moved = true; moved; ) {+ moved = false;+ for (const p of state.parts) if (p.status === "running") settle(state, p);+ // A failure fails every part that waits for it, directly or through another.+ const failedKeys = new Set(state.parts.filter((p) => p.status === "failed").flatMap((p) => keysOf(p.part)));+ for (const p of state.parts) {+ if (p.status !== "waiting") continue;+ const from = p.part.needs.find((k) => failedKeys.has(k));+ if (!from) continue;+ p.status = "failed";+ p.error = `Didn't start: ${labelOf(state, from)} failed`;+ moved = true;+ }+ const doneKeys = new Set(state.parts.filter((p) => p.status === "done").flatMap((p) => keysOf(p.part)));+ for (const p of state.parts) {+ if (p.status !== "waiting" || !p.part.needs.every((k) => doneKeys.has(k))) continue;+ await startPart(id, row.skill, state, p);+ moved = true;+ }+ }+ const first = state.parts.find((p) => p.status === "failed" && !p.error?.startsWith("Didn't start")) ?? state.parts.find((p) => p.status === "failed");+ if (first && !state.error) state.error = first.error?.startsWith("Didn't start") ? first.error : `${labelOf(state, first.failed ?? keysOf(first.part)[0])} failed: ${first.error ?? "it failed"}`;+ const finished = state.parts.every((p) => p.status === "done" || p.status === "failed");+ const status: SkillRunView["status"] = !finished ? "running" : first ? "failed" : "done";+ save(id, state, status);+ return view({ ...row, status, updated_at: Date.now() }, state);+ } finally {+ runLocks.delete(id);+ }+}++/**+ * Start a run of a staged recipe (compile → `staged`): its row, then every part whose inputs exist. `check`: a dry run+ * (every part on the demo provider, hidden from the skill's runs). The run's id is the batch of its pipelines' rows.+ */+export async function startSkillRun(skill: { name: string; title: string }, recipe: Recipe, parts: CompiledPart[], engine: Engine, values: RecipeValues, o: { check?: boolean; id?: string } = {}): Promise<SkillRunView> {+ const id = o.id ?? nanoid(10);+ const now = Date.now();+ const state: RunState = {+ engine,+ title: skill.title,+ labels: recipe.steps.map((s) => ({ key: s.key, label: stepLabel(s) })),+ parts: parts.map((part) => ({ part, status: "waiting", ids: [] })),+ ...(o.check && { check: true }),+ };+ db()+ .prepare("INSERT INTO skill_runs (id, skill, status, values_json, state_json, created_at, updated_at) VALUES (?, ?, 'running', ?, ?, ?, ?)")+ .run(id, skill.name, JSON.stringify(values), JSON.stringify(state), now, now);+ ensureSkillRunSweep();+ return (await advanceSkillRun(id))!;+}++/** One run as its progress shows it (null: no such run). */+export function getSkillRun(id: string): SkillRunView | null {+ const found = load(id);+ return found ? view(found.row, found.state) : null;+}++/** A skill's newest runs (dry runs left out). */+export function listSkillRuns(skill: string, limit = 8): SkillRunView[] {+ const rows = db().prepare("SELECT * FROM skill_runs WHERE skill = ? ORDER BY created_at DESC LIMIT ?").all(skill, limit * 2) as Row[];+ return rows+ .map((row) => ({ row, state: JSON.parse(row.state_json) as RunState }))+ .filter((r) => !r.state.check)+ .slice(0, limit)+ .map((r) => view(r.row, r.state));+}++/** Every generation a run made, with the rows each shares a batch with. */+export function skillRunGenerations(id: string): string[] {+ const found = load(id);+ return found ? withBatchMates(found.state.parts.flatMap((p) => p.ids)) : [];+}++/**+ * The end of a dry run: what it made goes to the Trash, the studio records it opened are deleted, and the row goes+ * (a check isn't a run the user asked for).+ */+export async function discardSkillRun(id: string): Promise<void> {+ const found = load(id);+ if (!found) return;+ await deleteRecords(found.state);+ trashGenerations(skillRunGenerations(id));+ db().prepare("DELETE FROM skill_runs WHERE id = ?").run(id);+}++/** Stop a run: its unfinished parts fail with the reason (a check whose time ran out). */+export function stopSkillRun(id: string, why: string): void {+ const found = load(id);+ if (!found || found.row.status !== "running") return;+ for (const p of found.state.parts) {+ if (p.status === "waiting" || p.status === "running") {+ p.status = "failed";+ p.error = why;+ }+ }+ found.state.error ??= why;+ save(id, found.state, "failed");+}++// ---------------------------------------------------------------------------+// The sweep++declare global {+ var __fuobeSkillRunSweep: { tick: () => void; timer: NodeJS.Timeout } | undefined;+}++/** How often running runs are moved on: a studio step's results start the steps that wait for them. */+const SWEEP_MS = 10_000;++/** Advance every running run (each on its own: one run's error never stops the others). */+export async function sweepSkillRuns(): Promise<void> {+ const ids = (db().prepare("SELECT id FROM skill_runs WHERE status = 'running'").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} couldn't move on: ${(e as Error).message}`);+ }+ }+}++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 starts); runs left running before a restart carry on. */+export function ensureSkillRunSweep(): void {+ const cur = globalThis.__fuobeSkillRunSweep;+ if (cur) {+ cur.tick = tick;+ return;+ }+ const state = { tick, timer: setInterval(() => globalThis.__fuobeSkillRunSweep?.tick(), SWEEP_MS) };+ state.timer.unref?.();+ globalThis.__fuobeSkillRunSweep = state;+}diff --git a/tests/recipe.test.ts b/tests/recipe.test.tsindex 48d80383..f657e855 100644--- a/tests/recipe.test.ts+++ b/tests/recipe.test.ts@@ -68,7 +68,9 @@ 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") });+ // Version 2 (W7: step references) loads; version 1 files still do.+ expect(parseRecipe(JSON.stringify({ ...lamp(), fuobeRecipe: 2 }))).toMatchObject({ ok: true });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..ca9d90fd 100644--- a/tests/recipes.test.ts+++ b/tests/recipes.test.ts@@ -217,8 +217,8 @@ describe("running a recipe", () => {makeSkill("caption-it", captions(), "Caption it");const check = await recipes.verifyRecipe("caption-it", "demo");expect(check.ok).toBe(true);- // A studio step gets the plan check only in W1 (its dry run would make a record the user sees).- expect(check.engines.map((e) => e.dryRun?.skipped)).toEqual([expect.stringContaining("checked by its plan only"), expect.stringContaining("checked by its plan only")]);+ // A studio step's dry run runs the studio as a demo (W7), then deletes what it made.+ expect(check.engines.map((e) => e.dryRun)).toEqual([{ ok: true, problems: [] }, { ok: true, problems: [] }]);const out = await recipes.runRecipe("caption-it", { values: { video: clip, lang: "German" } }, "open");expect(out.runs).toHaveLength(1);expect(out.runs[0].href).toMatch(/^\/video-tools\/captions\?video=/);diff --git a/tests/skill-runs.test.ts b/tests/skill-runs.test.tsnew file mode 100644index 00000000..6a422755--- /dev/null+++ b/tests/skill-runs.test.ts@@ -0,0 +1,224 @@+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 });++const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-skill-runs-"));+process.env.FUOBE_DATA_DIR = dir;+// Nothing listens: models run on the demo provider, and there's no LLM.+process.env.COMFYUI_URL = "http://127.0.0.1:9";+process.env.OLLAMA_URL = "http://127.0.0.1:9";++const { setSetting } = await import("@/server/settings");+const skills = await import("@/server/skills");+const recipes = await import("@/server/recipes");+const runs = await import("@/server/skill-runs");+const gens = await import("@/server/generations");+const { db } = await import("@/server/db");+const { saveFile } = await import("@/server/storage");+const { executeTool } = await import("@/server/assist/tools");+const { inDemoScope, runAsDemo } = await import("@/server/demo-scope");+const lib = await import("@/lib/recipe");+const runsRoute = await import("@/app/api/assist/skills/[name]/runs/route");++afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));++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;+});++/** The user story's "Spanish short": dub the clip, burn captions into the dub, cut a 9:16 version of the captioned clip. */+const spanishShort = () => ({+ fuobeRecipe: 2,+ params: [+ { id: "video", label: "Clip", type: "video", required: true, example: clip },+ { id: "lang", label: "Language", type: "choice", options: ["Spanish", "German"], default: "Spanish" },+ ],+ steps: [+ { key: "dub", kind: "tool", label: "Dub", tool: "dub_video", input: { video: "{{video}}", languages: ["{{lang}}"], review: false } },+ { key: "captions", kind: "tool", label: "Captions", tool: "add_captions", input: { video: "{{steps.dub.output}}" } },+ { key: "cut", kind: "generate", label: "9:16 cut", request: { feature: "skill", modelId: "ltx-reframe", op: "reframe", inputs: { video: "{{steps.captions.output}}" }, params: { aspectRatio: "9:16" } } },+ ],+ checks: { cut: { kind: "video" } },+});++function makeSkill(name: string, recipe: unknown, title = "Spanish short") {+ skills.createSkill({ name, title, description: "Dub, captions and a 9:16 cut.", body: "# Spanish short" });+ return recipes.saveRecipe(name, recipe);+}++/** Move a run on until it ends (the sweep does this every few seconds in the app). */+async function finish(id: string, ms = 150_000, mod = runs) {+ const until = Date.now() + ms;+ for (;;) {+ const v = (await mod.advanceSkillRun(id))!;+ if (v.status !== "running") return v;+ if (Date.now() > until) throw new Error(`timed out: ${lib.runLine(v.steps)}`);+ await new Promise((r) => setTimeout(r, 300));+ }+}++const count = (table: string) => (db().prepare(`SELECT COUNT(*) AS n FROM ${table}`).get() as { n: number }).n;++describe("the recipe format, version 2", () => {+ it("checks that every step reference points at an earlier step of a kind that fits", () => {+ const r = lib.RecipeSchema.parse(spanishShort());+ expect(lib.recipeProblems(r)).toEqual([]);+ expect(lib.isStaged(r)).toBe(true);+ expect(lib.recipeParts(r)).toEqual([+ { keys: ["dub"], needs: [] },+ { keys: ["captions"], needs: ["dub"] },+ { keys: ["cut"], needs: ["captions"] },+ ]);+ const broken = lib.RecipeSchema.parse({+ ...spanishShort(),+ steps: [+ { key: "dub", kind: "tool", tool: "dub_video", input: { video: "{{steps.captions.output}}", languages: ["{{lang}}"] } },+ { key: "captions", kind: "tool", tool: "add_captions", input: { video: "{{video}} {{steps.dub.output}}" } },+ { key: "layers", kind: "tool", tool: "split_layers", input: { image: "{{steps.dub.output}}" } },+ { key: "cut", kind: "generate", after: "captions", request: { feature: "skill", modelId: "ltx-reframe", op: "reframe", inputs: { video: "{{steps.nope.output}}" } } },+ ],+ });+ const problems = lib.recipeProblems(broken).join("\n");+ expect(problems).toMatch(/“dub” uses the output of “captions”, which comes after it/);+ expect(problems).toMatch(/a step's output fills a whole field/);+ expect(problems).toMatch(/“layers” takes an image from “dub”, which makes a video/);+ expect(problems).toMatch(/there's no step “nope”/);+ expect(problems).toMatch(/waits for the studio step “captions”: put \{\{steps.captions.output\}\} in its input instead/);+ // A dub that waits for its lines to be reviewed makes no video for the next step.+ expect(problems).toMatch(/“dub” waits for you to review its lines in Translate & dub/);+ // Version 1 files still load, and keep their rule: a tool step alone.+ const v1 = lib.RecipeSchema.parse({ ...spanishShort(), fuobeRecipe: 1 });+ expect(lib.recipeProblems(v1).join("\n")).toMatch(/needs "fuobeRecipe": 2/);+ });++ it("compiles to parts, and fills a reference with the step's first output of the field's kind", () => {+ const r = lib.RecipeSchema.parse(spanishShort());+ const c = lib.compile(r, { video: clip, lang: "Spanish" }, { skill: "s", run: "r", title: "Spanish short" });+ expect(c.kind).toBe("staged");+ if (c.kind !== "staged") return;+ expect(c.parts.map((p) => p.kind)).toEqual(["tool", "tool", "pipeline"]);+ const filled = lib.fillRefs({ video: "{{steps.dub.output}}", images: ["{{steps.dub.output}}"] }, (key, kind) => `/api/files/${key}.${kind}`);+ expect(filled).toEqual({ video: "/api/files/dub.video", images: ["/api/files/dub.image"] });+ expect(() => lib.fillRefs({ video: "{{steps.dub.output}}" }, () => undefined)).toThrow(/“dub” made no video/);+ });+});++describe("a skill that spans studios, in demo mode", () => {+ it("starts the dub, waits, then starts captions and the 9:16 cut as each step finishes", async () => {+ makeSkill("spanish-short", spanishShort());+ expect((await recipes.verifyRecipe("spanish-short", "plan")).ok).toBe(true);+ // Priced step by step: the dub, then captions and the cut on a stand-in for what the step before makes.+ const est = recipes.estimateRecipe("spanish-short", { values: { video: clip } }, "cloud");+ expect(est.runnable).toBe(true);+ expect(est.demo).toBe(true);+ expect(est.place?.studio).toBe("Translate & dub");++ const out = await recipes.runRecipe("spanish-short", { values: { video: clip } }, "cloud");+ expect(out.demo).toBe(true);+ const [run] = out.runs;+ expect(run.run).toBeTruthy();+ // The result names the run and which steps wait.+ expect(run.waiting).toEqual(["Captions", "9:16 cut"]);+ expect(run.href).toMatch(/dub=/);+ const started = runs.getSkillRun(run.run!)!;+ expect(started.steps.map((s) => s.status)).toEqual(["running", "waiting", "waiting"]);+ expect(started.steps[0]).toMatchObject({ studio: "Translate & dub", href: expect.stringContaining("dub=") });++ const done = await finish(run.run!);+ expect(done.status).toBe("done");+ expect(done.steps.map((s) => s.status)).toEqual(["done", "done", "done"]);+ // Each step took the one before's video.+ const dubbed = gens.getGeneration(done.steps[0].ids[0])!;+ const captioned = gens.getGeneration(done.steps[1].ids[0])!;+ const cut = gens.getGeneration(done.steps[2].ids[0])!;+ expect(captioned.request.inputs?.video).toBe(dubbed.outputs.find((o) => o.kind === "video")!.url);+ expect(cut.request.inputs?.video).toBe(captioned.outputs.find((o) => o.kind === "video")!.url);+ expect(cut).toMatchObject({ op: "reframe", status: "succeeded", provider: "mock" });+ // Every row carries the run's stamp and the skill's title.+ for (const g of [dubbed, captioned, cut]) expect(g.request).toMatchObject({ skill: { name: "spanish-short", run: run.run }, batchTitle: "Spanish short" });+ expect(done.steps[1]).toMatchObject({ studio: "Captions", href: expect.stringMatching(/^\/video-tools\/captions\?video=/) });++ // The skill's dialog reads its runs.+ const res = await runsRoute.GET(new Request("http://x/api"), { params: Promise.resolve({ name: "spanish-short" }) } as never);+ const body = (await res.json()) as { items: { id: string; status: string }[] };+ expect(body.items[0]).toMatchObject({ id: run.run, status: "done" });+ expect(lib.runLine(done.steps)).toBe("Dub · done → Captions · done → 9:16 cut · done");+ });++ it("a failed dub fails the steps after it, and says which step failed and why", async () => {+ const out = await recipes.runRecipe("spanish-short", { values: { video: clip } }, "cloud");+ const id = out.runs[0].run!;+ const dub = runs.getSkillRun(id)!.steps[0].ids;+ for (const g of dub) {+ await gens.cancelGeneration(g);+ db().prepare("UPDATE generations SET status = 'failed', error = 'No speech found in the clip' WHERE id = ?").run(g);+ }+ const v = await finish(id);+ expect(v.status).toBe("failed");+ expect(v.error).toBe("Dub failed: No speech found in the clip");+ expect(v.steps.map((s) => [s.status, s.error])).toEqual([+ ["failed", "No speech found in the clip"],+ ["failed", "Didn't start: Dub failed"],+ ["failed", "Didn't start: Captions failed"],+ ]);+ });++ it("keeps its state through a restart: a fresh server reads the run from skill_runs and carries on", async () => {+ const out = await recipes.runRecipe("spanish-short", { values: { video: clip, lang: "German" } }, "cloud");+ const id = out.runs[0].run!;+ // A new process: modules loaded again, nothing in memory but the database.+ vi.resetModules();+ const fresh = await import("@/server/skill-runs");+ const v = await finish(id, 150_000, fresh);+ expect(v.status).toBe("done");+ expect(v.steps.map((s) => s.status)).toEqual(["done", "done", "done"]);+ const row = db().prepare("SELECT values_json, state_json FROM skill_runs WHERE id = ?").get(id) as { values_json: string; state_json: string };+ expect(JSON.parse(row.values_json)).toMatchObject({ video: clip, lang: "German" });+ });+});++describe("the studio dry run", () => {+ it("runs a studio module as a demo with no change to its code", async () => {+ expect(inDemoScope()).toBe(false);+ setSetting("demoMode", "off");+ try {+ const out = await runAsDemo(async () => {+ expect(inDemoScope()).toBe(true);+ return executeTool("add_captions", { video: clip }, { engine: "cloud" });+ });+ expect(out.isError).toBeFalsy();+ const ids = (out.items ?? []).flatMap((i) => (i.role === "generations" ? i.ids : []));+ for (const g of ids) expect(gens.getGeneration(g)).toMatchObject({ provider: "mock", request: { demo: true } });+ } finally {+ setSetting("demoMode", "auto");+ }+ });++ it("checks a recipe that spans studios for free with Demo mode off, then deletes the studio records it made", async () => {+ setSetting("demoMode", "off");+ try {+ makeSkill("spanish-check", spanishShort());+ const before = { dubs: count("dub_sessions"), runs: count("skill_runs") };+ const check = await recipes.verifyRecipe("spanish-check", "demo", "cloud");+ expect(check.engines[0].dryRun).toEqual({ ok: true, problems: [] });+ expect(check.view.recipe.verified?.cloud?.dryRun).toBeTruthy();+ // The dub session it opened is gone, and the run isn't one of the skill's runs.+ expect(count("dub_sessions")).toBe(before.dubs);+ expect(count("skill_runs")).toBe(before.runs);+ // What it made is in the Trash.+ const live = db().prepare("SELECT COUNT(*) AS n FROM generations g WHERE json_extract(request_json, '$.skill.name') = 'spanish-check' AND NOT EXISTS (SELECT 1 FROM generation_trash t WHERE t.generation_id = g.id)").get() as { n: number };+ expect(live.n).toBe(0);+ const made = db().prepare("SELECT COUNT(*) AS n FROM generations WHERE json_extract(request_json, '$.skill.name') = 'spanish-check'").get() as { n: number };+ expect(made.n).toBeGreaterThanOrEqual(3);+ } finally {+ setSetting("demoMode", "auto");+ }+ });+});