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: Fuobe notices a chain you keep making, keeps each skill's run history, and finds a fix for a failing step
Claudea7aa92321e67
diff --git a/src/app/api/assist/skills/[name]/fixes/route.ts b/src/app/api/assist/skills/[name]/fixes/route.tsnew file mode 100644index 00000000..700d7745--- /dev/null+++ b/src/app/api/assist/skills/[name]/fixes/route.ts@@ -0,0 +1,27 @@+import { connection } from "next/server";+import { z } from "zod";+import { badBody, recipeFailure } from "@/server/recipe-routes";+import { applyFix, stepFixes } from "@/server/recipes";++/** The steps that need a fix (failing, replaced or switched off), each with the models that could take its place, priced. */+export async function GET(_request: Request, ctx: RouteContext<"/api/assist/skills/[name]/fixes">) {+ await connection();+ try {+ return Response.json({ items: stepFixes((await ctx.params).name) });+ } catch (e) {+ return recipeFailure(e);+ }+}++const Body = z.object({ step: z.string().min(1).max(40), modelId: z.string().min(1).max(120) });++/** Use the picked model in that step: saved only once its plan and the free dry run pass. */+export async function POST(request: Request, ctx: RouteContext<"/api/assist/skills/[name]/fixes">) {+ const parsed = Body.safeParse(await request.json().catch(() => null));+ if (!parsed.success) return badBody(parsed.error.issues);+ try {+ return Response.json(await applyFix((await ctx.params).name, parsed.data.step, parsed.data.modelId));+ } catch (e) {+ return recipeFailure(e);+ }+}diff --git a/src/app/api/assist/skills/[name]/history/route.ts b/src/app/api/assist/skills/[name]/history/route.tsnew file mode 100644index 00000000..cba67e84--- /dev/null+++ b/src/app/api/assist/skills/[name]/history/route.ts@@ -0,0 +1,13 @@+import { connection } from "next/server";+import { recipeFailure } from "@/server/recipe-routes";+import { skillHistory } from "@/server/recipes";++/** A skill's runs (from the skill stamp on the owner's generations): counts, success rate, spend and the last 10. */+export async function GET(_request: Request, ctx: RouteContext<"/api/assist/skills/[name]/history">) {+ await connection();+ try {+ return Response.json(skillHistory((await ctx.params).name));+ } catch (e) {+ return recipeFailure(e);+ }+}diff --git a/src/app/api/assist/skills/suggestions/route.ts b/src/app/api/assist/skills/suggestions/route.tsnew file mode 100644index 00000000..eec4a584--- /dev/null+++ b/src/app/api/assist/skills/suggestions/route.ts@@ -0,0 +1,33 @@+import { connection } from "next/server";+import { z } from "zod";+import { isGuest } from "@/lib/guest-access";+import { badBody, recipeFailure } from "@/server/recipe-routes";+import { dismissSuggestion, skillSuggestions } from "@/server/recipes";++/**+ * Chains the owner made often lately that no saved skill has yet (the Library's "Save it as a skill?" card). The sweep+ * runs at most once a day, when the Library asks. A guest or an account (public sign-up) gets none: the runs are the owner's.+ */+export async function GET(request: Request) {+ await connection();+ if (isGuest(request)) return Response.json({ items: [] });+ try {+ return Response.json({ items: skillSuggestions() });+ } catch (e) {+ return recipeFailure(e);+ }+}++const Body = z.object({ shape: z.string().regex(/^[0-9a-f]{16}$/), action: z.enum(["dismiss", "later"]) });++/** "Don't suggest this" (dismiss) or "Not now" (later: a week). */+export async function POST(request: Request) {+ const parsed = Body.safeParse(await request.json().catch(() => null));+ if (!parsed.success) return badBody(parsed.error.issues);+ try {+ dismissSuggestion(parsed.data.shape, parsed.data.action === "dismiss" ? "never" : "later");+ return Response.json({ ok: true });+ } catch (e) {+ return recipeFailure(e);+ }+}diff --git a/src/lib/recipe.ts b/src/lib/recipe.tsindex 42fdf920..81af2a3d 100644--- a/src/lib/recipe.ts+++ b/src/lib/recipe.ts@@ -14,7 +14,8 @@*/import { z } from "zod";import type { PlannedJob } from "./assist";-import type { ChainSlot, GenerationRequest, MediaKind, OutputFile } from "./catalog/types";+import { OPERATION_LABELS, type ChainSlot, type GenerationRequest, type MediaKind, type OutputFile } from "./catalog/types";+import { isHelperFeature } from "./library";import type { MediaInfo } from "./media-probe";export const RECIPE_FILE = "recipe.json";@@ -941,3 +942,185 @@ export interface VerifyResult {engines: EngineCheck[];view: RecipeView;}++// ---------------------------------------------------------------------------+// Noticing repeated work, run history and finding skills (package W6)++/**+ * One step of a DAG as shapeOf reads it: from a generation row (its request_json and depends_on) or from a recipe's+ * generate step. `modelId` is the model it runs on now (the server moves a retired id first); `slots` are the chain+ * slots its earlier steps fill, in `after` order.+ */+export interface ShapeNode {+ id: string;+ modelId: string;+ op?: string;+ feature?: string;+ after: string[];+ slots: string[];+}++export interface DagShape {+ /** The shape's identity: equal for the same models, operations and chain slots, whatever the prompts and inputs. */+ key: string;+ /** Distinct steps (a step's several takes are one step). */+ steps: number;+ /** Each step's operation in words, earliest first ("Background removal", "Image edit", "Image to video"). */+ labels: string[];+}++/** 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);++const OP_WORDS: Record<string, string> = Object.fromEntries(Object.entries(OPERATION_LABELS));++/**+ * The shape of a DAG of steps: the sorted model ids, operations and chain slots of its steps and of the steps each one+ * waits for. Prompts, inputs, params and the run's own ids don't count; neither do helper rows (`isHelperFeature`,+ * the `eval` harness and a skill's dry run), which are dropped with their links. A step that made several takes is+ * one step. Pure: the Library's sweep groups runs by it, and a saved recipe's shape (shapeOfRecipe) is compared with it.+ */+export function shapeOf(nodes: ShapeNode[]): DagShape {+ const kept = nodes.filter((n) => !isShapeHelper(n.feature));+ const byId = new Map(kept.map((n) => [n.id, n]));+ const memo = new Map<string, string>();+ const depth = new Map<string, number>();+ const visiting = new Set<string>();+ const sig = (n: ShapeNode): string => {+ const known = memo.get(n.id);+ if (known !== undefined) return known;+ if (visiting.has(n.id)) return `${n.modelId}|${n.op ?? ""}`;+ visiting.add(n.id);+ const parents = n.after.flatMap((id, i) => {+ const p = byId.get(id);+ return p ? [`${n.slots[i] ?? "images"}<${sig(p)}>`] : [];+ });+ depth.set(n.id, 1 + Math.max(0, ...n.after.map((id) => (byId.has(id) ? (depth.get(id) ?? 0) : 0))));+ visiting.delete(n.id);+ const s = `${n.modelId}|${n.op ?? ""}${parents.length ? `(${parents.sort().join(",")})` : ""}`;+ memo.set(n.id, s);+ return s;+ };+ const steps = new Map<string, { op?: string; depth: number }>();+ for (const n of kept) {+ const s = sig(n);+ if (!steps.has(s)) steps.set(s, { op: n.op, depth: depth.get(n.id) ?? 1 });+ }+ const sorted = [...steps.entries()].sort((a, b) => a[1].depth - b[1].depth || (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0));+ return {+ key: [...steps.keys()].sort().join("\n"),+ steps: steps.size,+ labels: sorted.map(([, v]) => (v.op ? (OP_WORDS[v.op] ?? v.op) : "Generate")),+ };+}++const asIds = (a: string | string[] | undefined): string[] => (a === undefined ? [] : Array.isArray(a) ? a : [a]);++/**+ * A recipe's shape, as its runs would have it (none for a tool recipe: a studio's own steps aren't compared).+ * `current` gives each model id as it runs now (the server passes currentModelId).+ */+export function shapeOfRecipe(recipe: Pick<Recipe, "steps">, current: (id: string) => string = (id) => id): DagShape | null {+ if (recipe.steps.some((s) => s.kind !== "generate")) return null;+ return shapeOf(+ (recipe.steps as GenerateStep[]).map((s) => {+ const after = asIds(s.after);+ const chain = (s.chain ?? (s.request.chain as ChainSlot[] | undefined)) ?? [];+ return { id: s.key, modelId: current(s.request.modelId), op: typeof s.request.op === "string" ? s.request.op : undefined, feature: s.request.feature, after, slots: after.map((_, i) => chain[i]?.slot ?? "images") };+ }),+ );+}++/** "cut-out → scene → turntable": a suggestion's steps in words. */+export const shapeWords = (labels: string[]): string => labels.map((l, i) => (i ? l.toLowerCase() : l)).join(" → ");++/** A chain made often enough to offer as a skill (the Library's card). */+export interface SkillSuggestion {+ /** The shape's id (a hash of DagShape.key): what "Don't suggest this" remembers. */+ shape: string;+ labels: string[];+ /** Runs of it in the window. */+ count: number;+ /** The newest run's rows: Make a skill drafts from them (W2). */+ ids: string[];+ /** When the newest run was made. */+ last: number;+ /** Every run it was seen in ran on the demo provider: the card says so. */+ demo: boolean;+}++/** How many runs of one shape, within how many days, make a suggestion. */+export const SUGGEST_RULE = { runs: 3, days: 14 } as const;++/** One run of a saved skill (the rows that share its `skill.run` stamp). */+export interface SkillRunRecord {+ run: string;+ batchId: string | null;+ status: "running" | "succeeded" | "failed" | "canceled";+ /** What it cost, where known (the open engine is free). */+ costUsd: number | null;+ createdAt: number;+ steps: number;+ favorite: boolean;+ demo: boolean;+ error?: string;+}++/** A skill's run history (generations whose request_json carries its stamp; a skill's own checks don't count). */+export interface SkillHistory {+ runs: number;+ /** Finished runs that succeeded, 0–1 (null before one finishes). */+ successRate: number | null;+ spentUsd: number;+ lastRun: number | null;+ favorites: number;+ /** The newest runs, newest first. */+ recent: SkillRunRecord[];+}++/** A model that could stand in for a step that needs fixing: same operation and kind, switched on, priced. */+export interface FixCandidate {+ modelId: string;+ name: string;+ engine: RecipeEngine;+ /** The whole run's price with this model in the step (null: varies). */+ total: number | null;+ free: boolean;+}++/** A step of a saved skill that needs a fix, why, and what could replace its model. */+export interface StepFix {+ key: string;+ label: string;+ modelId: string;+ modelName: string;+ why: string;+ candidates: FixCandidate[];+}++/** How a skill is used (from its run history): Assist ranks skills by it. */+export interface SkillUse {+ runs: number;+ last: number;+}++/**+ * 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 now = o.now ?? Date.now();+ const score = (s: T) => {+ const hay = `${s.name} ${s.title} ${s.description} ${s.whenToUse ?? ""}`.toLowerCase();+ const match = words.filter((w) => hay.includes(w)).length;+ const use = o.uses?.get(s.name);+ const fresh = use ? Math.pow(0.5, Math.max(0, now - use.last) / (30 * 86_400_000)) : 0;+ return { match, use: use ? Math.log2(1 + use.runs) * (0.5 + fresh) : 0, last: use?.last ?? 0 };+ };+ return list+ .map((s, i) => ({ s, i, ...score(s) }))+ .sort((a, b) => b.match - a.match || b.use - a.use || b.last - a.last || a.i - b.i)+ .map((x) => x.s);+}diff --git a/src/server/recipe-builder.ts b/src/server/recipe-builder.tsindex dfff2490..8fb520cf 100644--- a/src/server/recipe-builder.ts+++ b/src/server/recipe-builder.ts@@ -696,7 +696,7 @@ function titleFor(g: Generation, label: string): string {function freeName(title: string): string {const base = slugify(title).slice(0, 56).replace(/-+$/, "") || "my-skill";let name = base;- for (let i = 2; getSkill(name) || ["upload", "new", "draft"].includes(name); i++) name = `${base}-${i}`;+ for (let i = 2; getSkill(name) || ["upload", "new", "draft", "suggestions"].includes(name); i++) name = `${base}-${i}`;return name;}diff --git a/src/server/recipes.ts b/src/server/recipes.tsindex 22f521fa..59def432 100644--- a/src/server/recipes.ts+++ b/src/server/recipes.ts@@ -4,10 +4,10 @@ import fs from "node:fs";import path from "node:path";import { nanoid } from "nanoid";import { planRunnable, totalCost, type PlannedJob } from "@/lib/assist";-import { getModel } from "@/lib/catalog";+import { getModel, modelsFor } from "@/lib/catalog";import { dualEngine } from "@/lib/catalog/engines";import { currentModelId, replacedBy } from "@/lib/catalog/replaced";-import type { Engine, Generation, GenerationRequest, MediaKind } from "@/lib/catalog/types";+import { OPERATION_LABELS, type Engine, type Generation, type GenerationRequest, type MediaKind, type Operation } from "@/lib/catalog/types";import { probeMedia, type MediaInfo } from "@/lib/media-probe";import {checkOutputs,@@ -22,7 +22,10 @@ import {RECIPE_LIMITS,recipeProblems,RecipeSchema,+ shapeOf,+ shapeOfRecipe,SKILL_CHECK_FEATURE,+ SUGGEST_RULE,today,verifiedLine,type Compiled,@@ -36,6 +39,13 @@ import {type RecipeView,type VerifiedEngine,type VerifyResult,+ type FixCandidate,+ type ShapeNode,+ type SkillHistory,+ type SkillRunRecord,+ type SkillSuggestion,+ type SkillUse,+ type StepFix,} from "@/lib/recipe";import type { Skill } from "@/lib/assist";import { planSteps } from "./assist/studio-tools";@@ -44,10 +54,11 @@ import { createPipeline } from "./chains";import { llmSeesImages, llmText } from "./enhance";import { cancelGeneration, createGenerations, currentRequest, getGeneration, previewChained, stampRequests } from "./generations";import { trashGenerations } from "./library";-import { isOffered, modelLicence } from "./model-access";+import { db } from "./db";+import { isOffered, modelLicence, offeredModels } from "./model-access";import { GenerationRequestSchema } from "./request-schema";import { engineMode } from "./settings";-import { createSkill, deleteSkill, getSkill, setSkillFile, skillFile, SkillError } from "./skills";+import { createSkill, deleteSkill, getSkill, listSkills, setSkillFile, skillFile, skillRecipe, SkillError } from "./skills";import { absolutePath, readRef, saveFile } from "./storage";/**@@ -925,3 +936,377 @@ export async function saveDraft(input: DraftSave): Promise<RecipeView> {draftChecks().set(key, { verified: { ...known, ...verified }, at: Date.now(), saved: input.name });return recipeView(input.name);}++// ---------------------------------------------------------------------------+// Suggestions, run history, fixes and use (package W6: Fuobe suggests skills and keeps them working)++const DAY_MS = 86_400_000;++/** The settings row that remembers the sweep and the shapes not to suggest (JSON; no migration). The owner's alone. */+const SUGGEST_KEY = "skills.suggestions";++interface SuggestState {+ /** "Don't suggest this": shape ids. */+ dismissed: string[];+ /** "Not now": shape id → when it may come back. */+ later: Record<string, number>;+ /** The last sweep: when, and what it found (before dismissals and saved skills are taken out). */+ swept?: { at: number; list: SkillSuggestion[] };+}++function suggestState(): SuggestState {+ const row = db().prepare("SELECT value FROM settings WHERE key = ?").get(SUGGEST_KEY) as { value: string } | undefined;+ try {+ const v = row ? (JSON.parse(row.value) as Partial<SuggestState>) : {};+ return { dismissed: Array.isArray(v.dismissed) ? v.dismissed.filter((x) => typeof x === "string") : [], later: v.later && typeof v.later === "object" ? v.later : {}, ...(v.swept && { swept: v.swept }) };+ } catch {+ return { dismissed: [], later: {} };+ }+}++function saveSuggestState(s: SuggestState): void {+ db().prepare("INSERT INTO settings (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(SUGGEST_KEY, JSON.stringify(s));+}++/** A shape's id: short, stable, and what dismissals remember. */+const shapeId = (key: string) => crypto.createHash("sha256").update(key).digest("hex").slice(0, 16);++const depList = (v: string | null): string[] => {+ if (!v) return [];+ if (!v.startsWith("[")) return [v];+ try {+ const a = JSON.parse(v) as unknown;+ return Array.isArray(a) ? a.filter((x): x is string => typeof x === "string") : [];+ } catch {+ return [];+ }+};++/** The rows the sweep reads at most (the newest first). */+const SWEEP_ROWS = 5000;++interface SweepRow {+ id: string;+ feature: string;+ provider: string;+ created_at: number;+ depends_on: string | null;+ request_json: string;+}++/**+ * 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.+ */+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 FROM generations g+ LEFT JOIN generation_trash t ON t.generation_id = g.id+ WHERE t.deleted_at IS NULL AND g.created_at >= ? AND g.status != 'canceled'+ AND json_extract(g.request_json, '$.account') IS NULL AND json_extract(g.request_json, '$.skill') IS NULL+ ORDER BY g.created_at DESC LIMIT ${SWEEP_ROWS}`,+ )+ .all(now - SUGGEST_RULE.days * DAY_MS) as SweepRow[];+ const byId = new Map(rows.map((r) => [r.id, r]));+ // Chains: rows joined by depends_on (union-find over the window).+ const parent = new Map(rows.map((r) => [r.id, r.id]));+ const find = (id: string): string => {+ let p = parent.get(id)!;+ while (p !== parent.get(p)) p = parent.get(p)!;+ parent.set(id, p);+ return p;+ };+ const nodes = new Map<string, ShapeNode>();+ for (const r of rows) {+ let req: GenerationRequest;+ try {+ req = JSON.parse(r.request_json) as GenerationRequest;+ } catch {+ continue;+ }+ const after = depList(r.depends_on).filter((d) => byId.has(d));+ for (const d of after) parent.set(find(r.id), find(d));+ nodes.set(r.id, { id: r.id, modelId: currentModelId(req.modelId), op: req.op, feature: req.feature ?? r.feature, after, slots: after.map((_, i) => req.chain?.[i]?.slot ?? "images") });+ }+ const chains = new Map<string, ShapeNode[]>();+ for (const n of nodes.values()) {+ const root = find(n.id);+ 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 shape = shapeOf(chain);+ if (shape.steps < 2) continue;+ const ids = chain.map((n) => n.id);+ const run = { ids, last: Math.max(...ids.map((id) => byId.get(id)!.created_at)), demo: ids.every((id) => byId.get(id)!.provider === "mock") };+ const id = shapeId(shape.key);+ const g = groups.get(id) ?? { labels: shape.labels, runs: [] };+ g.runs.push(run);+ groups.set(id, g);+ }+ return [...groups.entries()]+ .filter(([, g]) => g.runs.length >= SUGGEST_RULE.runs)+ .map(([shape, g]) => {+ const newest = g.runs.reduce((a, b) => (b.last > a.last ? b : a));+ // The newest run's rows, oldest first (as the builder walks them).+ const ids = [...newest.ids].sort((a, b) => byId.get(a)!.created_at - byId.get(b)!.created_at);+ return { shape, labels: g.labels, count: g.runs.length, ids, last: newest.last, demo: g.runs.every((r) => r.demo) };+ })+ .sort((a, b) => b.count - a.count || b.last - a.last);+}++/** The shapes the owner's saved recipe skills already have (a tool recipe has none). */+function savedShapes(): Set<string> {+ const out = new Set<string>();+ for (const s of listSkills()) {+ if (s.source !== "user" || !s.recipe) continue;+ const r = skillRecipe(s.name);+ const shape = r && shapeOfRecipe(r, currentModelId);+ if (shape) out.add(shapeId(shape.key));+ }+ return out;+}++/**+ * The Library's suggestions: the day's sweep (run again at most once a day, when the Library opens, or with `fresh`),+ * without the shapes the owner dismissed or put off, those a saved skill already has, and runs since trashed.+ */+export function skillSuggestions(o: { now?: number; fresh?: boolean } = {}): SkillSuggestion[] {+ const now = o.now ?? Date.now();+ const state = suggestState();+ let list = state.swept?.list;+ if (!list || o.fresh || !(now - state.swept!.at < DAY_MS && state.swept!.at <= now)) {+ list = sweepSuggestions(now);+ // Put-offs that have come back are forgotten.+ const later = Object.fromEntries(Object.entries(state.later).filter(([, until]) => until > now));+ saveSuggestState({ ...state, later, swept: { at: now, list } });+ }+ const saved = savedShapes();+ const dismissed = new Set(state.dismissed);+ const shown = list.filter((s) => !dismissed.has(s.shape) && !((state.later[s.shape] ?? 0) > now) && !saved.has(s.shape));+ if (!shown.length) return [];+ // The newest run's rows must still be there (not trashed since the sweep) for Make a skill to draft from them.+ const ids = shown.flatMap((s) => s.ids);+ const there = new Set(+ (db().prepare(`SELECT g.id FROM generations g LEFT JOIN generation_trash t ON t.generation_id = g.id WHERE t.deleted_at IS NULL AND g.id IN (${ids.map(() => "?").join(", ")})`).all(...ids) as { id: string }[]).map((r) => r.id),+ );+ return shown.filter((s) => s.ids.every((id) => there.has(id)));+}++/** How long "Not now" puts a suggestion off. */+const LATER_MS = 7 * DAY_MS;+const DISMISSED_MAX = 500;++/** "Don't suggest this" (never again) or "Not now" (a week). */+export function dismissSuggestion(shape: string, how: "never" | "later", now = Date.now()): void {+ if (!/^[0-9a-f]{16}$/.test(shape)) throw new SkillError("No such suggestion", 404);+ const state = suggestState();+ if (how === "never") state.dismissed = [...state.dismissed.filter((s) => s !== shape), shape].slice(-DISMISSED_MAX);+ else state.later = { ...state.later, [shape]: now + LATER_MS };+ saveSuggestState(state);+}++interface HistoryRow {+ id: string;+ batch_id: string | null;+ status: string;+ cost_usd: number | null;+ favorite: number;+ created_at: number;+ provider: string;+ engine: string;+ error: string | null;+ model: string | null;+ run: 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. */+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+ FROM generations g+ WHERE json_extract(g.request_json, '$.skill.name') = ? AND g.feature != ? AND json_extract(g.request_json, '$.account') IS NULL+ ORDER BY g.created_at DESC LIMIT ?`,+ )+ .all(name, SKILL_CHECK_FEATURE, limit) as HistoryRow[];+}++/** Rows grouped into runs (by the run stamp), newest first. */+function runsOf(rows: HistoryRow[]): { run: string; rows: HistoryRow[] }[] {+ const runs = new Map<string, HistoryRow[]>();+ for (const r of rows) {+ const key = r.run ?? r.batch_id ?? r.id;+ runs.set(key, [...(runs.get(key) ?? []), r]);+ }+ return [...runs.entries()].map(([run, list]) => ({ run, rows: list })).sort((a, b) => Math.max(...b.rows.map((r) => r.created_at)) - Math.max(...a.rows.map((r) => r.created_at)));+}++function runRecord(run: string, rows: HistoryRow[]): SkillRunRecord {+ const statuses = rows.map((r) => r.status);+ const status: SkillRunRecord["status"] = statuses.some((s) => s === "queued" || s === "running")+ ? "running"+ : statuses.includes("failed")+ ? "failed"+ : statuses.includes("canceled")+ ? "canceled"+ : "succeeded";+ const demo = rows.every((r) => r.provider === "mock");+ const known = rows.filter((r) => r.cost_usd !== null);+ const free = demo || rows.every((r) => r.engine === "open");+ const error = rows.find((r) => r.status === "failed")?.error ?? undefined;+ return {+ run,+ batchId: rows.find((r) => r.batch_id)?.batch_id ?? null,+ status,+ costUsd: free ? 0 : known.length ? Math.round(known.reduce((s, r) => s + (r.cost_usd ?? 0), 0) * 1000) / 1000 : null,+ createdAt: Math.min(...rows.map((r) => r.created_at)),+ steps: rows.length,+ favorite: rows.some((r) => r.favorite === 1),+ demo,+ ...(error && { error }),+ };+}++/** A skill's run history: runs, success rate, spend, last run, favourites and the newest `limit` runs. */+export function skillHistory(name: string, limit = 10): SkillHistory {+ if (!getSkill(name)) throw new SkillError("No such skill", 404);+ const runs = runsOf(historyRows(name)).map((r) => runRecord(r.run, r.rows));+ const finished = runs.filter((r) => r.status === "succeeded" || r.status === "failed");+ return {+ runs: runs.length,+ successRate: finished.length ? Math.round((finished.filter((r) => r.status === "succeeded").length / finished.length) * 100) / 100 : null,+ spentUsd: Math.round(runs.reduce((s, r) => s + (r.costUsd ?? 0), 0) * 1000) / 1000,+ lastRun: runs[0]?.createdAt ?? null,+ favorites: runs.filter((r) => r.favorite).length,+ recent: runs.slice(0, limit),+ };+}++declare global {+ var __fuobeSkillUse: { at: number; uses: Map<string, SkillUse> } | undefined;+}++/** How each skill is used (runs and the last one), from the owner's runs; read again at most once a minute. */+export function skillUses(now = Date.now()): Map<string, SkillUse> {+ const cached = globalThis.__fuobeSkillUse;+ if (cached && now - cached.at < 60_000 && cached.at <= now) return cached.uses;+ const rows = db()+ .prepare(+ `SELECT json_extract(request_json, '$.skill.name') AS name, COUNT(DISTINCT COALESCE(json_extract(request_json, '$.skill.run'), batch_id, id)) AS runs, MAX(created_at) AS last+ FROM generations WHERE json_extract(request_json, '$.skill.name') IS NOT NULL AND feature != ? AND json_extract(request_json, '$.account') IS NULL+ GROUP BY name`,+ )+ .all(SKILL_CHECK_FEATURE) as { name: string; runs: number; last: number }[];+ const uses = new Map(rows.map((r) => [r.name, { runs: r.runs, last: r.last }]));+ globalThis.__fuobeSkillUse = { at: now, uses };+ return uses;+}++/** Forget the cached use counts (a test, or right after a run). */+export const forgetSkillUses = () => void (globalThis.__fuobeSkillUse = undefined);++/** Candidates considered for one step at most, and shown. */+const FIX_CONSIDER = 16;+const FIX_SHOW = 6;++/** A recipe with one step's model swapped (its engine left to the new model). */+function withModel(recipe: Recipe, key: string, modelId: string): Recipe {+ return {+ ...recipe,+ steps: recipe.steps.map((s) => {+ if (s.kind !== "generate" || s.key !== key) return s;+ const { engine: _engine, ...request } = s.request;+ return { ...s, request: { ...request, modelId } as typeof s.request };+ }),+ };+}++/** 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 {+ 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}`;+ const id = currentModelId(s.request.modelId);+ const m = getModel(id);+ if (!m) return `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`;+ return null;+}++/**+ * The steps of a saved skill that need a fix, each with the models that could take its place: the same operation and+ * kind, switched on (search_models' list), each priced as the whole run would be with it. Nothing is swapped here.+ */+export function stepFixes(name: string): StepFix[] {+ const { recipe } = getRecipe(name);+ const lastRuns = runsOf(historyRows(name, 400))+ .slice(0, 5)+ .filter((r) => r.rows.every((x) => x.status !== "queued" && x.status !== "running"));+ const mode = engineMode();+ const out: StepFix[] = [];+ for (const s of recipe.steps) {+ if (s.kind !== "generate") continue;+ const why = stepTrouble(s, lastRuns);+ if (!why) continue;+ const was = getModel(s.request.modelId);+ const id = currentModelId(s.request.modelId);+ const m = getModel(id) ?? was;+ const op = (typeof s.request.op === "string" ? s.request.op : m?.routes[0]?.op) as Operation | undefined;+ const replaced = id !== s.request.modelId;+ const candidates: FixCandidate[] = [];+ if (m && op) {+ const pool = offeredModels(modelsFor({ kind: m.kind, ops: [op], engine: mode === "both" ? "all" : mode })).filter((c) => (replaced ? true : c.id !== id) && c.id !== s.request.modelId);+ // What replaced it first (a re-check's own fix), then the catalog's order.+ pool.sort((a, b) => Number(b.id === id) - Number(a.id === id));+ for (const c of pool.slice(0, FIX_CONSIDER)) {+ const next = withModel(recipe, s.key, c.id);+ const engines = recipeEngines(next);+ let found: FixCandidate | null = null;+ for (const e of engines) {+ try {+ const plan = planCheck(compileRun({ name, title: "Check" }, next, valuesForCheck(next), e, { run: "check" }), e);+ if (plan.errors.length) continue;+ found = { modelId: c.id, name: c.name, engine: e, total: plan.total, free: e === "open" || plan.total === 0 };+ break;+ } catch {+ continue;+ }+ }+ if (found) candidates.push(found);+ 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 });+ }+ return out;+}++/**+ * Put the picked model in a step that needs a fix, after W1's checks pass with it (the plan, then the free dry run) on+ * an engine: then it is saved with what passed. Only a candidate stepFixes offers is taken; nothing changes otherwise.+ */+export async function applyFix(name: string, key: string, modelId: string): Promise<VerifyResult> {+ const found = getRecipe(name);+ if (found.skill.source === "builtin") throw new SkillError("Built-in skills can't be changed — Duplicate it first, then change your copy", 403);+ const fix = stepFixes(name).find((f) => f.key === key);+ if (!fix) throw new SkillError(`Step “${key}” doesn't need a fix`, 409);+ if (!fix.candidates.some((c) => c.modelId === modelId)) throw new SkillError("Pick one of the models offered for this step", 422);+ const next = withModel(found.recipe, key, modelId);+ const problems = allProblems(next);+ if (problems.length) throw new RecipeError(problems);+ const engines = recipeEngines(next);+ if (!engines.length) throw new SkillError(noEngine(next), 422);+ const { checks, verified } = await checkEngines(found.skill, next, "demo", engines, {});+ const passed = checks.filter((c) => c.plan.ok && (c.dryRun?.ok ?? true));+ if (!passed.length) throw new RecipeError([...new Set(checks.flatMap((c) => [...c.plan.errors, ...(c.dryRun?.problems ?? [])]))].slice(0, 6));+ if (!sameRecipe(getRecipe(name).recipe, found.recipe)) throw new SkillError("The recipe changed while it was being checked — try again", 409);+ saveRecipe(name, { ...next, verified }, { keepVerified: true });+ return { ok: allPassed(checks), engines: checks, view: recipeView(name) };+}diff --git a/src/server/skills.ts b/src/server/skills.tsindex c97d094f..b91eab31 100644--- a/src/server/skills.ts+++ b/src/server/skills.ts@@ -248,7 +248,7 @@ function validated(input: SkillInput & { name: string }) {}/** Names the API routes use (static routes beside /api/assist/skills/[name]). */-const RESERVED = new Set(["upload", "new", "draft"]);+const RESERVED = new Set(["upload", "new", "draft", "suggestions"]);function taken(name: string): string | null {if (RESERVED.has(name)) return `“${name}” is reserved — pick another name`;diff --git a/tests/public-signup-visitors.test.ts b/tests/public-signup-visitors.test.tsindex 1e853a36..79cc762d 100644--- a/tests/public-signup-visitors.test.ts+++ b/tests/public-signup-visitors.test.ts@@ -90,6 +90,21 @@ describe("a built-in skill opens for a guest and an account", () => {});});+describe("skill suggestions are the owner's", () => {+ it("passes the Library's read to the route marked as a guest's, which answers none; history and fixes stay closed", async () => {+ for (const cookie of [undefined, account]) {+ const r = proxy(req("/api/assist/skills/suggestions", { cookie }));+ expect(passed(r)).toBe(true);+ expect(toldGuest(r)).toBe(true);+ for (const p of ["/api/assist/skills/s1/history", "/api/assist/skills/s1/fixes"]) expect(proxy(req(p, { cookie })).status, p).toBe(cookie ? 403 : 401);+ }+ expect(toldGuest(proxy(req("/api/assist/skills/suggestions", { cookie: owner })))).toBe(false);+ const route = await import("@/app/api/assist/skills/suggestions/route");+ const r = await route.GET(new Request("http://localhost:3000/api/assist/skills/suggestions", { headers: { [access.GUEST_HEADER]: "1" } }));+ expect(await r.json()).toEqual({ items: [] });+ });+});+describe("Assist is the owner's", () => {const changes: [string, string][] = [["POST", "/api/assist"],@@ -102,6 +117,9 @@ describe("Assist is the owner's", () => {["POST", "/api/assist/skills/draft/name"],["PATCH", "/api/assist/skills/ad-multiplier"],["POST", "/api/assist/skills/product-photoshoot/run"],+ // Skills W6: "Don't suggest this" / "Not now", and a fix for a skill's step.+ ["POST", "/api/assist/skills/suggestions"],+ ["POST", "/api/assist/skills/s1/fixes"],["POST", "/api/assist/memory"],["POST", "/api/assist/memory/import"],["POST", "/api/assist/projects"],diff --git a/tests/public-signup.test.ts b/tests/public-signup.test.tsindex ad74b5b1..4ba9a854 100644--- a/tests/public-signup.test.ts+++ b/tests/public-signup.test.ts@@ -292,6 +292,12 @@ describe("accounts never see or change the owner's library", () => {records: ["/api/assist/t1", "/api/assist/projects/p1"],changes: [["PATCH", "/api/assist/t1"], ["DELETE", "/api/assist/t1"], ["POST", "/api/assist/projects"], ["POST", "/api/assist/memory"]],},+ // Skills W6: a skill's run history and its fixes are the owner's; so are the suggestions' answers.+ skills: {+ lists: [],+ records: ["/api/assist/skills/s1/history", "/api/assist/skills/s1/fixes"],+ changes: [["POST", "/api/assist/skills/suggestions"], ["POST", "/api/assist/skills/s1/fixes"]],+ },brands: { lists: ["/api/brands", "/api/products"], records: ["/api/brands/b1"], changes: [["POST", "/api/brands"], ["DELETE", "/api/brands/b1"], ["POST", "/api/products"]] },};