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: folder counts, covers and zips follow the helper-step rule; empty parentId refused

Claude4db77a5af6d9
diff --git a/src/app/api/folders/[id]/route.ts b/src/app/api/folders/[id]/route.ts
index 985872cb..a0f0d235 100644
--- a/src/app/api/folders/[id]/route.ts
+++ b/src/app/api/folders/[id]/route.ts
@@ -5,8 +5,8 @@ import { deleteFolder, getFolder, LibraryError, updateFolder } from "@/server/li
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(),
+ /** Move it into another folder, or (null) to the library root ("" is refused). */
+ parentId: z.string().min(1).max(40).nullable().optional(),
pinned: z.boolean().optional(),
});
@@ -21,7 +21,7 @@ export async function GET(_req: Request, ctx: RouteContext<"/api/folders/[id]">)
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 });
+ if (!parsed.success) return Response.json({ error: parsed.error.issues.some((i) => i.path[0] === "parentId") ? "Pick a folder to move it into, or null for the top of the Library" : "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 });
diff --git a/src/app/api/folders/[id]/zip/route.ts b/src/app/api/folders/[id]/zip/route.ts
index ec334615..03bae3e7 100644
--- a/src/app/api/folders/[id]/zip/route.ts
+++ b/src/app/api/folders/[id]/zip/route.ts
@@ -5,13 +5,15 @@ 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.
+ * Helper steps are left out, as on the folder's page, unless `?steps=1` (Show steps is on).
*/
export async function GET(request: Request, ctx: RouteContext<"/api/folders/[id]/zip">) {
await connection();
const { id } = await ctx.params;
+ const sp = new URL(request.url).searchParams;
let zip: ReturnType<typeof folderZipEntries>;
try {
- zip = folderZipEntries(id);
+ zip = folderZipEntries(id, { steps: sp.get("steps") === "1" });
} catch (e) {
return Response.json({ error: (e as Error).message }, { status: e instanceof LibraryError ? e.status : 500 });
}
@@ -19,7 +21,7 @@ export async function GET(request: Request, ctx: RouteContext<"/api/folders/[id]
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 });
+ if (sp.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: {
diff --git a/src/app/api/folders/route.ts b/src/app/api/folders/route.ts
index 236a7edd..02c01a80 100644
--- a/src/app/api/folders/route.ts
+++ b/src/app/api/folders/route.ts
@@ -2,7 +2,8 @@ import { connection } from "next/server";
import { z } from "zod";
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(), parentId: z.string().max(40).nullable().optional() });
+/** `parentId`: a folder's id, or null (or left out) for the library root; "" is refused, not stored as a parent nothing has. */
+const Body = z.object({ name: z.string().trim().min(1).max(60), color: z.string().max(20).optional(), parentId: z.string().min(1).max(40).nullable().optional() });
/** Every folder, flat: each has its parentId (null at the library root) and pinnedAt. */
export async function GET() {
@@ -13,7 +14,7 @@ export async function GET() {
/** 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 });
+ if (!parsed.success) return Response.json({ error: parsed.error.issues.some((i) => i.path[0] === "parentId") ? "Pick a folder to put it in, or null for the top of the Library" : "Give the folder a name" }, { status: 400 });
try {
return Response.json(createFolder(parsed.data), { status: 201 });
} catch (e) {
diff --git a/src/components/library/folders.tsx b/src/components/library/folders.tsx
index 95bd75ac..c769d9b4 100644
--- a/src/components/library/folders.tsx
+++ b/src/components/library/folders.tsx
@@ -222,10 +222,13 @@ export function FolderDialog({
);
}
-/** Download a folder (and its subfolders) as a zip, after asking the server whether there's anything to zip. */
-async function downloadFolder(f: Folder) {
- const url = `/api/folders/${encodeURIComponent(f.id)}/zip`;
- const res = await fetch(`${url}?check=1`).catch(() => null);
+/**
+ * Download a folder (and its subfolders) as a zip, after asking the server whether there's anything
+ * to zip. Helper steps go in only when `steps` (Show steps is on), so the zip has what the pages show.
+ */
+async function downloadFolder(f: Folder, steps?: boolean) {
+ const url = `/api/folders/${encodeURIComponent(f.id)}/zip${steps ? "?steps=1" : ""}`;
+ const res = await fetch(`${url}${steps ? "&" : "?"}check=1`).catch(() => null);
const body = ((await res?.json().catch(() => null)) ?? {}) as { files?: number; error?: string };
if (!res?.ok) return void toast(body.error ?? "Couldn't make the zip. Try again in a moment.");
downloadUrl(url);
@@ -234,9 +237,10 @@ async function downloadFolder(f: Folder) {
/**
* A folder's ⋯ menu (its card and its page header): open, new folder inside, rename or recolour,
- * pin, move into another folder, download as a zip, delete. `onGone` runs after a delete.
+ * pin, move into another folder, download as a zip, delete. `onGone` runs after a delete; `steps`:
+ * the Library shows helper steps, so the zip takes them too.
*/
-function FolderMenu({ folder, all, onOpen, onGone, triggerClassName }: { folder: Folder; all: Folder[]; onOpen?: () => void; onGone?: () => void; triggerClassName: string }) {
+function FolderMenu({ folder, all, onOpen, onGone, steps, triggerClassName }: { folder: Folder; all: Folder[]; onOpen?: () => void; onGone?: () => void; steps?: boolean; triggerClassName: string }) {
const actions = useFolderActions();
const move = useMoveFolder(all);
const [dialog, setDialog] = useState<null | "edit" | "new" | "delete">(null);
@@ -284,7 +288,7 @@ function FolderMenu({ folder, all, onOpen, onGone, triggerClassName }: { folder:
))}
</DropdownMenuSubContent>
</DropdownMenuSub>
- <DropdownMenuItem onSelect={() => void downloadFolder(folder)}>
+ <DropdownMenuItem onSelect={() => void downloadFolder(folder, steps)}>
<Download /> Download (.zip)
</DropdownMenuItem>
<DropdownMenuSeparator />
@@ -322,7 +326,7 @@ function FolderMenu({ folder, all, onOpen, onGone, triggerClassName }: { folder:
);
}
-function FolderCard({ folder, all, onOpen, onDropIds }: { folder: Folder; all: Folder[]; onOpen: () => void; onDropIds: (ids: string[]) => void }) {
+function FolderCard({ folder, all, onOpen, onDropIds, steps }: { folder: Folder; all: Folder[]; onOpen: () => void; onDropIds: (ids: string[]) => void; steps?: boolean }) {
const move = useMoveFolder(all);
const drag = useFolderDrag(folder);
const drop = useDropTarget({ items: onDropIds, folder: (id) => move(id, folder), folderError: (id) => folderMoveError(all, id, folder.id) });
@@ -364,6 +368,7 @@ function FolderCard({ folder, all, onOpen, onDropIds }: { folder: Folder; all: F
folder={folder}
all={all}
onOpen={onOpen}
+ steps={steps}
// With a mouse it appears over the card's corner on hover, so names keep the full width; touch screens always show it.
triggerClassName={cn(
"grid shrink-0 place-items-center rounded-lg text-muted-foreground transition-opacity hover:text-foreground focus-visible:opacity-100 data-[state=open]:opacity-100",
@@ -374,15 +379,15 @@ function FolderCard({ folder, all, onOpen, onDropIds }: { folder: Folder; all: F
);
}
-/** The folders inside `parent` (the library root with null), pinned first, and a New folder tile. */
-export function FolderStrip({ all, parent, onOpen, onMove }: { all: Folder[]; parent: Folder | null; onOpen: (f: Folder) => void; onMove: (ids: string[], f: Folder) => void }) {
+/** The folders inside `parent` (the library root with null), pinned first, and a New folder tile. `steps`: Show steps is on. */
+export function FolderStrip({ all, parent, onOpen, onMove, steps }: { all: Folder[]; parent: Folder | null; onOpen: (f: Folder) => void; onMove: (ids: string[], f: Folder) => void; steps?: boolean }) {
const [creating, setCreating] = useState(false);
const kids = childFolders(all, parent?.id ?? null);
return (
<div className="scrollbar-none -mx-1 flex gap-2 overflow-x-auto px-1 py-1" role="list" aria-label={parent ? `Folders in ${parent.name}` : "Folders"}>
{kids.map((f) => (
<div role="listitem" key={f.id} className="shrink-0">
- <FolderCard folder={f} all={all} onOpen={() => onOpen(f)} onDropIds={(ids) => onMove(ids, f)} />
+ <FolderCard folder={f} all={all} onOpen={() => onOpen(f)} onDropIds={(ids) => onMove(ids, f)} steps={steps} />
</div>
))}
{roomInside(all, parent) && (
@@ -429,7 +434,20 @@ function Crumb({ target, all, label, onGo, onMoveItems, back }: { target: Folder
* A folder's page header: breadcrumbs back up the tree (each one a drop target, so cards and
* folders can be moved up), then the folder's name, count and ⋯ menu.
*/
-export function FolderHeader({ folder, all, onGo, onMoveItems }: { folder: Folder; all: Folder[]; onGo: (f: Folder | null) => void; onMoveItems: (ids: string[], target: Folder | null) => void }) {
+export function FolderHeader({
+ folder,
+ all,
+ onGo,
+ onMoveItems,
+ steps,
+}: {
+ folder: Folder;
+ all: Folder[];
+ onGo: (f: Folder | null) => void;
+ onMoveItems: (ids: string[], target: Folder | null) => void;
+ /** Show steps is on (the folder's zip takes them too). */
+ steps?: boolean;
+}) {
const ancestors = folderPath(all, folder.id).slice(0, -1);
// Deep folders show the two nearest crumbs; the ones above fold into "…".
const shown = ancestors.slice(-2);
@@ -463,6 +481,7 @@ export function FolderHeader({ folder, all, onGo, onMoveItems }: { folder: Folde
folder={folder}
all={all}
onGone={() => onGo(all.find((f) => f.id === folder.parentId) ?? null)}
+ steps={steps}
triggerClassName="grid size-8 shrink-0 place-items-center rounded-lg text-muted-foreground hover:bg-accent hover:text-foreground"
/>
</div>
diff --git a/src/lib/library.ts b/src/lib/library.ts
index bdae5c67..0e06bcc6 100644
--- a/src/lib/library.ts
+++ b/src/lib/library.ts
@@ -29,7 +29,10 @@ export interface FeedFilter {
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. */
+ /**
+ * Also helper steps (see isHelperFeature). A list that names no features (and no batch) leaves them
+ * out unless this is set, so a list that must see every job (a count of running jobs) sets it.
+ */
steps?: boolean;
}
@@ -156,11 +159,11 @@ export interface Folder {
id: string;
name: string;
color: string;
- /** Results directly in it (not in its subfolders, not in the Trash). */
+ /** Results directly in it, as its page shows them by default (not in its subfolders or the Trash, not helper steps). */
count: number;
/** Subfolders directly in it. */
folders: number;
- /** The newest output in the folder, for its cover. */
+ /** The newest output in the folder (not a helper step's), for its cover. */
cover: OutputFile | null;
/** The folder it's in (null: the library root). */
parentId: string | null;
@@ -436,8 +439,12 @@ export function stackLabel(items: Generation[]): string {
return `${items.length} results`;
}
-/** 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[] {
+/**
+ * Group a newest-first list into cards: generations sharing a batch become one stack, placed where its
+ * newest member is. `prefix` goes in front of stack keys, for a second list on the same page (the
+ * Pinned section): a batch with members in both gets a stack in each, and their keys must differ.
+ */
+export function buildEntries(items: Generation[], opts: { stacks?: boolean; prefix?: string } = {}): 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) {
@@ -456,7 +463,7 @@ export function buildEntries(items: Generation[], opts: { stacks?: boolean } = {
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 });
+ out.push({ type: "stack", key: `${opts.prefix ?? ""}stack:${k}`, title: stackTitle(group), label: stackLabel(group), items: sorted });
}
return out;
}
diff --git a/src/server/library.ts b/src/server/library.ts
index a80232b2..546c9e76 100644
--- a/src/server/library.ts
+++ b/src/server/library.ts
@@ -223,6 +223,9 @@ export function setReview(list: string[], review: ReviewStatus | null): number {
// ---------------------------------------------------------------------------
// Folders (nested: each has a parent, null at the library root; one folder per generation)
+/** The SQL test for a helper step of `g` (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(", ")}))`;
+
interface FolderRow {
id: string;
name: string;
@@ -245,19 +248,20 @@ const toFolder = (r: FolderRow): Folder => {
count: r.count,
folders: r.folders,
cover: outputs[0] ?? null,
- parentId: r.parent_id ?? null,
+ parentId: r.parent_id || null,
pinnedAt: r.pinned_at ?? null,
createdAt: r.created_at,
updatedAt: r.updated_at,
};
};
+/** A folder's count and cover are what its page shows by default: not the Trash, not helper steps (as the lists). */
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,
+ WHERE i.folder_id = f.id AND t.generation_id IS NULL AND NOT ${HELPER_SQL}) 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
+ WHERE i.folder_id = f.id AND t.generation_id IS NULL AND NOT ${HELPER_SQL} 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. */
@@ -272,7 +276,7 @@ export function getFolder(id: string): Folder | 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 }));
+ 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. */
@@ -282,11 +286,11 @@ const nameTaken = (name: string, parentId: string | null, 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);
-/** A new folder, at the library root or inside `parentId`. */
+/** A new folder, at the library root or inside `parentId` ("" counts as the root, like null). */
export function createFolder(input: { name: string; color?: string; parentId?: string | null }): Folder {
const name = input.name.trim().slice(0, 60);
if (!name) throw new LibraryError("Give the folder a name", 400);
- const parentId = input.parentId ?? null;
+ const parentId = input.parentId || null;
if (parentId) {
const links = folderLinks();
if (!links.some((f) => f.id === parentId)) throw new LibraryError(GONE, 404);
@@ -300,7 +304,7 @@ export function createFolder(input: { name: string; color?: string; parentId?: s
}
/**
- * Rename, recolour, pin or move a folder. A move (`parentId`, null for the root) is refused into
+ * Rename, recolour, pin or move a folder. A move (`parentId`, null or "" 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 {
@@ -308,7 +312,7 @@ export function updateFolder(id: string, patch: { name?: string; color?: string;
if (!f) return null;
const name = patch.name !== undefined ? patch.name.trim().slice(0, 60) : f.name;
if (!name) throw new LibraryError("Give the folder a name", 400);
- const parentId = patch.parentId !== undefined ? patch.parentId : f.parentId;
+ const parentId = patch.parentId !== undefined ? patch.parentId || null : f.parentId;
if (parentId !== f.parentId) {
const err = folderMoveError(folderLinks(), id, parentId);
if (err) throw new LibraryError(err, err === GONE ? 404 : 409);
@@ -332,7 +336,7 @@ export const moveFolder = (id: string, parentId: string | null) => updateFolder(
export function deleteFolder(id: string): boolean {
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 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);
@@ -386,9 +390,6 @@ export interface LibraryFacets {
reviews: Partial<Record<ReviewStatus, number>>;
}
-/** 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";
@@ -449,9 +450,10 @@ export function zipEntries(list: string[]): ZipEntry[] {
/**
* 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.
+ * ("Shots/Close-ups/fox-ab12cd.png"), at any depth. It holds what the folder pages show: results in
+ * the Trash are left out, and helper steps too unless `steps` (the Library's Show steps is on).
*/
-export function folderZipEntries(id: string): { name: string; entries: ZipEntry[] } | null {
+export function folderZipEntries(id: string, opts: { steps?: boolean } = {}): { name: string; entries: ZipEntry[] } | null {
const links = folderLinks();
const root = links.find((f) => f.id === id);
if (!root) return null;
@@ -459,7 +461,7 @@ export function folderZipEntries(id: string): { name: string; entries: ZipEntry[
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`,
+ WHERE t.generation_id IS NULL${opts.steps ? "" : ` AND NOT ${HELPER_SQL}`} 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);
diff --git a/tests/library.test.ts b/tests/library.test.ts
index 051bec38..383ed754 100644
--- a/tests/library.test.ts
+++ b/tests/library.test.ts
@@ -25,6 +25,7 @@ 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");
+const { childFolders, folderTree } = await import("@/lib/library");
beforeAll(() => setSetting("demoMode", "auto"));
afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));
@@ -574,6 +575,43 @@ describe("nested folders", () => {
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);
});
+
+ it("refuses an empty parentId in the routes, and reads one as the root everywhere else", async () => {
+ const top = lib.createFolder({ name: "Blank parent top" });
+ expect((await folderRoutes.POST(jsonReq("/api/folders", "POST", { name: "Ghost", parentId: "" }))).status).toBe(400);
+ const patch = await folderIdRoutes.PATCH(jsonReq("/x", "PATCH", { parentId: "" }), ctxOf(top.id));
+ expect(patch.status).toBe(400);
+ expect(((await patch.json()) as { error: string }).error).toMatch(/Pick a folder/);
+ // Called directly (Assist, the CLI), "" is the library root: never a parent nothing has.
+ const ghost = lib.createFolder({ name: "Ghost", parentId: "" });
+ expect(ghost.parentId).toBeNull();
+ const sub = lib.createFolder({ name: "Blank parent sub", parentId: top.id });
+ expect(lib.updateFolder(sub.id, { parentId: "" })).toMatchObject({ parentId: null });
+ const all = lib.listFolders();
+ expect(childFolders(all, null).map((f) => f.id)).toEqual(expect.arrayContaining([top.id, ghost.id, sub.id]));
+ expect(folderTree(all).map((t) => t.folder.id)).toEqual(expect.arrayContaining([top.id, ghost.id, sub.id]));
+ expect(db().prepare("SELECT COUNT(*) AS n FROM folders WHERE parent_id = ''").get()).toEqual({ n: 0 });
+ for (const f of [sub, ghost, top]) lib.deleteFolder(f.id);
+ });
+
+ it("counts, covers and zips a folder as its page shows it: helper steps only with Show steps", async () => {
+ const f = lib.createFolder({ name: "Steps inside" });
+ const result = made("steps inside result", "shorts").g;
+ const step = made("steps inside cut", "shorts-step").g;
+ lib.moveToFolder([result.id, step.id], f.id);
+ // The step is the newest, but the cover is the result's.
+ db().prepare("UPDATE generations SET created_at = created_at + 1000 WHERE id = ?").run(step.id);
+ expect(lib.getFolder(f.id)).toMatchObject({ count: 1, cover: { url: result.outputs[0].url } });
+ expect(listIds({ folderId: f.id })).toEqual([result.id]);
+ expect(listIds({ folderId: f.id, steps: true }).sort()).toEqual([result.id, step.id].sort());
+ expect(lib.folderZipEntries(f.id)!.entries).toHaveLength(1);
+ expect(lib.folderZipEntries(f.id, { steps: true })!.entries).toHaveLength(2);
+ const check = async (qs: string) => (await (await folderZipRoute.GET(new Request(`http://x/zip?${qs}`), ctxOf(f.id))).json()) as { files: number };
+ expect((await check("check=1")).files).toBe(1);
+ expect((await check("steps=1&check=1")).files).toBe(2);
+ lib.deleteFolder(f.id);
+ lib.trashGenerations([result.id, step.id]);
+ });
});
describe("pins and review status", () => {