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: Suggest a fix names only the step that failed, and a suggestion counts only chains that worked
Claudeae6e49115817
diff --git a/src/components/assist/hooks.ts b/src/components/assist/hooks.tsindex f3c355a8..858c4229 100644--- a/src/components/assist/hooks.ts+++ b/src/components/assist/hooks.ts@@ -227,6 +227,8 @@ export function useRecipeActions() {throw e;} finally {void qc.invalidateQueries({ queryKey: ["assist-skills"] });+ // A re-check can move a step to what replaced it: what needs a fix is read again.+ void qc.invalidateQueries({ queryKey: ["assist-skill-fixes", name] });}},};diff --git a/src/components/assist/skills-view.tsx b/src/components/assist/skills-view.tsxindex e1c4009c..47b62904 100644--- a/src/components/assist/skills-view.tsx+++ b/src/components/assist/skills-view.tsx@@ -293,7 +293,10 @@ function RecipeStatus({ skill }: { skill: Skill }) {const fixes = useStepFixes(skill.name, !!skill.recipe && canCheck).data ?? [];const v = recipe.data;if (!skill.recipe || !v) return null;- const recheck = [...Object.values(v.recheck).flat(), ...fixes.map((f) => f.why)];+ const recheck = [...Object.values(v.recheck).flat(), ...fixes.filter((f) => !f.failing).map((f) => f.why)];+ // A step that keeps failing in its runs: a re-check doesn't change its history, so it's said apart, with Suggest a fix.+ const failing = fixes.filter((f) => f.failing).map((f) => f.why);+ const warn = recheck.length > 0 || failing.length > 0 || !!v.why;const recheckNow = async () => {setBusy(true);try {@@ -308,9 +311,9 @@ function RecipeStatus({ skill }: { skill: Skill }) {}};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>+ <div className={cn("mt-2 flex flex-wrap items-center gap-x-2 gap-y-1 text-[12px]", warn ? "text-amber-700 dark:text-amber-300" : "text-muted-foreground")}>+ {warn ? <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]}` : failing.length ? `Keeps failing: ${failing[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)"}diff --git a/src/lib/catalog/types.ts b/src/lib/catalog/types.tsindex 3fba4dd1..6d19bea4 100644--- a/src/lib/catalog/types.ts+++ b/src/lib/catalog/types.ts@@ -1165,9 +1165,10 @@ export interface GenerationRequest {batchTitle?: string;/*** Server-set: made by a run of a skill's recipe (src/lib/recipe.ts): the skill's name and the run's id (its batch), so- * a run's history can be read back. Stripped from API input, like chainFilled.+ * a run's history can be read back; `step` is the recipe step's key, so a failure is laid at the step that failed.+ * Stripped from API input, like chainFilled.*/- skill?: { name: string; run: string };+ skill?: { name: string; run: string; step?: string };/*** Server-set: run on the demo provider whatever Settings → Demo mode says (a recipe's free dry run): chooseRoute* returns the demo route, and a waiting step runs as a demo after demo steps even with Demo mode off. Stripped fromdiff --git a/src/lib/recipe.ts b/src/lib/recipe.tsindex 09b0b934..00ad2da3 100644--- a/src/lib/recipe.ts+++ b/src/lib/recipe.ts@@ -399,7 +399,7 @@ export function compile(recipe: Recipe, values: RecipeValues, o: CompileOptions)request: {...s.request,batchTitle: o.title.slice(0, 200),- skill: { name: o.skill, run: o.run },+ skill: { name: o.skill, run: o.run, step: s.key },...(s.label && { step: { label: s.label, index: i, of: n } }),...(o.demo && { demo: true, feature: SKILL_CHECK_FEATURE }),},@@ -970,7 +970,7 @@ export interface DagShape {}/** Helper rows a shape never counts (a studio's own steps, the evaluation harness, a skill's dry run). */-const isShapeHelper = (feature: string | undefined) => !!feature && isHelperFeature(feature);+export const isShapeHelper = (feature: string | undefined) => !!feature && isHelperFeature(feature);const OP_WORDS: Record<string, string> = Object.fromEntries(Object.entries(OPERATION_LABELS));@@ -1097,6 +1097,8 @@ export interface StepFix {modelId: string;modelName: string;why: string;+ /** Why is its recent runs (it keeps failing), which a re-check doesn't change; else its model moved or is off. */+ failing?: boolean;candidates: FixCandidate[];}@@ -1106,13 +1108,16 @@ export interface SkillUse {last: number;}+/** Words too common to tell skills apart (a chat's first message is matched word by word). */+const COMMON_WORDS = new Set(["an", "and", "as", "at", "be", "by", "can", "do", "for", "from", "get", "in", "into", "is", "it", "make", "me", "my", "new", "of", "on", "or", "our", "please", "some", "the", "this", "that", "to", "we", "with", "you", "your"]);+/*** Skills in the order Assist should see them: those matching the words first (by how many words match), then the* most used, then the most recently used, then as listed. `now` and the 30-day half-life keep an old favourite from* outranking what's used this week forever.*/export function rankSkills<T extends { name: string; title: string; description: string; whenToUse?: string }>(list: T[], o: { query?: string; uses?: Map<string, SkillUse>; now?: number } = {}): T[] {- const words = (o.query ?? "").toLowerCase().split(/\s+/).filter((w) => w.length > 1);+ const words = [...new Set((o.query ?? "").toLowerCase().split(/[^\p{L}\p{N}-]+/u))].filter((w) => w.length > 1 && !COMMON_WORDS.has(w));const now = o.now ?? Date.now();const score = (s: T) => {const hay = `${s.name} ${s.title} ${s.description} ${s.whenToUse ?? ""}`.toLowerCase();diff --git a/src/server/assist/agent.ts b/src/server/assist/agent.tsindex da95cf27..39dca36c 100644--- a/src/server/assist/agent.ts+++ b/src/server/assist/agent.ts@@ -1326,6 +1326,14 @@ function ordered(results: ToolResult[], order: string[]): ToolResult[] {return [...results].sort((a, b) => order.indexOf(a.tool_use_id) - order.indexOf(b.tool_use_id));}+/** The chat's first message from the user, as text (the skills index ranks the skills that match it first). */+function firstWords(messages: MessageParam[]): string | undefined {+ const first = messages.find((m) => m.role === "user");+ if (!first) return undefined;+ const text = typeof first.content === "string" ? first.content : first.content.flatMap((b) => (b.type === "text" ? [b.text] : [])).join(" ");+ return text.trim().slice(0, 500) || undefined;+}+/*** The chat's system prompt and, when something changed since the model last looked, the* "Context update" message to append. The first call freezes the context into the system prompt.@@ -1339,6 +1347,7 @@ function contextFor(s: State, connectors: Connector[]): { system: ModelRequest["capUsd: s.ext.capUsd,scheduleId: s.ext.scheduleId,connectors: connectors.map((c) => c.name),+ words: firstWords(s.messages),});const sent = factMap(facts);if (!s.ext.context) {diff --git a/src/server/recipes.ts b/src/server/recipes.tsindex e152097a..ec4fc314 100644--- a/src/server/recipes.ts+++ b/src/server/recipes.ts@@ -22,6 +22,7 @@ import {RECIPE_LIMITS,recipeProblems,RecipeSchema,+ isShapeHelper,shapeOf,shapeOfRecipe,SKILL_CHECK_FEATURE,@@ -51,7 +52,7 @@ 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, previewChained, stampRequests, waitedOnFailure } from "./generations";import { trashGenerations } from "./library";import { db } from "./db";import { isOffered, modelLicence, offeredModels } from "./model-access";@@ -988,6 +989,7 @@ interface SweepRow {id: string;feature: string;provider: string;+ status: string;created_at: number;depends_on: string | null;request_json: string;@@ -1001,15 +1003,17 @@ const ONE_INPUTS = ["endImage", "video", "audio", "audio2", "voiceAudio"] as con/*** Group the owner's chains of the last SUGGEST_RULE.days days by shape (shapeOf) and keep the shapes made* SUGGEST_RULE.runs times or more. Only the owner's own runs count (an account's stay out of the owner's lists), and- * never a skill's own runs, a helper row or a canceled one. A chain is the rows linked by depends_on, or by a result- * handed on by hand (its file is another step's input, as the skill builder links them).+ * never a skill's own runs or a helper row. A chain is the rows linked by depends_on, or by a result handed on by hand+ * (its file is another step's input, as the skill builder links them). Only a finished chain counts, and only when it+ * worked: a step that failed or was stopped must have been made again in it (a retry), and its shape and rows are the+ * steps that succeeded, so Make a skill is handed rows the builder can repeat.*/export function sweepSuggestions(now = Date.now()): SkillSuggestion[] {const rows = db().prepare(- `SELECT g.id, g.feature, g.provider, g.created_at, g.depends_on, g.request_json, g.outputs_json FROM generations g+ `SELECT g.id, g.feature, g.provider, g.status, g.created_at, g.depends_on, g.request_json, g.outputs_json FROM generations gLEFT JOIN generation_trash t ON t.generation_id = g.id- WHERE t.deleted_at IS NULL AND g.created_at >= ? AND g.created_at <= ? AND g.status != 'canceled'+ WHERE t.deleted_at IS NULL AND g.created_at >= ? AND g.created_at <= ?AND json_extract(g.request_json, '$.account') IS NULL AND json_extract(g.request_json, '$.skill') IS NULLORDER BY g.created_at DESC LIMIT ${SWEEP_ROWS}`,)@@ -1060,7 +1064,13 @@ export function sweepSuggestions(now = Date.now()): SkillSuggestion[] {chains.set(root, [...(chains.get(root) ?? []), n]);}const groups = new Map<string, { labels: string[]; runs: { ids: string[]; last: number; demo: boolean }[] }>();- for (const chain of chains.values()) {+ const statusOf = (n: ShapeNode) => byId.get(n.id)!.status;+ for (const all of chains.values()) {+ // Still running: it counts once it has finished.+ if (all.some((n) => statusOf(n) === "queued" || statusOf(n) === "running")) continue;+ const chain = all.filter((n) => statusOf(n) === "succeeded");+ const done = (n: ShapeNode) => chain.some((o) => o.modelId === n.modelId && o.op === n.op);+ if (all.some((n) => statusOf(n) !== "succeeded" && !isShapeHelper(n.feature) && !done(n))) continue;const shape = shapeOf(chain);if (shape.steps < 2) continue;const ids = chain.map((n) => n.id);@@ -1144,6 +1154,8 @@ interface HistoryRow {error: string | null;model: string | null;run: string | null;+ /** The recipe step that made the row (older rows have none). */+ step: string | null;}/** The owner's runs of a skill (its stamp in request_json), newest first; a skill's own dry runs don't count. */@@ -1151,7 +1163,8 @@ function historyRows(name: string, limit = 2000): HistoryRow[] {return db().prepare(`SELECT g.id, g.batch_id, g.status, g.cost_usd, g.favorite, g.created_at, g.provider, g.engine, g.error,- json_extract(g.request_json, '$.modelId') AS model, json_extract(g.request_json, '$.skill.run') AS run+ json_extract(g.request_json, '$.modelId') AS model, json_extract(g.request_json, '$.skill.run') AS run,+ json_extract(g.request_json, '$.skill.step') AS stepFROM generations gWHERE json_extract(g.request_json, '$.skill.name') = ? AND g.feature != ? AND json_extract(g.request_json, '$.account') IS NULLORDER BY g.created_at DESC LIMIT ?`,@@ -1215,31 +1228,44 @@ export function skillHistory(name: string, limit = 10): SkillHistory {const FIX_CONSIDER = 16;const FIX_SHOW = 6;-/** A recipe with one step's model swapped (its engine left to the new model). */+/**+ * A recipe with one step's model swapped. A step kept on one engine (for what only that engine does) stays there when+ * the new model also runs on both; otherwise its engine is left to the new model.+ */function withModel(recipe: Recipe, key: string, modelId: string): Recipe {+ const next = getModel(modelId);return {...recipe,steps: recipe.steps.map((s) => {if (s.kind !== "generate" || s.key !== key) return s;const request: Record<string, unknown> = { ...s.request, modelId };- delete request.engine;+ const pinned = s.request.engine;+ if (!(pinned && dualEngine(next) && next!.engines!.includes(pinned))) delete request.engine;return { ...s, request: request as typeof s.request };}),};}+/** A waiting step's failure that an earlier step caused (advanceDependents: waitedOnFailure, or an input that fell short). */+const UPSTREAM = waitedOnFailure().replace(/ didn't finish$/, " ");+const upstreamFailure = (error: string | null) => !!error && (error === waitedOnFailure() || error.startsWith(UPSTREAM));+/** Why a step needs a fix: it failed in 2 of the last 5 runs, it was moved by REPLACED_BY, or it's switched off. */-function stepTrouble(s: Recipe["steps"][number], lastRuns: { rows: HistoryRow[] }[]): string | null {+function stepTrouble(s: Recipe["steps"][number], lastRuns: { rows: HistoryRow[] }[]): { why: string; failing?: boolean } | null {if (s.kind !== "generate") return null;const r = replacedBy(s.request.modelId);- if (r) return `${r.was} was replaced by ${getModel(r.id)?.name ?? r.id}`;+ if (r) return { why: `${r.was} was replaced by ${getModel(r.id)?.name ?? r.id}` };const id = currentModelId(s.request.modelId);const m = getModel(id);- if (!m) return `Fuobe has no model “${s.request.modelId}” anymore`;+ if (!m) return { why: `Fuobe has no model “${s.request.modelId}” anymore` };const engines = dualEngine(m) ? (s.request.engine ? [s.request.engine] : (m.engines ?? ENGINES)) : [undefined];- if (!engines.some((e) => isOffered(id, e))) return `${m.name} is switched off in Settings → Models & licences`;- const failed = lastRuns.filter((run) => run.rows.some((row) => row.status === "failed" && row.model !== null && currentModelId(row.model) === id)).length;- if (failed >= 2) return `${m.name} failed in ${failed} of the last ${lastRuns.length} runs`;+ if (!engines.some((e) => isOffered(id, e))) return { why: `${m.name} is switched off in Settings → Models & licences` };+ // A step's own failure only: a step failed by what an earlier one did ("An earlier step didn't finish", or made too+ // little) never ran, so it isn't blamed. A row says which step made it; an older row without that is matched by model.+ const ownFailure = (row: HistoryRow) =>+ row.status === "failed" && !upstreamFailure(row.error) && (row.step !== null ? row.step === s.key : row.model !== null && currentModelId(row.model) === id);+ const failed = lastRuns.filter((run) => run.rows.some(ownFailure)).length;+ if (failed >= 2) return { why: `${m.name} failed in ${failed} of the last ${lastRuns.length} runs`, failing: true };return null;}@@ -1256,8 +1282,9 @@ export function stepFixes(name: string): StepFix[] {const out: StepFix[] = [];for (const s of recipe.steps) {if (s.kind !== "generate") continue;- const why = stepTrouble(s, lastRuns);- if (!why) continue;+ const trouble = stepTrouble(s, lastRuns);+ if (!trouble) continue;+ const { why, failing } = trouble;const was = getModel(s.request.modelId);const id = currentModelId(s.request.modelId);const m = getModel(id) ?? was;@@ -1287,7 +1314,7 @@ export function stepFixes(name: string): StepFix[] {if (candidates.length >= FIX_SHOW) break;}}- out.push({ key: s.key, label: s.label ?? (op ? (OPERATION_LABELS[op] ?? op) : s.key), modelId: s.request.modelId, modelName: was?.name ?? m?.name ?? s.request.modelId, why, candidates });+ out.push({ key: s.key, label: s.label ?? (op ? (OPERATION_LABELS[op] ?? op) : s.key), modelId: s.request.modelId, modelName: was?.name ?? m?.name ?? s.request.modelId, why, ...(failing && { failing }), candidates });}return out;}diff --git a/tests/recipe.test.ts b/tests/recipe.test.tsindex 48d80383..e3344921 100644--- a/tests/recipe.test.ts+++ b/tests/recipe.test.ts@@ -222,7 +222,7 @@ describe("fill and compile", () => {expect(c.steps[1]).toMatchObject({ after: ["cutout"], chain: [{ slot: "images", position: "first" }] });for (const s of c.steps) {expect(s.request.batchTitle).toBe("Lamp turntable");- expect(s.request.skill).toEqual({ name: "lamp-turntable", run: "run123" });+ expect(s.request.skill).toEqual({ name: "lamp-turntable", run: "run123", step: s.key });expect(s.request.demo).toBeUndefined();expect(s.request.feature).toBe("skill");}diff --git a/tests/recipes.test.ts b/tests/recipes.test.tsindex d16dc34c..7dda487f 100644--- a/tests/recipes.test.ts+++ b/tests/recipes.test.ts@@ -164,9 +164,9 @@ describe("running a recipe", () => {expect(run.ids).toHaveLength(3);const rows = run.ids.map(rowOf);expect(new Set(rows.map((r) => r.batch_id))).toEqual(new Set([run.batchId]));- for (const r of rows) {+ for (const [i, r] of rows.entries()) {const req = JSON.parse(r.request_json);- expect(req.skill).toEqual({ name: "lamp", run: run.batchId });+ expect(req.skill).toEqual({ name: "lamp", run: run.batchId, step: ["cutout", "scene", "spin"][i] });expect(req.batchTitle).toBe("Lamp turntable");expect(req.demo).toBeUndefined();}@@ -571,4 +571,53 @@ describe("run history, fixes and use (W6)", () => {const index = chatFacts({ engine: "cloud", autoApprove: false, projectId: null, skills: [] }).filter((f) => f.section === "skills");expect(index[0].key).toBe("hist");});++ it("puts a skill that matches the chat's words first in Assist's skills index, ahead of the most used", async () => {+ skills.createSkill({ name: "gig-poster", title: "Gig poster", description: "A bold gig poster for a band night.", body: "# Poster" });+ const { chatFacts } = await import("@/server/assist/context");+ const index = (words?: string) => chatFacts({ engine: "cloud", autoApprove: false, projectId: null, skills: [], words }).filter((f) => f.section === "skills").map((f) => f.key);+ expect(index()[0]).toBe("hist");+ expect(index("Make us a gig poster for our band night, please")[0]).toBe("gig-poster");+ // Common words alone match nothing.+ expect(index("make it for me with the")[0]).toBe("hist");+ });++ it("blames only the step that failed, not the steps after it that never ran", async () => {+ makeSkill("hist-up", lamp(), "Upstream lamp");+ const { waitedOnFailure } = await import("@/server/generations");+ const at = Date.now() + 120_000;+ let n = 0;+ const insert = (run: string, step: string, model: string, status: string, error: string | null) =>+ db()+ .prepare(+ `INSERT INTO generations (id, batch_id, feature, model_id, engine, provider, op, kind, status, request_json, outputs_json, created_at, updated_at, error)+ VALUES (?, ?, 'skill', ?, 'cloud', 'fal', 'edit', 'image', ?, ?, '[]', ?, ?, ?)`,+ )+ .run(`up${++n}`.padEnd(12, "x"), run, model, status, JSON.stringify({ feature: "skill", modelId: model, skill: { name: "hist-up", run, step } }), at + n, at + n, error);+ for (const run of ["uprun1", "uprun2"]) {+ insert(run, "cutout", "birefnet-cloud", "succeeded", null);+ insert(run, "scene", "nano-banana-pro", "failed", "The provider refused it");+ insert(run, "spin", "kling-3", "failed", waitedOnFailure());+ }+ const fixes = recipes.stepFixes("hist-up");+ expect(fixes.map((f) => [f.key, f.why, f.failing])).toEqual([["scene", "Nano Banana Pro failed in 2 of the last 2 runs", true]]);+ });++ it("keeps a step on the engine it was kept on when the fix runs on both", async () => {+ const pinned = soul();+ (pinned.steps[0].request as Record<string, unknown>).engine = "open";+ makeSkill("soul-pinned", pinned, "Pinned portrait");+ expect((await recipes.verifyRecipe("soul-pinned", "plan")).view.ready).toEqual(["open"]);+ changeAccess([{ kind: "model", id: "fuobe-soul", on: false }]);+ try {+ const [fix] = recipes.stepFixes("soul-pinned");+ const pick = fix.candidates.find((c) => c.modelId === "fuobe-soul-hd");+ expect(pick).toMatchObject({ engine: "open" });+ const done = await recipes.applyFix("soul-pinned", "portrait", "fuobe-soul-hd");+ expect(done.view.recipe.steps[0]).toMatchObject({ request: { modelId: "fuobe-soul-hd", engine: "open" } });+ expect(done.view.engines).toEqual(["open"]);+ } finally {+ changeAccess([{ kind: "model", id: "fuobe-soul", on: true }]);+ }+ });});diff --git a/tests/skill-suggest.test.ts b/tests/skill-suggest.test.tsindex 4a87d3e0..04d00338 100644--- a/tests/skill-suggest.test.ts+++ b/tests/skill-suggest.test.ts@@ -214,6 +214,33 @@ describe("the Library's sweep", () => {expect(Array.isArray((await res.json()).items)).toBe(true);});+ it("counts only chains that finished and worked, and hands Make a skill the newest one that did", () => {+ const at = Date.UTC(2027, 0, 15, 12);+ const chain = (t: number, o: { last?: string; first?: string; retry?: boolean } = {}) => {+ const a = row({ at: t, status: o.first, request: { modelId: "birefnet-cloud", op: "bg-remove" } });+ const b = row({ at: t + 1, after: [a], status: o.last, request: { modelId: "seedream-5-pro", op: "edit" } });+ // A step made again after it failed (a retry) is the chain's step.+ const again = o.retry ? row({ at: t + 2, after: [a], request: { modelId: "seedream-5-pro", op: "edit" } }) : undefined;+ return again ? [a, again] : [a, b];+ };+ const pick = (t: number) => recipes.sweepSuggestions(t).find((s) => s.labels.join() === "Background removal,Image edit");+ chain(at - 5 * DAY);+ chain(at - 4 * DAY);+ // Failed (the last step, or the first so the next never ran) or still running: not one of the times.+ chain(at - 3 * DAY, { last: "failed" });+ chain(at - 3 * DAY + 100, { first: "failed", last: "failed" });+ chain(at - 3 * DAY + 200, { first: "canceled", last: "canceled" });+ expect(pick(at)).toBeUndefined();+ const third = chain(at - 2 * DAY);+ chain(at - DAY, { last: "failed" });+ chain(at - DAY / 2, { last: "running" });+ chain(at - DAY / 3, { last: "queued" });+ expect(pick(at)).toMatchObject({ count: 3, ids: third });+ // A failed step made again counts, with the rows that worked.+ const retried = chain(at - DAY / 4, { last: "failed", retry: true });+ expect(pick(at)).toMatchObject({ count: 4, ids: retried });+ });+it("keeps \"suggestions\" from being a skill's name", () => {expect(() => skills.createSkill({ name: "suggestions", title: "S", description: "d", body: "b" })).toThrow(/reserved/);});