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: helper steps hidden, nested folders, pins, review status and safe upload delete on the server

Claude0c9e9bbea016
diff --git a/src/app/api/assets/[id]/route.ts b/src/app/api/assets/[id]/route.ts
index c9d529d1..0c142bd9 100644
--- a/src/app/api/assets/[id]/route.ts
+++ b/src/app/api/assets/[id]/route.ts
@@ -1,7 +1,27 @@
-import { deleteAsset } from "@/server/storage";
+import { connection } from "next/server";
+import { assetUses } from "@/server/generations";
+import { deleteUnusedAsset } from "@/server/library";
+import { getAsset } from "@/server/storage";
+import { describeUses } from "@/lib/library";
+/** A stored file and where it's used (`uses`, and `usedBy`: the same in one line, empty when nothing uses it). */
+export async function GET(_req: Request, ctx: RouteContext<"/api/assets/[id]">) {
+ await connection();
+ const { id } = await ctx.params;
+ const asset = getAsset(id);
+ if (!asset) return Response.json({ error: "Not found" }, { status: 404 });
+ const uses = assetUses(id);
+ return Response.json({ ...asset, uses, usedBy: describeUses(uses) });
+}
+
+/** Delete the file for good, only when nothing uses it (409 with `uses` and `usedBy` otherwise). */
export async function DELETE(_req: Request, ctx: RouteContext<"/api/assets/[id]">) {
const { id } = await ctx.params;
- deleteAsset(id);
+ const r = deleteUnusedAsset(id);
+ if (!r) return Response.json({ error: "That file is already gone" }, { status: 404 });
+ if (!r.deleted) {
+ const usedBy = describeUses(r.uses);
+ return Response.json({ error: `It's still used by ${usedBy}.`, uses: r.uses, usedBy }, { status: 409 });
+ }
return new Response(null, { status: 204 });
}
diff --git a/src/app/api/folders/[id]/route.ts b/src/app/api/folders/[id]/route.ts
index 0b1785eb..985872cb 100644
--- a/src/app/api/folders/[id]/route.ts
+++ b/src/app/api/folders/[id]/route.ts
@@ -1,8 +1,14 @@
import { connection } from "next/server";
import { z } from "zod";
-import { deleteFolder, getFolder, updateFolder } from "@/server/library";
+import { deleteFolder, getFolder, LibraryError, updateFolder } from "@/server/library";
-const Patch = z.object({ name: z.string().trim().min(1).max(60).optional(), color: z.string().max(20).optional() });
+const Patch = z.object({
+ name: z.string().trim().min(1).max(60).optional(),
+ color: z.string().max(20).optional(),
+ /** Move it into another folder, or (null) to the library root. */
+ parentId: z.string().max(40).nullable().optional(),
+ pinned: z.boolean().optional(),
+});
export async function GET(_req: Request, ctx: RouteContext<"/api/folders/[id]">) {
await connection();
@@ -11,6 +17,7 @@ export async function GET(_req: Request, ctx: RouteContext<"/api/folders/[id]">)
return f ? Response.json(f) : Response.json({ error: "Not found" }, { status: 404 });
}
+/** Rename, recolour, pin or move (refused into itself or one of its subfolders). */
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));
@@ -19,11 +26,11 @@ export async function PATCH(request: Request, ctx: RouteContext<"/api/folders/[i
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 });
+ return Response.json({ error: (e as Error).message }, { status: e instanceof LibraryError ? e.status : 409 });
}
}
-/** Delete the folder; its contents go back to the library. */
+/** Delete the folder; its results and subfolders move up to its parent (the library root at the top). */
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/[id]/zip/route.ts b/src/app/api/folders/[id]/zip/route.ts
new file mode 100644
index 00000000..ec334615
--- /dev/null
+++ b/src/app/api/folders/[id]/zip/route.ts
@@ -0,0 +1,32 @@
+import { connection } from "next/server";
+import { folderZipEntries, LibraryError, ZIP_MAX_BYTES } from "@/server/library";
+import { zipSize, zipStream } from "@/server/zip";
+
+/**
+ * Download a folder as one zip: its finished results, and each subfolder's in a folder of its own.
+ * `?check=1` answers {files, size} (or the error) without the zip, so the page can explain a refusal.
+ */
+export async function GET(request: Request, ctx: RouteContext<"/api/folders/[id]/zip">) {
+ await connection();
+ const { id } = await ctx.params;
+ let zip: ReturnType<typeof folderZipEntries>;
+ try {
+ zip = folderZipEntries(id);
+ } catch (e) {
+ return Response.json({ error: (e as Error).message }, { status: e instanceof LibraryError ? e.status : 500 });
+ }
+ if (!zip) return Response.json({ error: "That folder doesn't exist anymore" }, { status: 404 });
+ if (!zip.entries.length) return Response.json({ error: "Nothing finished in this folder yet" }, { status: 404 });
+ const size = zipSize(zip.entries);
+ if (size > ZIP_MAX_BYTES) return Response.json({ error: "That's over 4 GB. Download its subfolders one at a time." }, { status: 413 });
+ if (new URL(request.url).searchParams.get("check") === "1") return Response.json({ files: zip.entries.length, size });
+ const slug = zip.name.replace(/[^\w]+/g, "-").replace(/^-|-$/g, "").slice(0, 40) || "folder";
+ return new Response(zipStream(zip.entries), {
+ headers: {
+ "Content-Type": "application/zip",
+ "Content-Length": String(size),
+ "Content-Disposition": `attachment; filename="${slug}-${new Date().toISOString().slice(0, 10)}.zip"`,
+ "Cache-Control": "no-store",
+ },
+ });
+}
diff --git a/src/app/api/folders/route.ts b/src/app/api/folders/route.ts
index 93dabb83..236a7edd 100644
--- a/src/app/api/folders/route.ts
+++ b/src/app/api/folders/route.ts
@@ -1,20 +1,22 @@
import { connection } from "next/server";
import { z } from "zod";
-import { createFolder, listFolders } from "@/server/library";
+import { createFolder, LibraryError, listFolders } from "@/server/library";
-const Body = z.object({ name: z.string().trim().min(1).max(60), color: z.string().max(20).optional() });
+const Body = z.object({ name: z.string().trim().min(1).max(60), color: z.string().max(20).optional(), parentId: z.string().max(40).nullable().optional() });
+/** Every folder, flat: each has its parentId (null at the library root) and pinnedAt. */
export async function GET() {
await connection();
return Response.json({ items: listFolders() });
}
+/** A new folder; `parentId` makes it a subfolder. */
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 });
+ return Response.json({ error: (e as Error).message }, { status: e instanceof LibraryError ? e.status : 409 });
}
}
diff --git a/src/app/api/generations/[id]/route.ts b/src/app/api/generations/[id]/route.ts
index ed6fa2c4..e27de293 100644
--- a/src/app/api/generations/[id]/route.ts
+++ b/src/app/api/generations/[id]/route.ts
@@ -1,6 +1,7 @@
import { connection } from "next/server";
import { getGeneration, setFavorite } from "@/server/generations";
-import { deleteForever, trashGenerations } from "@/server/library";
+import { deleteForever, setPinned, setReview, trashGenerations } from "@/server/library";
+import { isReviewStatus } from "@/lib/library";
export async function GET(_req: Request, ctx: RouteContext<"/api/generations/[id]">) {
await connection();
@@ -9,10 +10,14 @@ export async function GET(_req: Request, ctx: RouteContext<"/api/generations/[id
return g ? Response.json(g) : Response.json({ error: "Not found" }, { status: 404 });
}
+/** Favorite, pin (`pinned`) or set the review status (`review`, null clears it). */
export async function PATCH(request: Request, ctx: RouteContext<"/api/generations/[id]">) {
const { id } = await ctx.params;
- const body = (await request.json().catch(() => ({}))) as { favorite?: boolean };
+ const body = (await request.json().catch(() => ({}))) as { favorite?: boolean; pinned?: boolean; review?: unknown };
+ if (body.review !== undefined && body.review !== null && !isReviewStatus(body.review)) return Response.json({ error: "Pick a review status" }, { status: 400 });
if (typeof body.favorite === "boolean") setFavorite(id, body.favorite);
+ if (typeof body.pinned === "boolean") setPinned([id], body.pinned);
+ if (body.review !== undefined) setReview([id], body.review);
const g = getGeneration(id);
return g ? Response.json(g) : Response.json({ error: "Not found" }, { status: 404 });
}
diff --git a/src/app/api/generations/bulk/route.ts b/src/app/api/generations/bulk/route.ts
index 366b3039..1478d64c 100644
--- a/src/app/api/generations/bulk/route.ts
+++ b/src/app/api/generations/bulk/route.ts
@@ -1,18 +1,20 @@
import { z } from "zod";
-import { deleteForever, moveToFolder, restoreGenerations, setFavorites, trashGenerations } from "@/server/library";
+import { deleteForever, moveToFolder, restoreGenerations, setFavorites, setPinned, setReview, trashGenerations } from "@/server/library";
const Body = z.object({
- action: z.enum(["trash", "restore", "delete", "favorite", "unfavorite", "move"]),
+ action: z.enum(["trash", "restore", "delete", "favorite", "unfavorite", "move", "pin", "unpin", "review"]),
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(),
+ /** For "review": the status, or null to clear it. */
+ review: z.enum(["in-progress", "needs-review", "approved", "rejected"]).nullable().optional(),
});
-/** One action on many generations: Trash / Restore / Delete forever / (un)favorite / move to a folder. */
+/** One action on many generations: Trash / Restore / Delete forever / (un)favorite / move to a folder / (un)pin / review status. */
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;
+ const { action, ids, folderId, review } = parsed.data;
try {
const count =
action === "trash"
@@ -23,7 +25,11 @@ export async function POST(request: Request) {
? await deleteForever(ids)
: action === "move"
? moveToFolder(ids, folderId ?? null)
- : setFavorites(ids, action === "favorite");
+ : action === "pin" || action === "unpin"
+ ? setPinned(ids, action === "pin")
+ : action === "review"
+ ? setReview(ids, review ?? 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
index c80cf4aa..3d81521f 100644
--- a/src/app/api/generations/facets/route.ts
+++ b/src/app/api/generations/facets/route.ts
@@ -1,8 +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() {
+/** Counts for the Library's filter menus: models used, kinds, favorites, failed, pinned, review statuses, helper steps, Trash. `steps=1` counts the steps in. */
+export async function GET(request: Request) {
await connection();
- return Response.json(libraryFacets());
+ return Response.json(libraryFacets({ steps: new URL(request.url).searchParams.get("steps") === "1" }));
}
diff --git a/src/lib/catalog/types.ts b/src/lib/catalog/types.ts
index 6f77b271..ea76701d 100644
--- a/src/lib/catalog/types.ts
+++ b/src/lib/catalog/types.ts
@@ -508,6 +508,9 @@ export interface GenInput extends GenParams {
export type GenerationStatus = "queued" | "running" | "succeeded" | "failed" | "canceled";
+/** Where a result is in review (the Library's review status; none when unset). */
+export type ReviewStatus = "in-progress" | "needs-review" | "approved" | "rejected";
+
export interface OutputFile {
url: string;
/** Text outputs (transcribe, translate, write): the content, also saved as a file at `url`. */
@@ -557,6 +560,10 @@ export interface Generation {
deletedAt?: number | null;
/** Library folder it's in. */
folderId?: string | null;
+ /** Pinned to the top of the Library's views at (null: not pinned). */
+ pinnedAt?: number | null;
+ /** Review status (null: none). */
+ review?: ReviewStatus | null;
}
/** Input slot a preset asks the user for. */
diff --git a/src/lib/generation-stream.ts b/src/lib/generation-stream.ts
index 0ffb7f0a..73073189 100644
--- a/src/lib/generation-stream.ts
+++ b/src/lib/generation-stream.ts
@@ -8,10 +8,10 @@
*/
import { replaceEqualDeep } from "@tanstack/react-query";
import type { Generation } from "./catalog/types";
-import { byDeleted, byNewest, matchesFilter, type FeedFilter } from "./library";
+import { listOrder, matchesFilter, type FeedFilter } from "./library";
-/** Lists are newest first; the Trash is most recently deleted first. */
-const orderFor = (f: FeedFilter) => (f.trashed ? byDeleted : byNewest);
+/** Lists are newest first; the Trash is most recently deleted first, a pinned list most recently pinned first. */
+const orderFor = listOrder;
export type StreamEvent = { type: "generation"; generation: Generation } | { type: "deleted"; id: string };
diff --git a/src/lib/library.ts b/src/lib/library.ts
index b56c9b04..bdae5c67 100644
--- a/src/lib/library.ts
+++ b/src/lib/library.ts
@@ -1,8 +1,9 @@
/**
- * 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.
+ * Library (Assets) logic shared by the browser and the server: feed filters, helper steps, nested
+ * folders, pins, review statuses, the Trash, where a file is used, download names, date sections
+ * and batch stacks. Pure: no React, no database.
*/
-import { OPERATION_LABELS, type Generation, type GenerationStatus, type MediaKind, type OutputFile } from "./catalog/types";
+import { OPERATION_LABELS, type Generation, type GenerationStatus, type MediaKind, type OutputFile, type ReviewStatus } from "./catalog/types";
// ---------------------------------------------------------------------------
// Filters (GET /api/generations query ⇄ client-side matching for live cache updates)
@@ -20,13 +21,29 @@ export interface FeedFilter {
since?: number;
until?: number;
folderId?: string;
+ /** Any of these folders (a folder and its subfolders: "Show subfolders content"). */
+ folderIds?: string[];
/** The Trash instead of the library. */
trashed?: boolean;
+ /** Pinned ones only (most recently pinned first), or (false) the ones that aren't pinned. */
+ pinned?: boolean;
+ /** Review statuses; "none" is a result without one. */
+ reviews?: ReviewFilter[];
+ /** Also helper steps (see isHelperFeature) in a list that doesn't name its features. */
+ steps?: boolean;
}
-/** The paging cursor for the page after `last`: its timestamp (deletedAt in the Trash) and id, so equal timestamps aren't skipped. */
-export function cursorAfter(last: Generation, trashed?: boolean): string | undefined {
- const ts = trashed ? last.deletedAt : last.createdAt;
+/** Which timestamp a list is ordered (and paged) by: deletedAt in the Trash, pinnedAt in a pinned list, else createdAt. */
+function sortTime(g: Generation, f: Pick<FeedFilter, "trashed" | "pinned">): number | null | undefined {
+ return f.trashed ? g.deletedAt : f.pinned ? g.pinnedAt : g.createdAt;
+}
+
+/**
+ * The paging cursor for the page after `last`: its sort timestamp and id, so equal timestamps aren't
+ * skipped. `f` is the list's filter (or, as before, whether it's the Trash).
+ */
+export function cursorAfter(last: Generation, f?: boolean | Pick<FeedFilter, "trashed" | "pinned">): string | undefined {
+ const ts = sortTime(last, typeof f === "boolean" ? { trashed: f } : (f ?? {}));
return ts ? `${ts}:${last.id}` : undefined;
}
@@ -42,7 +59,11 @@ export function filterToSearch(f: FeedFilter, before?: string | number): URLSear
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.folderIds?.length) qs.set("folders", f.folderIds.join(","));
if (f.trashed) qs.set("trash", "1");
+ if (f.pinned !== undefined) qs.set("pinned", f.pinned ? "1" : "0");
+ if (f.reviews?.length) qs.set("reviews", f.reviews.join(","));
+ if (f.steps) qs.set("steps", "1");
if (before) qs.set("before", String(before));
qs.set("limit", String(f.limit ?? 80));
return qs;
@@ -62,6 +83,10 @@ export function matchesFilter(g: Generation, f: FeedFilter): boolean {
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;
+ if (f.folderIds?.length && !f.folderIds.includes(g.folderId ?? "")) return false;
+ if (f.pinned !== undefined && !!g.pinnedAt !== f.pinned) return false;
+ if (f.reviews?.length && !f.reviews.includes(g.review ?? "none")) return false;
+ if (!f.steps && !f.features?.length && isHelperFeature(g.feature)) return false;
const q = f.q?.trim().toLowerCase();
if (q && !`${g.prompt ?? ""}\n${g.request.prompt ?? ""}`.toLowerCase().includes(q)) return false;
return true;
@@ -79,6 +104,51 @@ export function byDeleted(a: Generation, b: Generation): number {
return (b.deletedAt ?? 0) - (a.deletedAt ?? 0) || byIdDesc(a, b);
}
+/** A pinned list's order: most recently pinned first (ties: id descending, like the server). */
+export function byPinned(a: Generation, b: Generation): number {
+ return (b.pinnedAt ?? 0) - (a.pinnedAt ?? 0) || byIdDesc(a, b);
+}
+
+/** The order of a list with this filter, as the server sends it. */
+export function listOrder(f: Pick<FeedFilter, "trashed" | "pinned">): (a: Generation, b: Generation) => number {
+ return f.trashed ? byDeleted : f.pinned ? byPinned : byNewest;
+}
+
+// ---------------------------------------------------------------------------
+// Helper steps
+
+/**
+ * Jobs nobody asked to see on their own: the steps a chain runs before its result (a Shorts cut, a
+ * Click to Ad voiceover, an Ad Multiplier hook: every "<studio>-step" feature), and helper jobs a
+ * studio starts by itself (a Mixed Media preview frame, a Faceless channel avatar or narrator sample,
+ * a moodboard's cover). The Library and the home feed leave them out unless "Show steps" is on; a
+ * list that names its features (a studio reading its own steps) gets what it asks for.
+ */
+export const HELPER_SUFFIX = "-step";
+export const HELPER_FEATURES = ["mixed-media-preview", "faceless-avatar", "faceless-voice", "moodboard"] as const;
+
+export function isHelperFeature(feature: string): boolean {
+ return feature.endsWith(HELPER_SUFFIX) || (HELPER_FEATURES as readonly string[]).includes(feature);
+}
+
+// ---------------------------------------------------------------------------
+// Review status (Higgsfield's Assets: In progress, Needs review, Approved, Rejected)
+
+export const REVIEW_STATUSES: { id: ReviewStatus; label: string; color: string }[] = [
+ { id: "in-progress", label: "In progress", color: "#029dfe" },
+ { id: "needs-review", label: "Needs review", color: "#fe7802" },
+ { id: "approved", label: "Approved", color: "#d1fe17" },
+ { id: "rejected", label: "Rejected", color: "#ef4444" },
+];
+
+export type ReviewFilter = ReviewStatus | "none";
+
+export const isReviewStatus = (v: unknown): v is ReviewStatus => REVIEW_STATUSES.some((r) => r.id === v);
+
+export function reviewInfo(status: ReviewStatus | null | undefined): (typeof REVIEW_STATUSES)[number] | null {
+ return REVIEW_STATUSES.find((r) => r.id === status) ?? null;
+}
+
// ---------------------------------------------------------------------------
// Folders
@@ -86,13 +156,107 @@ export interface Folder {
id: string;
name: string;
color: string;
+ /** Results directly in it (not in its subfolders, not in the Trash). */
count: number;
+ /** Subfolders directly in it. */
+ folders: number;
/** The newest output in the folder, for its cover. */
cover: OutputFile | null;
+ /** The folder it's in (null: the library root). */
+ parentId: string | null;
+ /** Pinned to the top of its parent at (null: not pinned). */
+ pinnedAt: number | null;
createdAt: number;
updatedAt: number;
}
+/** How deep folders nest (the breadcrumbs, the zip paths and the Move menu stay readable). */
+export const MAX_FOLDER_DEPTH = 8;
+
+type FolderLink = Pick<Folder, "id" | "parentId">;
+
+/** A folder's subfolders (the root's with null): pinned first, in the order they were pinned, then oldest first. */
+export function childFolders<F extends FolderLink & Pick<Folder, "pinnedAt" | "createdAt">>(all: F[], parentId: string | null): F[] {
+ return all
+ .filter((f) => (f.parentId ?? null) === parentId)
+ .sort((a, b) => (a.pinnedAt ? 0 : 1) - (b.pinnedAt ? 0 : 1) || (a.pinnedAt ?? 0) - (b.pinnedAt ?? 0) || a.createdAt - b.createdAt || (a.id < b.id ? -1 : 1));
+}
+
+/** The folders from the root down to `id`, for breadcrumbs ([] when it's gone; a loop in bad data stops the walk). */
+export function folderPath<F extends FolderLink>(all: F[], id: string | null | undefined): F[] {
+ const byId = new Map(all.map((f) => [f.id, f]));
+ const out: F[] = [];
+ const seen = new Set<string>();
+ for (let f = id ? byId.get(id) : undefined; f && !seen.has(f.id); f = f.parentId ? byId.get(f.parentId) : undefined) {
+ seen.add(f.id);
+ out.unshift(f);
+ }
+ return out;
+}
+
+/** `id` and every folder inside it, at any depth. */
+export function folderAndDescendants(all: FolderLink[], id: string): string[] {
+ const out = [id];
+ for (let i = 0; i < out.length; i++) for (const f of all) if (f.parentId === out[i] && !out.includes(f.id)) out.push(f.id);
+ return out;
+}
+
+/** How many levels a folder's subtree spans (1: no subfolders). */
+function subtreeHeight(all: FolderLink[], id: string, seen = new Set<string>()): number {
+ seen.add(id);
+ const kids = all.filter((f) => f.parentId === id && !seen.has(f.id));
+ return 1 + Math.max(0, ...kids.map((k) => subtreeHeight(all, k.id, seen)));
+}
+
+/** Why folder `id` can't go into `parentId` (null: the library root), in Higgsfield's words; null when it can. */
+export function folderMoveError(all: FolderLink[], id: string, parentId: string | null): string | null {
+ const f = all.find((x) => x.id === id);
+ if (!f || (parentId && !all.some((x) => x.id === parentId))) return "That folder doesn't exist anymore";
+ if (parentId === id) return "Cannot move into itself";
+ if ((f.parentId ?? null) === parentId) return "Already in this folder";
+ if (parentId && folderAndDescendants(all, id).includes(parentId)) return "Cannot move into a subfolder";
+ if (folderPath(all, parentId).length + subtreeHeight(all, id) > MAX_FOLDER_DEPTH) return `Folders go ${MAX_FOLDER_DEPTH} levels deep at most`;
+ return null;
+}
+
+/** Every folder in tree order with its depth (0 at the root), for Move menus. */
+export function folderTree<F extends FolderLink & Pick<Folder, "pinnedAt" | "createdAt">>(all: F[]): { folder: F; depth: number }[] {
+ const out: { folder: F; depth: number }[] = [];
+ const seen = new Set<string>();
+ const walk = (parentId: string | null, depth: number) => {
+ for (const f of childFolders(all, parentId)) {
+ if (seen.has(f.id)) continue;
+ seen.add(f.id);
+ out.push({ folder: f, depth });
+ walk(f.id, depth + 1);
+ }
+ };
+ walk(null, 0);
+ return out;
+}
+
+/** A name no sibling has yet: "Drafts" → "Drafts 2" (case-insensitive, like the folder names). */
+export function freeName(name: string, taken: string[]): string {
+ const used = new Set(taken.map((t) => t.toLowerCase()));
+ if (!used.has(name.toLowerCase())) return name;
+ for (let k = 2; ; k++) {
+ const next = `${name.slice(0, 56)} ${k}`;
+ if (!used.has(next.toLowerCase())) return next;
+ }
+}
+
+/** A folder name as one path segment in a zip ("Spring / Summer" → "Spring - Summer"). */
+export function zipSegment(name: string): string {
+ const clean = [...name]
+ .filter((c) => c.charCodeAt(0) >= 32 && !'<>:"|?*'.includes(c))
+ .join("")
+ .replace(/[\\/]+/g, " - ")
+ .replace(/\s+/g, " ")
+ .trim()
+ .replace(/^\.+|\.+$/g, "");
+ return clean.slice(0, 80) || "Folder";
+}
+
/** 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 },
@@ -121,6 +285,38 @@ export function trashDaysLeft(deletedAt: number, now = Date.now()): number {
return Math.max(0, Math.ceil((deletedAt + TRASH_DAYS * DAY - now) / DAY));
}
+// ---------------------------------------------------------------------------
+// Where a stored file is used (an upload can only be deleted when nothing refers to it)
+
+/** One row that refers to a file: what it is ("result", "element"), which one (rows of two tables can be one thing) and its name. */
+export interface AssetUse {
+ what: string;
+ key: string;
+ name: string | null;
+ /** A result in the Trash (it can still be restored, so it still counts). */
+ trashed?: boolean;
+}
+
+const plural = (what: string) => (/(s|x|ch|sh)$/.test(what) ? `${what}es` : `${what}s`);
+
+/** "2 results (1 in the Trash), the element “Maya” and 3 canvases": where a file is used, in one line. */
+export function describeUses(uses: AssetUse[]): string {
+ const groups = new Map<string, Map<string, AssetUse>>();
+ for (const u of uses) {
+ const g = groups.get(u.what) ?? new Map<string, AssetUse>();
+ groups.set(u.what, g);
+ if (!g.has(u.key)) g.set(u.key, u);
+ }
+ const parts = [...groups].map(([what, rows]) => {
+ const list = [...rows.values()];
+ const trashed = list.filter((u) => u.trashed).length;
+ const inTrash = trashed ? ` (${trashed === list.length && list.length === 1 ? "in the Trash" : `${trashed} in the Trash`})` : "";
+ if (list.length === 1 && list[0].name?.trim()) return `the ${what} “${list[0].name.trim().slice(0, 60)}”${inTrash}`;
+ return `${list.length} ${list.length === 1 ? what : plural(what)}${inTrash}`;
+ });
+ return parts.length <= 1 ? (parts[0] ?? "") : `${parts.slice(0, -1).join(", ")} and ${parts.at(-1)}`;
+}
+
// ---------------------------------------------------------------------------
// Download names
diff --git a/src/server/db.ts b/src/server/db.ts
index c64ccf4d..12a5931f 100644
--- a/src/server/db.ts
+++ b/src/server/db.ts
@@ -438,6 +438,13 @@ const MIGRATIONS: string[] = [
sent_json TEXT
);
CREATE INDEX IF NOT EXISTS assist_thread_state_project ON assist_thread_state(project_id);`,
+ // round 4 (r4/library-plus): nested library folders (a parent), pins on folders and results, and a review status on results.
+ `ALTER TABLE folders ADD COLUMN parent_id TEXT;
+ ALTER TABLE folders ADD COLUMN pinned_at INTEGER;
+ CREATE INDEX IF NOT EXISTS folders_parent ON folders(parent_id);
+ ALTER TABLE generations ADD COLUMN pinned_at INTEGER;
+ ALTER TABLE generations ADD COLUMN review TEXT;
+ CREATE INDEX IF NOT EXISTS generations_pinned ON generations(pinned_at) WHERE pinned_at IS NOT NULL;`,
];
declare global {
diff --git a/src/server/generations.ts b/src/server/generations.ts
index 672b29db..a0af67e5 100644
--- a/src/server/generations.ts
+++ b/src/server/generations.ts
@@ -7,6 +7,7 @@ import { applyMentions } from "@/lib/catalog/elements";
import { withSignatureWords } from "@/lib/catalog/palettes";
import { applySketch, stripMotionPaths } from "@/lib/catalog/sketch";
import { cueText, type Cue } from "@/lib/cues";
+import { HELPER_FEATURES, HELPER_SUFFIX, isReviewStatus, type AssetUse, type ReviewFilter } from "@/lib/library";
import { estimateCost, planGeneration, routesFor } from "@/lib/catalog/plan";
import {
LAST_FRAME_CHAIN,
@@ -60,6 +61,9 @@ interface Row {
updated_at: number;
completed_at: number | null;
depends_on: string | null;
+ /** Library pin and review status (NULL until set; inserts leave them out). */
+ pinned_at?: number | null;
+ review?: string | null;
/** Joined by the library readers (generation_trash, folder_items); looked up when absent. */
deleted_at?: number | null;
folder_id?: string | null;
@@ -109,6 +113,8 @@ export function toGeneration(r: Row): Generation {
aspectRatio: ar && ar !== "auto" ? ar : null,
deletedAt: lib.deleted_at ?? null,
folderId: lib.folder_id ?? null,
+ pinnedAt: r.pinned_at ?? null,
+ review: isReviewStatus(r.review) ? r.review : null,
};
}
@@ -141,6 +147,18 @@ export interface ListOptions {
/** Only the Trash, newest deletion first (`before` is then a deletedAt cursor). Otherwise the Trash is left out. */
trashed?: boolean;
folderId?: string;
+ /** In any of these folders (a folder and its subfolders). */
+ folderIds?: string[];
+ /** Only pinned ones, most recently pinned first (`before` is then a pinnedAt cursor); false: only the others. */
+ pinned?: boolean;
+ /** Review statuses ("none": no status). */
+ reviews?: ReviewFilter[];
+ /**
+ * Also list helper steps (chain steps and helper jobs: isHelperFeature in src/lib/library.ts). A list
+ * that names its features or its batch always gets them; others (the Library, the home feed,
+ * Assist's list_recent) leave them out unless this is set.
+ */
+ steps?: boolean;
limit?: number;
/**
* Paging cursor: made before this (deleted before, in the Trash). With `beforeId` it is the last
@@ -175,8 +193,19 @@ 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.folderIds?.length) oneOf("fi.folder_id", o.folderIds);
+ if (o.pinned !== undefined) add(o.pinned ? "g.pinned_at IS NOT NULL" : "g.pinned_at IS NULL");
+ if (o.reviews?.length) {
+ const set = o.reviews.filter((r) => r !== "none");
+ const any = [set.length ? `g.review IN (${set.map(() => "?").join(", ")})` : "", o.reviews.includes("none") ? "g.review IS NULL" : ""].filter(Boolean);
+ add(`(${any.join(" OR ")})`, ...set);
+ }
+ if (!o.steps && !o.feature && !o.features?.length && !o.batchId) {
+ add(`g.feature NOT LIKE ? AND g.feature NOT IN (${HELPER_FEATURES.map(() => "?").join(", ")})`, `%${HELPER_SUFFIX}`, ...HELPER_FEATURES);
+ }
+ // The cursor's order: the Trash by deletion, a pinned list by pin, the rest by creation (then id, all descending).
+ const col = o.trashed ? "t.deleted_at" : o.pinned ? "g.pinned_at" : "g.created_at";
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);
}
@@ -185,9 +214,7 @@ export function listGenerations(o: ListOptions = {}): Generation[] {
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}%`);
- // 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 ?`;
+ const sql = `SELECT ${LIBRARY_COLUMNS} FROM ${LIBRARY_JOIN} WHERE ${where.join(" AND ")} ORDER BY ${col} DESC, g.id DESC LIMIT ?`;
return (db().prepare(sql).all(...args, Math.max(1, Math.min(o.limit ?? 60, 200))) as Row[]).map(toGeneration);
}
@@ -195,49 +222,111 @@ export function setFavorite(id: string, favorite: boolean): void {
update(id, { favorite: favorite ? 1 : 0 });
}
+export interface AssetRef {
+ table: string;
+ cols: string[];
+ /** A column whose row belongs to the generation being purged (its own row and Cinema membership don't keep its files). */
+ except?: string;
+ /** What a row is, for "where is it used" ("element", "Cinema project"). */
+ what: string;
+ /** SQL that names the row, and the key that tells rows apart (default `id`; a Cinema take and its project are one project). */
+ name?: string;
+ key?: string;
+}
+
/**
* 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).
+ * by id: other jobs' inputs and outputs (an upload a request still names keeps Retry and Reuse
+ * working), elements, Assist chats and projects, every studio's sessions, projects and presets.
+ * When a table starts storing file URLs, add it here (tests/library.test.ts checks every `_json` /
+ * `_url` column is either here or in ASSET_FREE).
*/
-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"] },
- { table: "layer_projects", cols: ["source_url", "cover_url"] },
- { table: "layer_versions", cols: ["doc_json"] },
- { table: "shorts_sessions", cols: ["source_json", "look_json"] },
- { table: "shorts_presets", cols: ["references_json"] },
- { table: "brand_kits", cols: ["kit_json", "chat_json"] },
- { table: "products", cols: ["images_json"] },
- { table: "ad_creatives", cols: ["meta_json"] },
- { table: "marketing_runs", cols: ["meta_json"] },
+export const ASSET_REFS: AssetRef[] = [
+ { table: "generations", cols: ["request_json", "outputs_json"], except: "id", what: "result" },
+ { table: "characters", cols: ["reference_asset_ids_json", "loras_json", "lora_file"], what: "element", name: "name" },
+ { table: "trainings", cols: ["meta_json"], what: "element", key: "element_id", name: "(SELECT name FROM characters WHERE id = element_id)" },
+ { table: "assist_threads", cols: ["messages_json", "items_json", "pending_json"], what: "Assist chat", name: "title" },
+ // A chat's frozen context names its project's sources; a project's file sources are uploads.
+ { table: "assist_thread_state", cols: ["context", "sent_json"], what: "Assist chat", key: "thread_id", name: "(SELECT title FROM assist_threads WHERE id = thread_id)" },
+ { table: "assist_project_sources", cols: ["url", "content"], what: "Assist project", key: "project_id", name: "(SELECT name FROM assist_projects WHERE id = project_id)" },
+ { table: "cinema_projects", cols: ["cover_url", "palettes_json", "director_json", "chat_json", "brief_body"], what: "Cinema project", name: "name" },
+ { table: "cinema_items", cols: ["meta_json"], except: "generation_id", what: "Cinema project", key: "project_id", name: "(SELECT name FROM cinema_projects WHERE id = project_id)" },
+ { table: "canvases", cols: ["graph_json", "runs_json"], what: "canvas", name: "name" },
+ // A Layers project's source, cover, its tools' inputs (a picked image) and every saved version.
+ { table: "layer_projects", cols: ["source_url", "cover_url", "jobs_json"], what: "Layers project", name: "name" },
+ { table: "layer_versions", cols: ["doc_json"], what: "Layers project", key: "project_id", name: "(SELECT name FROM layer_projects WHERE id = project_id)" },
+ { table: "shorts_sessions", cols: ["source_json", "look_json"], what: "Shorts session", name: "title" },
+ { table: "shorts_presets", cols: ["references_json"], what: "Shorts preset", name: "name" },
+ { table: "brand_kits", cols: ["kit_json", "chat_json"], what: "brand kit", name: "name" },
+ { table: "products", cols: ["images_json"], what: "product", name: "name" },
+ { table: "ad_creatives", cols: ["meta_json"], what: "ad", name: "headline" },
+ { table: "marketing_runs", cols: ["meta_json"], what: "marketing run", name: "title" },
// Image studios: a palette's thumbnail, a moodboard's images, collages and cover, an Instadump pack's photos.
- { table: "palettes", cols: ["thumb_url"] },
- { table: "moodboards", cols: ["images_json", "collages_json", "cover_url"] },
- { table: "photodump_packs", cols: ["refs_json"] },
- // Faceless / Explainer: a channel's avatar, style references and voice samples, episode sources.
- { table: "faceless_channels", cols: ["avatar_url", "reference_json", "settings_json"] },
- { table: "faceless_episodes", cols: ["settings_json", "sources_json"] },
+ { table: "palettes", cols: ["thumb_url"], what: "palette", name: "name" },
+ { table: "moodboards", cols: ["images_json", "collages_json", "cover_url"], what: "moodboard", name: "name" },
+ { table: "photodump_packs", cols: ["refs_json"], what: "photo pack", name: "name" },
+ // Faceless / Explainer: a channel's avatar, style references and voice samples; an episode's sources, script and picture edits.
+ { table: "faceless_channels", cols: ["avatar_url", "reference_json", "settings_json"], what: "Faceless channel", name: "name" },
+ { table: "faceless_episodes", cols: ["settings_json", "sources_json", "script_json", "plan_json"], what: "episode", name: "title" },
+ // Translate & dub sessions and Katana jobs: the source video, the subject picture and each step's files.
+ { table: "dub_sessions", cols: ["data_json"], what: "dub", name: "json_extract(data_json, '$.title')" },
+ { table: "katana_jobs", cols: ["data_json"], what: "Katana job", name: "json_extract(data_json, '$.title')" },
];
-/** Whether anything still refers to this stored file (see ASSET_REFS). */
-export function assetInUse(assetId: string, exceptGeneration = ""): boolean {
+/**
+ * Columns that look like they could hold a file (`_json`, `_url`) but never hold one of Fuobe's
+ * stored files, with the reason. The ASSET_REFS coverage test reads this list.
+ */
+export const ASSET_FREE: Record<string, string> = {
+ "generations.provider_input_json": "what a provider was sent: its own upload URLs or file names, never ours",
+ "generations.external_meta_json": "the provider's job handles",
+ "shorts_sessions.range_json": "start and end times",
+ "shorts_sessions.settings_json": "ratio, language, model and resolution",
+ "shorts_sessions.segments_json": "generation ids of each take",
+ "shorts_sessions.stitches_json": "generation ids of each stitch",
+ "brand_kits.progress_json": "research progress labels",
+ "products.selling_points_json": "words",
+ "products.url": "the product's own web page",
+ "marketing_runs.final_ids_json": "generation ids",
+ "palettes.colors_json": "hex colours",
+ "assist_projects.skills_json": "skill names",
+ "assist_thread_state.skills_json": "skill names",
+ "skills.meta_json": "SKILL.md front matter",
+ "skills.files_json": "a skill's own text files, stored inline",
+};
+
+/** The query that finds the rows of one ASSET_REFS table naming a file (@id), except the purged generation's own (@g). */
+export function assetRefSql(r: AssetRef): string {
+ const where = r.cols.map((c) => `instr(COALESCE(${c}, ''), @id) > 0`).join(" OR ");
+ const except = r.except ? ` AND ${r.except} != @g` : "";
+ const trashed = r.table === "generations" ? ", EXISTS (SELECT 1 FROM generation_trash t WHERE t.generation_id = generations.id) AS trashed" : "";
+ return `SELECT ${r.key ?? "id"} AS k, ${r.name ?? "NULL"} AS n${trashed} FROM ${r.table} WHERE (${where})${except} LIMIT @max`;
+}
+
+/**
+ * Where a stored file is still used (see ASSET_REFS), at most `max` rows: enough to say where
+ * ("2 results and the element “Maya”", describeUses in src/lib/library.ts) or, with max 1, whether.
+ */
+export function assetUses(assetId: string, opts: { exceptGeneration?: string; max?: number } = {}): AssetUse[] {
+ const max = opts.max ?? 50;
+ const out: AssetUse[] = [];
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;
+ const rows = db()
+ .prepare(assetRefSql(r))
+ .all({ id: assetId, g: opts.exceptGeneration ?? "", max: max - out.length }) as { k: string; n: string | null; trashed?: number }[];
+ for (const row of rows) out.push({ what: r.what, key: String(row.k), name: row.n ?? null, ...(row.trashed ? { trashed: true } : {}) });
} catch {
// A table or column this install doesn't have yet: nothing there to keep the file for.
}
+ if (out.length >= max) break;
}
- return false;
+ return out;
+}
+
+/** Whether anything still refers to this stored file (see ASSET_REFS). */
+export function assetInUse(assetId: string, exceptGeneration = ""): boolean {
+ return assetUses(assetId, { exceptGeneration, max: 1 }).length > 0;
}
/**
diff --git a/src/server/library.ts b/src/server/library.ts
index b84da1eb..8e49570b 100644
--- a/src/server/library.ts
+++ b/src/server/library.ts
@@ -2,17 +2,34 @@ 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 type { MediaKind, OutputFile, ReviewStatus } from "@/lib/catalog/types";
+import {
+ DEFAULT_FOLDER_COLOR,
+ downloadName,
+ FOLDER_COLORS,
+ folderAndDescendants,
+ folderMoveError,
+ folderPath,
+ freeName,
+ HELPER_FEATURES,
+ HELPER_SUFFIX,
+ isReviewStatus,
+ MAX_FOLDER_DEPTH,
+ TRASH_DAYS,
+ zipSegment,
+ type AssetUse,
+ type Folder,
+ type ReviewFilter,
+} from "@/lib/library";
import { db } from "./db";
-import { cancelGeneration, deleteGeneration, getGeneration, type ListOptions } from "./generations";
-import { absolutePath } from "./storage";
+import { assetUses, cancelGeneration, deleteGeneration, getGeneration, type ListOptions } from "./generations";
+import { absolutePath, deleteAsset, getAsset } 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).
+ * The Assets library on top of generations: the Trash (soft delete, kept 30 days), nested folders,
+ * pins, review statuses, bulk actions, zip downloads and deleting uploads nothing uses. Every
+ * generation reader leaves trashed rows out (listGenerations / getGeneration join generation_trash).
*/
const DAY = 86_400_000;
@@ -21,6 +38,16 @@ const MAX_IDS = 500;
const STATUSES = new Set(["queued", "running", "succeeded", "failed", "canceled"]);
const KINDS = new Set(["image", "video", "audio", "text", "model3d"]);
+/** A library request that can't be done, with the HTTP status the routes answer with. */
+export class LibraryError extends Error {
+ constructor(
+ message: string,
+ readonly status = 409,
+ ) {
+ super(message);
+ }
+}
+
/** `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() ?? "");
@@ -35,6 +62,8 @@ export function listOptionsFrom(sp: URLSearchParams): ListOptions {
const v = Number(sp.get(k));
return sp.get(k) && Number.isFinite(v) && v > 0 ? v : undefined;
};
+ const reviews = list("reviews")?.filter((r): r is ReviewFilter => r === "none" || isReviewStatus(r));
+ const pinned = sp.get("pinned");
return {
feature: sp.get("feature") ?? undefined,
features: list("features"),
@@ -45,7 +74,11 @@ export function listOptionsFrom(sp: URLSearchParams): ListOptions {
status: sp.get("status") ?? undefined,
statuses: list("statuses")?.filter((s) => STATUSES.has(s)),
folderId: sp.get("folder") ?? undefined,
+ folderIds: list("folders")?.filter((id) => id.length <= 40).slice(0, MAX_IDS),
trashed: sp.get("trash") === "1",
+ pinned: pinned === "1" ? true : pinned === "0" ? false : undefined,
+ reviews: reviews?.length ? reviews : undefined,
+ steps: sp.get("steps") === "1",
q: sp.get("q") ?? undefined,
...cursorFrom(sp.get("before")),
since: num("since"),
@@ -162,8 +195,9 @@ 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
+// Favorites, pins, review status
export function setFavorites(list: string[], favorite: boolean): number {
const found = ids(list);
@@ -171,30 +205,65 @@ export function setFavorites(list: string[], favorite: boolean): number {
return db().prepare(`UPDATE generations SET favorite = ?, updated_at = ? WHERE id IN (${placeholders(found.length)})`).run(favorite ? 1 : 0, Date.now(), ...found).changes;
}
+/** Pin to the top of the Library's views (one already pinned keeps its place), or unpin. */
+export function setPinned(list: string[], pinned: boolean, now = Date.now()): number {
+ const found = ids(list);
+ if (!found.length) return 0;
+ const value = pinned ? "COALESCE(pinned_at, ?)" : "?";
+ return db().prepare(`UPDATE generations SET pinned_at = ${value}, updated_at = ? WHERE id IN (${placeholders(found.length)})`).run(pinned ? now : null, Date.now(), ...found).changes;
+}
+
+/** Set a review status (null clears it). */
+export function setReview(list: string[], review: ReviewStatus | null): number {
+ if (review !== null && !isReviewStatus(review)) throw new LibraryError("Pick a review status", 400);
+ const found = ids(list);
+ if (!found.length) return 0;
+ return db().prepare(`UPDATE generations SET review = ?, updated_at = ? WHERE id IN (${placeholders(found.length)})`).run(review, Date.now(), ...found).changes;
+}
+
+// ---------------------------------------------------------------------------
+// Folders (nested: each has a parent, null at the library root; one folder per generation)
+
interface FolderRow {
id: string;
name: string;
color: string;
+ parent_id: string | null;
+ pinned_at: number | null;
created_at: number;
updated_at: number;
count: number;
+ folders: 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 };
+ return {
+ id: r.id,
+ name: r.name,
+ color: r.color,
+ count: r.count,
+ folders: r.folders,
+ cover: outputs[0] ?? null,
+ parentId: r.parent_id ?? null,
+ pinnedAt: r.pinned_at ?? 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 COUNT(*) FROM folders c WHERE c.parent_id = f.id) AS folders,
(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, g.id DESC LIMIT 1) AS cover_json
FROM folders f`;
+/** Every folder, flat (each with its parentId): pinned first in the order they were pinned, then oldest first. */
export function listFolders(): Folder[] {
- return (db().prepare(`${FOLDER_SELECT} ORDER BY f.created_at ASC`).all() as FolderRow[]).map(toFolder);
+ return (db().prepare(`${FOLDER_SELECT} ORDER BY f.pinned_at IS NULL, f.pinned_at ASC, f.created_at ASC, f.id ASC`).all() as FolderRow[]).map(toFolder);
}
export function getFolder(id: string): Folder | null {
@@ -202,45 +271,91 @@ export function getFolder(id: string): Folder | null {
return r ? toFolder(r) : null;
}
+/** The tree without counts or covers (moves, deletes and zips walk it). */
+function folderLinks(): { id: string; name: string; parentId: string | null }[] {
+ return (db().prepare("SELECT id, name, parent_id FROM folders").all() as { id: string; name: string; parent_id: string | null }[]).map((r) => ({ id: r.id, name: r.name, parentId: r.parent_id ?? null }));
+}
+
+/** Folder names are unique among siblings (case-insensitive), like files in a folder. */
+const nameTaken = (name: string, parentId: string | null, except = "") =>
+ !!db().prepare("SELECT 1 FROM folders WHERE lower(name) = lower(?) AND parent_id IS ? AND id != ?").get(name, parentId, except);
+
+const GONE = "That folder doesn't exist anymore";
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 {
+/** A new folder, at the library root or inside `parentId`. */
+export function createFolder(input: { name: string; color?: string; parentId?: string | null }): 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}”`);
+ if (!name) throw new LibraryError("Give the folder a name", 400);
+ const parentId = input.parentId ?? null;
+ if (parentId) {
+ const links = folderLinks();
+ if (!links.some((f) => f.id === parentId)) throw new LibraryError(GONE, 404);
+ if (folderPath(links, parentId).length >= MAX_FOLDER_DEPTH) throw new LibraryError(`Folders go ${MAX_FOLDER_DEPTH} levels deep at most`);
+ }
+ if (nameTaken(name, parentId)) throw new LibraryError(`There's already a folder called “${name}”${parentId ? " here" : ""}`);
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);
+ db().prepare("INSERT INTO folders (id, name, color, parent_id, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?)").run(id, name, colorOf(input.color), parentId, now, now);
return getFolder(id)!;
}
-export function updateFolder(id: string, patch: { name?: string; color?: string }): Folder | null {
+/**
+ * Rename, recolour, pin or move a folder. A move (`parentId`, null for the root) is refused into
+ * itself or one of its own subfolders, deeper than MAX_FOLDER_DEPTH, or next to a folder of the same name.
+ */
+export function updateFolder(id: string, patch: { name?: string; color?: string; parentId?: string | null; pinned?: boolean }): 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}”`);
+ if (!name) throw new LibraryError("Give the folder a name", 400);
+ const parentId = patch.parentId !== undefined ? patch.parentId : f.parentId;
+ if (parentId !== f.parentId) {
+ const err = folderMoveError(folderLinks(), id, parentId);
+ if (err) throw new LibraryError(err, err === GONE ? 404 : 409);
+ }
+ if ((name.toLowerCase() !== f.name.toLowerCase() || parentId !== f.parentId) && nameTaken(name, parentId, id)) {
+ throw new LibraryError(`There's already a folder called “${name}”${parentId !== f.parentId ? " there" : ""}`);
}
- db().prepare("UPDATE folders SET name = ?, color = ?, updated_at = ? WHERE id = ?").run(name, patch.color !== undefined ? colorOf(patch.color) : f.color, Date.now(), id);
+ const pinnedAt = patch.pinned === undefined ? f.pinnedAt : patch.pinned ? (f.pinnedAt ?? Date.now()) : null;
+ const color = patch.color !== undefined ? colorOf(patch.color) : f.color;
+ db().prepare("UPDATE folders SET name = ?, color = ?, parent_id = ?, pinned_at = ?, updated_at = ? WHERE id = ?").run(name, color, parentId, pinnedAt, Date.now(), id);
return getFolder(id);
}
-/** Delete a folder; what was in it goes back to the library (nothing is deleted). */
+/** Move a folder into another (null: the library root); see updateFolder for what's refused. */
+export const moveFolder = (id: string, parentId: string | null) => updateFolder(id, { parentId });
+
+/**
+ * Delete a folder; nothing in it is deleted. Its results and its subfolders move up to its parent
+ * (the library root for a top-level folder); a subfolder whose name the parent already has becomes "Name 2".
+ */
export function deleteFolder(id: string): boolean {
- let n = 0;
+ const f = db().prepare("SELECT parent_id FROM folders WHERE id = ?").get(id) as { parent_id: string | null } | undefined;
+ if (!f) return false;
+ const parentId = f.parent_id ?? null;
+ const now = Date.now();
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;
+ if (parentId) db().prepare("UPDATE folder_items SET folder_id = ?, added_at = ? WHERE folder_id = ?").run(parentId, now, id);
+ else db().prepare("DELETE FROM folder_items WHERE folder_id = ?").run(id);
+ const taken = (db().prepare("SELECT name FROM folders WHERE parent_id IS ? AND id != ?").all(parentId, id) as { name: string }[]).map((r) => r.name);
+ const kids = db().prepare("SELECT id, name FROM folders WHERE parent_id = ? ORDER BY created_at ASC, id ASC").all(id) as { id: string; name: string }[];
+ for (const k of kids) {
+ const name = freeName(k.name, taken);
+ taken.push(name);
+ db().prepare("UPDATE folders SET parent_id = ?, name = ?, updated_at = ? WHERE id = ?").run(parentId, name, now, k.id);
+ }
+ db().prepare("DELETE FROM folders WHERE id = ?").run(id);
+ if (parentId) db().prepare("UPDATE folders SET updated_at = ? WHERE id = ?").run(now, parentId);
touch(members);
})();
- return n > 0;
+ return true;
}
/** 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");
+ if (folderId && !db().prepare("SELECT 1 FROM folders WHERE id = ?").get(folderId)) throw new LibraryError(GONE, 404);
const found = existing(ids(list));
const now = Date.now();
db().transaction(() => {
@@ -266,12 +381,22 @@ export interface LibraryFacets {
favorites: number;
failed: number;
trash: number;
+ pinned: number;
+ /** Helper steps (counted whether they're shown or not, for the "Show steps" toggle). */
+ steps: number;
+ reviews: Partial<Record<ReviewStatus, 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";
+/** The SQL test for a helper step (isHelperFeature); the names are constants, not input. */
+const HELPER_SQL = `(g.feature LIKE '%${HELPER_SUFFIX}' OR g.feature IN (${HELPER_FEATURES.map((f) => `'${f}'`).join(", ")}))`;
+
+/** Counts for the Library's tabs and filters; helper steps are left out unless `steps` (as the lists do). */
+export function libraryFacets(opts: { steps?: boolean } = {}): LibraryFacets {
+ const all = "FROM generations g LEFT JOIN generation_trash t ON t.generation_id = g.id WHERE t.generation_id IS NULL";
+ const live = opts.steps ? all : `${all} AND NOT ${HELPER_SQL}`;
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 reviews = db().prepare(`SELECT g.review AS review, COUNT(*) AS n ${live} AND g.review IS NOT NULL GROUP BY g.review`).all() as { review: string; 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 })),
@@ -280,6 +405,9 @@ export function libraryFacets(): LibraryFacets {
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(),
+ pinned: one(`SELECT COUNT(*) AS n ${live} AND g.pinned_at IS NOT NULL`),
+ steps: one(`SELECT COUNT(*) AS n ${all} AND ${HELPER_SQL}`),
+ reviews: Object.fromEntries(reviews.filter((r) => isReviewStatus(r.review)).map((r) => [r.review, r.n])),
};
}
@@ -287,12 +415,12 @@ export function libraryFacets(): LibraryFacets {
// Zip download
export const ZIP_MAX_BYTES = 4 * 1024 ** 3 - 1;
+/** Results a folder zip takes at most, its subfolders' included (the zip format counts entries in 16 bits). */
+export const FOLDER_ZIP_MAX = 5000;
-/** 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)) {
+/** Add the finished output files of these generations under `prefix`, with readable names unique in the zip. */
+function addEntries(list: string[], prefix: string, used: Set<string>, out: ZipEntry[]): void {
+ for (const id of list) {
const g = getGeneration(id, { includeDeleted: true });
if (!g || g.status !== "succeeded") continue;
g.outputs.forEach((o, i) => {
@@ -304,12 +432,68 @@ export function zipEntries(list: string[]): ZipEntry[] {
return;
}
if (!fs.existsSync(file)) return;
- const base = downloadName(g, o, i);
+ const base = `${prefix}${downloadName(g, o, i)}`;
let name = base;
- for (let k = 2; used.has(name); k++) name = base.replace(/(\.[^.]+)?$/, (ext) => `-${k}${ext}`);
+ 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 });
});
}
+}
+
+/** The finished output files of these generations, with readable, unique names. */
+export function zipEntries(list: string[]): ZipEntry[] {
+ const out: ZipEntry[] = [];
+ addEntries(ids(list), "", new Set(), out);
return out;
}
+
+/**
+ * A folder as a zip: its finished outputs at the top and each subfolder's in a folder of its own
+ * ("Shots/Close-ups/fox-ab12cd.png"), at any depth. Results in the Trash are left out.
+ */
+export function folderZipEntries(id: string): { name: string; entries: ZipEntry[] } | null {
+ const links = folderLinks();
+ const root = links.find((f) => f.id === id);
+ if (!root) return null;
+ const tree = folderAndDescendants(links, id);
+ const members = db()
+ .prepare(
+ `SELECT i.generation_id AS id, i.folder_id AS folder 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 t.generation_id IS NULL AND i.folder_id IN (${placeholders(tree.length)}) ORDER BY g.created_at DESC, g.id DESC`,
+ )
+ .all(...tree) as { id: string; folder: string }[];
+ if (members.length > FOLDER_ZIP_MAX) throw new LibraryError(`“${root.name}” and its subfolders hold over ${FOLDER_ZIP_MAX.toLocaleString("en-US")} results. Download its subfolders one at a time.`, 413);
+ const depth = folderPath(links, id).length;
+ const out: ZipEntry[] = [];
+ const used = new Set<string>();
+ for (const fid of tree) {
+ const prefix = folderPath(links, fid)
+ .slice(depth)
+ .map((f) => `${zipSegment(f.name)}/`)
+ .join("");
+ addEntries(
+ members.filter((m) => m.folder === fid).map((m) => m.id),
+ prefix,
+ used,
+ out,
+ );
+ }
+ return { name: root.name, entries: out };
+}
+
+// ---------------------------------------------------------------------------
+// Uploads
+
+/**
+ * Delete a stored file for good (the Uploads tab), its file on disk included, but only when nothing
+ * refers to it (assetUses: results' requests and outputs, in the Trash too, elements, chats, every
+ * studio). Otherwise nothing changes and `uses` says where it's used. null: no such file.
+ */
+export function deleteUnusedAsset(id: string): { deleted: boolean; uses: AssetUse[] } | null {
+ if (!getAsset(id)) return null;
+ const uses = assetUses(id);
+ if (uses.length) return { deleted: false, uses };
+ deleteAsset(id);
+ return { deleted: true, uses: [] };
+}
diff --git a/tests/library.test.ts b/tests/library.test.ts
index a7d683cf..051bec38 100644
--- a/tests/library.test.ts
+++ b/tests/library.test.ts
@@ -20,6 +20,10 @@ 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 folderZipRoute = await import("@/app/api/folders/[id]/zip/route");
+const generationRoutes = await import("@/app/api/generations/route");
+const generationIdRoutes = await import("@/app/api/generations/[id]/route");
+const assetIdRoutes = await import("@/app/api/assets/[id]/route");
const { db } = await import("@/server/db");
beforeAll(() => setSetting("demoMode", "auto"));
@@ -29,10 +33,10 @@ 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) {
+function made(prompt: string, feature = "grade") {
const asset = saveFile({ data: Buffer.concat([PNG, Buffer.from(prompt)]), contentType: "image/png", source: "generation" });
const g = gens.recordLocalGeneration({
- feature: "grade",
+ feature,
modelId: "local-color-grade",
op: "grade",
prompt,
@@ -398,3 +402,315 @@ describe("zip download", () => {
expect(out.trim()).toBe("None 2 zip me");
});
});
+
+// ---------------------------------------------------------------------------
+// Round 4 (library-plus): helper steps, nested folders, pins, review status, deleting uploads, ASSET_REFS
+
+const ctxOf = (id: string) => ({ params: Promise.resolve({ id }) }) as never;
+const jsonReq = (url: string, method: string, b?: unknown) => new Request(`http://x${url}`, { method, ...(b !== undefined && { body: JSON.stringify(b) }) });
+
+describe("helper steps", () => {
+ it("are left out of the Library, the home feed and Assist's list_recent, unless asked for", async () => {
+ const final = made("helper final", "shorts").g;
+ const cut = made("helper cut", "shorts-step").g;
+ const preview = made("helper preview", "mixed-media-preview").g;
+ const avatar = made("helper avatar", "faceless-avatar").g;
+ db().prepare(`UPDATE generations SET batch_id = 'hb1' WHERE id IN (?, ?)`).run(final.id, cut.id);
+ const q = { q: "helper", limit: 200 };
+ expect(gens.listGenerations(q).map((g) => g.id)).toEqual([final.id]);
+ expect(gens.listGenerations({ ...q, steps: true }).map((g) => g.id).sort()).toEqual([final.id, cut.id, preview.id, avatar.id].sort());
+ // Lists that name their features (a studio's own feed) or their batch get the steps as asked.
+ expect(gens.listGenerations({ ...q, features: ["shorts", "shorts-step"] }).map((g) => g.id).sort()).toEqual([final.id, cut.id].sort());
+ expect(gens.listGenerations({ ...q, features: ["mixed-media*"] }).map((g) => g.id)).toEqual([preview.id]);
+ expect(gens.listGenerations({ ...q, feature: "faceless-avatar" }).map((g) => g.id)).toEqual([avatar.id]);
+ expect(gens.listGenerations({ batchId: "hb1" }).map((g) => g.id).sort()).toEqual([final.id, cut.id].sort());
+ // GET /api/generations: steps=1 shows them.
+ const get = async (qs: string) => ((await (await generationRoutes.GET(new Request(`http://x/api/generations?${qs}`))).json()) as { items: { id: string }[] }).items.map((g) => g.id);
+ expect(await get("q=helper")).toEqual([final.id]);
+ expect((await get("q=helper&steps=1")).length).toBe(4);
+ // Assist / MCP list_recent reads the same list.
+ const recent = TOOLS.find((t) => t.name === "list_recent")!;
+ const out = String((await recent.run({ limit: 30 }, {} as never)).content);
+ expect(out).not.toContain(cut.id);
+ // Facets count them apart, for the Show steps toggle.
+ const hidden = lib.libraryFacets();
+ const shown = lib.libraryFacets({ steps: true });
+ expect(hidden.steps).toBeGreaterThanOrEqual(3);
+ expect(shown.total - hidden.total).toBe(hidden.steps);
+ lib.trashGenerations([final.id, cut.id, preview.id, avatar.id]);
+ });
+});
+
+describe("nested folders", () => {
+ it("makes subfolders, with names unique among siblings only", () => {
+ const top = lib.createFolder({ name: "Nest top" });
+ const sub = lib.createFolder({ name: "Shots", parentId: top.id });
+ expect(sub.parentId).toBe(top.id);
+ expect(lib.getFolder(top.id)).toMatchObject({ folders: 1, parentId: null });
+ // Another "Shots" is fine elsewhere, not next to this one.
+ const elsewhere = lib.createFolder({ name: "Shots" });
+ expect(() => lib.createFolder({ name: "shots", parentId: top.id })).toThrow(/already a folder/);
+ expect(() => lib.createFolder({ name: "Lost", parentId: "missing" })).toThrow(/doesn't exist/);
+ expect(lib.listFolders().find((f) => f.id === sub.id)).toMatchObject({ parentId: top.id, pinnedAt: null });
+ for (const f of [sub, top, elsewhere]) lib.deleteFolder(f.id);
+ });
+
+ it("moves folders into others, refusing loops, namesakes and depth past the limit", () => {
+ const a = lib.createFolder({ name: "Move A" });
+ const b = lib.createFolder({ name: "Move B", parentId: a.id });
+ const c = lib.createFolder({ name: "Move C", parentId: b.id });
+ const d = lib.createFolder({ name: "Move D" });
+ expect(() => lib.moveFolder(a.id, a.id)).toThrow("Cannot move into itself");
+ expect(() => lib.moveFolder(a.id, c.id)).toThrow("Cannot move into a subfolder");
+ expect(() => lib.moveFolder(a.id, "missing")).toThrow(/doesn't exist/);
+ expect(lib.moveFolder(c.id, d.id)).toMatchObject({ parentId: d.id });
+ expect(lib.getFolder(b.id)!.folders).toBe(0);
+ expect(lib.moveFolder(c.id, null)).toMatchObject({ parentId: null });
+ // A namesake already there.
+ const twin = lib.createFolder({ name: "Move C", parentId: d.id });
+ expect(() => lib.moveFolder(c.id, d.id)).toThrow(/already a folder called “Move C” there/);
+ // Renaming and moving at once is checked against the new place.
+ expect(lib.updateFolder(c.id, { name: "Move C2", parentId: d.id })).toMatchObject({ name: "Move C2", parentId: d.id });
+ // Depth: a chain at the limit takes no more.
+ let parent = d.id;
+ const chain: string[] = [];
+ for (let i = 1; i < 8; i++) chain.push((parent = lib.createFolder({ name: `Deep ${i}`, parentId: parent }).id));
+ expect(() => lib.createFolder({ name: "Too deep", parentId: parent })).toThrow(/levels deep/);
+ expect(() => lib.moveFolder(a.id, chain[5])).toThrow(/levels deep/);
+ for (const id of [...chain.reverse(), twin.id, c.id, d.id, b.id, a.id]) lib.deleteFolder(id);
+ });
+
+ it("deletes a folder by moving its results and subfolders up to its parent", () => {
+ const top = lib.createFolder({ name: "Del top" });
+ const mid = lib.createFolder({ name: "Del mid", parentId: top.id });
+ const leaf = lib.createFolder({ name: "Drafts", parentId: mid.id });
+ const clash = lib.createFolder({ name: "Drafts", parentId: top.id });
+ const g1 = made("del in mid").g;
+ const g2 = made("del in leaf").g;
+ lib.moveToFolder([g1.id], mid.id);
+ lib.moveToFolder([g2.id], leaf.id);
+ expect(lib.deleteFolder(mid.id)).toBe(true);
+ expect(gens.getGeneration(g1.id)!.folderId).toBe(top.id);
+ expect(gens.getGeneration(g2.id)!.folderId).toBe(leaf.id);
+ // The subfolder moved up next to a namesake, so it was renamed.
+ expect(lib.getFolder(leaf.id)).toMatchObject({ parentId: top.id, name: "Drafts 2" });
+ expect(lib.getFolder(clash.id)!.name).toBe("Drafts");
+ // A top-level folder: everything goes to the library root.
+ expect(lib.deleteFolder(top.id)).toBe(true);
+ expect(gens.getGeneration(g1.id)!.folderId).toBeNull();
+ expect(lib.getFolder(leaf.id)!.parentId).toBeNull();
+ expect(lib.deleteFolder(top.id)).toBe(false);
+ for (const f of [leaf, clash]) lib.deleteFolder(f.id);
+ });
+
+ it("lists a folder with its subfolders' results (folders=…), and keeps the flat routes working", async () => {
+ const top = (await (await folderRoutes.POST(jsonReq("/api/folders", "POST", { name: "Route top" }))).json()) as { id: string; parentId: null };
+ expect(top.parentId).toBeNull();
+ const subRes = await folderRoutes.POST(jsonReq("/api/folders", "POST", { name: "Route sub", parentId: top.id }));
+ expect(subRes.status).toBe(201);
+ const sub = (await subRes.json()) as { id: string; parentId: string };
+ expect(sub.parentId).toBe(top.id);
+ expect((await folderRoutes.POST(jsonReq("/api/folders", "POST", { name: "Orphan", parentId: "missing" }))).status).toBe(404);
+ // The flat list has both, each with its parent.
+ const all = ((await (await folderRoutes.GET()).json()) as { items: { id: string; parentId: string | null }[] }).items;
+ expect(all.find((f) => f.id === sub.id)?.parentId).toBe(top.id);
+ // PATCH moves (409 into its own subfolder), pins and unpins.
+ expect((await folderIdRoutes.PATCH(jsonReq("/x", "PATCH", { parentId: sub.id }), ctxOf(top.id))).status).toBe(409);
+ const pinned = (await (await folderIdRoutes.PATCH(jsonReq("/x", "PATCH", { pinned: true }), ctxOf(sub.id))).json()) as { pinnedAt: number | null };
+ expect(pinned.pinnedAt).toBeTypeOf("number");
+ const moved = (await (await folderIdRoutes.PATCH(jsonReq("/x", "PATCH", { parentId: null }), ctxOf(sub.id))).json()) as { parentId: string | null; pinnedAt: number | null };
+ expect(moved).toMatchObject({ parentId: null, pinnedAt: pinned.pinnedAt });
+ await folderIdRoutes.PATCH(jsonReq("/x", "PATCH", { parentId: top.id, pinned: false }), ctxOf(sub.id));
+ // Results in either, through GET /api/generations?folders=.
+ const a = made("tree a").g;
+ const b = made("tree b").g;
+ lib.moveToFolder([a.id], top.id);
+ lib.moveToFolder([b.id], sub.id);
+ const ids = (qs: string) => gens.listGenerations({ ...lib.listOptionsFrom(new URLSearchParams(qs)), limit: 200 }).map((g) => g.id);
+ expect(ids(`folder=${top.id}`)).toEqual([a.id]);
+ expect(ids(`folders=${top.id},${sub.id}`).sort()).toEqual([a.id, b.id].sort());
+ lib.deleteFolder(sub.id);
+ lib.deleteFolder(top.id);
+ });
+
+ it("orders folders with the pinned ones first", () => {
+ const x = lib.createFolder({ name: "Order x" });
+ const y = lib.createFolder({ name: "Order y" });
+ lib.updateFolder(y.id, { pinned: true });
+ const order = lib.listFolders().map((f) => f.id);
+ expect(order.indexOf(y.id)).toBeLessThan(order.indexOf(x.id));
+ expect(order[0]).toBe(y.id);
+ lib.deleteFolder(x.id);
+ lib.deleteFolder(y.id);
+ });
+
+ it("downloads a folder as a zip with its subfolders inside", async () => {
+ const top = lib.createFolder({ name: "Zip/top" });
+ const sub = lib.createFolder({ name: "Close ups", parentId: top.id });
+ const deeper = lib.createFolder({ name: "Hands", parentId: sub.id });
+ const empty = lib.createFolder({ name: "Zip empty" });
+ const a = made("zip top").g;
+ const b = made("zip sub").g;
+ const c = made("zip deep").g;
+ const gone = made("zip trashed").g;
+ lib.moveToFolder([a.id], top.id);
+ lib.moveToFolder([b.id, gone.id], sub.id);
+ lib.moveToFolder([c.id], deeper.id);
+ lib.trashGenerations([gone.id]);
+ const zip = lib.folderZipEntries(top.id)!;
+ expect(zip.name).toBe("Zip/top");
+ expect(zip.entries.map((e) => e.name.replace(/-[\w-]{6}\.png$/, "")).sort()).toEqual(["Close ups/Hands/zip-deep", "Close ups/zip-sub", "zip-top"]);
+ expect(lib.folderZipEntries("missing")).toBeNull();
+ // The route: ?check=1 answers the count, then the zip itself reads back in Python.
+ const check = await folderZipRoute.GET(new Request("http://x/zip?check=1"), ctxOf(top.id));
+ expect(await check.json()).toMatchObject({ files: 3 });
+ const res = await folderZipRoute.GET(new Request("http://x/zip"), ctxOf(top.id));
+ expect(res.headers.get("Content-Disposition")).toMatch(/filename="Zip-top-\d{4}-\d{2}-\d{2}\.zip"/);
+ const file = path.join(dir, "folder.zip");
+ fs.writeFileSync(file, Buffer.from(await res.arrayBuffer()));
+ const names = execFileSync("python3", ["-I", "-c", "import sys,zipfile;z=zipfile.ZipFile(sys.argv[1]);assert z.testzip() is None;print('|'.join(sorted(z.namelist())))", file]).toString().trim();
+ expect(names.split("|").map((n) => n.replace(/-[\w-]{6}\.png$/, ""))).toEqual(["Close ups/Hands/zip-deep", "Close ups/zip-sub", "zip-top"]);
+ expect((await folderZipRoute.GET(new Request("http://x/zip"), ctxOf(empty.id))).status).toBe(404);
+ expect((await folderZipRoute.GET(new Request("http://x/zip"), ctxOf("missing"))).status).toBe(404);
+ for (const f of [deeper, sub, top, empty]) lib.deleteFolder(f.id);
+ });
+});
+
+describe("pins and review status", () => {
+ it("pins results to their own list, most recently pinned first, and unpins them", () => {
+ const [a, b, c] = [made("pin a").g, made("pin b").g, made("pin c").g];
+ expect(lib.setPinned([a.id], true, 1000)).toBe(1);
+ expect(lib.setPinned([c.id, b.id], true, 2000)).toBe(2);
+ // Pinning again keeps the first pin time (its place).
+ lib.setPinned([a.id], true, 9000);
+ expect(gens.getGeneration(a.id)!.pinnedAt).toBe(1000);
+ const pinned = gens.listGenerations({ q: "pin ", pinned: true });
+ expect(pinned.map((g) => g.id)).toEqual([[b.id, c.id].sort().reverse(), a.id].flat());
+ expect(gens.listGenerations({ q: "pin ", pinned: false })).toEqual([]);
+ // Paging a pinned list goes by pin time.
+ const first = gens.listGenerations({ q: "pin ", pinned: true, limit: 2 });
+ const next = gens.listGenerations({ q: "pin ", pinned: true, limit: 2, ...lib.cursorFrom(`${first[1].pinnedAt}:${first[1].id}`) });
+ expect(next.map((g) => g.id)).toEqual([a.id]);
+ expect(lib.libraryFacets().pinned).toBeGreaterThanOrEqual(3);
+ lib.setPinned([a.id, b.id, c.id], false);
+ expect(gens.getGeneration(a.id)!.pinnedAt).toBeNull();
+ expect(gens.listGenerations({ q: "pin ", pinned: true })).toEqual([]);
+ });
+
+ it("sets, filters and clears review statuses", async () => {
+ const [a, b] = [made("review a").g, made("review b").g];
+ expect(lib.setReview([a.id], "approved")).toBe(1);
+ expect(gens.getGeneration(a.id)!.review).toBe("approved");
+ expect(() => lib.setReview([a.id], "great" as never)).toThrow(/review status/);
+ const ids = (qs: string) => gens.listGenerations({ ...lib.listOptionsFrom(new URLSearchParams(qs)), limit: 200 }).map((g) => g.id);
+ expect(ids("q=review&reviews=approved")).toEqual([a.id]);
+ expect(ids("q=review&reviews=none")).toEqual([b.id]);
+ expect(ids("q=review&reviews=approved,none").sort()).toEqual([a.id, b.id].sort());
+ expect(ids("q=review&reviews=bogus").sort()).toEqual([a.id, b.id].sort());
+ expect(lib.libraryFacets().reviews.approved).toBeGreaterThanOrEqual(1);
+ // The bulk endpoint and the single PATCH.
+ const call = async (body: unknown) => (await bulk(jsonReq("/api/generations/bulk", "POST", body))).json() as Promise<{ count?: number }>;
+ expect(await call({ action: "review", ids: [a.id, b.id], review: "needs-review" })).toEqual({ count: 2 });
+ expect(gens.getGeneration(b.id)!.review).toBe("needs-review");
+ expect((await bulk(jsonReq("/api/generations/bulk", "POST", { action: "review", ids: [a.id], review: "great" }))).status).toBe(400);
+ expect(await call({ action: "pin", ids: [a.id] })).toEqual({ count: 1 });
+ expect(gens.getGeneration(a.id)!.pinnedAt).toBeTypeOf("number");
+ expect(await call({ action: "unpin", ids: [a.id] })).toEqual({ count: 1 });
+ const patched = (await (await generationIdRoutes.PATCH(jsonReq("/x", "PATCH", { review: null, pinned: true }), ctxOf(b.id))).json()) as { review: string | null; pinnedAt: number | null };
+ expect(patched.review).toBeNull();
+ expect(patched.pinnedAt).toBeTypeOf("number");
+ expect((await generationIdRoutes.PATCH(jsonReq("/x", "PATCH", { review: "great" }), ctxOf(b.id))).status).toBe(400);
+ expect(await call({ action: "review", ids: [a.id], review: null })).toEqual({ count: 1 });
+ expect(gens.getGeneration(a.id)!.review).toBeNull();
+ lib.setPinned([b.id], false);
+ });
+});
+
+describe("deleting uploads", () => {
+ const upload = (tag: string) => saveFile({ data: Buffer.concat([PNG, Buffer.from(tag)]), contentType: "image/png", source: "upload", name: `${tag}.png` });
+ const del = async (id: string) => {
+ const res = await assetIdRoutes.DELETE(new Request("http://x", { method: "DELETE" }), ctxOf(id));
+ return { status: res.status, body: res.status === 204 ? null : ((await res.json()) as { error?: string; usedBy?: string }) };
+ };
+
+ it("deletes an upload nothing uses, file and all", async () => {
+ const free = upload("free upload");
+ const file = fileOf(free.url);
+ expect(fs.existsSync(file)).toBe(true);
+ const info = (await (await assetIdRoutes.GET(new Request("http://x"), ctxOf(free.id))).json()) as { usedBy: string; uses: unknown[] };
+ expect(info).toMatchObject({ usedBy: "", uses: [] });
+ expect((await del(free.id)).status).toBe(204);
+ expect(fs.existsSync(file)).toBe(false);
+ expect(listAssets({ source: "upload", limit: 500 }).map((a) => a.id)).not.toContain(free.id);
+ expect((await del(free.id)).status).toBe(404);
+ });
+
+ it("refuses while a result's request uses it (in the Trash too), and says where", async () => {
+ const used = upload("used upload");
+ const [g] = gens.createGenerations({ feature: "edit", modelId: "nano-banana-pro", op: "edit", prompt: "make it blue", inputs: { images: [used.url] } });
+ let r = await del(used.id);
+ expect(r.status).toBe(409);
+ expect(r.body?.usedBy).toBe("1 result");
+ expect(r.body?.error).toBe("It's still used by 1 result.");
+ // Trashed results can be restored (and retried), so they still count.
+ lib.trashGenerations([g.id]);
+ r = await del(used.id);
+ expect(r.status).toBe(409);
+ expect(r.body?.usedBy).toBe("1 result (in the Trash)");
+ expect(fs.existsSync(fileOf(used.url))).toBe(true);
+ // Deleted for good: now it can go.
+ await lib.deleteForever([g.id]);
+ expect((await del(used.id)).status).toBe(204);
+ });
+
+ it("names the elements, Assist projects and studio sessions that use it", async () => {
+ const pic = upload("element upload");
+ const now = Date.now();
+ db().prepare("INSERT INTO characters (id, name, reference_asset_ids_json, status, created_at, updated_at) VALUES ('c-up', 'Juno', ?, 'ready', 0, 0)").run(JSON.stringify([pic.url]));
+ db().prepare("INSERT INTO assist_projects (id, name, created_at, updated_at) VALUES ('ap-up', 'Launch', ?, ?)").run(now, now);
+ db().prepare("INSERT INTO assist_project_sources (id, project_id, kind, title, url, created_at) VALUES ('s-up', 'ap-up', 'image', 'Ref', ?, ?)").run(pic.url, now);
+ db().prepare("INSERT INTO dub_sessions (id, data_json, created_at, updated_at) VALUES ('d-up', ?, ?, ?)").run(JSON.stringify({ title: "Interview", video: pic.url }), now, now);
+ const r = await del(pic.id);
+ expect(r.status).toBe(409);
+ expect(r.body?.usedBy).toBe("the element “Juno”, the Assist project “Launch” and the dub “Interview”");
+ for (const t of ["characters WHERE id = 'c-up'", "assist_project_sources WHERE id = 's-up'", "dub_sessions WHERE id = 'd-up'"]) db().prepare(`DELETE FROM ${t}`).run();
+ expect((await del(pic.id)).status).toBe(204);
+ });
+});
+
+describe("ASSET_REFS", () => {
+ it("keeps outputs a dub or Katana job still points at when their result is deleted for good", async () => {
+ const dubbed = made("dub source clip");
+ const cut = made("katana subject");
+ const now = Date.now();
+ db().prepare("INSERT INTO dub_sessions (id, data_json, created_at, updated_at) VALUES ('d-keep', ?, ?, ?)").run(JSON.stringify({ title: "Dub", video: dubbed.asset.url }), now, now);
+ db().prepare("INSERT INTO katana_jobs (id, data_json, created_at, updated_at) VALUES ('k-keep', ?, ?, ?)").run(JSON.stringify({ title: "Cut", subject: cut.asset.url }), now, now);
+ expect(gens.assetUses(dubbed.asset.id, { exceptGeneration: dubbed.g.id })).toEqual([{ what: "dub", key: "d-keep", name: "Dub" }]);
+ expect(gens.assetUses(cut.asset.id, { exceptGeneration: cut.g.id })).toEqual([{ what: "Katana job", key: "k-keep", name: "Cut" }]);
+ await lib.deleteForever([dubbed.g.id, cut.g.id]);
+ expect(fs.existsSync(fileOf(dubbed.asset.url))).toBe(true);
+ expect(fs.existsSync(fileOf(cut.asset.url))).toBe(true);
+ });
+
+ it("covers every column that can hold a file, and every entry's query runs", () => {
+ const tables = (db().prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%'").all() as { name: string }[]).map((t) => t.name);
+ const columns = new Map(tables.map((t) => [t, (db().prepare(`PRAGMA table_info(${t})`).all() as { name: string }[]).map((c) => c.name)]));
+ const covered = new Set(gens.ASSET_REFS.flatMap((r) => r.cols.map((c) => `${r.table}.${c}`)));
+ const missing: string[] = [];
+ for (const [t, cols] of columns) {
+ for (const c of cols) {
+ const key = `${t}.${c}`;
+ if (/(_json|_url|^url|_file)$/.test(c) && !covered.has(key) && !(key in gens.ASSET_FREE)) missing.push(key);
+ }
+ }
+ // A table that stores file URLs must be in ASSET_REFS (or in ASSET_FREE with the reason it never holds one).
+ expect(missing).toEqual([]);
+ for (const key of [...covered, ...Object.keys(gens.ASSET_FREE)]) {
+ const [t, c] = key.split(".");
+ expect(columns.get(t), `${key} is not a column`).toContain(c);
+ }
+ // assetUses skips a table whose query fails (an older install), so a typo here would go unnoticed: prepare each one.
+ for (const r of gens.ASSET_REFS) expect(() => db().prepare(gens.assetRefSql(r)).all({ id: "nothing-uses-this", g: "", max: 1 }), r.table).not.toThrow();
+ expect(gens.ASSET_REFS.map((r) => r.table)).toEqual(expect.arrayContaining(["dub_sessions", "katana_jobs", "assist_project_sources", "layer_projects", "faceless_episodes"]));
+ });
+});