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.

Library server: tie-safe paging, files kept while still used, Trash cancels jobs

Claude446d3c35c068
diff --git a/src/app/api/generations/route.ts b/src/app/api/generations/route.ts
index 855a61ac..c769017f 100644
--- a/src/app/api/generations/route.ts
+++ b/src/app/api/generations/route.ts
@@ -57,7 +57,8 @@ const RequestSchema = z.object({
/**
* List generations, newest first. Filters: kind / kinds, features (`x*` = prefix), models, statuses,
* favorites=1, folder=<id>, q, since / until (createdAt ms), trash=1 (the Trash, newest deletion first),
- * paging with before=<createdAt> (<deletedAt> in the Trash) and limit (≤ 200).
+ * paging with before=<createdAt>:<id> of the last row (<deletedAt>:<id> in the Trash; a bare
+ * timestamp still works) and limit (≤ 200).
*/
export async function GET(request: Request) {
await connection();
diff --git a/src/app/api/generations/trash/route.ts b/src/app/api/generations/trash/route.ts
index c0429b87..13f95375 100644
--- a/src/app/api/generations/trash/route.ts
+++ b/src/app/api/generations/trash/route.ts
@@ -2,7 +2,7 @@ import { connection } from "next/server";
import { listGenerations } from "@/server/generations";
import { emptyTrash, ensureTrashPurge, listOptionsFrom } from "@/server/library";
-/** The Trash, most recently deleted first (paging: before=<deletedAt>). Same filters as GET /api/generations. */
+/** The Trash, most recently deleted first (paging: before=<deletedAt>:<id> of the last row). Same filters as GET /api/generations. */
export async function GET(request: Request) {
await connection();
ensureTrashPurge();
diff --git a/src/instrumentation.ts b/src/instrumentation.ts
index 3d2eab69..c583f675 100644
--- a/src/instrumentation.ts
+++ b/src/instrumentation.ts
@@ -1,9 +1,12 @@
/**
* Runs once when the server starts: start the generation runner right away, so jobs that were in
* flight before a restart keep advancing (and live updates flow) even when the UI only lists them.
+ * Also empties what has been in the Trash for 30 days (then daily).
*/
export async function register() {
if (process.env.NEXT_RUNTIME !== "nodejs" || process.env.NEXT_PHASE === "phase-production-build") return;
const { ensureRunner } = await import("./server/generations");
ensureRunner();
+ const { ensureTrashPurge } = await import("./server/library");
+ ensureTrashPurge();
}
diff --git a/src/lib/catalog/types.ts b/src/lib/catalog/types.ts
index b29cf871..6c805cc3 100644
--- a/src/lib/catalog/types.ts
+++ b/src/lib/catalog/types.ts
@@ -402,6 +402,10 @@ export interface GenerationRequest {
frame?: { scene: string; index: number; of: number };
/** Part of a multi-step job (a shot of a multi-shot film, a step of an extend): shown on its tile. */
step?: { label: string; index: number; of: number };
+ /** Server-set: what the user calls this result, shown instead of the prompt (Library, feeds). */
+ title?: string;
+ /** Server-set: the name of the batch it belongs to (an Assist plan's summary): the Library stack's title. */
+ batchTitle?: string;
}
export interface ChainSlot {
diff --git a/src/server/assist/tools.ts b/src/server/assist/tools.ts
index 23cb5af9..4b77c861 100644
--- a/src/server/assist/tools.ts
+++ b/src/server/assist/tools.ts
@@ -1,5 +1,6 @@
import "server-only";
import type Anthropic from "@anthropic-ai/sdk";
+import { nanoid } from "nanoid";
import { z } from "zod";
import { getModel, modelsFor } from "@/lib/catalog";
import { OPERATION_LABELS, type ChainSlot, type GenerationRequest, type MediaKind, type ModelDef, type Operation } from "@/lib/catalog/types";
@@ -394,14 +395,16 @@ const generate = defineTool({
gated: true,
strict: true,
plan: ({ jobs }) => chainJobs(jobs.slice(0, 6)).map(plannedJob),
- async run({ jobs }) {
+ async run({ summary, jobs }) {
const list = jobs.slice(0, 6);
+ // The plan's jobs share a batch, so the Library stacks them under the plan's summary.
+ const batchTitle = summary.trim().slice(0, 200) || undefined;
if (list.some((j) => j.after !== undefined)) {
// Chained jobs: one pipeline, created only if every step is valid.
const chained = chainJobs(list);
const bad = chained.findIndex((c) => c.error);
if (bad >= 0) return { content: JSON.stringify({ error: `Job ${bad}: ${chained[bad].error}` }), isError: true };
- const p = createPipeline(chained.map((c, i) => ({ key: `job${i}`, request: c.req, ...(c.after !== undefined && { after: `job${c.after}` }) })));
+ const p = createPipeline(chained.map((c, i) => ({ key: `job${i}`, request: { ...c.req, batchTitle }, ...(c.after !== undefined && { after: `job${c.after}` }) })));
const results = chained.map((c, i) => {
const g = p.byKey[`job${i}`];
return { model: c.job.model_id, started: [g.id], ...(c.after !== undefined && { waitsFor: p.byKey[`job${c.after}`].id }), demo: g.provider === "mock" || undefined, costUsd: g.costUsd || undefined };
@@ -413,9 +416,10 @@ const generate = defineTool({
}
const ids: string[] = [];
const results: unknown[] = [];
+ const batch = list.length > 1 ? { batchId: nanoid(10) } : {};
for (const j of list) {
try {
- const gens = createGenerations(toRequest(j));
+ const gens = createGenerations({ ...toRequest(j), batchTitle }, batch);
ids.push(...gens.map((g) => g.id));
results.push({ model: j.model_id, started: gens.map((g) => g.id), demo: gens.some((g) => g.provider === "mock") || undefined, costUsd: gens.reduce((s, g) => s + (g.costUsd ?? 0), 0) || undefined });
} catch (e) {
diff --git a/src/server/generations.ts b/src/server/generations.ts
index f76c9e33..33770ad4 100644
--- a/src/server/generations.ts
+++ b/src/server/generations.ts
@@ -140,8 +140,13 @@ export interface ListOptions {
trashed?: boolean;
folderId?: string;
limit?: number;
- /** Paging cursor: made before this (deleted before, in the Trash). */
+ /**
+ * Paging cursor: made before this (deleted before, in the Trash). With `beforeId` it is the last
+ * row of the previous page, so rows sharing its timestamp (a bulk trash, a batch made in one
+ * millisecond) are paged by id instead of skipped.
+ */
before?: number;
+ beforeId?: string;
/** Date range on createdAt: since ≤ t < until. */
since?: number;
until?: number;
@@ -168,13 +173,18 @@ export function listGenerations(o: ListOptions = {}): Generation[] {
if (o.status) add("g.status = ?", o.status);
if (o.statuses?.length) oneOf("g.status", o.statuses);
if (o.folderId) add("fi.folder_id = ?", o.folderId);
- if (o.before) add(o.trashed ? "t.deleted_at < ?" : "g.created_at < ?", o.before);
+ if (o.before) {
+ const col = o.trashed ? "t.deleted_at" : "g.created_at";
+ if (o.beforeId) add(`(${col} < ? OR (${col} = ? AND g.id < ?))`, o.before, o.before, o.beforeId);
+ else add(`${col} < ?`, o.before);
+ }
if (o.since) add("g.created_at >= ?", o.since);
if (o.until) add("g.created_at < ?", o.until);
const q = o.q?.trim();
// The user's own words (request.prompt) and what the model got (prompt, with suffixes and templates).
if (q) add("(g.prompt LIKE ? OR json_extract(g.request_json, '$.prompt') LIKE ?)", `%${q}%`, `%${q}%`);
- const order = o.trashed ? "t.deleted_at DESC, g.created_at DESC" : "g.created_at DESC, g.id DESC";
+ // The cursor's order: timestamp, then id (both descending).
+ const order = o.trashed ? "t.deleted_at DESC, g.id DESC" : "g.created_at DESC, g.id DESC";
const sql = `SELECT ${LIBRARY_COLUMNS} FROM ${LIBRARY_JOIN} WHERE ${where.join(" AND ")} ORDER BY ${order} LIMIT ?`;
return (db().prepare(sql).all(...args, Math.max(1, Math.min(o.limit ?? 60, 200))) as Row[]).map(toGeneration);
}
@@ -183,10 +193,41 @@ export function setFavorite(id: string, favorite: boolean): void {
update(id, { favorite: favorite ? 1 : 0 });
}
+/**
+ * Everywhere a stored file can still be in use, by URL (which ends in the asset id, …/<id>.png) or
+ * by id: other jobs' inputs and outputs, elements, Assist chats (attachments, results), Cinema
+ * covers, palettes and takes, canvas nodes. `except` names a column whose row belongs to the
+ * generation being purged (its own row and Cinema membership don't keep its files).
+ */
+const ASSET_REFS: { table: string; cols: string[]; except?: string }[] = [
+ { table: "generations", cols: ["request_json", "outputs_json"], except: "id" },
+ { table: "characters", cols: ["reference_asset_ids_json", "loras_json", "lora_file"] },
+ { table: "trainings", cols: ["meta_json"] },
+ { table: "assist_threads", cols: ["messages_json", "items_json", "pending_json"] },
+ { table: "cinema_projects", cols: ["cover_url", "palettes_json", "director_json", "chat_json", "brief_body"] },
+ { table: "cinema_items", cols: ["meta_json"], except: "generation_id" },
+ { table: "canvases", cols: ["graph_json"] },
+];
+
+/** Whether anything still refers to this stored file (see ASSET_REFS). */
+export function assetInUse(assetId: string, exceptGeneration = ""): boolean {
+ for (const r of ASSET_REFS) {
+ const where = r.cols.map((c) => `instr(COALESCE(${c}, ''), @id) > 0`).join(" OR ");
+ const except = r.except ? ` AND ${r.except} != @g` : "";
+ try {
+ if (db().prepare(`SELECT 1 FROM ${r.table} WHERE (${where})${except} LIMIT 1`).get({ id: assetId, g: exceptGeneration })) return true;
+ } catch {
+ // A table or column this install doesn't have yet: nothing there to keep the file for.
+ }
+ }
+ return false;
+}
+
/**
* Delete for good (Trash → Delete forever, Empty trash, the 30-day purge): the row, its trash and
- * folder entries, and the output files nothing else still points at (an element's photos, another
- * job's inputs). Dependents still waiting on it fail ("An earlier step didn't finish").
+ * folder entries, and the output files nothing else still points at (assetInUse). Dependents still
+ * waiting on it fail ("An earlier step didn't finish"). Use deleteForever / emptyTrash in
+ * src/server/library.ts (they cancel running jobs first); moving to the Trash is trashGenerations.
*/
export function deleteGeneration(id: string): void {
const assets = db().prepare("SELECT id FROM assets WHERE generation_id = ?").all(id) as { id: string }[];
@@ -195,13 +236,7 @@ export function deleteGeneration(id: string): void {
db().prepare("DELETE FROM generation_trash WHERE generation_id = ?").run(id);
db().prepare("DELETE FROM folder_items WHERE generation_id = ?").run(id);
})();
- for (const a of assets) {
- // File URLs end in the asset id (…/<id>.png), so the id finds both URL and id references.
- const used =
- db().prepare("SELECT 1 FROM generations WHERE instr(request_json, ?) > 0 OR instr(outputs_json, ?) > 0 LIMIT 1").get(a.id, a.id) ??
- db().prepare("SELECT 1 FROM characters WHERE instr(reference_asset_ids_json, ?) > 0 LIMIT 1").get(a.id);
- if (!used) deleteAsset(a.id);
- }
+ for (const a of assets) if (!assetInUse(a.id, id)) deleteAsset(a.id);
}
// ---------------------------------------------------------------------------
diff --git a/src/server/library.ts b/src/server/library.ts
index 8a1887a0..c9f7d553 100644
--- a/src/server/library.ts
+++ b/src/server/library.ts
@@ -21,6 +21,13 @@ const MAX_IDS = 500;
const STATUSES = new Set(["queued", "running", "succeeded", "failed", "canceled"]);
const KINDS = new Set(["image", "video", "audio", "text", "model3d"]);
+/** `before=<ts>` or `before=<ts>:<id>` (the last row of the previous page) → the paging cursor. */
+export function cursorFrom(v: string | null): Pick<ListOptions, "before" | "beforeId"> {
+ const m = /^(\d+)(?::([\w-]{1,40}))?$/.exec(v?.trim() ?? "");
+ if (!m || !Number(m[1])) return {};
+ return { before: Number(m[1]), ...(m[2] && { beforeId: m[2] }) };
+}
+
/** GET /api/generations query → listGenerations options (unknown values are ignored). */
export function listOptionsFrom(sp: URLSearchParams): ListOptions {
const list = (k: string) => sp.get(k)?.split(",").map((s) => s.trim()).filter(Boolean);
@@ -40,7 +47,7 @@ export function listOptionsFrom(sp: URLSearchParams): ListOptions {
folderId: sp.get("folder") ?? undefined,
trashed: sp.get("trash") === "1",
q: sp.get("q") ?? undefined,
- before: num("before"),
+ ...cursorFrom(sp.get("before")),
since: num("since"),
until: num("until"),
limit: num("limit"),
@@ -64,7 +71,10 @@ function touch(list: string[]): void {
// ---------------------------------------------------------------------------
// Trash
-/** Move to the Trash. Running jobs keep running (cancel them from their tile); Restore brings them back as they are. */
+/**
+ * Move to the Trash. Jobs still queued or rendering are canceled (in the background), so a deleted
+ * job doesn't keep running and billing out of sight; Restore brings them back as canceled, with Retry.
+ */
export function trashGenerations(list: string[], now = Date.now()): number {
const found = existing(ids(list));
const insert = db().prepare("INSERT OR IGNORE INTO generation_trash (generation_id, deleted_at) VALUES (?, ?)");
@@ -73,9 +83,16 @@ export function trashGenerations(list: string[], now = Date.now()): number {
for (const id of found) n += insert.run(id, now).changes;
touch(found);
})();
+ for (const id of activeIds(found)) void cancelGeneration(id).catch(() => {});
return n;
}
+/** The ones among `list` still queued or rendering. */
+function activeIds(list: string[]): string[] {
+ if (!list.length) return [];
+ return (db().prepare(`SELECT id FROM generations WHERE status IN ('queued', 'running') AND id IN (${placeholders(list.length)})`).all(...list) as { id: string }[]).map((r) => r.id);
+}
+
export function restoreGenerations(list: string[]): number {
const found = ids(list);
if (!found.length) return 0;
@@ -92,9 +109,9 @@ export function restoreGenerations(list: string[]): number {
/** Delete for good; jobs still running are canceled first. */
export async function deleteForever(list: string[]): Promise<number> {
const found = existing(ids(list));
+ const active = new Set(activeIds(found));
for (const id of found) {
- const g = getGeneration(id, { includeDeleted: true });
- if (g && (g.status === "queued" || g.status === "running")) await cancelGeneration(id).catch(() => {});
+ if (active.has(id)) await cancelGeneration(id).catch(() => {});
deleteGeneration(id);
}
return found.length;
diff --git a/tests/library.test.ts b/tests/library.test.ts
index cdb2992d..ced98fac 100644
--- a/tests/library.test.ts
+++ b/tests/library.test.ts
@@ -2,7 +2,10 @@ import { execFileSync } from "node:child_process";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
-import { afterAll, beforeAll, describe, expect, it } from "vitest";
+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 () => {} }));
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-library-"));
process.env.FUOBE_DATA_DIR = dir;
@@ -15,6 +18,8 @@ const { saveFile, absolutePath } = await import("@/server/storage");
const { zipStream, zipSize } = await import("@/server/zip");
const { TOOLS } = await import("@/server/assist/tools");
const { POST: bulk } = await import("@/app/api/generations/bulk/route");
+const folderRoutes = await import("@/app/api/folders/route");
+const folderIdRoutes = await import("@/app/api/folders/[id]/route");
const { db } = await import("@/server/db");
beforeAll(() => setSetting("demoMode", "auto"));
@@ -107,13 +112,201 @@ describe("trash (soft delete)", () => {
expect(gens.listGenerations({ trashed: true })).toEqual([]);
});
- it("cancels a running job deleted for good", async () => {
+ it("cancels a job moved to the Trash (Restore brings it back canceled), and one deleted for good", async () => {
const [job] = gens.createGenerations({ feature: "image", modelId: "nano-banana-pro", prompt: "a slow one" });
lib.trashGenerations([job.id]);
- // Still running in the Trash (Restore brings it back as it is).
- expect(["queued", "running"]).toContain(gens.getGeneration(job.id, { includeDeleted: true })!.status);
- await lib.deleteForever([job.id]);
- expect(gens.getGeneration(job.id, { includeDeleted: true })).toBeNull();
+ // It doesn't keep rendering (and billing) out of sight.
+ await vi.waitFor(() => expect(gens.getGeneration(job.id, { includeDeleted: true })!.status).toBe("canceled"));
+ lib.restoreGenerations([job.id]);
+ expect(gens.getGeneration(job.id)?.status).toBe("canceled");
+ const [other] = gens.createGenerations({ feature: "image", modelId: "nano-banana-pro", prompt: "another slow one" });
+ await lib.deleteForever([other.id]);
+ expect(gens.getGeneration(other.id, { includeDeleted: true })).toBeNull();
+ });
+
+ it("keeps output files still used by Cinema, canvases or Assist chats when deleting for good", async () => {
+ const cover = made("cinema cover");
+ const node = made("canvas input");
+ const chat = made("chat attachment");
+ const lone = made("nobody uses this");
+ const now = Date.now();
+ db().prepare("INSERT INTO cinema_projects (id, name, cover_url, created_at, updated_at) VALUES ('p-keep', 'Keep', ?, ?, ?)").run(cover.asset.url, now, now);
+ // Its own Cinema membership doesn't keep a take's files.
+ db().prepare("INSERT INTO cinema_items (project_id, generation_id, meta_json, created_at) VALUES ('p-keep', ?, ?, ?)").run(lone.g.id, JSON.stringify({ tiles: [{ url: lone.asset.url, row: 0, col: 0 }] }), now);
+ db()
+ .prepare("INSERT INTO canvases (id, name, graph_json, created_at, updated_at) VALUES ('c-keep', 'Board', ?, ?, ?)")
+ .run(JSON.stringify({ nodes: [{ id: "n1", data: { url: node.asset.url } }], edges: [] }), now, now);
+ db()
+ .prepare("INSERT INTO assist_threads (id, title, status, agent, engine, messages_json, created_at, updated_at) VALUES ('t-keep', 'Chat', 'idle', 'offline', 'cloud', ?, ?, ?)")
+ .run(JSON.stringify([{ role: "user", content: [{ type: "text", text: `see ${chat.asset.url}` }] }]), now, now);
+ expect(gens.assetInUse(cover.asset.id)).toBe(true);
+ expect(gens.assetInUse(lone.asset.id, lone.g.id)).toBe(false);
+ lib.trashGenerations([cover.g.id, node.g.id, chat.g.id, lone.g.id]);
+ expect(await lib.deleteForever([cover.g.id, node.g.id, chat.g.id, lone.g.id])).toBe(4);
+ for (const kept of [cover, node, chat]) expect(fs.existsSync(fileOf(kept.asset.url))).toBe(true);
+ expect(fs.existsSync(fileOf(lone.asset.url))).toBe(false);
+ });
+
+ it("empties a Trash with dangling entries (rows already gone)", async () => {
+ const a = made("dangling a").g;
+ lib.trashGenerations([a.id]);
+ db().prepare("INSERT INTO generation_trash (generation_id, deleted_at) VALUES ('ghost', ?)").run(Date.now());
+ expect(await lib.emptyTrash()).toBe(1);
+ expect(db().prepare("SELECT COUNT(*) AS n FROM generation_trash").get()).toEqual({ n: 0 });
+ });
+});
+
+describe("paging", () => {
+ const pageAll = (o: NonNullable<Parameters<typeof gens.listGenerations>[0]>, limit: number) => {
+ const seen: string[] = [];
+ let cursor: { before?: number; beforeId?: string } = {};
+ for (let i = 0; i < 20; i++) {
+ const page = gens.listGenerations({ ...o, ...cursor, limit });
+ seen.push(...page.map((g) => g.id));
+ if (page.length < limit) break;
+ const last = page.at(-1)!;
+ cursor = lib.cursorFrom(`${o.trashed ? last.deletedAt : last.createdAt}:${last.id}`);
+ }
+ return seen;
+ };
+
+ it("pages a bulk trash (one deletedAt for all) without skipping any", () => {
+ const items = Array.from({ length: 70 }, (_, i) => made(`tie-trash ${i}`).g.id);
+ expect(lib.trashGenerations(items)).toBe(70);
+ const seen = pageAll({ trashed: true, q: "tie-trash" }, 60);
+ expect(seen).toHaveLength(70);
+ expect(new Set(seen).size).toBe(70);
+ // The old timestamp-only cursor lost the 10 that share the boundary's deletedAt.
+ const first = gens.listGenerations({ trashed: true, q: "tie-trash", limit: 60 });
+ expect(gens.listGenerations({ trashed: true, q: "tie-trash", limit: 60, before: first.at(-1)!.deletedAt! })).toHaveLength(0);
+ lib.restoreGenerations(items);
+ });
+
+ it("pages rows made in the same millisecond (storyboard frames, pipelines) without skipping any", () => {
+ const items = Array.from({ length: 6 }, (_, i) => made(`tie-created ${i}`).g.id);
+ db().prepare(`UPDATE generations SET created_at = 1234 WHERE id IN (${items.map(() => "?").join(",")})`).run(...items);
+ const seen = pageAll({ q: "tie-created" }, 4);
+ expect(seen.sort()).toEqual([...items].sort());
+ });
+
+ it("reads the cursor in both forms", () => {
+ expect(lib.cursorFrom("1700000000000:Ab_c-9")).toEqual({ before: 1700000000000, beforeId: "Ab_c-9" });
+ expect(lib.cursorFrom("1700000000000")).toEqual({ before: 1700000000000 });
+ expect(lib.cursorFrom("nope")).toEqual({});
+ expect(lib.cursorFrom(null)).toEqual({});
+ });
+});
+
+describe("list filters (GET /api/generations)", () => {
+ it("maps every query field and ignores unknown values", () => {
+ const sp = new URLSearchParams({
+ kinds: "image,video,bogus",
+ models: "a,b",
+ statuses: "failed,canceled,exploded",
+ since: "100",
+ until: "200",
+ folder: "f1",
+ q: "koi",
+ favorites: "1",
+ trash: "1",
+ limit: "30",
+ before: "150:xyz",
+ features: "image,video*",
+ kind: "nope",
+ });
+ expect(lib.listOptionsFrom(sp)).toMatchObject({
+ kinds: ["image", "video"],
+ models: ["a", "b"],
+ statuses: ["failed", "canceled"],
+ since: 100,
+ until: 200,
+ folderId: "f1",
+ q: "koi",
+ favorites: true,
+ trashed: true,
+ limit: 30,
+ before: 150,
+ beforeId: "xyz",
+ features: ["image", "video*"],
+ kind: undefined,
+ });
+ });
+
+ it("filters by kind, model, status, date, folder and the user's own words", () => {
+ const a = made("filter alpha").g;
+ const b = made("filter beta").g;
+ db().prepare("UPDATE generations SET status = 'failed', created_at = 50, request_json = ? WHERE id = ?").run(JSON.stringify({ ...b.request, prompt: "my words: zebra" }), b.id);
+ const f = lib.createFolder({ name: "Filters" });
+ lib.moveToFolder([a.id], f.id);
+ const ids = (q: Record<string, string>) => gens.listGenerations({ ...lib.listOptionsFrom(new URLSearchParams(q)), limit: 200 }).map((g) => g.id);
+ expect(ids({ q: "zebra" })).toEqual([b.id]); // request.prompt, not only the model's prompt
+ expect(ids({ statuses: "failed", q: "filter" })).toEqual([b.id]);
+ expect(ids({ until: "100", q: "filter" })).toEqual([b.id]);
+ expect(ids({ since: "100", q: "filter" })).toEqual([a.id]);
+ expect(ids({ folder: f.id })).toEqual([a.id]);
+ expect(ids({ kinds: "video", q: "filter" })).toEqual([]);
+ expect(ids({ models: "local-color-grade", q: "filter" }).sort()).toEqual([a.id, b.id].sort());
+ expect(ids({ models: "other", q: "filter" })).toEqual([]);
+ lib.deleteFolder(f.id);
+ });
+
+ it("counts facets for the filter menus", () => {
+ const before = lib.libraryFacets();
+ const g = made("facet one").g;
+ lib.setFavorites([g.id], true);
+ const failed = made("facet two").g;
+ db().prepare("UPDATE generations SET status = 'failed' WHERE id = ?").run(failed.id);
+ const gone = made("facet three").g;
+ lib.trashGenerations([gone.id]);
+ const after = lib.libraryFacets();
+ expect(after.total - before.total).toBe(2);
+ expect(after.favorites - before.favorites).toBe(1);
+ expect(after.failed - before.failed).toBe(1);
+ expect(after.trash - before.trash).toBe(1);
+ expect((after.kinds.image ?? 0) - (before.kinds.image ?? 0)).toBe(2);
+ expect(after.models.find((m) => m.id === "local-color-grade")?.name).toBe("Color Grading");
+ });
+});
+
+describe("Assist plans", () => {
+ it("puts a plan's independent jobs in one batch, titled with its summary, so the Library stacks them", async () => {
+ const generate = TOOLS.find((t) => t.name === "generate")!;
+ const out = await generate.run(
+ {
+ summary: "Two animal posters",
+ jobs: [
+ { model_id: "nano-banana-pro", prompt: "a fox poster" },
+ { model_id: "nano-banana-pro", prompt: "an owl poster" },
+ ],
+ },
+ { engine: "cloud" },
+ );
+ const ids = (out.items?.[0] as { ids: string[] }).ids;
+ const made = ids.map((id) => gens.getGeneration(id)!);
+ expect(made).toHaveLength(2);
+ expect(made[0].batchId).toBeTruthy();
+ expect(made[1].batchId).toBe(made[0].batchId);
+ expect(made.map((g) => g.request.batchTitle)).toEqual(["Two animal posters", "Two animal posters"]);
+ });
+});
+
+describe("folder routes", () => {
+ const ctx = (id: string) => ({ params: Promise.resolve({ id }) }) as never;
+ const body = (b: unknown, method = "POST") => new Request("http://x/api/folders", { method, body: JSON.stringify(b) });
+
+ it("creates, refuses duplicates, renames, 404s and deletes", async () => {
+ const res = await folderRoutes.POST(body({ name: "Routes", color: "cyan" }));
+ expect(res.status).toBe(201);
+ const f = (await res.json()) as { id: string; name: string };
+ expect((await folderRoutes.POST(body({ name: "routes" }))).status).toBe(409);
+ expect((await folderRoutes.POST(body({ name: " " }))).status).toBe(400);
+ expect(((await (await folderRoutes.GET()).json()) as { items: { id: string }[] }).items.map((x) => x.id)).toContain(f.id);
+ const renamed = await folderIdRoutes.PATCH(body({ name: "Routes 2" }, "PATCH"), ctx(f.id));
+ expect(((await renamed.json()) as { name: string }).name).toBe("Routes 2");
+ expect((await folderIdRoutes.PATCH(body({ name: "x" }, "PATCH"), ctx("missing"))).status).toBe(404);
+ expect((await folderIdRoutes.GET(new Request("http://x"), ctx("missing"))).status).toBe(404);
+ expect((await folderIdRoutes.DELETE(new Request("http://x"), ctx(f.id))).status).toBe(204);
+ expect((await folderIdRoutes.DELETE(new Request("http://x"), ctx(f.id))).status).toBe(404);
});
});