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.
TypeScript ai-videocomfyuicreative-toolsgenerative-aiideogramimage-generationimage-to-3dimage-to-videoltx-videominimax-h3nextjsopen-sourceopen-weightsqwen-imagetext-to-imagevideo-generationwan
Library UI: nested folders with breadcrumbs, pins, review status, Show steps and checked upload delete
Claude7d3c367e7b88
diff --git a/src/components/library-view.tsx b/src/components/library-view.tsxindex 0f6b6904..a4c85ce2 100644--- a/src/components/library-view.tsx+++ b/src/components/library-view.tsx@@ -1,6 +1,6 @@"use client";-import { ArchiveRestore, CheckSquare, ChevronUp, Download, FolderInput, Heart, Loader2, Search, Trash2, X } from "lucide-react";+import { ArchiveRestore, CheckSquare, ChevronUp, CircleDot, Download, FolderInput, Heart, Loader2, Pin, PinOff, Search, Trash2, X } from "lucide-react";import Link from "next/link";import { usePathname, useRouter, useSearchParams } from "next/navigation";import { Suspense, useCallback, useEffect, useMemo, useRef, useState } from "react";@@ -8,6 +8,8 @@ import { toast } from "sonner";import { AssetCard, cardRatio, type CardApi } from "@/components/library/asset-card";import { FilterBar, filterFields, hasFilters, NO_FILTERS, type Filters } from "@/components/library/filters";import { FolderDialog, FolderHeader, FolderStrip, MoveMenuItems } from "@/components/library/folders";+import { ReviewMenuItems } from "@/components/library/review";+import { UploadDeleteProvider } from "@/components/library/upload-delete";import { useViewPrefs, ViewOptions, type ViewPrefs } from "@/components/library/view-options";import { PageShell } from "@/components/page-shell";import { downloadUrl, ForeverConfirmProvider, useConfirmForever } from "@/components/studio/result-actions";@@ -28,7 +30,7 @@ import { Kbd } from "@/components/ui/kbd";import { Skeleton } from "@/components/ui/skeleton";import { BULK_MAX, useCreateGeneration, useFolders, useGenerationActions, useLibrary, useLibraryFacets, useUploads, type Asset, type FeedFilter } from "@/lib/api";import type { Generation, MediaKind } from "@/lib/catalog/types";-import { buildEntries, splitByDate, TRASH_DAYS, type LibraryEntry } from "@/lib/library";+import { buildEntries, folderAndDescendants, reviewInfo, splitByDate, TRASH_DAYS, type LibraryEntry } from "@/lib/library";import { isLayered, shownOutputs } from "@/lib/output-actions";import { cn } from "@/lib/utils";@@ -215,38 +217,48 @@ function Inner() {const dq = useDebounced(q.trim(), 250);const [filters, setFilters] = useState<Filters>(NO_FILTERS);const [prefs, setPrefs] = useViewPrefs();- const facets = useLibraryFacets();+ const facets = useLibraryFacets({ steps: filters.steps });const folders = useFolders();- const folder = folderId ? folders.data?.find((f) => f.id === folderId) : undefined;+ const allFolders = useMemo(() => folders.data ?? [], [folders.data]);+ const folder = folderId ? allFolders.find((f) => f.id === folderId) : undefined;const actions = useGenerationActions();const create = useCreateGeneration();+ // "Subfolders" on: the folder and every folder inside it.+ const subtree = useMemo(() => (folderId && filters.subfolders && folders.data ? folderAndDescendants(folders.data, folderId) : null), [folderId, filters.subfolders, folders.data]);const filter = useMemo<FeedFilter>(() => ({...(tab.kinds && { kinds: tab.kinds }),...(tab.id === "favorites" && { favorites: true }),...(trash && { trashed: true }),- ...(folderId && !trash && { folderId }),+ ...(folderId && !trash && (subtree ? { folderIds: subtree } : { folderId })),...(dq && { q: dq }),...filterFields(filters),}),- [tab, trash, folderId, dq, filters],+ [tab, trash, folderId, subtree, dq, filters],);- const lib = useLibrary(filter);+ // Pinned results sit above the rest of the view (not in the Trash or Uploads); the Pinned filter shows only them.+ const split = !trash && !uploadsTab && !filters.pinned;+ const pinnedLib = useLibrary(useMemo(() => ({ ...filter, pinned: true, limit: 200 }), [filter]), { enabled: split });+ const lib = useLibrary(useMemo(() => (trash || uploadsTab ? filter : { ...filter, pinned: filters.pinned }), [filter, trash, uploadsTab, filters.pinned]));const uploads = useUploads();- const items = useMemo(() => {+ const pinnedItems = useMemo(() => (split ? (pinnedLib.data?.pages.flat() ?? []) : []), [split, pinnedLib.data]);+ const mainItems = useMemo(() => {if (!uploadsTab) return lib.data?.pages.flat() ?? [];// Uploads search by file name.const all = (uploads.data?.pages.flat() ?? []).map(uploadAsGeneration);return dq ? all.filter((g) => g.request.prompt?.toLowerCase().includes(dq.toLowerCase())) : all;}, [uploadsTab, uploads.data, lib.data, dq]);- const built = useMemo(() => buildEntries(items, { stacks: prefs.stacks && !trash && !uploadsTab }), [items, prefs.stacks, trash, uploadsTab]);- const entries = useStableEntries(built);+ const items = useMemo(() => (pinnedItems.length ? [...pinnedItems, ...mainItems] : mainItems), [pinnedItems, mainItems]);+ const stacks = prefs.stacks && !trash && !uploadsTab;+ const entries = useStableEntries(useMemo(() => buildEntries(mainItems, { stacks }), [mainItems, stacks]));+ const pinnedEntries = useStableEntries(useMemo(() => buildEntries(pinnedItems, { stacks }), [pinnedItems, stacks]));const [expanded, setExpanded] = useState<Set<string>>(new Set());const sections = useMemo(() => {const when = (e: LibraryEntry) => Math.max(...members(e).map((g) => (trash ? (g.deletedAt ?? g.createdAt) : g.createdAt)));- return prefs.splitByDate ? splitByDate(entries, when) : [{ key: 0, label: "", items: entries }];- }, [entries, prefs.splitByDate, trash]);+ const rest = prefs.splitByDate ? splitByDate(entries, when) : [{ key: 0, label: pinnedEntries.length ? "Everything else" : "", items: entries }];+ return pinnedEntries.length ? [{ key: -1, label: "Pinned", items: pinnedEntries }, ...rest] : rest;+ }, [entries, pinnedEntries, prefs.splitByDate, trash]);// --- Selection ---------------------------------------------------------------------------const [selecting, setSelecting] = useState(false);@@ -400,6 +412,9 @@ function Inner() {};const visibleTabs = TABS.filter((t) => !t.kinds || t.id === "images" || t.id === "videos" || t.id === "audio" || (facets.data?.kinds[t.kinds[0]] ?? 0) > 0 || tab.id === t.id);const allFav = selectedGens.length > 0 && selectedGens.every((g) => g.favorite);+ const allPinned = selectedGens.length > 0 && selectedGens.every((g) => g.pinnedAt);+ // The bulk bar's review menu checks a status only when every selected result has it.+ const sameReview = selectedGens.length && selectedGens.every((g) => (g.review ?? null) === (selectedGens[0].review ?? null)) ? (selectedGens[0].review ?? null) : undefined;const empty = () => {if (dq) {@@ -412,6 +427,16 @@ function Inner() {</Empty>);}+ if (filters.pinned && !dq) {+ return (+ <Empty title="Nothing pinned here yet">+ Pin results from their ⋯ menu (or select some and choose Pin) to keep them at the top.{" "}+ <button onClick={() => setFilters({ ...filters, pinned: false })} className="text-brand-text hover:underline">+ Show everything+ </button>+ </Empty>+ );+ }if (hasFilters(filters)) {return (<Empty title="Nothing matches your filters">@@ -422,6 +447,16 @@ function Inner() {);}if (trash) return <Empty title="Trash is empty">Generations you delete stay here for {TRASH_DAYS} days, then go for good.</Empty>;+ if (folder?.folders) {+ return (+ <Empty title="Nothing here directly">+ What's in this folder is in the folders above.{" "}+ <button onClick={() => setFilters({ ...filters, subfolders: true })} className="text-brand-text hover:underline">+ Show their results here+ </button>+ </Empty>+ );+ }if (folder) return <Empty title="This folder is empty">Drag cards onto it, or select some and choose Move to folder.</Empty>;if (tab.id === "favorites") return <Empty title="Nothing liked yet">Mark the ones you like with the heart to keep them here.</Empty>;if (uploadsTab) return <Empty title="No uploads yet">Files you add to a studio show up here.</Empty>;@@ -439,11 +474,11 @@ function Inner() {<PageShell wide><div className="flex flex-wrap items-end justify-between gap-x-4 gap-y-3 pb-5">{folder ? (- <FolderHeader folder={folder} onBack={() => go({ folder: undefined })} onMoveOut={(list) => void moveTo(list, null, "Library")} />+ <FolderHeader folder={folder} all={allFolders} onGo={(f) => go({ folder: f?.id })} onMoveItems={(list, to) => void moveTo(list, to?.id ?? null, to?.name ?? "Library")} />) : foldersLoading ? (- <div className="flex h-[52px] min-w-0 items-center gap-2" aria-busy="true" aria-label="Loading folder">- <Skeleton className="h-8 w-24 rounded-full" />- <Skeleton className="h-7 w-48 rounded-lg" />+ <div className="flex min-w-0 flex-col gap-1.5" aria-busy="true" aria-label="Loading folder">+ <Skeleton className="h-7 w-28 rounded-full" />+ <Skeleton className="h-8 w-48 rounded-lg" /></div>) : (<div className="min-w-0">@@ -533,15 +568,15 @@ function Inner() {</div>)}- {tab.id === "all" && !folderId && (folders.data?.length || !loading) ? (+ {(tab.id === "all" && !folderId && (folders.data?.length || !loading)) || (folder && !trash) ? (<div className="mb-4">- <FolderStrip folders={folders.data ?? []} onOpen={(f) => go({ folder: f.id })} onMove={(list, f) => void moveTo(list, f.id, f.name)} />+ <FolderStrip all={allFolders} parent={folder ?? null} onOpen={(f) => go({ folder: f.id })} onMove={(list, f) => void moveTo(list, f.id, f.name)} /></div>) : null}{!uploadsTab && !missingFolder && (<div className="mb-4 flex flex-wrap items-center justify-between gap-2">- <FilterBar value={filters} onChange={setFilters} facets={facets.data} />+ <FilterBar value={filters} onChange={setFilters} facets={facets.data} subfolders={!!folder?.folders} scoped={!!folderId || tab.id !== "all" || !!dq} />{trash && (<div className="flex items-center gap-3 text-[13px] text-muted-foreground"><span>Items stay here for {TRASH_DAYS} days.</span>@@ -575,7 +610,8 @@ function Inner() {{sections.map((s) => (<section key={s.key} aria-label={s.label || "Results"}>{s.label && (- <h2 className="mb-2.5 flex items-baseline gap-2 text-[13px] font-medium">+ <h2 className="mb-2.5 flex items-center gap-1.5 text-[13px] font-medium">+ {s.key === -1 && <Pin className="size-3.5 text-muted-foreground" />}{s.label} <span className="font-mono text-[11px] font-normal text-muted-foreground">{s.items.reduce((n, e) => n + members(e).length, 0)}</span></h2>)}@@ -636,7 +672,19 @@ function Inner() {{(selecting || selected.size > 0) && !uploadsTab && (<div className="pointer-events-none fixed inset-x-0 bottom-0 z-30 flex justify-center px-3 pb-[max(1rem,env(safe-area-inset-bottom))] md:pl-[var(--sidebar-width,0px)]"><div role="toolbar" aria-label="Selection" className="pointer-events-auto flex max-w-full items-center gap-1 overflow-x-auto rounded-full border bg-background p-1.5 shadow-strong">- <span className="shrink-0 px-2.5 text-[13px] font-medium whitespace-nowrap">{selected.size ? `${selected.size} selected` : "Select items"}</span>+ {/* Phones show just the count, so every action fits at 390 px. */}+ <span className="shrink-0 px-2.5 text-[13px] font-medium whitespace-nowrap">+ {selected.size ? (+ <>+ {selected.size}+ <span className="hidden sm:inline"> selected</span>+ </>+ ) : (+ <>+ Select<span className="hidden sm:inline"> items</span>+ </>+ )}+ </span>{trash ? (<><BarButton icon={ArchiveRestore} label="Restore" disabled={!selected.size} onClick={() => void actions.restore(selectedGens).then((n) => (n && toast(`Restored ${n}`), clear()))} />@@ -655,6 +703,22 @@ function Inner() {}}/><BarButton icon={Heart} label={allFav ? "Unlike" : "Like"} disabled={!selected.size} onClick={() => void actions.favoriteMany(selectedGens, !allFav)} />+ <BarButton+ icon={allPinned ? PinOff : Pin}+ label={allPinned ? "Unpin" : "Pin"}+ disabled={!selected.size}+ onClick={() => void actions.pin(selectedGens, !allPinned).then((n) => n && toast(allPinned ? `Unpinned ${n}` : `Pinned ${n} to the top`))}+ />+ <DropdownMenu modal={false}>+ <DropdownMenuTrigger asChild disabled={!selected.size}>+ <button className={BAR} disabled={!selected.size} aria-label="Review status" title="Review status">+ <CircleDot className="size-4" /> <span className="hidden sm:inline">Review</span>+ </button>+ </DropdownMenuTrigger>+ <DropdownMenuContent side="top" align="center" collisionPadding={12} className="min-w-44">+ <ReviewMenuItems value={sameReview} onPick={(r) => void actions.review(selectedGens, r).then((n) => n && toast(r ? `Marked ${n} as ${reviewInfo(r)?.label}` : `Cleared the review status of ${n}`))} />+ </DropdownMenuContent>+ </DropdownMenu><DropdownMenu modal={false}><DropdownMenuTrigger asChild disabled={!selected.size}><button className={BAR} disabled={!selected.size}>@@ -687,6 +751,7 @@ function Inner() {{newFolderFor && (<FolderDialog+ parent={folder ?? null}openonOpenChange={(v) => !v && setNewFolderFor(null)}onSaved={(f) => {@@ -744,7 +809,9 @@ export function LibraryView() {return (<Suspense fallback={null}><ForeverConfirmProvider>- <Inner />+ <UploadDeleteProvider>+ <Inner />+ </UploadDeleteProvider></ForeverConfirmProvider></Suspense>);diff --git a/src/components/library/asset-card.tsx b/src/components/library/asset-card.tsxindex 525618d9..325ae9eb 100644--- a/src/components/library/asset-card.tsx+++ b/src/components/library/asset-card.tsx@@ -1,6 +1,6 @@"use client";-import { Check, ChevronDown, Heart, Layers, MoreHorizontal, RotateCcw } from "lucide-react";+import { Check, ChevronDown, Heart, Layers, MoreHorizontal, Pin, RotateCcw } from "lucide-react";import { memo, useMemo, useState } from "react";import { tileRatio } from "@/components/studio/feed";import { TileActions, useCanHover, type RunnerOptions } from "@/components/studio/result-actions";@@ -11,6 +11,7 @@ import { coverOf, trashDaysLeft, userTitle, type LibraryEntry } from "@/lib/librimport { isLayered, shownOutputs } from "@/lib/output-actions";import { cn } from "@/lib/utils";import { DRAG_TYPE } from "./folders";+import { ReviewBadge } from "./review";import type { Layout } from "./view-options";/** Stable callbacks from the Library (refs inside), so cards re-render only when their own data changes. */@@ -185,7 +186,13 @@ export const AssetCard = memo(function AssetCard({const badges = (<><div className={cn("absolute top-2 right-2 flex items-center gap-1.5", audio && canHover && "group-focus-within/card:opacity-0 group-hover/card:opacity-0")}>+ {!stack && !trashed && <ReviewBadge narrow status={g.review} />}{!stack && count > 1 && !isLayered(g) && <span className="rounded-full bg-black/55 px-1.5 py-0.5 font-mono text-[11px] text-white backdrop-blur">×{count}</span>}+ {g.pinnedAt && !stack && !trashed && (+ <span className="grid size-5 place-items-center rounded-full bg-black/55 text-white backdrop-blur" title="Pinned">+ <Pin className="size-3" aria-label="Pinned" />+ </span>+ )}{g.favorite && !stack && <Heart className="m-0.5 size-4 fill-highlight text-highlight drop-shadow" />}{audio && touchMenu}</div>@@ -225,7 +232,11 @@ export const AssetCard = memo(function AssetCard({<SelectDot selected={selected} visible={selecting} onToggle={(s) => api.toggle(entry.key, ids, s)} label={`Select ${title}`} /></div><div className="min-w-0 flex-1">- <p className="truncate text-[14px] font-medium">{title}</p>+ <p className="flex min-w-0 items-center gap-1.5">+ <span className="truncate text-[14px] font-medium">{title}</span>+ {g.pinnedAt && !stack && !trashed && <Pin className="size-3 shrink-0 text-muted-foreground" aria-label="Pinned" />}+ {!stack && !trashed && <ReviewBadge status={g.review} className="bg-muted" />}+ </p><p className="truncate text-[12px] text-muted-foreground">{stack ? `${stack.label} · ` : `${g.modelName ?? g.modelId} · ${OPERATION_LABELS[g.op]} · `}{trashed ? `${trashDaysLeft(g.deletedAt!)} days left in Trash` : timeAgo(g.createdAt)}@@ -276,7 +287,7 @@ export const AssetCard = memo(function AssetCard({<div{...common}className={cn(- "relative w-full cursor-pointer overflow-hidden rounded-xl bg-muted transition-[box-shadow]",+ "@container relative w-full cursor-pointer overflow-hidden rounded-xl bg-muted transition-[box-shadow]",!selecting && done && !stack && "cursor-zoom-in",selected && "ring-3 ring-primary",expanded && "ring-2 ring-border-strong",diff --git a/src/components/library/filters.tsx b/src/components/library/filters.tsxindex fe3a9aea..e47c19a6 100644--- a/src/components/library/filters.tsx+++ b/src/components/library/filters.tsx@@ -1,12 +1,12 @@"use client";-import { Calendar, Check, ChevronDown, CircleDot, Cpu, X } from "lucide-react";+import { Calendar, Check, ChevronDown, CircleDot, Cpu, FolderTree, ListTree, Pin, X } from "lucide-react";import { useState } from "react";+import { ReviewDot } from "@/components/library/review";import { useEdgeFade } from "@/components/studio/use-edge-fade";import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";import type { LibraryFacets } from "@/lib/api";-import type { GenerationStatus } from "@/lib/catalog/types";-import { dayStart } from "@/lib/library";+import { dayStart, REVIEW_STATUSES, reviewInfo, type FeedFilter, type ReviewFilter } from "@/lib/library";import { cn } from "@/lib/utils";export type DateRange = { id: "any" | "today" | "7d" | "30d" } | { id: "custom"; from: string; to: string };@@ -16,15 +16,25 @@ export interface Filters {models: string[];date: DateRange;status: StatusFilter;+ /** A review status ("none": results without one), or any. */+ review: ReviewFilter | "all";+ /** Only pinned results. */+ pinned: boolean;+ /** Show helper steps (a Shorts cut, a Click to Ad voiceover…), hidden by default. */+ steps: boolean;+ /** In a folder: its subfolders' results too ("Show subfolders content"). */+ subfolders: boolean;}-export const NO_FILTERS: Filters = { models: [], date: { id: "any" }, status: "all" };+export const NO_FILTERS: Filters = { models: [], date: { id: "any" }, status: "all", review: "all", pinned: false, steps: false, subfolders: false };const DAY = 86_400_000;-/** Filters → FeedFilter fields (createdAt range and statuses). */-export function filterFields(f: Filters, now = Date.now()): { models?: string[]; since?: number; until?: number; statuses?: GenerationStatus[] } {- const out: { models?: string[]; since?: number; until?: number; statuses?: GenerationStatus[] } = {};+type FilterFields = Pick<FeedFilter, "models" | "since" | "until" | "statuses" | "reviews" | "steps">;++/** Filters → FeedFilter fields (createdAt range, statuses, review, steps). Pinned and subfolders shape the lists in the Library itself. */+export function filterFields(f: Filters, now = Date.now()): FilterFields {+ const out: FilterFields = {};if (f.models.length) out.models = f.models;const d = f.date;if (d.id === "today") out.since = dayStart(now);@@ -38,10 +48,12 @@ export function filterFields(f: Filters, now = Date.now()): { models?: string[];else if (f.status === "active") out.statuses = ["queued", "running"];else if (f.status === "failed") out.statuses = ["failed", "canceled"];else if (f.status === "hide-failed") out.statuses = ["queued", "running", "succeeded"];+ if (f.review !== "all") out.reviews = [f.review];+ if (f.steps) out.steps = true;return out;}-export const hasFilters = (f: Filters) => f.models.length > 0 || f.date.id !== "any" || f.status !== "all";+export const hasFilters = (f: Filters) => f.models.length > 0 || f.date.id !== "any" || f.status !== "all" || f.review !== "all" || f.pinned || f.steps || f.subfolders;function Chip({ active, children, ...props }: { active: boolean; children: React.ReactNode } & React.ComponentProps<"button">) {return (@@ -84,12 +96,39 @@ const DATES: { id: Exclude<DateRange["id"], "custom">; label: string }[] = [const STATUSES: { id: StatusFilter; label: string }[] = [{ id: "all", label: "Any status" },{ id: "done", label: "Finished" },- { id: "active", label: "In progress" },+ { id: "active", label: "Rendering" },{ id: "failed", label: "Failed" },{ id: "hide-failed", label: "Hide failed" },];-export function FilterBar({ value, onChange, facets }: { value: Filters; onChange: (f: Filters) => void; facets?: LibraryFacets }) {+const REVIEWS: { id: Filters["review"]; label: string }[] = [{ id: "all", label: "Any review" }, ...REVIEW_STATUSES, { id: "none", label: "No review status" }];++/** The Status chip's label: the progress pick, the review pick, or both. */+function statusLabel(f: Filters): string {+ const parts = [f.status !== "all" ? STATUSES.find((s) => s.id === f.status)!.label : "", f.review !== "all" ? (REVIEWS.find((r) => r.id === f.review)?.label ?? "") : ""].filter(Boolean);+ return parts.join(" · ") || "Any status";+}++/**+ * The Library's filters: model, date, status (progress and review), Pinned, and the toggles that+ * reveal helper steps and, inside a folder with subfolders, their results.+ */+export function FilterBar({+ value,+ onChange,+ facets,+ subfolders,+ scoped,+}: {+ value: Filters;+ onChange: (f: Filters) => void;+ facets?: LibraryFacets;+ /** The view is a folder with subfolders: offer their results too. */+ subfolders?: boolean;+ /** A folder, a tab or a search: the library-wide counts (pinned, steps, failed, review) would mislead, so they're left off. */+ scoped?: boolean;+}) {+ const counts = scoped ? undefined : facets;const [custom, setCustom] = useState<{ from: string; to: string }>(value.date.id === "custom" ? { from: value.date.from, to: value.date.to } : { from: "", to: "" });const models = facets?.models ?? [];const modelLabel = value.models.length === 0 ? "Any model" : value.models.length === 1 ? (models.find((m) => m.id === value.models[0])?.name ?? "1 model") : `${value.models.length} models`;@@ -156,20 +195,56 @@ export function FilterBar({ value, onChange, facets }: { value: Filters; onChang</Popover><Popover><PopoverTrigger asChild>- <Chip active={value.status !== "all"}>- <CircleDot className="size-3.5" /> {STATUSES.find((s) => s.id === value.status)!.label}- {facets?.failed && value.status === "all" ? <span className="font-mono text-[11px] text-muted-foreground">{facets.failed} failed</span> : null}+ <Chip active={value.status !== "all" || value.review !== "all"}>+ {value.review !== "all" && value.review !== "none" ? <ReviewDot status={value.review} /> : <CircleDot className="size-3.5" />} {statusLabel(value)}+ {counts?.failed && value.status === "all" && value.review === "all" ? <span className="font-mono text-[11px] text-muted-foreground">{counts.failed} failed</span> : null}<ChevronDown className="size-3.5 opacity-60" /></Chip></PopoverTrigger>- <PopoverContent align="start" collisionPadding={12} className="w-[min(92vw,220px)] p-1.5" role="radiogroup" aria-label="Status">- {STATUSES.map((s) => (- <Option key={s.id} kind="radio" checked={value.status === s.id} onClick={() => onChange({ ...value, status: s.id })}>- {s.label}- </Option>- ))}+ <PopoverContent align="start" collisionPadding={12} className="max-h-[min(70vh,420px)] w-[min(92vw,240px)] space-y-1.5 overflow-y-auto p-1.5">+ <div role="radiogroup" aria-label="Status">+ {STATUSES.map((s) => (+ <Option key={s.id} kind="radio" checked={value.status === s.id} onClick={() => onChange({ ...value, status: s.id })}>+ {s.label}+ </Option>+ ))}+ </div>+ <div role="radiogroup" aria-label="Review status" className="border-t pt-1.5">+ <p className="px-2 pb-1 text-[12px] font-medium text-muted-foreground">Review</p>+ {REVIEWS.map((r) => {+ const info = reviewInfo(r.id === "all" || r.id === "none" ? null : r.id);+ const n = info ? counts?.reviews[info.id] : undefined;+ return (+ <Option key={r.id} kind="radio" checked={value.review === r.id} onClick={() => onChange({ ...value, review: r.id })}>+ <span className="inline-flex items-center gap-1.5">+ {info && <ReviewDot status={info.id} />} {r.label} {n ? <span className="font-mono text-[11px] text-muted-foreground">{n}</span> : null}+ </span>+ </Option>+ );+ })}+ </div></PopoverContent></Popover>+ <Chip active={value.pinned} aria-pressed={value.pinned} onClick={() => onChange({ ...value, pinned: !value.pinned })} title="Only pinned results">+ <Pin className="size-3.5" /> Pinned+ {counts?.pinned ? <span className="font-mono text-[11px] text-muted-foreground">{counts.pinned}</span> : null}+ </Chip>+ {subfolders && (+ <Chip active={value.subfolders} aria-pressed={value.subfolders} onClick={() => onChange({ ...value, subfolders: !value.subfolders })} title="Include results from the folders inside this one">+ <FolderTree className="size-3.5" /> Subfolders+ </Chip>+ )}+ {(facets?.steps || value.steps) && (+ <Chip+ active={value.steps}+ aria-pressed={value.steps}+ onClick={() => onChange({ ...value, steps: !value.steps })}+ title="Helper steps are the in-between jobs of a chain: a Shorts cut, a voiceover, a preview frame"+ >+ <ListTree className="size-3.5" /> {value.steps ? "Showing steps" : "Show steps"}+ {counts?.steps ? <span className="font-mono text-[11px] text-muted-foreground">{counts.steps}</span> : null}+ </Chip>+ )}{hasFilters(value) && (<button onClick={() => onChange(NO_FILTERS)} className="inline-flex h-8 shrink-0 items-center gap-1 rounded-full px-2.5 text-[13px] text-muted-foreground hover:bg-accent hover:text-foreground"><X className="size-3.5" /> Clear filtersdiff --git a/src/components/library/folders.tsx b/src/components/library/folders.tsxindex e7754964..e1bbf39a 100644--- a/src/components/library/folders.tsx+++ b/src/components/library/folders.tsx@@ -1,8 +1,10 @@"use client";-import { Check, ChevronLeft, Folder as FolderIcon, FolderPlus, MoreHorizontal, Pencil, Trash2 } from "lucide-react";+import { Check, ChevronLeft, ChevronRight, Download, Folder as FolderIcon, FolderInput, FolderOpen, FolderPlus, MoreHorizontal, Pencil, Pin, PinOff, Trash2 } from "lucide-react";import { useRef, useState } from "react";import { toast } from "sonner";+import { downloadUrl, useCanHover } from "@/components/studio/result-actions";+import { MediaThumb } from "@/components/studio/result-media";import {AlertDialog,AlertDialogAction,@@ -14,14 +16,27 @@ import {AlertDialogTitle,} from "@/components/ui/alert-dialog";import { Dialog, DialogContent, DialogDescription, DialogTitle } from "@/components/ui/dialog";-import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuSeparator,+ DropdownMenuSub,+ DropdownMenuSubContent,+ DropdownMenuSubTrigger,+ DropdownMenuTrigger,+} from "@/components/ui/dropdown-menu";import { useFolderActions } from "@/lib/api";-import { DEFAULT_FOLDER_COLOR, FOLDER_COLORS, folderSwatch, type Folder } from "@/lib/library";+import { childFolders, DEFAULT_FOLDER_COLOR, FOLDER_COLORS, folderMoveError, folderPath, folderSwatch, folderTree, MAX_FOLDER_DEPTH, type Folder } from "@/lib/library";import { cn } from "@/lib/utils";-import { MediaThumb } from "@/components/studio/result-media";/** Generation ids dragged from a card (the selection when the card is selected). */export const DRAG_TYPE = "application/x-fuobe-generations";+/** A folder dragged onto another folder or a breadcrumb, to move it there. */+export const FOLDER_DRAG_TYPE = "application/x-fuobe-folder";++/** The folder being dragged: targets check the move while hovering (a drag's data can only be read on drop). */+let draggingFolder: string | null = null;export function readDrag(e: React.DragEvent): string[] | null {if (!e.dataTransfer.types.includes(DRAG_TYPE)) return null;@@ -32,43 +47,115 @@ export function readDrag(e: React.DragEvent): string[] | null {}}-/** A drop target for dragged cards (folders, the "Library" crumb). */-export function useDropTarget(onDrop: (ids: string[]) => void) {- const [over, setOver] = useState(false);+const plural = (n: number, one: string) => `${n} ${one}${n === 1 ? "" : "s"}`;++/**+ * A drop target for dragged cards and folders (folder cards, breadcrumbs). `over` is null while+ * nothing hovers, "" when the drop would work, or why it can't ("Cannot move into a subfolder").+ */+export function useDropTarget(on: { items?: (ids: string[]) => void; folder?: (id: string) => void; folderError?: (id: string) => string | null }) {+ const [over, setOver] = useState<string | null>(null);return {over,props: {onDragOver: (e: React.DragEvent) => {- if (!e.dataTransfer.types.includes(DRAG_TYPE)) return;- e.preventDefault();- e.dataTransfer.dropEffect = "move";- setOver(true);+ const types = e.dataTransfer.types;+ if (on.items && types.includes(DRAG_TYPE)) {+ e.preventDefault();+ e.dataTransfer.dropEffect = "move";+ setOver("");+ } else if (on.folder && types.includes(FOLDER_DRAG_TYPE) && draggingFolder) {+ const error = on.folderError?.(draggingFolder) ?? null;+ // Only a valid move lets the drop through; the target says why otherwise.+ if (!error) e.preventDefault();+ e.dataTransfer.dropEffect = error ? "none" : "move";+ setOver(error ?? "");+ }+ },+ onDragLeave: (e: React.DragEvent) => {+ // Moving onto one of the target's own children isn't leaving it.+ if (e.relatedTarget instanceof Node && e.currentTarget.contains(e.relatedTarget)) return;+ setOver(null);},- onDragLeave: () => setOver(false),onDrop: (e: React.DragEvent) => {- setOver(false);- const ids = readDrag(e);- if (!ids?.length) return;- e.preventDefault();- onDrop(ids);+ setOver(null);+ const ids = on.items ? readDrag(e) : null;+ if (ids?.length) {+ e.preventDefault();+ on.items!(ids);+ return;+ }+ const id = on.folder ? e.dataTransfer.getData(FOLDER_DRAG_TYPE) : "";+ if (id && !on.folderError?.(id)) {+ e.preventDefault();+ on.folder!(id);+ }},},};}-export function FolderDialog({ folder, open, onOpenChange, onSaved }: { folder?: Folder; open: boolean; onOpenChange: (v: boolean) => void; onSaved?: (f: Folder) => void }) {+/** Makes a folder draggable onto other folders and breadcrumbs (devices with a pointer). */+function useFolderDrag(folder: Folder) {+ const canHover = useCanHover();+ return {+ draggable: canHover,+ onDragStart: (e: React.DragEvent) => {+ draggingFolder = folder.id;+ e.dataTransfer.setData(FOLDER_DRAG_TYPE, folder.id);+ e.dataTransfer.setData("text/plain", folder.name);+ e.dataTransfer.effectAllowed = "move";+ },+ onDragEnd: () => {+ draggingFolder = null;+ },+ };+}++/** Move a folder (drag and drop, the Move to menu) and say where it went, or why it didn't. */+export function useMoveFolder(all: Folder[]) {+ const actions = useFolderActions();+ return (id: string, target: Folder | null) => {+ const f = all.find((x) => x.id === id);+ if (!f) return;+ const error = folderMoveError(all, id, target?.id ?? null);+ if (error) return void toast(error);+ actions.update(id, { parentId: target?.id ?? null }).then(+ () => toast.success(target ? `Moved “${f.name}” into “${target.name}”` : `Moved “${f.name}” to the top of your Library`),+ (e: Error) => toast.error(e.message),+ );+ };+}++/** A folder can take a subfolder while it's above the depth limit. */+const roomInside = (all: Folder[], f: Folder | null | undefined) => !f || folderPath(all, f.id).length < MAX_FOLDER_DEPTH;++export function FolderDialog({+ folder,+ parent,+ open,+ onOpenChange,+ onSaved,+}: {+ folder?: Folder;+ /** A new folder goes inside this one (the library root without it). */+ parent?: Folder | null;+ open: boolean;+ onOpenChange: (v: boolean) => void;+ onSaved?: (f: Folder) => void;+}) {const actions = useFolderActions();const [name, setName] = useState(folder?.name ?? "");- const [color, setColor] = useState(folder?.color ?? DEFAULT_FOLDER_COLOR);+ const [color, setColor] = useState(folder?.color ?? parent?.color ?? DEFAULT_FOLDER_COLOR);const [busy, setBusy] = useState(false);const input = useRef<HTMLInputElement>(null);const save = async () => {setBusy(true);try {- const f = folder ? await actions.update(folder.id, { name, color }) : await actions.create({ name, color });+ const f = folder ? await actions.update(folder.id, { name, color }) : await actions.create({ name, color, parentId: parent?.id ?? null });onOpenChange(false);onSaved?.(f);- if (!folder) toast.success(`Created “${f.name}”`);+ if (!folder) toast.success(parent ? `Created “${f.name}” in “${parent.name}”` : `Created “${f.name}”`);} catch (e) {toast.error((e as Error).message);} finally {@@ -86,7 +173,7 @@ export function FolderDialog({ folder, open, onOpenChange, onSaved }: { folder?:input.current?.select();}}>- <DialogTitle className="font-heading text-[22px] font-normal">{folder ? "Edit folder" : "New folder"}</DialogTitle>+ <DialogTitle className="font-heading text-[22px] font-normal break-words">{folder ? "Edit folder" : parent ? `New folder in “${parent.name}”` : "New folder"}</DialogTitle><DialogDescription className="sr-only">Name and colour</DialogDescription><formclassName="space-y-4"@@ -135,91 +222,87 @@ export function FolderDialog({ folder, open, onOpenChange, onSaved }: { folder?:);}-function FolderCard({ folder, onOpen, onDropIds }: { folder: Folder; onOpen: () => void; onDropIds: (ids: string[]) => void }) {- const drop = useDropTarget(onDropIds);- return (- <button- onClick={onOpen}- {...drop.props}- className={cn(- "group flex w-[min(44vw,190px)] shrink-0 items-center gap-2.5 rounded-xl border bg-background p-2 text-left transition-[background-color,box-shadow,border-color] hover:bg-accent",- drop.over && "border-primary shadow-heavy ring-4 ring-brand-faint",- )}- >- <span className="relative grid size-11 shrink-0 place-items-center overflow-hidden rounded-lg" style={{ background: folderSwatch(folder.color) }}>- {folder.cover ? <MediaThumb output={folder.cover} className="pointer-events-none" /> : <FolderIcon className="size-5 text-black/60" />}- {folder.cover && <span className="absolute inset-x-0 bottom-0 h-1.5" style={{ background: folderSwatch(folder.color) }} />}- </span>- <span className="min-w-0">- <span className="block truncate text-[13px] font-medium">{folder.name}</span>- <span className="block text-[12px] text-muted-foreground">{drop.over ? "Drop to move here" : `${folder.count} item${folder.count === 1 ? "" : "s"}`}</span>- </span>- </button>- );-}--export function FolderStrip({ folders, onOpen, onMove }: { folders: Folder[]; onOpen: (f: Folder) => void; onMove: (ids: string[], f: Folder) => void }) {- const [creating, setCreating] = useState(false);- return (- <div className="scrollbar-none -mx-1 flex gap-2 overflow-x-auto px-1 py-1">- {folders.map((f) => (- <FolderCard key={f.id} folder={f} onOpen={() => onOpen(f)} onDropIds={(ids) => onMove(ids, f)} />- ))}- <button- onClick={() => setCreating(true)}- className="flex w-[min(44vw,160px)] shrink-0 items-center gap-2.5 rounded-xl border border-dashed p-2 text-left text-muted-foreground transition-colors hover:bg-accent hover:text-foreground"- >- <span className="grid size-11 shrink-0 place-items-center rounded-lg bg-muted">- <FolderPlus className="size-5" />- </span>- <span className="text-[13px] font-medium">New folder</span>- </button>- {creating && <FolderDialog open onOpenChange={setCreating} />}- </div>- );+/** 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);+ 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);+ toast(`Downloading “${f.name}” · ${plural(body.files ?? 0, "file")}`);}-/** Folder view header: back to the Library (also a drop target to take items out), rename, colour, delete. */-export function FolderHeader({ folder, onBack, onMoveOut }: { folder: Folder; onBack: () => void; onMoveOut: (ids: string[]) => void }) {+/**+ * 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.+ */+function FolderMenu({ folder, all, onOpen, onGone, triggerClassName }: { folder: Folder; all: Folder[]; onOpen?: () => void; onGone?: () => void; triggerClassName: string }) {const actions = useFolderActions();- const [editing, setEditing] = useState(false);- const [deleting, setDeleting] = useState(false);- const drop = useDropTarget(onMoveOut);+ const move = useMoveFolder(all);+ const [dialog, setDialog] = useState<null | "edit" | "new" | "delete">(null);+ const parent = folder.parentId ? all.find((f) => f.id === folder.parentId) : undefined;+ // Open dialogs once the menu has closed and handed focus back, so the dialog keeps it.+ const later = (d: "edit" | "new" | "delete") => () => setTimeout(() => setDialog(d), 0);+ const moved = [folder.count ? plural(folder.count, "item") : "", folder.folders ? plural(folder.folders, "folder") : ""].filter(Boolean).join(" and ");return (- <div className="flex min-w-0 items-center gap-2">- <button- onClick={onBack}- {...drop.props}- className={cn("inline-flex h-8 shrink-0 items-center gap-1 rounded-full pr-3 pl-2 text-[13px] text-muted-foreground transition-colors hover:bg-accent hover:text-foreground", drop.over && "bg-brand-faint text-brand-text ring-4 ring-brand-faint")}- >- <ChevronLeft className="size-4" /> {drop.over ? "Drop to take out" : "Library"}- </button>- <span className="size-3 shrink-0 rounded-full" style={{ background: folderSwatch(folder.color) }} />- <h2 className="min-w-0 truncate font-heading text-[24px] leading-none">{folder.name}</h2>- <span className="shrink-0 text-[13px] text-muted-foreground">{folder.count}</span>+ // Clicks in the menu and its dialogs (portals bubble through React) never reach the card, which opens the folder.+ <span className="contents" onClick={(e) => e.stopPropagation()}><DropdownMenu modal={false}><DropdownMenuTrigger asChild>- <button className="grid size-8 shrink-0 place-items-center rounded-lg text-muted-foreground hover:bg-accent hover:text-foreground" aria-label="Folder actions">+ <button className={triggerClassName} aria-label={`Actions for ${folder.name}`}><MoreHorizontal className="size-4" /></button></DropdownMenuTrigger>- <DropdownMenuContent align="start">- {/* Open dialogs once the menu has closed and handed focus back, so the dialog keeps it. */}- <DropdownMenuItem onSelect={() => setTimeout(() => setEditing(true), 0)}>+ <DropdownMenuContent align="start" collisionPadding={12} className="min-w-52">+ {onOpen && (+ <DropdownMenuItem onSelect={onOpen}>+ <FolderOpen /> Open+ </DropdownMenuItem>+ )}+ <DropdownMenuItem onSelect={later("new")} disabled={!roomInside(all, folder)}>+ <FolderPlus /> New folder inside+ </DropdownMenuItem>+ <DropdownMenuItem onSelect={later("edit")}><Pencil /> Rename or recolour</DropdownMenuItem>+ <DropdownMenuItem onSelect={() => void actions.update(folder.id, { pinned: !folder.pinnedAt }).catch((e: Error) => toast.error(e.message))}>+ {folder.pinnedAt ? <PinOff /> : <Pin />} {folder.pinnedAt ? "Unpin" : "Pin to top"}+ </DropdownMenuItem>+ <DropdownMenuSub>+ <DropdownMenuSubTrigger>+ <FolderInput /> Move to+ </DropdownMenuSubTrigger>+ <DropdownMenuSubContent collisionPadding={12} className="max-h-72 min-w-48 overflow-y-auto">+ <DropdownMenuItem disabled={!folder.parentId} onSelect={() => move(folder.id, null)}>+ <ChevronLeft /> Top of the Library+ </DropdownMenuItem>+ <DropdownMenuSeparator />+ {folderTree(all).map(({ folder: t, depth }) => (+ <DropdownMenuItem key={t.id} disabled={!!folderMoveError(all, folder.id, t.id)} onSelect={() => move(folder.id, t)} style={{ paddingLeft: 6 + Math.min(depth, 5) * 12 }}>+ <span className="size-3 shrink-0 rounded-full" style={{ background: folderSwatch(t.color) }} /> <span className="truncate">{t.name}</span>+ </DropdownMenuItem>+ ))}+ </DropdownMenuSubContent>+ </DropdownMenuSub>+ <DropdownMenuItem onSelect={() => void downloadFolder(folder)}>+ <Download /> Download (.zip)+ </DropdownMenuItem><DropdownMenuSeparator />- <DropdownMenuItem variant="destructive" onSelect={() => setTimeout(() => setDeleting(true), 0)}>+ <DropdownMenuItem variant="destructive" onSelect={later("delete")}><Trash2 /> Delete folder</DropdownMenuItem></DropdownMenuContent></DropdownMenu>- {editing && <FolderDialog folder={folder} open onOpenChange={setEditing} />}- <AlertDialog open={deleting} onOpenChange={setDeleting}>+ {dialog === "edit" && <FolderDialog folder={folder} open onOpenChange={(v) => !v && setDialog(null)} />}+ {dialog === "new" && <FolderDialog parent={folder} open onOpenChange={(v) => !v && setDialog(null)} />}+ <AlertDialog open={dialog === "delete"} onOpenChange={(v) => !v && setDialog(null)}><AlertDialogContent><AlertDialogHeader>- <AlertDialogTitle>Delete “{folder.name}”?</AlertDialogTitle>- <AlertDialogDescription>The folder goes away; the {folder.count} item{folder.count === 1 ? "" : "s"} in it stay in your Library.</AlertDialogDescription>+ <AlertDialogTitle className="break-words">Delete “{folder.name}”?</AlertDialogTitle>+ <AlertDialogDescription>+ The folder goes away; nothing in it is deleted.+ {moved && ` Its ${moved} move ${parent ? `to “${parent.name}”` : "to the top of your Library"}.`}+ </AlertDialogDescription></AlertDialogHeader><AlertDialogFooter><AlertDialogCancel>Cancel</AlertDialogCancel>@@ -227,7 +310,7 @@ export function FolderHeader({ folder, onBack, onMoveOut }: { folder: Folder; ononClick={async () => {await actions.remove(folder.id);toast("Folder deleted");- onBack();+ onGone?.();}}>Delete folder@@ -235,22 +318,168 @@ export function FolderHeader({ folder, onBack, onMoveOut }: { folder: Folder; on</AlertDialogFooter></AlertDialogContent></AlertDialog>+ </span>+ );+}++function FolderCard({ folder, all, onOpen, onDropIds }: { folder: Folder; all: Folder[]; onOpen: () => void; onDropIds: (ids: string[]) => void }) {+ 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) });+ const canHover = useCanHover();+ const meta = [plural(folder.count, "item"), folder.folders ? plural(folder.folders, "folder") : ""].filter(Boolean).join(" · ");+ return (+ <div+ {...drop.props}+ {...drag}+ onClick={onOpen}+ className={cn(+ "group/folder relative flex w-[min(60vw,220px)] shrink-0 cursor-pointer items-center gap-2.5 rounded-xl border bg-background p-2 text-left transition-[background-color,box-shadow,border-color] hover:bg-accent",+ drop.over === "" && "border-primary shadow-heavy ring-4 ring-brand-faint",+ !!drop.over && "border-dashed",+ )}+ >+ {/* The card takes the clicks (and drags: a drag can't start on a button); keyboards and screen+ readers use this button over it. The ⋯ button is its sibling (buttons don't nest). */}+ <button+ onClick={(e) => {+ e.stopPropagation();+ onOpen();+ }}+ aria-label={`Open ${folder.name}`}+ className="pointer-events-none absolute inset-0 rounded-xl outline-none focus-visible:ring-2 focus-visible:ring-ring"+ />+ <span className="pointer-events-none relative grid size-11 shrink-0 place-items-center overflow-hidden rounded-lg" style={{ background: folderSwatch(folder.color) }}>+ {folder.cover ? <MediaThumb output={folder.cover} /> : <FolderIcon className="size-5 text-black/60" />}+ {folder.cover && <span className="absolute inset-x-0 bottom-0 h-1.5" style={{ background: folderSwatch(folder.color) }} />}+ </span>+ <span className="pointer-events-none relative min-w-0 flex-1">+ <span className="flex min-w-0 items-center gap-1">+ <span className="truncate text-[13px] font-medium">{folder.name}</span>+ {folder.pinnedAt && <Pin className="size-3 shrink-0 text-muted-foreground" aria-label="Pinned" />}+ </span>+ <span className={cn("block truncate text-[12px] text-muted-foreground", !!drop.over && "text-destructive")}>{drop.over === "" ? "Drop to move here" : drop.over || meta}</span>+ </span>+ <FolderMenu+ folder={folder}+ all={all}+ onOpen={onOpen}+ // 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",+ canHover ? "absolute top-1 right-1 size-7 bg-background/90 opacity-0 shadow-soft backdrop-blur group-focus-within/folder:opacity-100 group-hover/folder:opacity-100" : "relative -mr-1 size-7",+ )}+ />+ </div>+ );+}++/** 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 }) {+ 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)} />+ </div>+ ))}+ {roomInside(all, parent) && (+ <button+ onClick={() => setCreating(true)}+ className="flex w-[min(44vw,160px)] shrink-0 items-center gap-2.5 rounded-xl border border-dashed p-2 text-left text-muted-foreground transition-colors hover:bg-accent hover:text-foreground"+ >+ <span className="grid size-11 shrink-0 place-items-center rounded-lg bg-muted">+ <FolderPlus className="size-5" />+ </span>+ <span className="text-[13px] font-medium">{parent ? "New folder inside" : "New folder"}</span>+ </button>+ )}+ {creating && <FolderDialog parent={parent} open onOpenChange={setCreating} />}+ </div>+ );+}++/** One breadcrumb: opens its folder, and takes dropped cards and folders. */+function Crumb({ target, all, label, onGo, onMoveItems, back }: { target: Folder | null; all: Folder[]; label: string; onGo: () => void; onMoveItems: (ids: string[], target: Folder | null) => void; back?: boolean }) {+ const move = useMoveFolder(all);+ const drop = useDropTarget({ items: (ids) => onMoveItems(ids, target), folder: (id) => move(id, target), folderError: (id) => folderMoveError(all, id, target?.id ?? null) });+ return (+ <button+ onClick={onGo}+ {...drop.props}+ title={drop.over || undefined}+ className={cn(+ "inline-flex h-7 min-w-0 shrink items-center gap-0.5 rounded-full px-2 text-[13px] text-muted-foreground transition-colors hover:bg-accent hover:text-foreground",+ back && "shrink-0 pl-1",+ drop.over === "" && "bg-brand-faint text-brand-text ring-4 ring-brand-faint",+ !!drop.over && "text-destructive",+ )}+ >+ {back && <ChevronLeft className="size-4 shrink-0" />}+ <span className="truncate">{drop.over === "" ? `Move to ${label}` : label}</span>+ </button>+ );+}++/**+ * 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 }) {+ 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);+ return (+ <div className="min-w-0 flex-1">+ <nav aria-label="Folder path" className="flex min-w-0 items-center gap-0.5 overflow-hidden">+ <Crumb target={null} all={all} label="Library" back onGo={() => onGo(null)} onMoveItems={onMoveItems} />+ {ancestors.length > shown.length && (+ <>+ <ChevronRight className="size-3.5 shrink-0 text-subtle-foreground" />+ <span className="shrink-0 px-1 text-[13px] text-muted-foreground" title={ancestors.slice(0, -2).map((f) => f.name).join(" / ")}>+ …+ </span>+ </>+ )}+ {shown.map((f) => (+ <span key={f.id} className="flex min-w-0 items-center gap-0.5">+ <ChevronRight className="size-3.5 shrink-0 text-subtle-foreground" />+ <Crumb target={f} all={all} label={f.name} onGo={() => onGo(f)} onMoveItems={onMoveItems} />+ </span>+ ))}+ </nav>+ <div className="mt-1 flex min-w-0 items-center gap-2">+ <span className="size-3 shrink-0 rounded-full" style={{ background: folderSwatch(folder.color) }} />+ <h1 className="min-w-0 truncate font-heading text-[28px] leading-tight">{folder.name}</h1>+ {folder.pinnedAt && <Pin className="size-3.5 shrink-0 text-muted-foreground" aria-label="Pinned" />}+ <span className="shrink-0 font-mono text-[12px] text-muted-foreground" aria-label={plural(folder.count, "item")}>+ {folder.count}+ </span>+ <FolderMenu+ folder={folder}+ all={all}+ onGone={() => onGo(all.find((f) => f.id === folder.parentId) ?? null)}+ triggerClassName="grid size-8 shrink-0 place-items-center rounded-lg text-muted-foreground hover:bg-accent hover:text-foreground"+ />+ </div></div>);}-/** "Move to folder" choices for the bulk bar and card menus. */+/** "Move to folder" choices for the bulk bar: every folder as a tree, out of folders, then a new one. */export function MoveMenuItems({ folders, current, onMove, onNew }: { folders: Folder[]; current?: string; onMove: (folderId: string | null, name: string) => void; onNew: () => void }) {return (<>- {folders.map((f) => (- <DropdownMenuItem key={f.id} disabled={f.id === current} onSelect={() => onMove(f.id, f.name)}>- <span className="size-3 rounded-full" style={{ background: folderSwatch(f.color) }} /> {f.name}+ {folderTree(folders).map(({ folder: f, depth }) => (+ <DropdownMenuItem key={f.id} disabled={f.id === current} onSelect={() => onMove(f.id, f.name)} style={{ paddingLeft: 6 + Math.min(depth, 5) * 12 }}>+ <span className="size-3 shrink-0 rounded-full" style={{ background: folderSwatch(f.color) }} /> <span className="truncate">{f.name}</span></DropdownMenuItem>))}{current && (<DropdownMenuItem onSelect={() => onMove(null, "Library")}>- <ChevronLeft /> Take out of the folder+ <ChevronLeft /> Take out of folders</DropdownMenuItem>)}{folders.length > 0 && <DropdownMenuSeparator />}diff --git a/src/components/library/review.tsx b/src/components/library/review.tsxnew file mode 100644index 00000000..d81c3c01--- /dev/null+++ b/src/components/library/review.tsx@@ -0,0 +1,74 @@+"use client";++import { DropdownMenuRadioGroup, DropdownMenuRadioItem } from "@/components/ui/dropdown-menu";+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";+import { useGenerationActions } from "@/lib/api";+import type { Generation, ReviewStatus } from "@/lib/catalog/types";+import { REVIEW_STATUSES, reviewInfo } from "@/lib/library";+import { cn } from "@/lib/utils";++/** The status colour (Higgsfield's), ringed so the lime stays visible on a light card. */+export function ReviewDot({ status, className }: { status: ReviewStatus; className?: string }) {+ return <span aria-hidden className={cn("size-2 shrink-0 rounded-full ring-1 ring-black/15 dark:ring-white/20", className)} style={{ background: reviewInfo(status)?.color }} />;+}++/**+ * A small pill on a card or row: the status colour and its name. `narrow`: inside an `@container`+ * card, the name shows only from 200 px wide (two-column phone cards get the dot).+ */+export function ReviewBadge({ status, className, narrow }: { status: ReviewStatus | null | undefined; className?: string; narrow?: boolean }) {+ const info = reviewInfo(status);+ if (!info) return null;+ return (+ <span+ className={cn("inline-flex h-5 shrink-0 items-center gap-1 rounded-full bg-background/90 px-1.5 text-[11px] font-medium whitespace-nowrap text-foreground backdrop-blur", className)}+ title={`Review: ${info.label}`}+ aria-label={`Review: ${info.label}`}+ >+ <ReviewDot status={info.id} /> <span className={cn(narrow && "hidden @min-[200px]:inline")}>{info.label}</span>+ </span>+ );+}++const NoStatusDot = () => <span className="mx-1 size-2 shrink-0 rounded-full border border-dashed border-muted-foreground" aria-hidden />;++/**+ * "No status" and the four statuses, as menu radio items (a tile's ⋯ sub-menu, the bulk bar).+ * `value` undefined: nothing is checked (a selection with mixed statuses).+ */+export function ReviewMenuItems({ value, onPick }: { value?: ReviewStatus | null; onPick: (status: ReviewStatus | null) => void }) {+ return (+ <DropdownMenuRadioGroup value={value === undefined ? "" : (value ?? "none")} onValueChange={(v) => onPick(v === "none" ? null : (v as ReviewStatus))}>+ <DropdownMenuRadioItem value="none">+ <NoStatusDot /> No status+ </DropdownMenuRadioItem>+ {REVIEW_STATUSES.map((s) => (+ <DropdownMenuRadioItem key={s.id} value={s.id}>+ <ReviewDot status={s.id} className="mx-1" /> {s.label}+ </DropdownMenuRadioItem>+ ))}+ </DropdownMenuRadioGroup>+ );+}++/** The viewer's review picker: a result's status, changed in place. */+export function ReviewSelect({ g }: { g: Generation }) {+ const actions = useGenerationActions();+ return (+ <Select value={g.review ?? "none"} onValueChange={(v) => void actions.review([g], v === "none" ? null : (v as ReviewStatus))}>+ <SelectTrigger size="sm" aria-label="Review status" className="h-7 min-w-0 text-[13px]">+ <SelectValue />+ </SelectTrigger>+ <SelectContent align="end">+ <SelectItem value="none">+ <NoStatusDot /> No status+ </SelectItem>+ {REVIEW_STATUSES.map((s) => (+ <SelectItem key={s.id} value={s.id}>+ <ReviewDot status={s.id} /> {s.label}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ );+}diff --git a/src/components/library/upload-delete.tsx b/src/components/library/upload-delete.tsxnew file mode 100644index 00000000..e08e6cfe--- /dev/null+++ b/src/components/library/upload-delete.tsx@@ -0,0 +1,89 @@+"use client";++import { Loader2 } from "lucide-react";+import { useCallback, useState } from "react";+import { toast } from "sonner";+import { UploadDeleteContext } from "@/components/studio/result-actions";+import {+ AlertDialog,+ AlertDialogAction,+ AlertDialogCancel,+ AlertDialogContent,+ AlertDialogDescription,+ AlertDialogFooter,+ AlertDialogHeader,+ AlertDialogTitle,+} from "@/components/ui/alert-dialog";+import { assetUsage, useDeleteUpload } from "@/lib/api";+import type { Generation } from "@/lib/catalog/types";++type Check = { state: "checking" } | { state: "free" } | { state: "used"; usedBy: string } | { state: "error"; message: string };++/**+ * Deleting an upload (the Library's Uploads tab and its viewer): first ask the server where the+ * file is used. Nothing: confirm, then delete it for good (uploads skip the Trash, as on Higgsfield).+ * Something: say where, so the person knows what to remove first.+ */+export function UploadDeleteProvider({ children }: { children: React.ReactNode }) {+ const remove = useDeleteUpload();+ const [pending, setPending] = useState<{ g: Generation; after?: () => void; check: Check } | null>(null);+ const ask = useCallback((g: Generation, after?: () => void) => {+ setPending({ g, after, check: { state: "checking" } });+ assetUsage(g.id)+ .then((u) => setPending((p) => (p?.g.id === g.id ? { ...p, check: u.usedBy ? { state: "used", usedBy: u.usedBy } : { state: "free" } } : p)))+ .catch((e: Error) => setPending((p) => (p?.g.id === g.id ? { ...p, check: { state: "error", message: e.message } } : p)));+ }, []);+ const check = pending?.check;+ const name = pending?.g.request.prompt?.trim() || "this upload";+ return (+ <UploadDeleteContext.Provider value={ask}>+ {children}+ <AlertDialog open={!!pending} onOpenChange={(v) => !v && setPending(null)}>+ <AlertDialogContent>+ <AlertDialogHeader>+ <AlertDialogTitle className="break-words">{check?.state === "used" ? "This upload is still in use" : `Delete “${name}”?`}</AlertDialogTitle>+ <AlertDialogDescription asChild>+ <div>+ {check?.state === "checking" && (+ <span className="inline-flex items-center gap-1.5">+ <Loader2 className="size-3.5 animate-spin" /> Checking where it's used…+ </span>+ )}+ {check?.state === "free" && "Nothing in your library uses it. The file is removed for good and can't be recovered."}+ {check?.state === "used" && (+ <>+ It's used by {check.usedBy}. Keep the upload, or delete what uses it first: removing the file now would break that.+ </>+ )}+ {check?.state === "error" && check.message}+ </div>+ </AlertDialogDescription>+ </AlertDialogHeader>+ <AlertDialogFooter>+ {check?.state === "used" || check?.state === "error" ? (+ <AlertDialogCancel>OK</AlertDialogCancel>+ ) : (+ <>+ <AlertDialogCancel>Cancel</AlertDialogCancel>+ <AlertDialogAction+ variant="destructive"+ disabled={check?.state !== "free"}+ onClick={() => {+ if (!pending) return;+ remove.mutate(pending.g.id, {+ onSuccess: () => toast("Upload deleted"),+ onError: (e) => toast.error((e as Error).message),+ });+ pending.after?.();+ }}+ >+ Delete upload+ </AlertDialogAction>+ </>+ )}+ </AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog>+ </UploadDeleteContext.Provider>+ );+}diff --git a/src/components/studio/result-actions.tsx b/src/components/studio/result-actions.tsxindex 47ae5bae..b19cf797 100644--- a/src/components/studio/result-actions.tsx+++ b/src/components/studio/result-actions.tsx@@ -4,6 +4,7 @@ import {ArchiveRestore,AudioLines,Box,+ CircleDot,Clapperboard,Columns2,Copy,@@ -17,6 +18,7 @@ import {Layers2,Mic2,MoreHorizontal,+ Pin,RotateCcw,SlidersHorizontal,Sparkles,@@ -45,8 +47,12 @@ import {DropdownMenuContent,DropdownMenuItem,DropdownMenuSeparator,+ DropdownMenuSub,+ DropdownMenuSubContent,+ DropdownMenuSubTrigger,DropdownMenuTrigger,} from "@/components/ui/dropdown-menu";+import { ReviewMenuItems } from "@/components/library/review";import { Popover, PopoverAnchor, PopoverContent } from "@/components/ui/popover";import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";import { useCreateGeneration, useGenerationActions, useSaveElement } from "@/lib/api";@@ -82,7 +88,10 @@ export const ACTION_ICONS: Record<OutputActionId, LucideIcon> = {compare: Columns2,reuse: RotateCcw,"copy-prompt": Copy,+ pin: Pin,+ review: CircleDot,delete: Trash2,+ "delete-upload": Trash2,restore: ArchiveRestore,"delete-forever": Trash2,};@@ -170,11 +179,18 @@ export function ForeverConfirmProvider({ children }: { children: React.ReactNode/** The Trash's confirm step (null outside a ForeverConfirmProvider). */export const useConfirmForever = () => useContext(ForeverCtx);+/**+ * Deleting an upload checks first that nothing uses it (UploadDeleteProvider in+ * components/library/upload-delete.tsx fills this in; null elsewhere, where uploads aren't shown).+ */+export const UploadDeleteContext = createContext<((g: Generation, after?: () => void) => void) | null>(null);+/** Handlers for the actions that aren't plain links. "save-character" is handled by the caller's popover. */export function useActionRunner(opts: RunnerOptions = {}) {const actions = useGenerationActions();const create = useCreateGeneration();const confirmForever = useConfirmForever();+ const deleteUpload = useContext(UploadDeleteContext);return (a: OutputAction, g: Generation, index: number) => {const o = g.outputs[index];switch (a.id) {@@ -203,6 +219,11 @@ export function useActionRunner(opts: RunnerOptions = {}) {return opts.onCompare?.();case "view-3d":return opts.onOpen?.(g, index);+ case "pin":+ void actions.pin([g], !g.pinnedAt);+ return void toast(g.pinnedAt ? "Unpinned" : "Pinned to the top of the Library", { id: "pin" });+ case "delete-upload":+ return deleteUpload?.(g, opts.onDeleted);case "delete":void actions.trash([g]);return opts.onDeleted?.();@@ -444,12 +465,25 @@ export function ActionMenu({label?: string;defaultOpen?: boolean;}) {+ const actions = useGenerationActions();const destructive = list.filter((a) => a.destructive);const rest = list.filter((a) => !a.destructive);// Focus goes back to ⋯ when the menu closes, except when it hands over to the Save-as-element popover.const handingOff = useRef(false);const item = (a: OutputAction) => {const Icon = ACTION_ICONS[a.id];+ if (a.id === "review") {+ return (+ <DropdownMenuSub key={a.id}>+ <DropdownMenuSubTrigger>+ <Icon /> {a.label}+ </DropdownMenuSubTrigger>+ <DropdownMenuSubContent collisionPadding={12} className="min-w-44">+ <ReviewMenuItems value={g.review ?? null} onPick={(r) => void actions.review([g], r)} />+ </DropdownMenuSubContent>+ </DropdownMenuSub>+ );+ }if (a.href && a.download !== undefined) {return (<DropdownMenuItem key={a.id} asChild>diff --git a/src/components/studio/viewer.tsx b/src/components/studio/viewer.tsxindex bc0e345e..55009b4b 100644--- a/src/components/studio/viewer.tsx+++ b/src/components/studio/viewer.tsx@@ -17,6 +17,7 @@ import { cn } from "@/lib/utils";import { CompareSlider } from "./compare-slider";import { ACTION_ICONS, downloadUrl, SaveElementForm, useActionRunner } from "./result-actions";import { LayersStack, ModelViewer, TextReader } from "./result-media";+import { ReviewSelect } from "@/components/library/review";function Row({ label, value, mono }: { label: string; value?: React.ReactNode; mono?: boolean }) {@@ -93,6 +94,7 @@ function Details({ g, index }: { g: Generation; index: number }) {<Row label="Cost" value={g.costUsd != null ? formatCost(g.costUsd) : undefined} mono /><Row label="Made" value={timeAgo(g.createdAt)} />{g.deletedAt && <Row label="In Trash" value={`${trashDaysLeft(g.deletedAt)} days left`} />}+ {!g.deletedAt && <Row label="Review" value={<ReviewSelect g={g} />} />}</div>{g.request.negativePrompt && <p className="text-[12px] text-muted-foreground">Negative: {g.request.negativePrompt}</p>}</div>@@ -168,6 +170,7 @@ export function Viewer({if (e.key === "ArrowLeft" && onPrev) onPrev();else if (e.key === "ArrowRight" && onNext) onNext();else if (k === "f") act("favorite");+ else if (k === "p") act("pin");else if (k === "c" && source) setComparing((v) => !v);else if (k === "d") act("download");else if (k === "r") act("reuse");@@ -198,8 +201,8 @@ export function Viewer({const primary = list.find((a) => a.placement === "primary");const bar = list.filter((a) => a.placement === "bar");- // "Copy prompt" sits under the title in the details, so it isn't repeated as a button.- const menu = list.filter((a) => a.placement === "menu" && a.id !== "copy-prompt");+ // "Copy prompt" sits under the title in the details, and the review status is picked there too.+ const menu = list.filter((a) => a.placement === "menu" && a.id !== "copy-prompt" && a.id !== "review");const actionButton = (a: OutputAction, opts: { variant?: "default" | "secondary" | "ghost"; className?: string; onDone?: () => void } = {}) => {const Icon = ACTION_ICONS[a.id];@@ -245,7 +248,7 @@ export function Viewer({variant={variant}size="sm"className={cls}- aria-pressed={a.id === "favorite" ? g.favorite : a.id === "compare" ? comparing : undefined}+ aria-pressed={a.id === "favorite" ? g.favorite : a.id === "compare" ? comparing : a.id === "pin" ? !!g.pinnedAt : undefined}onClick={() => {run(a, g, index);opts.onDone?.();@@ -384,11 +387,16 @@ export function Viewer({<Kbd>←</Kbd> <Kbd>→</Kbd> browse</span>)}- {!g.deletedAt && (+ {!g.deletedAt && g.feature !== "upload" && (<span><Kbd>F</Kbd> favorite</span>)}+ {!g.deletedAt && g.feature !== "upload" && (+ <span>+ <Kbd>P</Kbd> pin+ </span>+ )}{source && (<span><Kbd>C</Kbd> comparediff --git a/src/lib/api.ts b/src/lib/api.tsindex 4bf366d4..33c8c338 100644--- a/src/lib/api.ts+++ b/src/lib/api.ts@@ -5,7 +5,7 @@ import { useCallback, useEffect, useMemo, useRef, useSyncExternalStore } from "rimport { toast } from "sonner";import type { AssistThread, AssistThreadSummary, AssistThreadView } from "./assist";import type { ElementKind, StudioElement } from "./catalog/elements";-import type { Engine, Generation, GenerationRequest, MediaKind } from "./catalog/types";+import type { Engine, Generation, GenerationRequest, MediaKind, ReviewStatus } from "./catalog/types";import {applyToCanvasView,applyToList,@@ -24,7 +24,7 @@ import {type Pages,type StreamEvent,} from "./generation-stream";-import { cursorAfter, filterToSearch, type FeedFilter, type Folder } from "./library";+import { cursorAfter, filterToSearch, type AssetUse, type FeedFilter, type Folder } from "./library";export interface Asset {id: string;@@ -397,16 +397,17 @@ export function useGenerations(filter: FeedFilter, opts: { keepPrevious?: booleaexport const LIBRARY_PAGE = 60;/** The Library's paged list ("Load more" pages back with the before cursor). */-export function useLibrary(filter: FeedFilter) {+export function useLibrary(filter: FeedFilter, opts: { enabled?: boolean } = {}) {const connected = useGenerationStream();const f = { ...filter, limit: filter.limit ?? LIBRARY_PAGE };return useInfiniteQuery({queryKey: ["library", f] as const,+ enabled: opts.enabled ?? true,initialPageParam: undefined as string | undefined,queryFn: async ({ pageParam }) =>(await json<{ items: Generation[] }>(await fetch(`/api/generations${f.trashed ? "/trash" : ""}?${filterToSearch(f, pageParam)}`))).items,// The last row's timestamp and id: rows sharing a timestamp across the page boundary aren't skipped.- getNextPageParam: (last) => (last.length < f.limit ? undefined : cursorAfter(last.at(-1)!, f.trashed)),+ getNextPageParam: (last) => (last.length < f.limit ? undefined : cursorAfter(last.at(-1)!, f)),placeholderData: keepPreviousData,structuralSharing: sharePagesById,refetchInterval: (q) => pollEvery(q.state.data?.pages.flat(), connected),@@ -420,13 +421,19 @@ export interface LibraryFacets {favorites: number;failed: number;trash: number;+ pinned: number;+ /** Helper steps, counted whether they're shown or not. */+ steps: number;+ reviews: Partial<Record<ReviewStatus, number>>;}-export function useLibraryFacets() {+/** Counts for the Library's tabs and filters (with the helper steps counted in when they're shown). */+export function useLibraryFacets(opts: { steps?: boolean } = {}) {return useQuery({- queryKey: ["library-facets"],- queryFn: async () => json<LibraryFacets>(await fetch("/api/generations/facets")),+ queryKey: ["library-facets", { steps: !!opts.steps }],+ queryFn: async () => json<LibraryFacets>(await fetch(`/api/generations/facets${opts.steps ? "?steps=1" : ""}`)),staleTime: 15_000,+ placeholderData: keepPreviousData,});}@@ -452,16 +459,16 @@ export function useCreateGeneration() {});}-export type BulkAction = "trash" | "restore" | "delete" | "favorite" | "unfavorite" | "move";+export type BulkAction = "trash" | "restore" | "delete" | "favorite" | "unfavorite" | "move" | "pin" | "unpin" | "review";/** The bulk endpoint takes this many ids per request. */export const BULK_MAX = 500;/** One bulk action, sent in batches of BULK_MAX (a select-all after a few "Load more" can be bigger). */-async function bulkRequest(action: BulkAction, ids: string[], folderId?: string | null): Promise<number> {+async function bulkRequest(action: BulkAction, ids: string[], extra: { folderId?: string | null; review?: ReviewStatus | null } = {}): Promise<number> {let n = 0;for (let i = 0; i < ids.length; i += BULK_MAX) {- const body = JSON.stringify({ action, ids: ids.slice(i, i + BULK_MAX), folderId });+ const body = JSON.stringify({ action, ids: ids.slice(i, i + BULK_MAX), ...extra });n += (await json<{ count: number }>(await fetch("/api/generations/bulk", { method: "POST", headers: { "Content-Type": "application/json" }, body }))).count;}return n;@@ -477,18 +484,21 @@ export function useGenerationActions() {void qc.invalidateQueries({ queryKey: ["library-facets"] });void qc.invalidateQueries({ queryKey: ["folders"] });};- const local = (gs: Generation[], patch: Partial<Generation> | null) => {+ /** A patch for every one (or per one, from its freshest copy); null removes them from the caches. */+ type Patch = Partial<Generation> | ((cur: Generation) => Partial<Generation>) | null;+ const local = (gs: Generation[], patch: Patch) => {for (const g of gs) {const cur = cached(qc, g.id) ?? g;- applyEvent(qc, patch ? { type: "generation", generation: patched(cur, patch) } : { type: "deleted", id: g.id });+ const p = typeof patch === "function" ? patch(cur) : patch;+ applyEvent(qc, p ? { type: "generation", generation: patched(cur, p) } : { type: "deleted", id: g.id });}};/** Optimistic, then the server; on failure the caches are refetched and the error shown. */- const run = async (gs: Generation[], patch: Partial<Generation> | null, action: BulkAction, folderId?: string | null) => {+ const run = async (gs: Generation[], patch: Patch, action: BulkAction, extra?: Parameters<typeof bulkRequest>[2]) => {if (!gs.length) return 0;local(gs, patch);try {- return await bulkRequest(action, gs.map((g) => g.id), folderId);+ return await bulkRequest(action, gs.map((g) => g.id), extra);} catch (e) {toast.error((e as Error).message);return 0;@@ -530,7 +540,14 @@ export function useGenerationActions() {await fetch("/api/generations/trash", { method: "DELETE" });refresh();},- move: (gs: Generation[], folderId: string | null) => run(gs, { folderId }, "move", folderId),+ move: (gs: Generation[], folderId: string | null) => run(gs, { folderId }, "move", { folderId }),+ /** Pin to the top of the Library (ones already pinned keep their place), or unpin. */+ pin: (gs: Generation[], value: boolean) => {+ const now = Date.now();+ // One already pinned keeps its pin time (and its place), as on the server.+ return run(gs, (cur) => ({ pinnedAt: value ? (cur.pinnedAt ?? now) : null }), value ? "pin" : "unpin");+ },+ review: (gs: Generation[], review: ReviewStatus | null) => run(gs, { review }, "review", { review }),cancel: async (g: Generation) => {local([g], { status: "canceled" });await fetch(`/api/generations/${g.id}/cancel`, { method: "POST" });@@ -579,8 +596,11 @@ export function useFolderActions() {return out;};return {- create: (body: { name: string; color?: string }) => send<Folder>("/api/folders", "POST", body),- update: (id: string, body: { name?: string; color?: string }) => send<Folder>(`/api/folders/${id}`, "PATCH", body),+ /** A new folder; with parentId, a subfolder. */+ create: (body: { name: string; color?: string; parentId?: string | null }) => send<Folder>("/api/folders", "POST", body),+ /** Rename, recolour, pin, or move (parentId; null: the library root). */+ update: (id: string, body: { name?: string; color?: string; parentId?: string | null; pinned?: boolean }) => send<Folder>(`/api/folders/${id}`, "PATCH", body),+ /** Delete; its results and subfolders move up to its parent. */remove: async (id: string) => {await send<void>(`/api/folders/${id}`, "DELETE");void qc.invalidateQueries({ queryKey: ["library"] });@@ -599,6 +619,23 @@ export async function uploadFile(file: File): Promise<Asset> {return json<Asset>(await fetch("/api/uploads", { method: "POST", body: form }));}+/** A stored file's uses: where it's used, in one line ("2 results and the element “Maya”"), empty when nothing uses it. */+export async function assetUsage(id: string): Promise<{ uses: AssetUse[]; usedBy: string }> {+ return json<{ uses: AssetUse[]; usedBy: string }>(await fetch(`/api/assets/${encodeURIComponent(id)}`));+}++/** Delete an upload for good (refused, with where it's used, while anything still uses it). */+export function useDeleteUpload() {+ const qc = useQueryClient();+ return useMutation({+ mutationFn: async (id: string) => {+ const res = await fetch(`/api/assets/${encodeURIComponent(id)}`, { method: "DELETE" });+ if (res.status !== 204) await json(res);+ },+ onSettled: () => qc.invalidateQueries({ queryKey: ["assets"] }),+ });+}+export function useAssets(source?: "upload" | "generation", kind?: MediaKind) {return useQuery({queryKey: ["assets", source, kind],diff --git a/src/lib/output-actions.ts b/src/lib/output-actions.tsindex 56948458..84ac611c 100644--- a/src/lib/output-actions.ts+++ b/src/lib/output-actions.ts@@ -34,7 +34,10 @@ export type OutputActionId =| "compare"| "reuse"| "copy-prompt"+ | "pin"+ | "review"| "delete"+ | "delete-upload"| "restore"| "delete-forever";@@ -114,13 +117,16 @@ export function outputActions(g: Generation, index: number, ctx: ActionContext =out.push({ ...file, label: `Download .${ext}` }, { id: "favorite", label: g.favorite ? "Unfavorite" : "Favorite", placement: "bar" });break;}- // Uploads (the Library's Uploads tab) are files, not generations: hand-offs and download only.- if (g.feature === "upload") return out.filter((a) => a.id !== "favorite");+ // Uploads (the Library's Uploads tab) are files, not generations: hand-offs, download, and a+ // delete that first checks nothing uses the file.+ if (g.feature === "upload") return [...out.filter((a) => a.id !== "favorite"), { id: "delete-upload", label: "Delete", placement: "menu", destructive: true }];if (g.outputs.length > 1) out.push({ id: "download-all", label: `Download all ${g.outputs.length} (.zip)`, placement: "menu", href: `/api/generations/zip?ids=${g.id}`, download: "" });if (o.draftId) out.push({ id: "finalize", label: "Render this draft in 1080p", placement: "menu" });if (ctx.compare) out.push({ id: "compare", label: "Compare with original", placement: "menu" });if (ctx.reuse) out.push({ id: "reuse", label: "Reuse settings", placement: "menu" });if (g.prompt) out.push({ id: "copy-prompt", label: "Copy prompt", placement: "menu" });+ // Library: pinned results stay at the top of their view; the review status is a sub-menu of its own.+ out.push({ id: "pin", label: g.pinnedAt ? "Unpin" : "Pin to top", placement: "menu" }, { id: "review", label: "Review status", placement: "menu" });out.push({ id: "delete", label: "Delete", placement: "menu", destructive: true });return out;}diff --git a/tests/library-pure.test.ts b/tests/library-pure.test.tsindex 2a233eb4..84aa2323 100644--- a/tests/library-pure.test.ts+++ b/tests/library-pure.test.ts@@ -1,7 +1,31 @@import { describe, expect, it } from "vitest";import type { Generation } from "@/lib/catalog/types";import { applyToList, applyToPages, applyToThread, backoff, needsCatchUp, parseSse, shareById, sharePagesById, streamResponse, toChannelMessage, toStreamEvent } from "@/lib/generation-stream";-import { buildEntries, byDeleted, byNewest, cursorAfter, dayLabel, downloadName, filterToSearch, matchesFilter, splitByDate, trashDaysLeft, userTitle } from "@/lib/library";+import {+ buildEntries,+ byDeleted,+ byNewest,+ byPinned,+ childFolders,+ cursorAfter,+ dayLabel,+ describeUses,+ downloadName,+ filterToSearch,+ folderAndDescendants,+ folderMoveError,+ folderPath,+ folderTree,+ freeName,+ isHelperFeature,+ matchesFilter,+ MAX_FOLDER_DEPTH,+ splitByDate,+ trashDaysLeft,+ userTitle,+ zipSegment,+ type Folder,+} from "@/lib/library";import { toSrt, toVtt } from "@/lib/cues";import { cueTime, layerInfo, modelPreview, outputActions, shownOutputs, textOf } from "@/lib/output-actions";@@ -52,6 +76,8 @@ describe("outputActions", () => {"menu:save-character","menu:reuse","menu:copy-prompt",+ "menu:pin",+ "menu:review","menu:delete",]);const [animate, download] = outputActions(gen({ id: "abcdef123456" }), 0);@@ -62,7 +88,21 @@ describe("outputActions", () => {it("gives videos Extend first and the video hand-offs", () => {const g = gen({ kind: "video", op: "t2v", outputs: [{ url: "/api/files/o/v.mp4", kind: "video", draftId: "d1" }] });- expect(ids(g)).toEqual(["primary:extend", "bar:download", "bar:favorite", "menu:reframe", "menu:lipsync", "menu:upscale", "menu:add-sound", "menu:grade", "menu:finalize", "menu:copy-prompt", "menu:delete"]);+ expect(ids(g)).toEqual([+ "primary:extend",+ "bar:download",+ "bar:favorite",+ "menu:reframe",+ "menu:lipsync",+ "menu:upscale",+ "menu:add-sound",+ "menu:grade",+ "menu:finalize",+ "menu:copy-prompt",+ "menu:pin",+ "menu:review",+ "menu:delete",+ ]);});it("handles audio, text, 3D, layers, favorites and the Trash", () => {@@ -321,3 +361,156 @@ describe("round-3 fixes", () => {expect(modelPreview(glb, glb.outputs[0]).video).toBe("/t.mp4");});});++describe("round 4: helper steps, pins, review, nested folders, where a file is used", () => {+ const ev = (g: Generation) => ({ type: "generation" as const, generation: g });++ it("knows every helper feature the studios create, and nothing else", () => {+ for (const f of ["shorts-step", "mixed-media-step", "marketing-step", "click-to-ad-step", "ad-multiplier-step", "mixed-media-preview", "faceless-avatar", "faceless-voice", "moodboard"]) {+ expect(isHelperFeature(f), f).toBe(true);+ }+ for (const f of ["image", "shorts", "mixed-media", "marketing", "click-to-ad", "ad-multiplier", "dub", "katana", "faceless", "explainer", "storyboard", "storyboard-film", "upload", "app:app-step-up"]) {+ expect(isHelperFeature(f), f).toBe(false);+ }+ });++ it("leaves helper steps out of lists that don't name their features, as the server does", () => {+ const step = gen({ feature: "shorts-step" });+ expect(matchesFilter(step, {})).toBe(false);+ expect(matchesFilter(step, { kinds: ["image"] })).toBe(false);+ expect(matchesFilter(step, { steps: true })).toBe(true);+ // A studio reading its own steps names them.+ expect(matchesFilter(gen({ feature: "mixed-media-step" }), { features: ["mixed-media", "mixed-media-step"] })).toBe(true);+ expect(matchesFilter(step, { features: ["shorts*"] })).toBe(true);+ // The live stream doesn't slip one into the home feed or the Library.+ const list = [gen()];+ expect(applyToList(list, { limit: 6 }, ev(step))).toBe(list);+ expect(applyToList(list, { limit: 6, steps: true }, ev(step))).toHaveLength(2);+ expect(filterToSearch({ steps: true }).get("steps")).toBe("1");+ expect(filterToSearch({}).get("steps")).toBeNull();+ });++ it("keeps pinned results in their own list, most recently pinned first", () => {+ const a = gen({ id: "pa", pinnedAt: 100 });+ const b = gen({ id: "pb", pinnedAt: 300 });+ const c = gen({ id: "pc", pinnedAt: null });+ expect(matchesFilter(a, { pinned: true })).toBe(true);+ expect(matchesFilter(c, { pinned: true })).toBe(false);+ expect(matchesFilter(a, { pinned: false })).toBe(false);+ expect(matchesFilter(c, { pinned: false })).toBe(true);+ expect(matchesFilter(c, {})).toBe(true);+ expect([a, b].sort(byPinned).map((g) => g.id)).toEqual(["pb", "pa"]);+ expect(cursorAfter(a, { pinned: true })).toBe("100:pa");+ expect(cursorAfter(a, {})).toBe(`${a.createdAt}:pa`);+ expect(filterToSearch({ pinned: true }).get("pinned")).toBe("1");+ expect(filterToSearch({ pinned: false }).get("pinned")).toBe("0");+ // Pinning moves a card from the main list to the pinned list (in pin order); unpinning moves it back.+ const pinnedList = [b, a];+ const pinnedC = { ...c, pinnedAt: 200, updatedAt: c.updatedAt + 1 };+ expect(applyToList(pinnedList, { pinned: true }, ev(pinnedC))!.map((g) => g.id)).toEqual(["pb", "pc", "pa"]);+ expect(applyToList([c], { pinned: false }, ev(pinnedC))).toEqual([]);+ expect(applyToList(pinnedList, { pinned: true }, ev({ ...a, pinnedAt: null, updatedAt: a.updatedAt + 1 }))!.map((g) => g.id)).toEqual(["pb"]);+ });++ it("filters by review status, with “none” for results without one", () => {+ const ok = gen({ review: "approved" });+ const none = gen({ review: null });+ expect(matchesFilter(ok, { reviews: ["approved"] })).toBe(true);+ expect(matchesFilter(ok, { reviews: ["rejected", "needs-review"] })).toBe(false);+ expect(matchesFilter(none, { reviews: ["none"] })).toBe(true);+ expect(matchesFilter(ok, { reviews: ["none"] })).toBe(false);+ expect(filterToSearch({ reviews: ["approved", "none"] }).get("reviews")).toBe("approved,none");+ expect(filterToSearch({ folderIds: ["a", "b"] }).get("folders")).toBe("a,b");+ expect(matchesFilter(gen({ folderId: "b" }), { folderIds: ["a", "b"] })).toBe(true);+ expect(matchesFilter(gen({ folderId: null }), { folderIds: ["a", "b"] })).toBe(false);+ });++ it("offers Pin and Review on results, and a checked Delete on uploads", () => {+ const ids = (g: Generation) => outputActions(g, 0).map((a) => a.id);+ expect(outputActions(gen(), 0).find((a) => a.id === "pin")?.label).toBe("Pin to top");+ expect(outputActions(gen({ pinnedAt: 5 }), 0).find((a) => a.id === "pin")?.label).toBe("Unpin");+ expect(ids(gen())).toContain("review");+ expect(ids(gen({ deletedAt: 5 }))).not.toContain("pin");+ const upload = gen({ feature: "upload" });+ expect(ids(upload)).toContain("delete-upload");+ expect(ids(upload)).not.toContain("pin");+ expect(ids(upload)).not.toContain("review");+ });++ const folder = (id: string, parentId: string | null, p: Partial<Folder> = {}): Folder => ({+ id,+ name: id.toUpperCase(),+ color: "lime",+ count: 0,+ folders: 0,+ cover: null,+ parentId,+ pinnedAt: null,+ createdAt: 1,+ updatedAt: 1,+ ...p,+ });+ // a ─ b ─ c, a ─ d; e at the root+ const tree = [folder("a", null, { createdAt: 1 }), folder("b", "a", { createdAt: 2 }), folder("c", "b"), folder("d", "a", { createdAt: 3 }), folder("e", null, { createdAt: 2 })];++ it("walks nested folders: children, breadcrumbs, subtrees, tree order", () => {+ expect(childFolders(tree, null).map((f) => f.id)).toEqual(["a", "e"]);+ expect(childFolders(tree, "a").map((f) => f.id)).toEqual(["b", "d"]);+ // Pinned first, in the order they were pinned.+ const pinned = tree.map((f) => (f.id === "e" ? { ...f, pinnedAt: 9 } : f.id === "d" ? { ...f, pinnedAt: 5 } : f));+ expect(childFolders(pinned, null).map((f) => f.id)).toEqual(["e", "a"]);+ expect(childFolders(pinned, "a").map((f) => f.id)).toEqual(["d", "b"]);+ expect(folderPath(tree, "c").map((f) => f.id)).toEqual(["a", "b", "c"]);+ expect(folderPath(tree, "gone")).toEqual([]);+ // A loop in bad data doesn't hang the breadcrumbs.+ expect(folderPath([folder("x", "y"), folder("y", "x")], "x").map((f) => f.id)).toEqual(["y", "x"]);+ expect(folderAndDescendants(tree, "a").sort()).toEqual(["a", "b", "c", "d"]);+ expect(folderAndDescendants(tree, "c")).toEqual(["c"]);+ expect(folderTree(tree).map(({ folder: f, depth }) => `${f.id}${depth}`)).toEqual(["a0", "b1", "c2", "d1", "e0"]);+ });++ it("refuses folder moves that would loop or nest too deep, in Higgsfield's words", () => {+ expect(folderMoveError(tree, "a", "a")).toBe("Cannot move into itself");+ expect(folderMoveError(tree, "a", "c")).toBe("Cannot move into a subfolder");+ expect(folderMoveError(tree, "a", "b")).toBe("Cannot move into a subfolder");+ expect(folderMoveError(tree, "b", "a")).toBe("Already in this folder");+ expect(folderMoveError(tree, "a", null)).toBe("Already in this folder");+ expect(folderMoveError(tree, "gone", null)).toBe("That folder doesn't exist anymore");+ expect(folderMoveError(tree, "a", "gone")).toBe("That folder doesn't exist anymore");+ expect(folderMoveError(tree, "a", "e")).toBeNull();+ expect(folderMoveError(tree, "c", null)).toBeNull();+ expect(folderMoveError(tree, "d", "c")).toBeNull();+ // A chain MAX_FOLDER_DEPTH deep can't take another level below its last folder, nor a 2-level subtree lower down.+ const chain = Array.from({ length: MAX_FOLDER_DEPTH }, (_, i) => folder(`l${i}`, i ? `l${i - 1}` : null));+ expect(folderMoveError([...chain, folder("z", null)], "z", `l${MAX_FOLDER_DEPTH - 1}`)).toMatch(/levels deep/);+ expect(folderMoveError([...chain, folder("z", null)], "z", `l${MAX_FOLDER_DEPTH - 2}`)).toBeNull();+ expect(folderMoveError([...chain, folder("z", null), folder("z2", "z")], "z", `l${MAX_FOLDER_DEPTH - 2}`)).toMatch(/levels deep/);+ });++ it("names folders that move up next to a namesake, and folder paths inside a zip", () => {+ expect(freeName("Drafts", ["Shots"])).toBe("Drafts");+ expect(freeName("Drafts", ["drafts", "Drafts 2"])).toBe("Drafts 3");+ expect(zipSegment("Spring / Summer")).toBe("Spring - Summer");+ expect(zipSegment('a<b>:"c|?*')).toBe("abc");+ expect(zipSegment("..")).toBe("Folder");+ expect(zipSegment(" ")).toBe("Folder");+ });++ it("says where a file is used, in one line", () => {+ expect(describeUses([])).toBe("");+ expect(describeUses([{ what: "result", key: "g1", name: null }])).toBe("1 result");+ expect(+ describeUses([+ { what: "result", key: "g1", name: "a fox" },+ { what: "result", key: "g2", name: null, trashed: true },+ { what: "element", key: "c1", name: "Maya" },+ // A chat found in two tables is one chat.+ { what: "Assist chat", key: "t1", name: "Posters" },+ { what: "Assist chat", key: "t1", name: "Posters" },+ { what: "canvas", key: "k1", name: "A" },+ { what: "canvas", key: "k2", name: "B" },+ ]),+ ).toBe("2 results (1 in the Trash), the element “Maya”, the Assist chat “Posters” and 2 canvases");+ expect(describeUses([{ what: "result", key: "g", name: "x", trashed: true }])).toBe("the result “x” (in the Trash)");+ });+});