Skip to content

armgit / fuobe

Public Imported from GitHub
0

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.

Assist: the most used skills come first in its skills list and context, with tests for suggestions, history and fixes

Claude8d830c52c650
diff --git a/src/server/assist/context-tools.ts b/src/server/assist/context-tools.ts
index 1dd26165..90dc4a7b 100644
--- a/src/server/assist/context-tools.ts
+++ b/src/server/assist/context-tools.ts
@@ -1,7 +1,8 @@
import "server-only";
import { z } from "zod";
import { guessCategory, MEMORY_CATEGORIES, MEMORY_MAX_CHARS, toCategory, type MemoryCategory } from "@/lib/assist";
-import { recipeMarkdown } from "@/lib/recipe";
+import { rankSkills, recipeMarkdown } from "@/lib/recipe";
+import { skillUses } from "../skill-uses";
import { getSkill, skillFile, skillRecipe } from "../skills";
import { canUseSkill, skillsFor } from "./context";
import { defineTool } from "./define";
@@ -22,9 +23,11 @@ const listSkills = defineTool({
let list = skillsFor(projectId);
if (query?.trim()) {
const words = query.toLowerCase().split(/\s+/).filter(Boolean);
- const scored = list.map((s) => ({ s, n: words.filter((w) => `${s.name} ${s.title} ${s.description} ${s.whenToUse}`.toLowerCase().includes(w)).length }));
- if (scored.some((x) => x.n)) list = scored.filter((x) => x.n).sort((a, b) => b.n - a.n).map((x) => x.s);
+ const hits = list.filter((s) => words.some((w) => `${s.name} ${s.title} ${s.description} ${s.whenToUse}`.toLowerCase().includes(w)));
+ if (hits.length) list = hits;
}
+ // Word matches first, then the most used and most recently used skills (their run history).
+ list = rankSkills(list, { query, uses: skillUses() });
return {
content: JSON.stringify(
list.map((s) => {
diff --git a/src/server/assist/context.ts b/src/server/assist/context.ts
index 51ddfbe6..b2914542 100644
--- a/src/server/assist/context.ts
+++ b/src/server/assist/context.ts
@@ -2,8 +2,9 @@ import "server-only";
import type { AssistMemory, ContextFact, Skill } from "@/lib/assist";
import { describeRule, zoneLabel, type ScheduleRule } from "@/lib/assist-schedule";
import type { Engine } from "@/lib/catalog/types";
-import { recipeMarkdown } from "@/lib/recipe";
+import { rankSkills, recipeMarkdown } from "@/lib/recipe";
import { db } from "../db";
+import { skillUses } from "../skill-uses";
import { engineMode } from "../settings";
import { enabledSkills, getSkill, skillRecipe } from "../skills";
import { memoriesFor } from "./memory";
@@ -35,6 +36,8 @@ export interface ChatInfo {
scheduleId?: string | null;
/** The custom MCP connectors Claude has in this chat (their names). */
connectors?: string[];
+ /** The chat's first words: skills that match them come first in the skills index (with the most used ones). */
+ words?: string;
}
export function engineLine(engine: Engine): string {
@@ -151,7 +154,8 @@ export function chatFacts(c: ChatInfo, now = new Date()): ContextFact[] {
if (chars > MEMORY_CHARS) break;
facts.push({ section: "memory", key: m.id, text: line });
}
- const available = skillsFor(project?.id ?? null);
+ // Past SKILL_INDEX skills, the ones that match the chat's words, then the most used and most recently used, are kept.
+ const available = rankSkills(skillsFor(project?.id ?? null), { query: c.words, uses: skillUses() });
for (const s of available.slice(0, SKILL_INDEX)) {
// A skill with a recipe runs by itself: said first, so a long description can't cut it off.
const runs = s.recipe ? runsByItself(s.name) : "";
diff --git a/src/server/recipes.ts b/src/server/recipes.ts
index 59def432..401bcb49 100644
--- a/src/server/recipes.ts
+++ b/src/server/recipes.ts
@@ -44,7 +44,6 @@ import {
type SkillHistory,
type SkillRunRecord,
type SkillSuggestion,
- type SkillUse,
type StepFix,
} from "@/lib/recipe";
import type { Skill } from "@/lib/assist";
@@ -1186,28 +1185,6 @@ export function skillHistory(name: string, limit = 10): SkillHistory {
};
}
-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;
diff --git a/src/server/skill-uses.ts b/src/server/skill-uses.ts
new file mode 100644
index 00000000..1bf809d0
--- /dev/null
+++ b/src/server/skill-uses.ts
@@ -0,0 +1,31 @@
+import "server-only";
+import { SKILL_CHECK_FEATURE, type SkillUse } from "@/lib/recipe";
+import { db } from "./db";
+
+/**
+ * How each saved skill is used, from the skill stamp on the owner's generations (request_json `skill.name`; a skill's
+ * own dry runs and an account's runs don't count). Assist ranks its skills index and list_skills by it (rankSkills).
+ */
+
+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);
diff --git a/tests/recipes.test.ts b/tests/recipes.test.ts
index 768f6e43..d16dc34c 100644
--- a/tests/recipes.test.ts
+++ b/tests/recipes.test.ts
@@ -466,3 +466,109 @@ describe("the recipe routes", () => {
expect((await recipeRoute.GET(new Request("http://x"), ctx("nope"))).status).toBe(404);
});
});
+
+describe("run history, fixes and use (W6)", () => {
+ const historyRoute = () => import("@/app/api/assist/skills/[name]/history/route");
+ const fixesRoute = () => import("@/app/api/assist/skills/[name]/fixes/route");
+
+ it("reads a skill's history from the skill stamp: runs, success, spend, last run and favourites; its checks don't count", async () => {
+ makeSkill("hist", lamp(), "History lamp");
+ // The free dry run makes rows with the stamp (feature skill-check): they aren't runs.
+ expect((await recipes.verifyRecipe("hist", "demo")).ok).toBe(true);
+ expect(recipes.skillHistory("hist")).toMatchObject({ runs: 0, successRate: null, spentUsd: 0, lastRun: null, favorites: 0, recent: [] });
+ const a = await recipes.runRecipe("hist", { values: { product: photo, name: "Desk lamp" } });
+ const b = await recipes.runRecipe("hist", { values: { product: photo, name: "Floor lamp" } });
+ await settle([...a.runs[0].ids, ...b.runs[0].ids]);
+ db().prepare("UPDATE generations SET favorite = 1 WHERE id = ?").run(a.runs[0].ids[2]);
+ const h = recipes.skillHistory("hist");
+ expect(h).toMatchObject({ runs: 2, successRate: 1, favorites: 1 });
+ expect(h.recent.map((r) => r.batchId)).toEqual([b.runs[0].batchId, a.runs[0].batchId]);
+ expect(h.recent[0]).toMatchObject({ status: "succeeded", steps: 3, demo: true, costUsd: 0 });
+ expect(h.lastRun).toBe(h.recent[0].createdAt);
+ // Over HTTP, and 404 for a skill that doesn't exist.
+ const res = await (await historyRoute()).GET(new Request("http://x"), ctx("hist"));
+ expect(await res.json()).toMatchObject({ runs: 2 });
+ expect((await (await historyRoute()).GET(new Request("http://x"), ctx("nope"))).status).toBe(404);
+ });
+
+ it("offers fixes for a step switched off: models with the same operation and kind that are on, priced; saved only after its checks pass", async () => {
+ const { getModel } = await import("@/lib/catalog");
+ const { isOffered } = await import("@/server/model-access");
+ expect(recipes.stepFixes("hist")).toEqual([]);
+ changeAccess([{ kind: "model", id: "nano-banana-pro", on: false }]);
+ try {
+ const fixes = recipes.stepFixes("hist");
+ expect(fixes.map((f) => f.key)).toEqual(["scene"]);
+ const [fix] = fixes;
+ expect(fix.why).toMatch(/switched off/);
+ expect(fix.candidates.length).toBeGreaterThan(0);
+ for (const c of fix.candidates) {
+ const m = getModel(c.modelId)!;
+ expect(c.modelId).not.toBe("nano-banana-pro");
+ expect(m.kind).toBe("image");
+ expect(m.routes.some((r) => r.op === "edit")).toBe(true);
+ expect(isOffered(c.modelId)).toBe(true);
+ expect(c.engine).toBe("cloud");
+ }
+ // Only an offered model is taken.
+ await expect(recipes.applyFix("hist", "scene", "kling-3")).rejects.toThrow(/Pick one of the models offered/);
+ const pick = fix.candidates[0];
+ const res = await (await fixesRoute()).POST(new Request("http://x", { method: "POST", body: JSON.stringify({ step: "scene", modelId: pick.modelId }) }), ctx("hist"));
+ expect(res.status).toBe(200);
+ const done = (await res.json()) as { ok: boolean; view: { recipe: { steps: { request: { modelId: string } }[] }; ready: string[]; recheck: object } };
+ expect(done.ok).toBe(true);
+ expect(done.view.recipe.steps[1].request.modelId).toBe(pick.modelId);
+ expect(done.view.ready).toEqual(["cloud"]);
+ expect(done.view.recheck).toEqual({});
+ expect(recipes.stepFixes("hist")).toEqual([]);
+ } finally {
+ changeAccess([{ kind: "model", id: "nano-banana-pro", on: true }]);
+ }
+ });
+
+ it("offers a fix for a step that failed in 2 of the last 5 runs", async () => {
+ const at = Date.now() + 60_000;
+ const insert = (run: string, i: number, status: string) =>
+ 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', 'kling-3', 'cloud', 'fal', 'i2v', 'video', ?, ?, '[]', ?, ?, ?)`,
+ )
+ .run(`fail${run}${i}`.padEnd(12, "x"), run, status, JSON.stringify({ feature: "skill", modelId: "kling-3", op: "i2v", skill: { name: "hist", run } }), at + i, at + i, status === "failed" ? "The provider refused it" : null);
+ insert("runfail1", 1, "failed");
+ expect(recipes.stepFixes("hist")).toEqual([]);
+ insert("runfail2", 2, "failed");
+ const [fix] = recipes.stepFixes("hist");
+ expect(fix).toMatchObject({ key: "spin", why: "Kling 3.0 failed in 2 of the last 4 runs" });
+ expect(fix.candidates.every((c) => c.modelId !== "kling-3")).toBe(true);
+ expect(recipes.skillHistory("hist")).toMatchObject({ runs: 4, successRate: 0.5 });
+ const res = await (await fixesRoute()).GET(new Request("http://x"), ctx("hist"));
+ expect((await res.json()).items[0]).toMatchObject({ key: "spin" });
+ });
+
+ it("ranks a used skill first, after the skills that match the words", async () => {
+ const { rankSkills } = await import("@/lib/recipe");
+ const { forgetSkillUses, skillUses } = await import("@/server/skill-uses");
+ forgetSkillUses();
+ const uses = skillUses();
+ expect(uses.get("hist")?.runs).toBe(4);
+ const list = [
+ { name: "alpha", title: "Alpha", description: "posters" },
+ { name: "hist", title: "History lamp", description: "turntables" },
+ { name: "gamma", title: "Gamma", description: "posters and banners" },
+ ];
+ expect(rankSkills(list, { uses }).map((s) => s.name)).toEqual(["hist", "alpha", "gamma"]);
+ expect(rankSkills(list, { query: "banners", uses }).map((s) => s.name)).toEqual(["gamma", "hist", "alpha"]);
+ // A run long ago weighs less than runs this week.
+ const now = Date.now();
+ const old = new Map([["alpha", { runs: 3, last: now - 200 * 86_400_000 }], ["gamma", { runs: 3, last: now }]]);
+ expect(rankSkills(list, { uses: old, now }).map((s) => s.name)).toEqual(["gamma", "alpha", "hist"]);
+ // list_skills and Assist's skills index use it.
+ const { executeTool } = await import("@/server/assist/tools");
+ const listed = JSON.parse(String((await executeTool("list_skills", {}, { engine: "cloud" })).content)) as { name: string }[];
+ expect(listed[0].name).toBe("hist");
+ const { chatFacts } = await import("@/server/assist/context");
+ const index = chatFacts({ engine: "cloud", autoApprove: false, projectId: null, skills: [] }).filter((f) => f.section === "skills");
+ expect(index[0].key).toBe("hist");
+ });
+});
diff --git a/tests/skill-suggest.test.ts b/tests/skill-suggest.test.ts
new file mode 100644
index 00000000..9368f4ed
--- /dev/null
+++ b/tests/skill-suggest.test.ts
@@ -0,0 +1,200 @@
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
+
+// Route handlers call connection() (no request scope in a test).
+vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));
+vi.setConfig({ testTimeout: 60_000 });
+
+/**
+ * Skills W6: the Library notices a chain made SUGGEST_RULE.runs times in SUGGEST_RULE.days days and offers to save it
+ * as a skill (shapeOf, the sweep, "Not now" and "Don't suggest this", and no card for a chain a saved skill has).
+ */
+
+const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-skill-suggest-"));
+process.env.FUOBE_DATA_DIR = dir;
+process.env.COMFYUI_URL = "http://127.0.0.1:9";
+process.env.OLLAMA_URL = "http://127.0.0.1:9";
+
+const { setSetting } = await import("@/server/settings");
+const { db } = await import("@/server/db");
+const skills = await import("@/server/skills");
+const recipes = await import("@/server/recipes");
+const { trashGenerations } = await import("@/server/library");
+const { shapeOf, shapeOfRecipe, shapeWords, SUGGEST_RULE } = await import("@/lib/recipe");
+const route = await import("@/app/api/assist/skills/suggestions/route");
+
+afterAll(() => {
+ try {
+ fs.rmSync(dir, { recursive: true, force: true });
+ } catch {}
+});
+
+beforeAll(() => {
+ setSetting("demoMode", "auto");
+ setSetting("enhanceProvider", "none");
+});
+
+const DAY = 86_400_000;
+let n = 0;
+
+/** One stored row, as the runner leaves a finished generation. */
+function row(o: { request: Record<string, unknown>; after?: string[]; at: number; provider?: string; feature?: string; status?: string; batch?: string }): string {
+ const id = `g${++n}`.padEnd(12, "x");
+ const req = { feature: o.feature ?? "image", ...o.request };
+ db()
+ .prepare(
+ `INSERT INTO generations (id, batch_id, feature, model_id, engine, provider, op, kind, status, request_json, outputs_json, created_at, updated_at, depends_on)
+ VALUES (?, ?, ?, ?, 'cloud', ?, ?, 'image', ?, ?, '[]', ?, ?, ?)`,
+ )
+ .run(id, o.batch ?? null, req.feature, String(req.modelId), o.provider ?? "fal", String(req.op ?? "t2i"), o.status ?? "succeeded", JSON.stringify(req), o.at, o.at, o.after?.length ? (o.after.length === 1 ? o.after[0] : JSON.stringify(o.after)) : null);
+ return id;
+}
+
+/** The turntable chain: a cut-out, a scene from it, a clip of the scene. Prompts and inputs vary with `i`. */
+function turntable(at: number, i: number, o: { provider?: string } = {}): string[] {
+ const batch = `b${at}${i}`;
+ const cut = row({ at, batch, provider: o.provider, request: { modelId: "birefnet-cloud", op: "bg-remove", inputs: { images: [`/api/files/uploads/p${i}.png`] } } });
+ const scene = row({ at: at + 1, batch, provider: o.provider, after: [cut], request: { modelId: "nano-banana-pro", op: "edit", prompt: `product ${i} on a plinth`, chain: [{ slot: "images", position: "first" }] } });
+ const spin = row({ at: at + 2, batch, provider: o.provider, after: [scene], request: { modelId: "kling-3", op: "i2v", prompt: `turntable ${i}`, params: { duration: 5 }, chain: [{ slot: "images" }] } });
+ return [cut, scene, spin];
+}
+
+const node = (id: string, modelId: string, op: string, after: string[] = [], o: { feature?: string; slots?: string[] } = {}) => ({ id, modelId, op, after, slots: o.slots ?? after.map(() => "images"), ...(o.feature && { feature: o.feature }) });
+
+describe("shapeOf", () => {
+ it("gives the same chain with other prompts and inputs one shape, and its steps in order", () => {
+ const a = shapeOf([node("a1", "birefnet-cloud", "bg-remove"), node("a2", "nano-banana-pro", "edit", ["a1"]), node("a3", "kling-3", "i2v", ["a2"])]);
+ const b = shapeOf([node("b3", "kling-3", "i2v", ["b2"]), node("b1", "birefnet-cloud", "bg-remove"), node("b2", "nano-banana-pro", "edit", ["b1"])]);
+ expect(a.key).toBe(b.key);
+ expect(a.steps).toBe(3);
+ expect(shapeWords(a.labels)).toBe("Background removal → image edit → image to video");
+ // Another model, another slot or another link is another shape.
+ expect(shapeOf([node("a1", "birefnet-cloud", "bg-remove"), node("a2", "seedream-5-pro", "edit", ["a1"]), node("a3", "kling-3", "i2v", ["a2"])]).key).not.toBe(a.key);
+ expect(shapeOf([node("a1", "birefnet-cloud", "bg-remove"), node("a2", "nano-banana-pro", "edit", ["a1"], { slots: ["endImage"] }), node("a3", "kling-3", "i2v", ["a2"])]).key).not.toBe(a.key);
+ expect(shapeOf([node("a1", "birefnet-cloud", "bg-remove"), node("a2", "nano-banana-pro", "edit", ["a1"]), node("a3", "kling-3", "i2v", ["a1"])]).key).not.toBe(a.key);
+ });
+
+ it("ignores helper rows and the evaluation harness, and counts a step's several takes once", () => {
+ const plain = shapeOf([node("a1", "birefnet-cloud", "bg-remove"), node("a2", "nano-banana-pro", "edit", ["a1"])]);
+ const helped = shapeOf([
+ node("a1", "birefnet-cloud", "bg-remove"),
+ node("a2", "nano-banana-pro", "edit", ["a1"]),
+ node("a3", "nano-banana-pro", "edit", ["a1"]),
+ node("h1", "oss-z-image-turbo", "t2i", [], { feature: "eval" }),
+ node("h2", "oss-z-image-turbo", "t2i", ["a2"], { feature: "faceless-step" }),
+ node("h3", "nano-banana-pro", "edit", ["a1"], { feature: "skill-check" }),
+ ]);
+ expect(helped).toEqual(plain);
+ expect(plain.steps).toBe(2);
+ });
+
+ it("matches a recipe's shape with its runs'", () => {
+ const recipe = {
+ steps: [
+ { key: "cutout", kind: "generate" as const, request: { feature: "skill", modelId: "birefnet-cloud", op: "bg-remove" } },
+ { key: "scene", kind: "generate" as const, after: ["cutout"], chain: [{ slot: "images" as const, position: "first" as const }], request: { feature: "skill", modelId: "nano-banana-pro", op: "edit" } },
+ ],
+ };
+ expect(shapeOfRecipe(recipe)!.key).toBe(shapeOf([node("x", "birefnet-cloud", "bg-remove"), node("y", "nano-banana-pro", "edit", ["x"])]).key);
+ expect(shapeOfRecipe({ steps: [{ key: "c", kind: "tool", tool: "add_captions", input: {} }] })).toBeNull();
+ });
+});
+
+describe("the Library's sweep", () => {
+ const now = Date.UTC(2026, 10, 3, 12);
+
+ it("suggests a chain made 3 times in 14 days, with the newest run's rows, and not before", () => {
+ expect(SUGGEST_RULE).toEqual({ runs: 3, days: 14 });
+ // One run a month ago doesn't count; two this week aren't enough.
+ turntable(now - 20 * DAY, 0);
+ turntable(now - 3 * DAY, 1);
+ turntable(now - 2 * DAY, 2);
+ // A one-step job made often is never a chain.
+ for (let i = 0; i < 5; i++) row({ at: now - DAY + i, request: { modelId: "nano-banana-pro", op: "t2i", prompt: `cat ${i}` } });
+ // The eval harness and a skill's own runs don't count.
+ const evalRun = row({ at: now - DAY, feature: "eval", request: { modelId: "birefnet-cloud", op: "bg-remove" } });
+ row({ at: now - DAY + 1, feature: "eval", after: [evalRun], request: { modelId: "nano-banana-pro", op: "edit" } });
+ const skilled = row({ at: now - DAY, request: { modelId: "birefnet-cloud", op: "bg-remove", skill: { name: "x", run: "r" } } });
+ row({ at: now - DAY + 1, after: [skilled], request: { modelId: "nano-banana-pro", op: "edit", skill: { name: "x", run: "r" } } });
+ row({ at: now - DAY + 2, request: { modelId: "kling-3", op: "i2v" } });
+ expect(recipes.sweepSuggestions(now)).toEqual([]);
+
+ const newest = turntable(now - DAY, 3);
+ const found = recipes.sweepSuggestions(now);
+ expect(found).toHaveLength(1);
+ expect(found[0]).toMatchObject({ count: 3, ids: newest, labels: ["Background removal", "Image edit", "Image to video"], demo: false, last: now - DAY + 2 });
+ expect(found[0].shape).toMatch(/^[0-9a-f]{16}$/);
+ });
+
+ it("keeps an account's runs out, and says when every run was a demo", () => {
+ const later = now + DAY;
+ for (let i = 0; i < 3; i++) {
+ const a = row({ at: later - 5 * DAY + i * 10, request: { modelId: "birefnet-cloud", op: "bg-remove", account: "acc1" } });
+ row({ at: later - 5 * DAY + i * 10 + 1, after: [a], request: { modelId: "seedream-5-pro", op: "edit", account: "acc1" } });
+ }
+ expect(recipes.sweepSuggestions(later).some((s) => s.labels.length === 2)).toBe(false);
+ for (let i = 0; i < 3; i++) {
+ const a = row({ at: later - 4 * DAY + i * 10, provider: "mock", request: { modelId: "birefnet-cloud", op: "bg-remove" } });
+ row({ at: later - 4 * DAY + i * 10 + 1, provider: "mock", after: [a], request: { modelId: "seedream-5-pro", op: "edit" } });
+ }
+ const demo = recipes.sweepSuggestions(later).find((s) => s.labels.length === 2);
+ expect(demo).toMatchObject({ count: 3, demo: true });
+ });
+
+ it("runs once a day, and leaves out what was dismissed or put off", async () => {
+ const first = recipes.skillSuggestions({ now });
+ const turn = first.find((s) => s.labels.length === 3)!;
+ expect(turn).toBeTruthy();
+ // A fourth run the same day: the day's sweep stands until tomorrow (or a fresh one).
+ turntable(now - 1000, 4);
+ expect(recipes.skillSuggestions({ now: now + 60_000 }).find((s) => s.shape === turn.shape)?.count).toBe(3);
+ expect(recipes.skillSuggestions({ now: now + DAY + 1 }).find((s) => s.shape === turn.shape)?.count).toBe(4);
+
+ // Not now: gone for a week, then back.
+ const res = await route.POST(new Request("http://x/api/assist/skills/suggestions", { method: "POST", body: JSON.stringify({ shape: turn.shape, action: "later" }) }));
+ expect(res.status).toBe(200);
+ expect(recipes.skillSuggestions({ now: now + DAY + 2 }).some((s) => s.shape === turn.shape)).toBe(false);
+ expect(recipes.skillSuggestions({ now: now + 3 * DAY, fresh: true }).some((s) => s.shape === turn.shape)).toBe(false);
+ // (Back after a week, if it's still made often: the window moves too, so the runs are made again here.)
+ for (let i = 0; i < 3; i++) turntable(now + 7 * DAY + i * 100, 10 + i);
+ expect(recipes.skillSuggestions({ now: now + 9 * DAY, fresh: true }).some((s) => s.shape === turn.shape)).toBe(true);
+
+ // Don't suggest this: never again.
+ recipes.dismissSuggestion(turn.shape, "never", now + 9 * DAY);
+ expect(recipes.skillSuggestions({ now: now + 9 * DAY, fresh: true }).some((s) => s.shape === turn.shape)).toBe(false);
+ expect((await route.POST(new Request("http://x", { method: "POST", body: JSON.stringify({ shape: "nope", action: "dismiss" }) }))).status).toBe(400);
+ });
+
+ it("offers nothing for a chain a saved skill has, and drops a suggestion whose rows were trashed", async () => {
+ const at = Date.UTC(2026, 11, 1, 12);
+ for (let i = 0; i < 3; i++) {
+ const a = row({ at: at - DAY + i * 10, request: { modelId: "birefnet-cloud", op: "bg-remove" } });
+ row({ at: at - DAY + i * 10 + 1, after: [a], request: { modelId: "gpt-image-2", op: "edit" } });
+ }
+ const found = recipes.skillSuggestions({ now: at, fresh: true }).find((s) => s.labels.length === 2)!;
+ expect(found).toBeTruthy();
+ skills.createSkill({ name: "cut-and-place", title: "Cut and place", description: "d", body: "b" });
+ recipes.saveRecipe("cut-and-place", {
+ fuobeRecipe: 1,
+ params: [{ id: "photo", label: "Photo", type: "image", required: true }],
+ steps: [
+ { key: "cut", kind: "generate", request: { feature: "skill", modelId: "birefnet-cloud", op: "bg-remove", inputs: { images: ["{{photo}}"] } } },
+ { key: "place", kind: "generate", after: ["cut"], chain: [{ slot: "images", position: "first" }], request: { feature: "skill", modelId: "gpt-image-2", op: "edit", prompt: "on a plinth" } },
+ ],
+ });
+ expect(recipes.skillSuggestions({ now: at }).some((s) => s.shape === found.shape)).toBe(false);
+ skills.deleteSkill("cut-and-place");
+ expect(recipes.skillSuggestions({ now: at }).some((s) => s.shape === found.shape)).toBe(true);
+ trashGenerations([found.ids[0]]);
+ expect(recipes.skillSuggestions({ now: at }).some((s) => s.shape === found.shape)).toBe(false);
+ // The route answers the owner with the same list.
+ const res = await route.GET(new Request("http://x/api/assist/skills/suggestions"));
+ expect(Array.isArray((await res.json()).items)).toBe(true);
+ });
+
+ it("keeps \"suggestions\" from being a skill's name", () => {
+ expect(() => skills.createSkill({ name: "suggestions", title: "S", description: "d", body: "b" })).toThrow(/reserved/);
+ });
+});