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: Trash (soft delete, 30-day purge), folders, bulk and zip endpoints, names on generations

Claudea0b57f3a2b1a
diff --git a/src/app/api/folders/[id]/route.ts b/src/app/api/folders/[id]/route.ts
new file mode 100644
index 00000000..0b1785eb
--- /dev/null
+++ b/src/app/api/folders/[id]/route.ts
@@ -0,0 +1,30 @@
+import { connection } from "next/server";
+import { z } from "zod";
+import { deleteFolder, getFolder, updateFolder } from "@/server/library";
+
+const Patch = z.object({ name: z.string().trim().min(1).max(60).optional(), color: z.string().max(20).optional() });
+
+export async function GET(_req: Request, ctx: RouteContext<"/api/folders/[id]">) {
+ await connection();
+ const { id } = await ctx.params;
+ const f = getFolder(id);
+ return f ? Response.json(f) : Response.json({ error: "Not found" }, { status: 404 });
+}
+
+export async function PATCH(request: Request, ctx: RouteContext<"/api/folders/[id]">) {
+ const { id } = await ctx.params;
+ const parsed = Patch.safeParse(await request.json().catch(() => null));
+ if (!parsed.success) return Response.json({ error: "Give the folder a name" }, { status: 400 });
+ try {
+ const f = updateFolder(id, parsed.data);
+ return f ? Response.json(f) : Response.json({ error: "Not found" }, { status: 404 });
+ } catch (e) {
+ return Response.json({ error: (e as Error).message }, { status: 409 });
+ }
+}
+
+/** Delete the folder; its contents go back to the library. */
+export async function DELETE(_req: Request, ctx: RouteContext<"/api/folders/[id]">) {
+ const { id } = await ctx.params;
+ return deleteFolder(id) ? new Response(null, { status: 204 }) : Response.json({ error: "Not found" }, { status: 404 });
+}
diff --git a/src/app/api/folders/route.ts b/src/app/api/folders/route.ts
new file mode 100644
index 00000000..93dabb83
--- /dev/null
+++ b/src/app/api/folders/route.ts
@@ -0,0 +1,20 @@
+import { connection } from "next/server";
+import { z } from "zod";
+import { createFolder, listFolders } from "@/server/library";
+
+const Body = z.object({ name: z.string().trim().min(1).max(60), color: z.string().max(20).optional() });
+
+export async function GET() {
+ await connection();
+ return Response.json({ items: listFolders() });
+}
+
+export async function POST(request: Request) {
+ const parsed = Body.safeParse(await request.json().catch(() => null));
+ if (!parsed.success) return Response.json({ error: "Give the folder a name" }, { status: 400 });
+ try {
+ return Response.json(createFolder(parsed.data), { status: 201 });
+ } catch (e) {
+ return Response.json({ error: (e as Error).message }, { status: 409 });
+ }
+}
diff --git a/src/app/api/generations/[id]/route.ts b/src/app/api/generations/[id]/route.ts
index fc0027e2..ed6fa2c4 100644
--- a/src/app/api/generations/[id]/route.ts
+++ b/src/app/api/generations/[id]/route.ts
@@ -1,5 +1,6 @@
import { connection } from "next/server";
-import { deleteGeneration, getGeneration, setFavorite } from "@/server/generations";
+import { getGeneration, setFavorite } from "@/server/generations";
+import { deleteForever, trashGenerations } from "@/server/library";
export async function GET(_req: Request, ctx: RouteContext<"/api/generations/[id]">) {
await connection();
@@ -16,8 +17,10 @@ export async function PATCH(request: Request, ctx: RouteContext<"/api/generation
return g ? Response.json(g) : Response.json({ error: "Not found" }, { status: 404 });
}
-export async function DELETE(_req: Request, ctx: RouteContext<"/api/generations/[id]">) {
+/** Move to the Trash (restore with POST /api/generations/bulk {action: "restore"}); `?forever=1` deletes for good. */
+export async function DELETE(request: Request, ctx: RouteContext<"/api/generations/[id]">) {
const { id } = await ctx.params;
- deleteGeneration(id);
+ if (new URL(request.url).searchParams.get("forever") === "1") await deleteForever([id]);
+ else trashGenerations([id]);
return new Response(null, { status: 204 });
}
diff --git a/src/app/api/generations/bulk/route.ts b/src/app/api/generations/bulk/route.ts
new file mode 100644
index 00000000..366b3039
--- /dev/null
+++ b/src/app/api/generations/bulk/route.ts
@@ -0,0 +1,31 @@
+import { z } from "zod";
+import { deleteForever, moveToFolder, restoreGenerations, setFavorites, trashGenerations } from "@/server/library";
+
+const Body = z.object({
+ action: z.enum(["trash", "restore", "delete", "favorite", "unfavorite", "move"]),
+ ids: z.array(z.string().min(1).max(40)).min(1).max(500),
+ /** For "move": the folder, or null for the library root. */
+ folderId: z.string().max(40).nullable().optional(),
+});
+
+/** One action on many generations: Trash / Restore / Delete forever / (un)favorite / move to a folder. */
+export async function POST(request: Request) {
+ const parsed = Body.safeParse(await request.json().catch(() => null));
+ if (!parsed.success) return Response.json({ error: "Pick something first" }, { status: 400 });
+ const { action, ids, folderId } = parsed.data;
+ try {
+ const count =
+ action === "trash"
+ ? trashGenerations(ids)
+ : action === "restore"
+ ? restoreGenerations(ids)
+ : action === "delete"
+ ? await deleteForever(ids)
+ : action === "move"
+ ? moveToFolder(ids, folderId ?? null)
+ : setFavorites(ids, action === "favorite");
+ return Response.json({ count });
+ } catch (e) {
+ return Response.json({ error: (e as Error).message }, { status: 422 });
+ }
+}
diff --git a/src/app/api/generations/facets/route.ts b/src/app/api/generations/facets/route.ts
new file mode 100644
index 00000000..c80cf4aa
--- /dev/null
+++ b/src/app/api/generations/facets/route.ts
@@ -0,0 +1,8 @@
+import { connection } from "next/server";
+import { libraryFacets } from "@/server/library";
+
+/** Counts for the Library's filter menus: models used, kinds, favorites, failed, Trash. */
+export async function GET() {
+ await connection();
+ return Response.json(libraryFacets());
+}
diff --git a/src/app/api/generations/route.ts b/src/app/api/generations/route.ts
index 46128bcf..855a61ac 100644
--- a/src/app/api/generations/route.ts
+++ b/src/app/api/generations/route.ts
@@ -1,6 +1,7 @@
import { connection } from "next/server";
import { z } from "zod";
import { createGenerations, listGenerations } from "@/server/generations";
+import { ensureTrashPurge, listOptionsFrom } from "@/server/library";
const RequestSchema = z.object({
feature: z.string().min(1),
@@ -53,20 +54,15 @@ const RequestSchema = z.object({
mix: z.object({ presetId: z.string().max(120), strength: z.number().min(0).max(1) }).optional(),
});
+/**
+ * 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).
+ */
export async function GET(request: Request) {
await connection();
- const u = new URL(request.url);
- const items = listGenerations({
- feature: u.searchParams.get("feature") ?? undefined,
- features: u.searchParams.get("features")?.split(",").filter(Boolean),
- kind: u.searchParams.get("kind") ?? undefined,
- favorites: u.searchParams.get("favorites") === "1",
- status: u.searchParams.get("status") ?? undefined,
- q: u.searchParams.get("q") ?? undefined,
- before: u.searchParams.get("before") ? Number(u.searchParams.get("before")) : undefined,
- limit: u.searchParams.get("limit") ? Number(u.searchParams.get("limit")) : undefined,
- });
- return Response.json({ items });
+ ensureTrashPurge();
+ return Response.json({ items: listGenerations(listOptionsFrom(new URL(request.url).searchParams)) });
}
export async function POST(request: Request) {
diff --git a/src/app/api/generations/trash/route.ts b/src/app/api/generations/trash/route.ts
new file mode 100644
index 00000000..c0429b87
--- /dev/null
+++ b/src/app/api/generations/trash/route.ts
@@ -0,0 +1,15 @@
+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. */
+export async function GET(request: Request) {
+ await connection();
+ ensureTrashPurge();
+ return Response.json({ items: listGenerations({ ...listOptionsFrom(new URL(request.url).searchParams), trashed: true }) });
+}
+
+/** Empty the Trash: everything in it is deleted for good. */
+export async function DELETE() {
+ return Response.json({ count: await emptyTrash() });
+}
diff --git a/src/app/api/generations/zip/route.ts b/src/app/api/generations/zip/route.ts
new file mode 100644
index 00000000..85e9b67d
--- /dev/null
+++ b/src/app/api/generations/zip/route.ts
@@ -0,0 +1,23 @@
+import { connection } from "next/server";
+import { ZIP_MAX_BYTES, zipEntries } from "@/server/library";
+import { zipSize, zipStream } from "@/server/zip";
+
+/** Download the finished outputs of several generations as one zip: GET ?ids=a,b,c (up to 500). */
+export async function GET(request: Request) {
+ await connection();
+ const ids = (new URL(request.url).searchParams.get("ids") ?? "").split(",").map((s) => s.trim()).filter(Boolean);
+ if (!ids.length) return Response.json({ error: "Pick something to download" }, { status: 400 });
+ const entries = zipEntries(ids);
+ if (!entries.length) return Response.json({ error: "Nothing finished to download yet" }, { status: 404 });
+ const size = zipSize(entries);
+ if (size > ZIP_MAX_BYTES) return Response.json({ error: "That's over 4 GB. Download fewer items at a time." }, { status: 413 });
+ const day = new Date().toISOString().slice(0, 10);
+ return new Response(zipStream(entries), {
+ headers: {
+ "Content-Type": "application/zip",
+ "Content-Length": String(size),
+ "Content-Disposition": `attachment; filename="fuobe-${day}-${entries.length}-files.zip"`,
+ "Cache-Control": "no-store",
+ },
+ });
+}
diff --git a/src/lib/catalog/types.ts b/src/lib/catalog/types.ts
index e4db470b..6e13fb05 100644
--- a/src/lib/catalog/types.ts
+++ b/src/lib/catalog/types.ts
@@ -462,6 +462,15 @@ export interface Generation {
createdAt: number;
updatedAt: number;
completedAt: number | null;
+ /** Display names resolved on the server, so result views need no catalog in the browser. */
+ modelName?: string;
+ presetName?: string | null;
+ /** The aspect ratio it was made at (the request's, else the model's default), for tile shapes. */
+ aspectRatio?: string | null;
+ /** Moved to the Trash at (soft delete; purged after 30 days). */
+ deletedAt?: number | null;
+ /** Library folder it's in. */
+ folderId?: string | null;
}
/** Input slot a preset asks the user for. */
diff --git a/src/lib/library.ts b/src/lib/library.ts
new file mode 100644
index 00000000..08c076c3
--- /dev/null
+++ b/src/lib/library.ts
@@ -0,0 +1,235 @@
+/**
+ * Library (Assets) logic shared by the browser and the server: feed filters, folders, the Trash,
+ * download names, date sections and batch stacks. Pure: no React, no database.
+ */
+import type { Generation, GenerationStatus, MediaKind, OutputFile } from "./catalog/types";
+
+// ---------------------------------------------------------------------------
+// Filters (GET /api/generations query ⇄ client-side matching for live cache updates)
+
+export interface FeedFilter {
+ kind?: MediaKind;
+ kinds?: MediaKind[];
+ features?: string[];
+ favorites?: boolean;
+ q?: string;
+ limit?: number;
+ models?: string[];
+ statuses?: GenerationStatus[];
+ /** createdAt range: since ≤ t < until. */
+ since?: number;
+ until?: number;
+ folderId?: string;
+ /** The Trash instead of the library. */
+ trashed?: boolean;
+}
+
+export function filterToSearch(f: FeedFilter, before?: number): URLSearchParams {
+ const qs = new URLSearchParams();
+ if (f.kind) qs.set("kind", f.kind);
+ if (f.kinds?.length) qs.set("kinds", f.kinds.join(","));
+ if (f.features?.length) qs.set("features", f.features.join(","));
+ if (f.favorites) qs.set("favorites", "1");
+ if (f.q?.trim()) qs.set("q", f.q.trim());
+ if (f.models?.length) qs.set("models", f.models.join(","));
+ if (f.statuses?.length) qs.set("statuses", f.statuses.join(","));
+ if (f.since) qs.set("since", String(f.since));
+ if (f.until) qs.set("until", String(f.until));
+ if (f.folderId) qs.set("folder", f.folderId);
+ if (f.trashed) qs.set("trash", "1");
+ if (before) qs.set("before", String(before));
+ qs.set("limit", String(f.limit ?? 80));
+ return qs;
+}
+
+const featureMatches = (feature: string, pattern: string) => (pattern.endsWith("*") ? feature.startsWith(pattern.slice(0, -1)) : feature === pattern);
+
+/** Whether a generation belongs in a list with this filter (mirrors listGenerations). */
+export function matchesFilter(g: Generation, f: FeedFilter): boolean {
+ if (!!f.trashed !== !!g.deletedAt) return false;
+ if (f.kind && g.kind !== f.kind) return false;
+ if (f.kinds?.length && !f.kinds.includes(g.kind)) return false;
+ if (f.features?.length && !f.features.some((p) => featureMatches(g.feature, p))) return false;
+ if (f.favorites && !g.favorite) return false;
+ if (f.models?.length && !f.models.includes(g.modelId)) return false;
+ if (f.statuses?.length && !f.statuses.includes(g.status)) return false;
+ if (f.since && g.createdAt < f.since) return false;
+ if (f.until && g.createdAt >= f.until) return false;
+ if (f.folderId && g.folderId !== f.folderId) return false;
+ const q = f.q?.trim().toLowerCase();
+ if (q && !`${g.prompt ?? ""}\n${g.request.prompt ?? ""}`.toLowerCase().includes(q)) return false;
+ return true;
+}
+
+/** Newest first, as the server orders lists (ties: id descending). */
+export function byNewest(a: Generation, b: Generation): number {
+ return b.createdAt - a.createdAt || (a.id < b.id ? 1 : a.id > b.id ? -1 : 0);
+}
+
+// ---------------------------------------------------------------------------
+// Folders
+
+export interface Folder {
+ id: string;
+ name: string;
+ color: string;
+ count: number;
+ /** The newest output in the folder, for its cover. */
+ cover: OutputFile | null;
+ createdAt: number;
+ updatedAt: number;
+}
+
+/** Higgsfield's seven folder swatches, as oklch hues (lime is the default). */
+export const FOLDER_COLORS = [
+ { id: "lime", label: "Lime", hue: 125, chroma: 0.21 },
+ { id: "cyan", label: "Cyan", hue: 205, chroma: 0.12 },
+ { id: "slate", label: "Slate", hue: 255, chroma: 0.03 },
+ { id: "violet", label: "Violet", hue: 290, chroma: 0.15 },
+ { id: "purple", label: "Purple", hue: 310, chroma: 0.16 },
+ { id: "pink", label: "Pink", hue: 350, chroma: 0.16 },
+ { id: "yellow", label: "Yellow", hue: 95, chroma: 0.16 },
+] as const;
+export type FolderColor = (typeof FOLDER_COLORS)[number]["id"];
+export const DEFAULT_FOLDER_COLOR: FolderColor = "lime";
+
+export function folderSwatch(color: string): string {
+ const c = FOLDER_COLORS.find((x) => x.id === color) ?? FOLDER_COLORS[0];
+ return `oklch(0.86 ${c.chroma} ${c.hue})`;
+}
+
+// ---------------------------------------------------------------------------
+// Trash
+
+export const TRASH_DAYS = 30;
+const DAY = 86_400_000;
+
+export function trashDaysLeft(deletedAt: number, now = Date.now()): number {
+ return Math.max(0, Math.ceil((deletedAt + TRASH_DAYS * DAY - now) / DAY));
+}
+
+// ---------------------------------------------------------------------------
+// Download names
+
+const EXT_BY_KIND: Record<MediaKind, string> = { image: "png", video: "mp4", audio: "wav", text: "txt", model3d: "glb" };
+
+export function extensionOf(o: Pick<OutputFile, "url" | "kind">): string {
+ const m = /\.([a-z0-9]{2,5})(?:[?#]|$)/i.exec(o.url.split("/").pop() ?? "");
+ return m ? m[1].toLowerCase() : EXT_BY_KIND[o.kind];
+}
+
+export function downloadName(g: Pick<Generation, "id" | "prompt" | "modelId" | "request">, o: Pick<OutputFile, "url" | "kind">, i: number, ext = extensionOf(o)): string {
+ const base = (g.request.prompt || g.prompt || g.modelId).slice(0, 40).replace(/[^\w]+/g, "-").replace(/^-|-$/g, "") || "fuobe";
+ return `${base}-${g.id.slice(0, 6)}${i ? `-${i + 1}` : ""}.${ext}`;
+}
+
+export const downloadHref = (url: string, name: string) => `${url}${url.includes("?") ? "&" : "?"}download=${encodeURIComponent(name)}`;
+
+// ---------------------------------------------------------------------------
+// Split by date
+
+export function dayStart(ts: number): number {
+ const d = new Date(ts);
+ d.setHours(0, 0, 0, 0);
+ return d.getTime();
+}
+
+export function dayLabel(ts: number, now = Date.now()): string {
+ const day = dayStart(ts);
+ const today = dayStart(now);
+ if (day === today) return "Today";
+ if (day === dayStart(today - DAY / 2)) return "Yesterday";
+ const d = new Date(ts);
+ const sameYear = d.getFullYear() === new Date(now).getFullYear();
+ return d.toLocaleDateString("en-US", sameYear ? { weekday: "short", month: "short", day: "numeric" } : { month: "short", day: "numeric", year: "numeric" });
+}
+
+export function splitByDate<T>(items: T[], ts: (t: T) => number, now = Date.now()): { key: number; label: string; items: T[] }[] {
+ const out: { key: number; label: string; items: T[] }[] = [];
+ for (const it of items) {
+ const key = dayStart(ts(it));
+ const last = out.at(-1);
+ if (last?.key === key) last.items.push(it);
+ else out.push({ key, label: dayLabel(key, now), items: [it] });
+ }
+ return out;
+}
+
+// ---------------------------------------------------------------------------
+// Batch stacks (storyboard + its film, multi-shot films, extend chains, pipelines, N takes)
+
+export type LibraryEntry = { type: "single"; key: string; g: Generation } | { type: "stack"; key: string; title: string; label: string; items: Generation[] };
+
+/** Storyboard films live in `${batchId}-film`: stack them with their board. */
+export function stackKey(g: Pick<Generation, "batchId">): string | null {
+ return g.batchId ? g.batchId.replace(/-film$/, "") : null;
+}
+
+/** The offline shot list wraps the story ("wide shot: <story> — beat 1 of 4"): unwrap it. */
+function unwrapScene(scene: string): string {
+ return /^[^:]{2,40}:\s*(.+?)\s+—\s+beat \d+ of \d+$/.exec(scene.trim())?.[1] ?? scene.trim();
+}
+
+/** What the user asked for, never the internal chain prompt. */
+export function userTitle(g: Generation): string {
+ const own = (g.request as { title?: string }).title?.trim();
+ if (own) return own;
+ if (g.request.frame) return unwrapScene(g.request.frame.scene);
+ return g.request.prompt?.trim() || g.presetName || g.prompt || "Untitled";
+}
+
+const order = (g: Generation) => g.request.step?.index ?? g.request.frame?.index ?? 0;
+
+export function stackTitle(items: Generation[]): string {
+ const titled = items.find((g) => (g.request as { title?: string }).title?.trim());
+ if (titled) return userTitle(titled);
+ const frames = items.filter((g) => g.request.frame).sort((a, b) => order(a) - order(b));
+ if (frames.length) return unwrapScene(frames[0].request.frame!.scene);
+ const film = items.find((g) => g.op === "concat" && g.prompt?.trim());
+ if (film) return unwrapScene(film.prompt!);
+ const first = [...items].sort((a, b) => order(a) - order(b) || a.createdAt - b.createdAt)[0];
+ return userTitle(first);
+}
+
+export function stackLabel(items: Generation[]): string {
+ const frames = items.filter((g) => g.request.frame).length;
+ const films = items.filter((g) => g.op === "concat" && g.request.step?.label?.startsWith("Film")).length;
+ const shots = items.filter((g) => /^Shot \d+/.test(g.request.step?.label ?? "")).length;
+ if (frames) return `Storyboard · ${frames} frame${frames === 1 ? "" : "s"}${films ? " + film" : ""}`;
+ if (films && shots) return `Film · ${shots} shots`;
+ if (items.every((g) => !g.request.step && g.request.prompt === items[0].request.prompt)) return `${items.length} takes`;
+ return `${items.length} steps`;
+}
+
+/** Group a newest-first list into cards: generations sharing a batch become one stack, placed where its newest member is. */
+export function buildEntries(items: Generation[], opts: { stacks?: boolean } = {}): LibraryEntry[] {
+ if (opts.stacks === false) return items.map((g) => ({ type: "single", key: g.id, g }));
+ const groups = new Map<string, Generation[]>();
+ for (const g of items) {
+ const k = stackKey(g);
+ if (k) groups.set(k, [...(groups.get(k) ?? []), g]);
+ }
+ const out: LibraryEntry[] = [];
+ const placed = new Set<string>();
+ for (const g of items) {
+ const k = stackKey(g);
+ const group = k ? groups.get(k)! : null;
+ if (!k || !group || group.length < 2) {
+ out.push({ type: "single", key: g.id, g });
+ continue;
+ }
+ if (placed.has(k)) continue;
+ placed.add(k);
+ const sorted = [...group].sort((a, b) => order(a) - order(b) || a.createdAt - b.createdAt);
+ out.push({ type: "stack", key: `stack:${k}`, title: stackTitle(group), label: stackLabel(group), items: sorted });
+ }
+ return out;
+}
+
+/** The output a card shows: a film's video first, else the first finished output. */
+export function coverOf(items: Generation[]): { g: Generation; o: OutputFile; index: number } | null {
+ const done = items.filter((g) => g.status === "succeeded" && g.outputs.length);
+ const film = done.find((g) => g.op === "concat");
+ const g = film ?? done[0];
+ return g ? { g, o: g.outputs[0], index: 0 } : null;
+}
diff --git a/src/server/db.ts b/src/server/db.ts
index 994f90a9..99035dd0 100644
--- a/src/server/db.ts
+++ b/src/server/db.ts
@@ -101,6 +101,25 @@ const MIGRATIONS: string[] = [
updated_at INTEGER NOT NULL
);
CREATE INDEX IF NOT EXISTS assist_threads_updated ON assist_threads(updated_at DESC);`,
+ // Library: Trash (soft delete, purged after 30 days) and folders (one folder per generation).
+ `CREATE TABLE IF NOT EXISTS generation_trash (
+ generation_id TEXT PRIMARY KEY,
+ deleted_at INTEGER NOT NULL
+ );
+ CREATE INDEX IF NOT EXISTS generation_trash_deleted ON generation_trash(deleted_at);
+ CREATE TABLE IF NOT EXISTS folders (
+ id TEXT PRIMARY KEY,
+ name TEXT NOT NULL,
+ color TEXT NOT NULL,
+ created_at INTEGER NOT NULL,
+ updated_at INTEGER NOT NULL
+ );
+ CREATE TABLE IF NOT EXISTS folder_items (
+ generation_id TEXT PRIMARY KEY,
+ folder_id TEXT NOT NULL,
+ added_at INTEGER NOT NULL
+ );
+ CREATE INDEX IF NOT EXISTS folder_items_folder ON folder_items(folder_id);`,
];
declare global {
diff --git a/src/server/generations.ts b/src/server/generations.ts
index 02a50be6..c99b432f 100644
--- a/src/server/generations.ts
+++ b/src/server/generations.ts
@@ -27,7 +27,7 @@ import { provider } from "./providers";
import type { RemoteOutput } from "./providers/types";
import { convertMask } from "./png";
import { engineMode, getSetting } from "./settings";
-import { contentTypeFor, readRef, saveFile } from "./storage";
+import { contentTypeFor, deleteAsset, readRef, saveFile } from "./storage";
interface Row {
id: string;
@@ -55,9 +55,28 @@ interface Row {
updated_at: number;
completed_at: number | null;
depends_on: string | null;
+ /** Joined by the library readers (generation_trash, folder_items); looked up when absent. */
+ deleted_at?: number | null;
+ folder_id?: string | null;
}
-function toGeneration(r: Row): Generation {
+/** Trash and folder columns, joined onto every library read. */
+const LIBRARY_COLUMNS = "g.*, t.deleted_at AS deleted_at, fi.folder_id AS folder_id";
+const LIBRARY_JOIN = "generations g LEFT JOIN generation_trash t ON t.generation_id = g.id LEFT JOIN folder_items fi ON fi.generation_id = g.id";
+
+export function toGeneration(r: Row): Generation {
+ const request = JSON.parse(r.request_json) as GenerationRequest;
+ const model = getModel(r.model_id);
+ const ar = request.params?.aspectRatio ?? model?.defaults?.aspectRatio;
+ // Rows read without the library join (the runner's own SELECTs) look the trash and folder up.
+ const lib =
+ r.deleted_at !== undefined && r.folder_id !== undefined
+ ? { deleted_at: r.deleted_at, folder_id: r.folder_id }
+ : (db()
+ .prepare(
+ "SELECT (SELECT deleted_at FROM generation_trash WHERE generation_id = ?) AS deleted_at, (SELECT folder_id FROM folder_items WHERE generation_id = ?) AS folder_id",
+ )
+ .get(r.id, r.id) as { deleted_at: number | null; folder_id: string | null });
return {
id: r.id,
batchId: r.batch_id,
@@ -72,7 +91,7 @@ function toGeneration(r: Row): Generation {
progress: r.progress,
message: r.message,
prompt: r.prompt,
- request: JSON.parse(r.request_json) as GenerationRequest,
+ request,
outputs: JSON.parse(r.outputs_json) as OutputFile[],
error: r.error,
costUsd: r.cost_usd,
@@ -80,6 +99,11 @@ function toGeneration(r: Row): Generation {
createdAt: r.created_at,
updatedAt: r.updated_at,
completedAt: r.completed_at,
+ modelName: model?.name ?? r.model_id,
+ presetName: r.preset_id ? (getPreset(r.preset_id)?.name ?? null) : null,
+ aspectRatio: ar && ar !== "auto" ? ar : null,
+ deletedAt: lib.deleted_at ?? null,
+ folderId: lib.folder_id ?? null,
};
}
@@ -91,10 +115,12 @@ function update(id: string, fields: Partial<Row>): void {
.run({ ...fields, __now: Date.now(), __id: id });
}
-export function getGeneration(id: string): Generation | null {
+/** One generation; a row in the Trash reads as missing unless `includeDeleted`. */
+export function getGeneration(id: string, opts: { includeDeleted?: boolean } = {}): Generation | null {
ensureRunner();
- const r = db().prepare("SELECT * FROM generations WHERE id = ?").get(id) as Row | undefined;
- return r ? toGeneration(r) : null;
+ const r = db().prepare(`SELECT ${LIBRARY_COLUMNS} FROM ${LIBRARY_JOIN} WHERE g.id = ?`).get(id) as Row | undefined;
+ if (!r || (r.deleted_at && !opts.includeDeleted)) return null;
+ return toGeneration(r);
}
export interface ListOptions {
@@ -102,55 +128,77 @@ export interface ListOptions {
feature?: string;
features?: string[];
kind?: string;
+ kinds?: string[];
+ models?: string[];
favorites?: boolean;
status?: string;
+ statuses?: string[];
+ /** Only the Trash, newest deletion first (`before` is then a deletedAt cursor). Otherwise the Trash is left out. */
+ trashed?: boolean;
+ folderId?: string;
limit?: number;
+ /** Paging cursor: made before this (deleted before, in the Trash). */
before?: number;
+ /** Date range on createdAt: since ≤ t < until. */
+ since?: number;
+ until?: number;
q?: string;
}
+const featureLike = (f: string) => (f.endsWith("*") ? `${f.slice(0, -1)}%` : f);
+
export function listGenerations(o: ListOptions = {}): Generation[] {
- const where: string[] = [];
+ const where: string[] = [o.trashed ? "t.deleted_at IS NOT NULL" : "t.deleted_at IS NULL"];
const args: unknown[] = [];
- if (o.batchId) {
- where.push("batch_id = ?");
- args.push(o.batchId);
- }
- if (o.feature) {
- where.push("feature = ?");
- args.push(o.feature);
- }
- if (o.features?.length) {
- where.push(`(${o.features.map(() => "feature LIKE ?").join(" OR ")})`);
- args.push(...o.features.map((f) => (f.endsWith("*") ? `${f.slice(0, -1)}%` : f)));
- }
- if (o.kind) {
- where.push("kind = ?");
- args.push(o.kind);
- }
- if (o.favorites) where.push("favorite = 1");
- if (o.status) {
- where.push("status = ?");
- args.push(o.status);
- }
- if (o.before) {
- where.push("created_at < ?");
- args.push(o.before);
- }
- if (o.q) {
- where.push("prompt LIKE ?");
- args.push(`%${o.q}%`);
- }
- const sql = `SELECT * FROM generations ${where.length ? `WHERE ${where.join(" AND ")}` : ""} ORDER BY created_at DESC LIMIT ?`;
- return (db().prepare(sql).all(...args, Math.min(o.limit ?? 60, 200)) as Row[]).map(toGeneration);
+ const add = (sql: string, ...values: unknown[]) => {
+ where.push(sql);
+ args.push(...values);
+ };
+ const oneOf = (col: string, values: unknown[]) => add(`${col} IN (${values.map(() => "?").join(", ")})`, ...values);
+ if (o.batchId) add("g.batch_id = ?", o.batchId);
+ if (o.feature) add("g.feature = ?", o.feature);
+ if (o.features?.length) add(`(${o.features.map(() => "g.feature LIKE ?").join(" OR ")})`, ...o.features.map(featureLike));
+ if (o.kind) add("g.kind = ?", o.kind);
+ if (o.kinds?.length) oneOf("g.kind", o.kinds);
+ if (o.models?.length) oneOf("g.model_id", o.models);
+ if (o.favorites) add("g.favorite = 1");
+ 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.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";
+ 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);
}
export function setFavorite(id: string, favorite: boolean): void {
update(id, { favorite: favorite ? 1 : 0 });
}
+/**
+ * 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").
+ */
export function deleteGeneration(id: string): void {
- db().prepare("DELETE FROM generations WHERE id = ?").run(id);
+ const assets = db().prepare("SELECT id FROM assets WHERE generation_id = ?").all(id) as { id: string }[];
+ db().transaction(() => {
+ db().prepare("DELETE FROM generations WHERE id = ?").run(id);
+ 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);
+ }
}
// ---------------------------------------------------------------------------
diff --git a/src/server/library.ts b/src/server/library.ts
new file mode 100644
index 00000000..8a1887a0
--- /dev/null
+++ b/src/server/library.ts
@@ -0,0 +1,298 @@
+import "server-only";
+import fs from "node:fs";
+import { nanoid } from "nanoid";
+import { getModel } from "@/lib/catalog";
+import type { MediaKind, OutputFile } from "@/lib/catalog/types";
+import { DEFAULT_FOLDER_COLOR, downloadName, FOLDER_COLORS, TRASH_DAYS, type Folder } from "@/lib/library";
+import { db } from "./db";
+import { cancelGeneration, deleteGeneration, getGeneration, type ListOptions } from "./generations";
+import { absolutePath } from "./storage";
+import type { ZipEntry } from "./zip";
+
+/**
+ * The Assets library on top of generations: the Trash (soft delete, kept 30 days), folders,
+ * bulk actions and zip downloads. Every generation reader leaves trashed rows out
+ * (listGenerations / getGeneration join generation_trash).
+ */
+
+const DAY = 86_400_000;
+const MAX_IDS = 500;
+
+const STATUSES = new Set(["queued", "running", "succeeded", "failed", "canceled"]);
+const KINDS = new Set(["image", "video", "audio", "text", "model3d"]);
+
+/** 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);
+ const num = (k: string) => {
+ const v = Number(sp.get(k));
+ return sp.get(k) && Number.isFinite(v) && v > 0 ? v : undefined;
+ };
+ return {
+ feature: sp.get("feature") ?? undefined,
+ features: list("features"),
+ kind: sp.get("kind") && KINDS.has(sp.get("kind")!) ? sp.get("kind")! : undefined,
+ kinds: list("kinds")?.filter((k) => KINDS.has(k)),
+ models: list("models"),
+ favorites: sp.get("favorites") === "1",
+ status: sp.get("status") ?? undefined,
+ statuses: list("statuses")?.filter((s) => STATUSES.has(s)),
+ folderId: sp.get("folder") ?? undefined,
+ trashed: sp.get("trash") === "1",
+ q: sp.get("q") ?? undefined,
+ before: num("before"),
+ since: num("since"),
+ until: num("until"),
+ limit: num("limit"),
+ batchId: sp.get("batch") ?? undefined,
+ };
+}
+
+const ids = (list: string[]) => [...new Set(list)].slice(0, MAX_IDS);
+const placeholders = (n: number) => Array.from({ length: n }, () => "?").join(", ");
+
+function existing(list: string[]): string[] {
+ if (!list.length) return [];
+ return (db().prepare(`SELECT id FROM generations WHERE id IN (${placeholders(list.length)})`).all(...list) as { id: string }[]).map((r) => r.id);
+}
+
+/** Touch rows so anything watching updated_at (the live stream) sees the change. */
+function touch(list: string[]): void {
+ if (list.length) db().prepare(`UPDATE generations SET updated_at = ? WHERE id IN (${placeholders(list.length)})`).run(Date.now(), ...list);
+}
+
+// ---------------------------------------------------------------------------
+// Trash
+
+/** Move to the Trash. Running jobs keep running (cancel them from their tile); Restore brings them back as they are. */
+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 (?, ?)");
+ let n = 0;
+ db().transaction(() => {
+ for (const id of found) n += insert.run(id, now).changes;
+ touch(found);
+ })();
+ return n;
+}
+
+export function restoreGenerations(list: string[]): number {
+ const found = ids(list);
+ if (!found.length) return 0;
+ let n = 0;
+ db().transaction(() => {
+ n = db().prepare(`DELETE FROM generation_trash WHERE generation_id IN (${placeholders(found.length)})`).run(...found).changes;
+ // A folder deleted meanwhile no longer holds it: it comes back to the library root.
+ db().prepare(`DELETE FROM folder_items WHERE generation_id IN (${placeholders(found.length)}) AND folder_id NOT IN (SELECT id FROM folders)`).run(...found);
+ touch(found);
+ })();
+ return n;
+}
+
+/** Delete for good; jobs still running are canceled first. */
+export async function deleteForever(list: string[]): Promise<number> {
+ const found = existing(ids(list));
+ for (const id of found) {
+ const g = getGeneration(id, { includeDeleted: true });
+ if (g && (g.status === "queued" || g.status === "running")) await cancelGeneration(id).catch(() => {});
+ deleteGeneration(id);
+ }
+ return found.length;
+}
+
+export function trashedIds(before?: number): string[] {
+ const rows = before
+ ? db().prepare("SELECT generation_id FROM generation_trash WHERE deleted_at < ?").all(before)
+ : db().prepare("SELECT generation_id FROM generation_trash").all();
+ return (rows as { generation_id: string }[]).map((r) => r.generation_id);
+}
+
+export async function emptyTrash(): Promise<number> {
+ let n = 0;
+ for (let batch = trashedIds().slice(0, MAX_IDS); batch.length; batch = trashedIds().slice(0, MAX_IDS)) {
+ const done = await deleteForever(batch);
+ // Ids whose generation row is already gone: drop the dangling trash entries.
+ db().prepare(`DELETE FROM generation_trash WHERE generation_id IN (${placeholders(batch.length)})`).run(...batch);
+ n += done;
+ }
+ return n;
+}
+
+/** Delete what has been in the Trash for more than 30 days. */
+export async function purgeTrash(now = Date.now()): Promise<number> {
+ const old = trashedIds(now - TRASH_DAYS * DAY);
+ let n = 0;
+ for (let i = 0; i < old.length; i += MAX_IDS) n += await deleteForever(old.slice(i, i + MAX_IDS));
+ if (old.length) db().prepare("DELETE FROM generation_trash WHERE deleted_at < ?").run(now - TRASH_DAYS * DAY);
+ return n;
+}
+
+declare global {
+ var __fuobeTrashPurge: { timer: NodeJS.Timeout } | undefined;
+}
+
+/** Purge once at startup (the first library read) and then daily. */
+export function ensureTrashPurge(): void {
+ if (globalThis.__fuobeTrashPurge) return;
+ const run = () => void purgeTrash().catch((e) => console.warn(`[fuobe] trash purge failed: ${(e as Error).message}`));
+ const timer = setInterval(run, DAY);
+ timer.unref?.();
+ globalThis.__fuobeTrashPurge = { timer };
+ run();
+}
+
+export function trashCount(): number {
+ return (db().prepare("SELECT COUNT(*) AS n FROM generation_trash t JOIN generations g ON g.id = t.generation_id").get() as { n: number }).n;
+}
+
+// ---------------------------------------------------------------------------
+// Favorites, folders
+
+export function setFavorites(list: string[], favorite: boolean): number {
+ const found = ids(list);
+ if (!found.length) return 0;
+ return db().prepare(`UPDATE generations SET favorite = ?, updated_at = ? WHERE id IN (${placeholders(found.length)})`).run(favorite ? 1 : 0, Date.now(), ...found).changes;
+}
+
+interface FolderRow {
+ id: string;
+ name: string;
+ color: string;
+ created_at: number;
+ updated_at: number;
+ count: number;
+ cover_json: string | null;
+}
+
+const toFolder = (r: FolderRow): Folder => {
+ const outputs = r.cover_json ? (JSON.parse(r.cover_json) as OutputFile[]) : [];
+ return { id: r.id, name: r.name, color: r.color, count: r.count, cover: outputs[0] ?? null, createdAt: r.created_at, updatedAt: r.updated_at };
+};
+
+const FOLDER_SELECT = `SELECT f.*,
+ (SELECT COUNT(*) FROM folder_items i JOIN generations g ON g.id = i.generation_id LEFT JOIN generation_trash t ON t.generation_id = g.id
+ WHERE i.folder_id = f.id AND t.generation_id IS NULL) AS count,
+ (SELECT g.outputs_json FROM folder_items i JOIN generations g ON g.id = i.generation_id LEFT JOIN generation_trash t ON t.generation_id = g.id
+ WHERE i.folder_id = f.id AND t.generation_id IS NULL AND g.status = 'succeeded' AND g.outputs_json != '[]' ORDER BY g.created_at DESC LIMIT 1) AS cover_json
+ FROM folders f`;
+
+export function listFolders(): Folder[] {
+ return (db().prepare(`${FOLDER_SELECT} ORDER BY f.created_at ASC`).all() as FolderRow[]).map(toFolder);
+}
+
+export function getFolder(id: string): Folder | null {
+ const r = db().prepare(`${FOLDER_SELECT} WHERE f.id = ?`).get(id) as FolderRow | undefined;
+ return r ? toFolder(r) : null;
+}
+
+const colorOf = (c: string | undefined) => (FOLDER_COLORS.some((x) => x.id === c) ? c! : DEFAULT_FOLDER_COLOR);
+
+export function createFolder(input: { name: string; color?: string }): Folder {
+ const name = input.name.trim().slice(0, 60);
+ if (!name) throw new Error("Give the folder a name");
+ if (db().prepare("SELECT 1 FROM folders WHERE lower(name) = lower(?)").get(name)) throw new Error(`There's already a folder called “${name}”`);
+ const now = Date.now();
+ const id = nanoid(10);
+ db().prepare("INSERT INTO folders (id, name, color, created_at, updated_at) VALUES (?, ?, ?, ?, ?)").run(id, name, colorOf(input.color), now, now);
+ return getFolder(id)!;
+}
+
+export function updateFolder(id: string, patch: { name?: string; color?: string }): Folder | null {
+ const f = getFolder(id);
+ if (!f) return null;
+ const name = patch.name !== undefined ? patch.name.trim().slice(0, 60) : f.name;
+ if (!name) throw new Error("Give the folder a name");
+ if (name.toLowerCase() !== f.name.toLowerCase() && db().prepare("SELECT 1 FROM folders WHERE lower(name) = lower(?) AND id != ?").get(name, id)) {
+ throw new Error(`There's already a folder called “${name}”`);
+ }
+ db().prepare("UPDATE folders SET name = ?, color = ?, updated_at = ? WHERE id = ?").run(name, patch.color !== undefined ? colorOf(patch.color) : f.color, Date.now(), id);
+ return getFolder(id);
+}
+
+/** Delete a folder; what was in it goes back to the library (nothing is deleted). */
+export function deleteFolder(id: string): boolean {
+ let n = 0;
+ db().transaction(() => {
+ const members = (db().prepare("SELECT generation_id FROM folder_items WHERE folder_id = ?").all(id) as { generation_id: string }[]).map((r) => r.generation_id);
+ db().prepare("DELETE FROM folder_items WHERE folder_id = ?").run(id);
+ n = db().prepare("DELETE FROM folders WHERE id = ?").run(id).changes;
+ touch(members);
+ })();
+ return n > 0;
+}
+
+/** Move generations into a folder (each is in at most one), or back to the library root with null. */
+export function moveToFolder(list: string[], folderId: string | null): number {
+ if (folderId && !db().prepare("SELECT 1 FROM folders WHERE id = ?").get(folderId)) throw new Error("That folder doesn't exist anymore");
+ const found = existing(ids(list));
+ const now = Date.now();
+ db().transaction(() => {
+ const del = db().prepare("DELETE FROM folder_items WHERE generation_id = ?");
+ const ins = db().prepare("INSERT INTO folder_items (generation_id, folder_id, added_at) VALUES (?, ?, ?)");
+ for (const id of found) {
+ del.run(id);
+ if (folderId) ins.run(id, folderId, now);
+ }
+ if (folderId) db().prepare("UPDATE folders SET updated_at = ? WHERE id = ?").run(now, folderId);
+ touch(found);
+ })();
+ return found.length;
+}
+
+// ---------------------------------------------------------------------------
+// Facets for the filter menus
+
+export interface LibraryFacets {
+ models: { id: string; name: string; count: number }[];
+ kinds: Partial<Record<MediaKind, number>>;
+ total: number;
+ favorites: number;
+ failed: number;
+ trash: number;
+}
+
+export function libraryFacets(): LibraryFacets {
+ const live = "FROM generations g LEFT JOIN generation_trash t ON t.generation_id = g.id WHERE t.generation_id IS NULL";
+ const models = db().prepare(`SELECT g.model_id AS id, COUNT(*) AS n ${live} GROUP BY g.model_id ORDER BY n DESC`).all() as { id: string; n: number }[];
+ const kinds = db().prepare(`SELECT g.kind AS kind, COUNT(*) AS n ${live} GROUP BY g.kind`).all() as { kind: MediaKind; n: number }[];
+ const one = (sql: string) => (db().prepare(sql).get() as { n: number }).n;
+ return {
+ models: models.map((m) => ({ id: m.id, name: getModel(m.id)?.name ?? m.id, count: m.n })),
+ kinds: Object.fromEntries(kinds.map((k) => [k.kind, k.n])),
+ total: one(`SELECT COUNT(*) AS n ${live}`),
+ favorites: one(`SELECT COUNT(*) AS n ${live} AND g.favorite = 1`),
+ failed: one(`SELECT COUNT(*) AS n ${live} AND g.status IN ('failed','canceled')`),
+ trash: trashCount(),
+ };
+}
+
+// ---------------------------------------------------------------------------
+// Zip download
+
+export const ZIP_MAX_BYTES = 4 * 1024 ** 3 - 1;
+
+/** The finished output files of these generations, with readable, unique names. */
+export function zipEntries(list: string[]): ZipEntry[] {
+ const out: ZipEntry[] = [];
+ const used = new Set<string>();
+ for (const id of ids(list)) {
+ const g = getGeneration(id, { includeDeleted: true });
+ if (!g || g.status !== "succeeded") continue;
+ g.outputs.forEach((o, i) => {
+ if (!o.url.startsWith("/api/files/")) return;
+ let file: string;
+ try {
+ file = absolutePath(decodeURIComponent(o.url.slice("/api/files/".length).split("?")[0]));
+ } catch {
+ return;
+ }
+ if (!fs.existsSync(file)) return;
+ const base = downloadName(g, o, i);
+ let name = base;
+ for (let k = 2; used.has(name); k++) name = base.replace(/(\.[^.]+)?$/, (ext) => `-${k}${ext}`);
+ used.add(name);
+ out.push({ name, path: file, size: fs.statSync(file).size });
+ });
+ }
+ return out;
+}
diff --git a/src/server/zip.ts b/src/server/zip.ts
index 6246bb78..3c5f3fc0 100644
--- a/src/server/zip.ts
+++ b/src/server/zip.ts
@@ -1,43 +1,134 @@
import "server-only";
+import fs from "node:fs";
+import zlib from "node:zlib";
import { crc32 } from "./png";
-/** Minimal ZIP writer (stored, no compression) — enough for training datasets and download kits. */
+/** Minimal ZIP writers (stored, no compression): media files are already compressed. */
+
+/** MS-DOS date and time of a timestamp (zip headers). */
+function dosTime(ts: number): { time: number; date: number } {
+ const d = new Date(ts);
+ if (d.getFullYear() < 1980) return { time: 0, date: (1 << 5) | 1 };
+ return {
+ time: (d.getHours() << 11) | (d.getMinutes() << 5) | Math.floor(d.getSeconds() / 2),
+ date: ((d.getFullYear() - 1980) << 9) | ((d.getMonth() + 1) << 5) | d.getDate(),
+ };
+}
+
+function localHeader(name: Buffer, crc: number, size: number, when: { time: number; date: number }): Buffer {
+ const head = Buffer.alloc(30);
+ head.writeUInt32LE(0x04034b50, 0);
+ head.writeUInt16LE(20, 4); // version needed
+ head.writeUInt16LE(0x0800, 6); // UTF-8 names
+ head.writeUInt16LE(0, 8); // stored
+ head.writeUInt16LE(when.time, 10);
+ head.writeUInt16LE(when.date, 12);
+ head.writeUInt32LE(crc, 14);
+ head.writeUInt32LE(size, 18);
+ head.writeUInt32LE(size, 22);
+ head.writeUInt16LE(name.length, 26);
+ return head;
+}
+
+function centralHeader(name: Buffer, crc: number, size: number, offset: number, when: { time: number; date: number }): Buffer {
+ const dir = Buffer.alloc(46);
+ dir.writeUInt32LE(0x02014b50, 0);
+ dir.writeUInt16LE(20, 4);
+ dir.writeUInt16LE(20, 6);
+ dir.writeUInt16LE(0x0800, 8);
+ dir.writeUInt16LE(when.time, 12);
+ dir.writeUInt16LE(when.date, 14);
+ dir.writeUInt32LE(crc, 16);
+ dir.writeUInt32LE(size, 20);
+ dir.writeUInt32LE(size, 24);
+ dir.writeUInt16LE(name.length, 28);
+ dir.writeUInt32LE(offset, 42);
+ return dir;
+}
+
+function endRecord(count: number, cdSize: number, cdOffset: number): Buffer {
+ const end = Buffer.alloc(22);
+ end.writeUInt32LE(0x06054b50, 0);
+ end.writeUInt16LE(count, 8);
+ end.writeUInt16LE(count, 10);
+ end.writeUInt32LE(cdSize, 12);
+ end.writeUInt32LE(cdOffset, 16);
+ return end;
+}
+
+/** A zip of in-memory files — enough for training datasets and download kits. */
export function zip(files: { name: string; data: Buffer }[]): Buffer {
const local: Buffer[] = [];
const central: Buffer[] = [];
+ const when = { time: 0, date: (1 << 5) | 1 };
let offset = 0;
for (const f of files) {
const name = Buffer.from(f.name, "utf8");
const crc = crc32(f.data);
- const head = Buffer.alloc(30);
- head.writeUInt32LE(0x04034b50, 0);
- head.writeUInt16LE(20, 4); // version needed
- head.writeUInt16LE(0x0800, 6); // UTF-8 names
- head.writeUInt16LE(0, 8); // stored
- head.writeUInt32LE(crc, 14);
- head.writeUInt32LE(f.data.length, 18);
- head.writeUInt32LE(f.data.length, 22);
- head.writeUInt16LE(name.length, 26);
+ const head = localHeader(name, crc, f.data.length, when);
local.push(head, name, f.data);
- const dir = Buffer.alloc(46);
- dir.writeUInt32LE(0x02014b50, 0);
- dir.writeUInt16LE(20, 4);
- dir.writeUInt16LE(20, 6);
- dir.writeUInt16LE(0x0800, 8);
- dir.writeUInt32LE(crc, 16);
- dir.writeUInt32LE(f.data.length, 20);
- dir.writeUInt32LE(f.data.length, 24);
- dir.writeUInt16LE(name.length, 28);
- dir.writeUInt32LE(offset, 42);
- central.push(dir, name);
+ central.push(centralHeader(name, crc, f.data.length, offset, when), name);
offset += head.length + name.length + f.data.length;
}
const cd = Buffer.concat(central);
- const end = Buffer.alloc(22);
- end.writeUInt32LE(0x06054b50, 0);
- end.writeUInt16LE(files.length, 8);
- end.writeUInt16LE(files.length, 10);
- end.writeUInt32LE(cd.length, 12);
- end.writeUInt32LE(offset, 16);
- return Buffer.concat([...local, cd, end]);
+ return Buffer.concat([...local, cd, endRecord(files.length, cd.length, offset)]);
+}
+
+export interface ZipEntry {
+ name: string;
+ /** Absolute path of the file on disk. */
+ path: string;
+ size: number;
+}
+
+async function fileCrc(path: string): Promise<number> {
+ let crc = 0;
+ for await (const chunk of fs.createReadStream(path)) crc = zlib.crc32(chunk as Buffer, crc);
+ return crc;
+}
+
+/** The zip's size in bytes, before streaming it (Content-Length, the 4 GB limit). */
+export function zipSize(entries: ZipEntry[]): number {
+ return entries.reduce((n, e) => n + 30 + 46 + 2 * Buffer.byteLength(e.name) + e.size, 22);
+}
+
+/**
+ * Stream a zip of files on disk. Each file is read twice (its CRC first, then its bytes), so memory
+ * stays flat whatever the size. Stays under 4 GB (no ZIP64): check `zipSize()` first.
+ */
+export function zipStream(entries: ZipEntry[]): ReadableStream<Uint8Array> {
+ async function* parts(): AsyncGenerator<Uint8Array> {
+ const central: Buffer[] = [];
+ let offset = 0;
+ for (const e of entries) {
+ const name = Buffer.from(e.name, "utf8");
+ const stat = fs.statSync(e.path);
+ const when = dosTime(stat.mtimeMs);
+ const crc = await fileCrc(e.path);
+ const head = localHeader(name, crc, stat.size, when);
+ yield head;
+ yield name;
+ for await (const chunk of fs.createReadStream(e.path)) yield chunk as Buffer;
+ central.push(centralHeader(name, crc, stat.size, offset, when), name);
+ offset += head.length + name.length + stat.size;
+ }
+ const cd = Buffer.concat(central);
+ yield cd;
+ yield endRecord(entries.length, cd.length, offset);
+ }
+ const it = parts();
+ return new ReadableStream<Uint8Array>({
+ async pull(controller) {
+ try {
+ const { value, done } = await it.next();
+ if (done) controller.close();
+ else controller.enqueue(value);
+ } catch (e) {
+ controller.error(e);
+ }
+ },
+ async cancel() {
+ await it.return(undefined);
+ },
+ });
}
diff --git a/tests/library.test.ts b/tests/library.test.ts
new file mode 100644
index 00000000..cdb2992d
--- /dev/null
+++ b/tests/library.test.ts
@@ -0,0 +1,191 @@
+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";
+
+const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-library-"));
+process.env.FUOBE_DATA_DIR = dir;
+process.env.COMFYUI_URL = "http://127.0.0.1:9";
+
+const { setSetting } = await import("@/server/settings");
+const gens = await import("@/server/generations");
+const lib = await import("@/server/library");
+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 { db } = await import("@/server/db");
+
+beforeAll(() => setSetting("demoMode", "auto"));
+afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));
+
+const DAY = 86_400_000;
+const PNG = Buffer.from("89504e470d0a1a0a0000000d4948445200000001000000010806000000", "hex");
+
+/** A finished generation with a real output file (recorded like a browser colour grade). */
+function made(prompt: string) {
+ const asset = saveFile({ data: Buffer.concat([PNG, Buffer.from(prompt)]), contentType: "image/png", source: "generation" });
+ const g = gens.recordLocalGeneration({
+ feature: "grade",
+ modelId: "local-color-grade",
+ op: "grade",
+ prompt,
+ inputs: { images: ["/api/files/uploads/x.png"] },
+ output: { url: asset.url, kind: "image", contentType: "image/png" },
+ });
+ db().prepare("UPDATE assets SET generation_id = ? WHERE id = ?").run(g.id, asset.id);
+ return { g, asset };
+}
+
+const fileOf = (url: string) => absolutePath(decodeURIComponent(url.slice("/api/files/".length)));
+const listIds = (o: Parameters<typeof gens.listGenerations>[0] = {}) => gens.listGenerations({ limit: 200, ...o }).map((g) => g.id);
+
+describe("generation names", () => {
+ it("carries the model and preset names and the aspect ratio, so result views need no catalog", () => {
+ const { g } = made("names");
+ expect(g.modelName).toBe("Color Grading");
+ expect(g.presetName).toBeNull();
+ const [img] = gens.createGenerations({ feature: "image", modelId: "nano-banana-pro", prompt: "a fox", params: { aspectRatio: "16:9" } });
+ expect(img.modelName).toBe("Nano Banana Pro");
+ expect(img.aspectRatio).toBe("16:9");
+ expect(img.deletedAt).toBeNull();
+ expect(img.folderId).toBeNull();
+ });
+});
+
+describe("trash (soft delete)", () => {
+ it("hides trashed generations from every reader and restores them", async () => {
+ const a = made("alpha lighthouse").g;
+ const b = made("beta lighthouse").g;
+ expect(lib.trashGenerations([a.id])).toBe(1);
+ expect(lib.trashGenerations([a.id])).toBe(0); // already there
+ expect(listIds()).not.toContain(a.id);
+ expect(listIds()).toContain(b.id);
+ expect(listIds({ q: "lighthouse" })).toEqual([b.id]);
+ expect(gens.getGeneration(a.id)).toBeNull();
+ expect(gens.getGeneration(a.id, { includeDeleted: true })?.deletedAt).toBeGreaterThan(0);
+ // Assist / MCP list_recent goes through listGenerations.
+ const recent = TOOLS.find((t) => t.name === "list_recent")!;
+ const out = await recent.run({ limit: 30 }, {} as never);
+ expect(String(out.content)).not.toContain(a.id);
+ // The Trash lists it, newest deletion first.
+ const trash = gens.listGenerations({ trashed: true });
+ expect(trash.map((g) => g.id)).toEqual([a.id]);
+ expect(trash[0].deletedAt).toBeTypeOf("number");
+ expect(lib.libraryFacets().trash).toBe(1);
+
+ expect(lib.restoreGenerations([a.id])).toBe(1);
+ expect(gens.getGeneration(a.id)?.deletedAt).toBeNull();
+ expect(listIds()).toContain(a.id);
+ });
+
+ it("deletes for good, keeping output files something else still uses", async () => {
+ const lone = made("lone");
+ const used = made("used as a character");
+ db()
+ .prepare("INSERT INTO characters (id, name, reference_asset_ids_json, status, created_at, updated_at) VALUES ('c1', 'Maya', ?, 'ready', 0, 0)")
+ .run(JSON.stringify([used.asset.url]));
+ lib.trashGenerations([lone.g.id, used.g.id]);
+ expect(await lib.deleteForever([lone.g.id, used.g.id])).toBe(2);
+ expect(gens.getGeneration(lone.g.id, { includeDeleted: true })).toBeNull();
+ expect(fs.existsSync(fileOf(lone.asset.url))).toBe(false);
+ expect(fs.existsSync(fileOf(used.asset.url))).toBe(true);
+ expect(gens.listGenerations({ trashed: true }).map((g) => g.id)).not.toContain(lone.g.id);
+ });
+
+ it("purges what has been in the Trash for 30 days", async () => {
+ const old = made("old").g;
+ const recent = made("recent").g;
+ const now = Date.now();
+ lib.trashGenerations([old.id], now - 31 * DAY);
+ lib.trashGenerations([recent.id], now - 2 * DAY);
+ expect(await lib.purgeTrash(now)).toBe(1);
+ expect(gens.getGeneration(old.id, { includeDeleted: true })).toBeNull();
+ expect(gens.getGeneration(recent.id, { includeDeleted: true })?.deletedAt).toBe(now - 2 * DAY);
+ expect(await lib.emptyTrash()).toBeGreaterThanOrEqual(1);
+ expect(gens.listGenerations({ trashed: true })).toEqual([]);
+ });
+
+ it("cancels a running job 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();
+ });
+});
+
+describe("folders", () => {
+ it("creates, renames, recolours, moves into and deletes folders", () => {
+ const f = lib.createFolder({ name: "Campaign", color: "pink" });
+ expect(f).toMatchObject({ name: "Campaign", color: "pink", count: 0, cover: null });
+ expect(() => lib.createFolder({ name: "campaign" })).toThrow(/already a folder/);
+ expect(lib.createFolder({ name: "Other", color: "nope" }).color).toBe("lime");
+ const a = made("in folder a").g;
+ const b = made("in folder b").g;
+ expect(lib.moveToFolder([a.id, b.id], f.id)).toBe(2);
+ expect(lib.getFolder(f.id)).toMatchObject({ count: 2 });
+ expect(lib.getFolder(f.id)!.cover?.url).toBe(b.outputs[0].url);
+ expect(listIds({ folderId: f.id }).sort()).toEqual([a.id, b.id].sort());
+ expect(gens.getGeneration(a.id)?.folderId).toBe(f.id);
+ // Trashed items don't count.
+ lib.trashGenerations([b.id]);
+ expect(lib.getFolder(f.id)!.count).toBe(1);
+ lib.restoreGenerations([b.id]);
+ // Moving back to the root.
+ lib.moveToFolder([b.id], null);
+ expect(listIds({ folderId: f.id })).toEqual([a.id]);
+ expect(lib.updateFolder(f.id, { name: "Launch", color: "cyan" })).toMatchObject({ name: "Launch", color: "cyan" });
+ expect(() => lib.moveToFolder([a.id], "missing")).toThrow(/doesn't exist/);
+ // Deleting the folder keeps what was in it.
+ expect(lib.deleteFolder(f.id)).toBe(true);
+ expect(gens.getGeneration(a.id)?.folderId).toBeNull();
+ expect(lib.listFolders().map((x) => x.name)).toEqual(["Other"]);
+ });
+});
+
+describe("bulk endpoint", () => {
+ const call = async (body: unknown) => {
+ const res = await bulk(new Request("http://x/api/generations/bulk", { method: "POST", body: JSON.stringify(body) }));
+ return { status: res.status, body: (await res.json()) as { count?: number; error?: string } };
+ };
+
+ it("favorites, moves, trashes, restores and deletes many at once", async () => {
+ const items = [made("bulk 1").g, made("bulk 2").g, made("bulk 3").g];
+ const ids = items.map((g) => g.id);
+ expect(await call({ action: "favorite", ids })).toEqual({ status: 200, body: { count: 3 } });
+ expect(gens.listGenerations({ favorites: true }).filter((g) => ids.includes(g.id))).toHaveLength(3);
+ const folder = lib.createFolder({ name: "Bulk" });
+ expect((await call({ action: "move", ids, folderId: folder.id })).body.count).toBe(3);
+ expect((await call({ action: "trash", ids: ids.slice(0, 2) })).body.count).toBe(2);
+ expect(listIds({ folderId: folder.id })).toEqual([ids[2]]);
+ expect((await call({ action: "restore", ids: [ids[0]] })).body.count).toBe(1);
+ expect((await call({ action: "delete", ids: [ids[1]] })).body.count).toBe(1);
+ expect(gens.getGeneration(ids[1], { includeDeleted: true })).toBeNull();
+ expect((await call({ action: "move", ids, folderId: "gone" })).status).toBe(422);
+ expect((await call({ action: "explode", ids })).status).toBe(400);
+ expect((await call({ action: "trash", ids: [] })).status).toBe(400);
+ });
+});
+
+describe("zip download", () => {
+ it("streams a zip other tools can read, with unique readable names", async () => {
+ const a = made("zip me").g;
+ const b = made("zip me").g;
+ const entries = lib.zipEntries([a.id, b.id, "missing"]);
+ expect(entries).toHaveLength(2);
+ expect(new Set(entries.map((e) => e.name)).size).toBe(2);
+ expect(entries[0].name).toMatch(/^zip-me-.{6}\.png$/);
+ const chunks: Uint8Array[] = [];
+ const reader = zipStream(entries).getReader();
+ for (let r = await reader.read(); !r.done; r = await reader.read()) chunks.push(r.value);
+ const buf = Buffer.concat(chunks);
+ expect(buf.length).toBe(zipSize(entries));
+ const file = path.join(dir, "out.zip");
+ fs.writeFileSync(file, buf);
+ const out = execFileSync("python3", ["-I", "-c", "import sys,zipfile;z=zipfile.ZipFile(sys.argv[1]);print(z.testzip(), len(z.namelist()), z.read(z.namelist()[0])[-6:].decode())", file]).toString();
+ expect(out.trim()).toBe("None 2 zip me");
+ });
+});