Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

feat(media): bulk actions on a collection + implicit Unsorted collection + per-card file delete

Adam Eivya7da2eceb2be
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index fe443dfbd0..3de6cf0ef8 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -24,6 +24,12 @@
- **Organize from the lightbox + from inside a collection.** `MediaLightbox` footer now hosts an Add-to-collection (folder+) button alongside Download — pick a collection (or create one) without closing the larger preview. `MediaCollectionDetail` cards no longer suppress the same menu, so you can move/copy an item between collections from inside any collection view. `AddToCollectionMenu` gained a `size` prop (`sm` default for the card action row, `md` for the lightbox footer) so both surfaces share one component without duplicate styling, and long collection names in the picker now wrap instead of getting clipped with ellipsis. `browser/data/` is now gitignored (CDP profile cache shouldn't be tracked).
+- **Bulk actions on a collection's contents.** A new "Select" button on `/media/collections/:id` flips the grid into selection mode — click cards to add to the selection, then act on the lot via a sticky toolbar: **Star** / **Unstar** all selected, **Move…** or **Copy…** to a target collection (pick from a popover anchored to the button, or create a new collection inline), **Remove** from the current collection without deleting the underlying file. Move/Copy guarantees data integrity by tracking which items actually placed in the target before removing them from the source. Sequential per-item HTTP because the server has no per-collection lock; PLAN.md tracks a bulk endpoint for the inevitable 50+-item case.
+
+- **Implicit "Unsorted" collection.** Every image or video that isn't filed in at least one real collection now shows up under a synthetic "Unsorted" entry pinned at the top of `/media/collections` (Inbox icon, accent border, count + thumbnail). Open it to browse the unfiled media at `/media/collections/unsorted` — same grid, same lightbox, same bulk-action bar (Move… is relabeled "File…" since there's no source-side remove). Cover / rename / Copy / Remove are hidden because they're nonsensical for a synthetic source. After filing items into a real collection from here, the view re-derives and the now-filed items disappear automatically. Implementation is fully client-side — `client/src/lib/unsorted.js#buildUnsortedCollection` projects the union of `listImageGallery` + `listVideoHistory` minus every filed `<kind>:<ref>` key — so no new server route was needed.
+
+- **Per-card trash in a collection now deletes the underlying file** (matches MediaHistory) instead of just unfiling it from the current collection. To unfile without deleting, the user can either uncheck the current collection via the folder+ menu, or select the item in select mode and use the bulk **Remove** action. Re-enabled on the Unsorted view too, since "delete the file" makes sense there even though "remove from collection" doesn't.
+
- **World Builder batch render reuses one collection per world.** Auto-generated collection names drop the ` — YYYY-MM-DD HH:MM` suffix: a batch render of "Echoes of the Choir" now files into `World: Echoes of the Choir` every time instead of minting a fresh date-stamped bucket. A user-supplied `collectionName` also flows through find-or-create (case-insensitive trimmed match), so repeat renders into a custom name append into the same collection. Backed by a new `findOrCreateCollectionByName()` helper in `server/services/mediaCollections.js`. One-shot migration at `data/migrations/001-merge-worldbuilder-collections.js` collapses legacy date-suffixed `World: <name> — <date>` collections into their base name (dedupes items by `kind:ref`, preserves the earliest `createdAt`, rewrites `world-builder.json` `runs[].collectionId` references). Run via `npm run migrations`; idempotent.
- **Clean → Light / Aggressive available beyond Image Gen.** The Eraser pill that strips render artifacts now appears in any image lightbox: Media History and Media Collection Detail both wire `onClean` into `MediaLightbox`. Cleaning from inside a collection automatically adds the cleaned file to that collection alongside the original, so the user can compare side-by-side before deciding which to keep. (Image Gen behaviour unchanged; Video Gen's lightbox only renders videos so it intentionally doesn't expose Clean.)
- **MediaCard thumbnails.** Removed the "IMAGE"/"VIDEO" badge overlay from the bottom-right of media cards — the icon and aspect already convey the kind, and the badge added visual noise on grid views.
diff --git a/PLAN.md b/PLAN.md
index 1da034c317..8cfe56e5c5 100644
--- a/PLAN.md
+++ b/PLAN.md
@@ -48,6 +48,8 @@ The dgrauet/ltx-2-mlx runtime ships with FFLF (true keyframe interpolation), aud
- [ ] **Extract `mockPathsDataRoot()` test helper** — `server/lib/storyBible.test.js`, `server/services/writersRoom/{characters,settings,objects,local,promoteToPipeline}.test.js` (6 files) all open with byte-identical setup: `let tempRoot; vi.mock('../../lib/fileUtils.js', async () => { const actual = await vi.importActual(...); return new Proxy(actual, { get(t,p){ if (p==='PATHS') return new Proxy(actual.PATHS,{get(tp,pp){ if(pp==='data') return tempRoot; ... }}); ... } }); }); beforeEach(() => { tempRoot = mkdtempSync(...) }); afterEach(() => rmSync(tempRoot, { recursive: true, force: true }))`. Extract into `server/test-utils/tempDataRoot.js` exposing `mockPathsDataRoot()` that returns a live tempRoot getter. ~20 LOC saved per file plus a single fix-point if PATHS mocking semantics ever change. Surfaced from the bibleStore-factory /simplify pass.
- [ ] **Widen `spawningTasks` try/finally in `agentLifecycle.js#spawnAgentForTask`** — pre-existing bug surfaced during /do:review. Today's try/finally (`server/services/agentLifecycle.js:536-547`) only wraps the spawn call itself. Between `spawningTasks.add(task.id)` (line 134) and the try-block, the function does ~400 lines of async work — `buildAgentPrompt`, `writeFile(prompt)`, `createAgentRun`, `registerAgent`, etc. — each of which can throw (ENOSPC, EACCES, network). A throw on any of those paths leaves `spawningTasks` registered FOREVER, permanently blocking future spawns of that task id. The detected-error paths call `cleanupOnError` which does delete, but an unhandled throw is the gap. Fix: hoist the try/finally up to wrap from line 134 (after `add`) through the spawn calls. `cleanupOnError`'s redundant `spawningTasks.delete` becomes a no-op (Set.delete on absent key) which is fine. Pre-existing bug, not introduced by the dedup-race fix.
- [ ] **`useAsyncAction` post-unmount setState guard** — the hook in `client/src/hooks/useAsyncAction.js` calls `setRunning(false)` after an awaited async fn resolves. If the owning component unmounts mid-action, React 18 silently warns; React 17 surfaces the warning. Add a `mountedRef` (set true in mount effect, false in cleanup) and gate `setRunning(false)` on `mountedRef.current`. YAGNI for current call sites (all stable parent components) but worth doing once the hook gains a 4th consumer or any consumer that unmounts during long-running ops. Surfaced from /do:review.
+- [ ] **Extract `CollectionPickerShell` from `AddToCollectionMenu` + `BulkTargetPicker`** — both files (`client/src/components/media/AddToCollectionMenu.jsx`, `client/src/components/media/BulkTargetPicker.jsx`) own a near-identical portal popover: same `MENU_WIDTH/GAP/VIEWPORT_PADDING/SEARCH_THRESHOLD` constants, line-for-line identical reposition math, identical click-away + Esc + rAF-scroll effects, identical "new collection" footer form. The only differences are local to the list row (membership-toggle w/ check vs single-pick) and the create-success path (add-after-create vs pick-after-create). Extract `<CollectionPickerShell anchorRef, title, busy, onClose, renderRow, onCreate>` that owns positioning/portal/search/create-form; each picker becomes a ~40-line `renderRow` function. Two files isn't a fire; a third would force this. While extracting, also accept a `collections` prop (optional, falls back to internal fetch) so `MediaCollectionDetail` can pass its already-fetched list and avoid the per-mount `listMediaCollections` round-trip when the user toggles Move/Copy. Surfaced from the bulk-actions /simplify pass.
+- [ ] **Server-side bulk endpoint for collection items** — `MediaCollectionDetail`'s bulk Move/Copy/Remove currently makes N sequential HTTP calls (server has no per-collection lock, so parallel writes would lose updates on the JSON read-modify-write). At ~30ms localhost RTT, 20 items ≈ 600ms; 50 items ≈ 1.5s (move = 2 × that). The user's stated use case is "select all" on a world-builder collection that could legitimately have 50+ items. Add `POST /api/media/collections/:id/items/bulk` taking `{ add: [{kind,ref}], remove: [key] }` and doing one read-modify-write per collection. Halves wall-clock for Move (single source-side commit instead of N), dodges the race window entirely. Surfaced from the bulk-actions /simplify pass.
- [ ] **Drop legacy `description` fallback in `sanitizeCharacter`** — `server/lib/storyBible.js:130` carries an inline `TODO(item-4): drop the description fallback once pipeline characters extract natively.` Item 4 (shared bible-extraction service) shipped 2026-05-10 — extraction now writes the canonical `physicalDescription` field directly. Plan: write a one-shot migration that rewrites every `series.characters[].description` → `physicalDescription` in `data/pipeline-series.json` (idempotent: skip entries that already have `physicalDescription`), drop the `|| raw.description` fallback at `storyBible.js:137`, and remove the TODO comment. Audit `data.sample/` + tests for any remaining `description` reads before merging.
### Civitai LoRA / Z-Image-Turbo follow-ups (from /simplify pass)
diff --git a/client/src/components/media/AddToCollectionMenu.jsx b/client/src/components/media/AddToCollectionMenu.jsx
index d1a77cd96f..34ed47294c 100644
--- a/client/src/components/media/AddToCollectionMenu.jsx
+++ b/client/src/components/media/AddToCollectionMenu.jsx
@@ -37,7 +37,7 @@ export default function AddToCollectionMenu({ item, size = 'sm' }) {
const triggerRef = useRef(null);
const menuRef = useRef(null);
- const itemKey = `${item.kind}:${item.kind === 'video' ? item.id : item.filename}`;
+ const itemKey = item.key;
const itemRef = item.kind === 'video' ? item.id : item.filename;
const filtered = useMemo(() => {
diff --git a/client/src/components/media/BulkTargetPicker.jsx b/client/src/components/media/BulkTargetPicker.jsx
new file mode 100644
index 0000000000..a9974896cd
--- /dev/null
+++ b/client/src/components/media/BulkTargetPicker.jsx
@@ -0,0 +1,185 @@
+import { useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
+import { createPortal } from 'react-dom';
+import { Plus, Search } from 'lucide-react';
+import toast from '../ui/Toast';
+import { listMediaCollections, createMediaCollection } from '../../services/api';
+
+// Single-target picker used by MediaCollectionDetail's bulk-action bar.
+// AddToCollectionMenu toggles membership for one item across many collections;
+// this picker is the inverse — one click picks a destination for many items.
+//
+// Sibling-component prior art (AddToCollectionMenu) handles popover positioning
+// the same way: portal into body, fixed coords, recompute on scroll/resize.
+
+const MENU_WIDTH = 260;
+const MENU_GAP = 6;
+const VIEWPORT_PADDING = 8;
+const SEARCH_THRESHOLD = 6;
+
+export default function BulkTargetPicker({
+ anchorRef,
+ excludeId,
+ busy,
+ title = 'Pick a collection',
+ onPick,
+ onClose,
+}) {
+ const [collections, setCollections] = useState(null);
+ const [query, setQuery] = useState('');
+ const [creating, setCreating] = useState(false);
+ const [newName, setNewName] = useState('');
+ const [style, setStyle] = useState(null);
+ const menuRef = useRef(null);
+ // Parent passes inline arrows for onClose; reading it through a ref keeps
+ // the listener effect from tearing down + re-attaching every parent render.
+ const onCloseRef = useRef(onClose);
+ useEffect(() => { onCloseRef.current = onClose; });
+
+ const filtered = useMemo(() => {
+ if (!collections) return null;
+ const base = excludeId ? collections.filter((c) => c.id !== excludeId) : collections;
+ const q = query.trim().toLowerCase();
+ return q ? base.filter((c) => c.name.toLowerCase().includes(q)) : base;
+ }, [collections, query, excludeId]);
+
+ useEffect(() => {
+ listMediaCollections().then(
+ (data) => setCollections(Array.isArray(data) ? data : []),
+ (err) => { toast.error(err?.message || 'Failed to load collections'); setCollections([]); },
+ );
+ }, []);
+
+ const reposition = () => {
+ const trigger = anchorRef?.current;
+ const menu = menuRef.current;
+ if (!trigger || !menu) return;
+ const vw = window.innerWidth;
+ const vh = window.innerHeight;
+ const width = Math.min(MENU_WIDTH, Math.max(200, vw - VIEWPORT_PADDING * 2));
+ menu.style.width = `${width}px`;
+ const tr = trigger.getBoundingClientRect();
+ const mr = menu.getBoundingClientRect();
+ const maxLeft = vw - width - VIEWPORT_PADDING;
+ const left = Math.min(Math.max(tr.right - width, VIEWPORT_PADDING), Math.max(VIEWPORT_PADDING, maxLeft));
+ const above = tr.top - mr.height - MENU_GAP;
+ const below = tr.bottom + MENU_GAP;
+ const top = above < VIEWPORT_PADDING ? below : above;
+ const maxTop = Math.max(VIEWPORT_PADDING, vh - mr.height - VIEWPORT_PADDING);
+ const clampedTop = Math.min(Math.max(top, VIEWPORT_PADDING), maxTop);
+ setStyle({ left: `${left}px`, top: `${clampedTop}px`, width: `${width}px` });
+ };
+
+ useLayoutEffect(reposition, [filtered, excludeId]);
+ useEffect(() => {
+ const close = () => onCloseRef.current?.();
+ const onKey = (e) => { if (e.key === 'Escape') close(); };
+ const onAway = (e) => {
+ const onTrigger = anchorRef?.current?.contains(e.target);
+ const onMenu = menuRef.current?.contains(e.target);
+ if (!onTrigger && !onMenu) close();
+ };
+ let raf = null;
+ const onScroll = () => { if (raf !== null) return; raf = requestAnimationFrame(() => { raf = null; reposition(); }); };
+ document.addEventListener('keydown', onKey);
+ document.addEventListener('mousedown', onAway);
+ window.addEventListener('resize', onScroll);
+ window.addEventListener('scroll', onScroll, true);
+ return () => {
+ if (raf !== null) cancelAnimationFrame(raf);
+ document.removeEventListener('keydown', onKey);
+ document.removeEventListener('mousedown', onAway);
+ window.removeEventListener('resize', onScroll);
+ window.removeEventListener('scroll', onScroll, true);
+ };
+ }, []);
+
+ const handleCreate = async (e) => {
+ e.preventDefault();
+ const name = newName.trim();
+ if (!name) return;
+ setCreating(true);
+ const created = await createMediaCollection({ name }).catch((err) => {
+ toast.error(err?.message || 'Create failed');
+ return null;
+ });
+ setCreating(false);
+ if (!created) return;
+ setNewName('');
+ onPick(created.id, created.name);
+ };
+
+ const showSearch = (collections?.length || 0) >= SEARCH_THRESHOLD;
+ const list = filtered ?? collections;
+
+ return createPortal(
+ <div
+ ref={menuRef}
+ role="menu"
+ className="fixed bg-port-card border border-port-border rounded-lg shadow-xl z-[100] p-1.5 flex flex-col"
+ style={{
+ left: style?.left ?? `${VIEWPORT_PADDING}px`,
+ top: style?.top ?? `${VIEWPORT_PADDING}px`,
+ width: style?.width ?? `${MENU_WIDTH}px`,
+ maxHeight: 'min(360px, calc(100vh - 16px))',
+ visibility: style ? 'visible' : 'hidden',
+ }}
+ onClick={(e) => e.stopPropagation()}
+ >
+ <div className="text-[10px] text-gray-500 uppercase tracking-wide px-1 pt-1 pb-1.5 shrink-0">{title}</div>
+ {showSearch && (
+ <div className="relative shrink-0 mb-1.5">
+ <Search className="absolute left-2 top-1/2 -translate-y-1/2 w-3 h-3 text-gray-500 pointer-events-none" />
+ <input
+ type="text"
+ value={query}
+ onChange={(e) => setQuery(e.target.value)}
+ placeholder="Search collections…"
+ className="w-full bg-port-bg border border-port-border rounded pl-7 pr-2 py-1 text-[11px] text-white focus:outline-none focus:border-port-accent"
+ autoFocus
+ />
+ </div>
+ )}
+ <div className="flex-1 min-h-0 overflow-y-auto">
+ {collections == null && <div className="text-[11px] text-gray-500 px-2 py-2">Loading…</div>}
+ {collections != null && list?.length === 0 && (
+ <div className="text-[11px] text-gray-500 px-2 py-2">
+ {query ? `No matches for "${query}"` : 'No other collections — create one below.'}
+ </div>
+ )}
+ {list?.map((c) => (
+ <button
+ key={c.id}
+ type="button"
+ disabled={busy}
+ onClick={() => onPick(c.id, c.name)}
+ className="w-full flex items-center gap-2 px-2 py-1.5 text-left text-[12px] text-gray-200 hover:bg-port-border rounded disabled:opacity-50"
+ role="menuitem"
+ >
+ <span className="break-words min-w-0 flex-1">{c.name}</span>
+ <span className="text-[10px] text-gray-500 shrink-0">{c.items?.length ?? 0}</span>
+ </button>
+ ))}
+ </div>
+ <form onSubmit={handleCreate} className="mt-1.5 pt-1.5 border-t border-port-border flex gap-1 shrink-0">
+ <input
+ type="text"
+ value={newName}
+ onChange={(e) => setNewName(e.target.value)}
+ placeholder="New collection"
+ maxLength={80}
+ disabled={busy}
+ className="flex-1 bg-port-bg border border-port-border rounded px-2 py-1 text-[11px] text-white focus:outline-none focus:border-port-accent disabled:opacity-50"
+ />
+ <button
+ type="submit"
+ disabled={creating || busy || !newName.trim()}
+ className="px-2 py-1 bg-port-accent/20 hover:bg-port-accent/40 text-port-accent text-[11px] rounded disabled:opacity-40 flex items-center gap-1"
+ title="Create and pick"
+ >
+ <Plus className="w-3 h-3" />
+ </button>
+ </form>
+ </div>,
+ document.body,
+ );
+}
diff --git a/client/src/lib/unsorted.js b/client/src/lib/unsorted.js
new file mode 100644
index 0000000000..7fd4914507
--- /dev/null
+++ b/client/src/lib/unsorted.js
@@ -0,0 +1,41 @@
+// Synthetic "Unsorted" collection: every image/video that isn't filed in at
+// least one real collection. Derived client-side from the three list
+// endpoints that both /media/collections and /media/collections/:id already
+// fetch, so no new server route is required.
+
+export const UNSORTED_ID = 'unsorted';
+
+export function buildUnsortedCollection(collections, images, videos) {
+ const filed = new Set();
+ for (const c of collections || []) {
+ for (const it of c.items || []) {
+ filed.add(`${it.kind}:${it.ref}`);
+ }
+ }
+ const items = [];
+ for (const img of images || []) {
+ if (!img?.filename) continue;
+ const key = `image:${img.filename}`;
+ if (!filed.has(key)) {
+ items.push({ kind: 'image', ref: img.filename, addedAt: img.createdAt });
+ }
+ }
+ for (const vid of videos || []) {
+ if (!vid?.id) continue;
+ const key = `video:${vid.id}`;
+ if (!filed.has(key)) {
+ items.push({ kind: 'video', ref: vid.id, addedAt: vid.createdAt });
+ }
+ }
+ items.sort((a, b) => new Date(b.addedAt || 0) - new Date(a.addedAt || 0));
+ return {
+ id: UNSORTED_ID,
+ name: 'Unsorted',
+ description: 'Media not in any collection',
+ items,
+ coverKey: null,
+ synthetic: true,
+ createdAt: null,
+ updatedAt: null,
+ };
+}
diff --git a/client/src/pages/MediaCollectionDetail.jsx b/client/src/pages/MediaCollectionDetail.jsx
index aa50eeb055..ec565261ee 100644
--- a/client/src/pages/MediaCollectionDetail.jsx
+++ b/client/src/pages/MediaCollectionDetail.jsx
@@ -1,16 +1,20 @@
-import { useCallback, useEffect, useMemo, useState } from 'react';
+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useParams, Link, useNavigate } from 'react-router-dom';
-import { ArrowLeft, Pencil, Star } from 'lucide-react';
+import { ArrowLeft, CheckSquare, Copy, FolderInput, Inbox, Pencil, Star, StarOff, Trash2, X } from 'lucide-react';
import toast from '../components/ui/Toast';
import MediaCard from '../components/media/MediaCard';
import MediaLightbox from '../components/media/MediaLightbox';
+import BulkTargetPicker from '../components/media/BulkTargetPicker';
import { normalizeImage, normalizeVideo } from '../components/media/normalize';
import { useMediaAnnotations } from '../hooks/useMediaAnnotations';
+import { UNSORTED_ID, buildUnsortedCollection } from '../lib/unsorted';
import {
getMediaCollection, updateMediaCollection,
+ listMediaCollections,
addMediaCollectionItem, removeMediaCollectionItem,
listImageGallery, listVideoHistory,
extractLastFrame, cleanGalleryImage,
+ deleteImage, deleteVideoHistoryItem,
} from '../services/api';
// Hydrate a collection's "<kind>:<ref>" pointer list into the same
@@ -36,6 +40,7 @@ const hydrate = (collection, imagesByName, videosById) => {
export default function MediaCollectionDetail() {
const { id } = useParams();
+ const isUnsorted = id === UNSORTED_ID;
const navigate = useNavigate();
const [collection, setCollection] = useState(null);
const [imagesByName, setImagesByName] = useState(new Map());
@@ -44,10 +49,29 @@ export default function MediaCollectionDetail() {
const [editingName, setEditingName] = useState(false);
const [nameDraft, setNameDraft] = useState('');
const [preview, setPreview] = useState(null);
+ const [selectMode, setSelectMode] = useState(false);
+ const [selected, setSelected] = useState(new Set());
+ const [bulkBusy, setBulkBusy] = useState(false);
+ // 'move' = add to target + remove from current; 'copy' = add only.
+ const [pickerMode, setPickerMode] = useState(null);
+ const moveBtnRef = useRef(null);
+ const copyBtnRef = useRef(null);
const { annotations, toggleStar, updateAnnotation } = useMediaAnnotations();
const refresh = useCallback(async () => {
setLoading(true);
+ if (isUnsorted) {
+ const [cols, images, videos] = await Promise.all([
+ listMediaCollections().catch(() => []),
+ listImageGallery().catch(() => []),
+ listVideoHistory().catch(() => []),
+ ]);
+ setCollection(buildUnsortedCollection(cols, images, videos));
+ setImagesByName(new Map((images || []).map((i) => [i.filename, i])));
+ setVideosById(new Map((videos || []).map((v) => [v.id, v])));
+ setLoading(false);
+ return;
+ }
const [c, images, videos] = await Promise.all([
getMediaCollection(id).catch((err) => {
toast.error(err.message || 'Collection not found');
@@ -61,7 +85,7 @@ export default function MediaCollectionDetail() {
setImagesByName(new Map((images || []).map((i) => [i.filename, i])));
setVideosById(new Map((videos || []).map((v) => [v.id, v])));
setLoading(false);
- }, [id]);
+ }, [id, isUnsorted]);
useEffect(() => { refresh(); }, [refresh]);
const items = useMemo(
@@ -83,8 +107,7 @@ export default function MediaCollectionDetail() {
};
const handleSetCover = async (item) => {
- const key = `${item.kind}:${item.kind === 'video' ? item.id : item.filename}`;
- const next = collection.coverKey === key ? null : key;
+ const next = collection.coverKey === item.key ? null : item.key;
const updated = await updateMediaCollection(collection.id, { coverKey: next }).catch((err) => {
toast.error(err.message || 'Failed to set cover');
return null;
@@ -95,13 +118,116 @@ export default function MediaCollectionDetail() {
}
};
- const handleRemove = async (item) => {
- const key = `${item.kind}:${item.kind === 'video' ? item.id : item.filename}`;
- const updated = await removeMediaCollectionItem(collection.id, key).catch((err) => {
- toast.error(err.message || 'Remove failed');
+ // Per-card trash deletes the underlying file (matches MediaHistory). To
+ // unfile an item from a single collection without deleting it, the user
+ // either un-checks the current collection via the folder+ menu, or selects
+ // it in select-mode and uses the bulk "Remove" action. Dropping the file
+ // from the local image/video maps makes `hydrate()` filter it out of every
+ // collection view at once — server-side `collection.items[]` may briefly
+ // hold a dangling ref until the next mutation rewrites the file.
+ const handleDelete = async (item) => {
+ const ok = await (item.kind === 'image'
+ ? deleteImage(item.filename)
+ : deleteVideoHistoryItem(item.id)
+ ).catch((err) => {
+ toast.error(err.message || 'Delete failed');
return null;
});
- if (updated) setCollection(updated);
+ if (!ok) return;
+ if (item.kind === 'image') {
+ setImagesByName((m) => {
+ const next = new Map(m);
+ next.delete(item.filename);
+ return next;
+ });
+ } else {
+ setVideosById((m) => {
+ const next = new Map(m);
+ next.delete(item.id);
+ return next;
+ });
+ }
+ toast.success(`Deleted ${item.kind === 'image' ? item.filename : 'video'}`);
+ };
+
+ // Unordered membership — Set, not array.
+ const toggleSelect = (key) => setSelected((prev) => {
+ const next = new Set(prev);
+ if (next.has(key)) next.delete(key); else next.add(key);
+ return next;
+ });
+ const exitSelectMode = () => { setSelectMode(false); setSelected(new Set()); setPickerMode(null); };
+ const selectedItems = useMemo(
+ () => items.filter((it) => selected.has(it.key)),
+ [items, selected],
+ );
+
+ // Sequential — annotations and collections both do read-modify-write of a
+ // single JSON file with no per-record lock; parallel writes lose updates.
+ const bulkStar = async (starred) => {
+ if (selectedItems.length === 0) return;
+ setBulkBusy(true);
+ for (const it of selectedItems) {
+ await updateAnnotation(it.key, { starred });
+ }
+ setBulkBusy(false);
+ toast.success(`${starred ? 'Favorited' : 'Unfavorited'} ${selectedItems.length} item${selectedItems.length === 1 ? '' : 's'}`);
+ };
+
+ const bulkRemove = async () => {
+ if (selectedItems.length === 0) return;
+ setBulkBusy(true);
+ let lastOk = null;
+ let failed = 0;
+ for (const it of selectedItems) {
+ const r = await removeMediaCollectionItem(collection.id, it.key, { silent: true }).catch(() => null);
+ if (r) lastOk = r; else failed++;
+ }
+ if (lastOk) setCollection(lastOk);
+ setBulkBusy(false);
+ exitSelectMode();
+ if (failed) toast.error(`Removed ${selectedItems.length - failed}; ${failed} failed`);
+ else toast.success(`Removed ${selectedItems.length} item${selectedItems.length === 1 ? '' : 's'} from "${collection.name}"`);
+ };
+
+ const bulkMoveOrCopy = async (targetId, targetName) => {
+ if (selectedItems.length === 0 || !pickerMode) return;
+ const mode = pickerMode;
+ setPickerMode(null);
+ setBulkBusy(true);
+ const placedKeys = new Set();
+ let added = 0;
+ let dupes = 0;
+ for (const it of selectedItems) {
+ const ref = it.kind === 'video' ? it.id : it.filename;
+ const r = await addMediaCollectionItem(targetId, { kind: it.kind, ref }, { silent: true }).catch((err) => {
+ if (err?.code === 'DUPLICATE') { dupes++; placedKeys.add(it.key); return 'dupe'; }
+ return null;
+ });
+ if (r && r !== 'dupe') { added++; placedKeys.add(it.key); }
+ }
+ if (mode === 'move' && placedKeys.size > 0) {
+ if (isUnsorted) {
+ // Source is synthetic — placing items in any real collection takes
+ // them out of Unsorted automatically. Just re-derive the view.
+ await refresh();
+ } else {
+ let lastOk = null;
+ for (const it of selectedItems) {
+ if (!placedKeys.has(it.key)) continue;
+ const r = await removeMediaCollectionItem(collection.id, it.key, { silent: true }).catch(() => null);
+ if (r) lastOk = r;
+ }
+ if (lastOk) setCollection(lastOk);
+ }
+ }
+ setBulkBusy(false);
+ exitSelectMode();
+ const verb = mode === 'move' ? (isUnsorted ? 'Filed' : 'Moved') : 'Copied';
+ const note = dupes > 0 ? ` (${dupes} already there)` : '';
+ const stranded = selectedItems.length - added - dupes;
+ if (stranded > 0) toast.error(`${verb} ${added} to "${targetName}"${note}; ${stranded} failed`);
+ else toast.success(`${verb} ${added} to "${targetName}"${note}`);
};
// Image-Gen "Remix" and "Send to Video" piping — same patterns as
@@ -158,69 +284,200 @@ export default function MediaCollectionDetail() {
</div>
);
+ const renderTitle = () => {
+ if (isUnsorted) return (
+ <h1 className="text-xl font-semibold text-white flex items-center gap-2">
+ <Inbox className="w-5 h-5 text-port-accent" />
+ {collection.name}
+ </h1>
+ );
+ if (editingName) return (
+ <input
+ autoFocus
+ type="text"
+ value={nameDraft}
+ onChange={(e) => setNameDraft(e.target.value)}
+ onBlur={handleRename}
+ onKeyDown={(e) => {
+ if (e.key === 'Enter') handleRename();
+ if (e.key === 'Escape') { setNameDraft(collection.name); setEditingName(false); }
+ }}
+ maxLength={80}
+ className="text-xl font-semibold bg-port-card border border-port-border rounded px-2 py-1 text-white focus:outline-none focus:border-port-accent"
+ />
+ );
+ return (
+ <button type="button" onClick={() => setEditingName(true)} className="text-xl font-semibold text-white hover:text-port-accent flex items-center gap-2">
+ {collection.name}
+ <Pencil className="w-4 h-4 text-gray-500" />
+ </button>
+ );
+ };
+
return (
<div className="space-y-4">
<div className="flex items-center gap-3">
<Link to="/media/collections" className="text-gray-400 hover:text-white" title="Back">
<ArrowLeft className="w-5 h-5" />
</Link>
- {editingName ? (
- <input
- autoFocus
- type="text"
- value={nameDraft}
- onChange={(e) => setNameDraft(e.target.value)}
- onBlur={handleRename}
- onKeyDown={(e) => {
- if (e.key === 'Enter') handleRename();
- if (e.key === 'Escape') { setNameDraft(collection.name); setEditingName(false); }
- }}
- maxLength={80}
- className="text-xl font-semibold bg-port-card border border-port-border rounded px-2 py-1 text-white focus:outline-none focus:border-port-accent"
- />
- ) : (
- <button type="button" onClick={() => setEditingName(true)} className="text-xl font-semibold text-white hover:text-port-accent flex items-center gap-2">
- {collection.name}
- <Pencil className="w-4 h-4 text-gray-500" />
+ {renderTitle()}
+ <span className="text-xs text-gray-500">{items.length} item{items.length === 1 ? '' : 's'}</span>
+ {items.length > 0 && !selectMode && (
+ <button
+ type="button"
+ onClick={() => setSelectMode(true)}
+ className="ml-auto px-2.5 py-1 text-xs bg-port-border hover:bg-port-border/70 text-white rounded flex items-center gap-1.5"
+ title="Select multiple to move, copy, star, or remove"
+ >
+ <CheckSquare className="w-3.5 h-3.5" /> Select
</button>
)}
- <span className="text-xs text-gray-500">{items.length} item{items.length === 1 ? '' : 's'}</span>
</div>
+ {selectMode && (
+ <div className="bg-port-card border border-port-border rounded-lg px-3 py-2 flex flex-wrap items-center gap-2 sticky top-0 z-30">
+ <span className="text-xs text-gray-300">
+ <span className="text-white font-medium">{selected.size}</span> of {items.length} selected
+ </span>
+ <button
+ type="button"
+ onClick={() => setSelected(new Set(items.map((it) => it.key)))}
+ disabled={bulkBusy || selected.size === items.length}
+ className="px-2 py-1 text-[11px] bg-port-border hover:bg-port-border/70 text-white rounded disabled:opacity-40"
+ >
+ Select all
+ </button>
+ <button
+ type="button"
+ onClick={() => setSelected(new Set())}
+ disabled={bulkBusy || selected.size === 0}
+ className="px-2 py-1 text-[11px] bg-port-border hover:bg-port-border/70 text-white rounded disabled:opacity-40"
+ >
+ Clear
+ </button>
+ <div className="flex flex-wrap items-center gap-1.5 ml-auto">
+ <button
+ type="button"
+ onClick={() => bulkStar(true)}
+ disabled={bulkBusy || selected.size === 0}
+ className="px-2 py-1 text-[11px] bg-port-warning/20 hover:bg-port-warning/40 text-port-warning rounded flex items-center gap-1 disabled:opacity-40"
+ title="Favorite selected"
+ >
+ <Star className="w-3 h-3" /> Star
+ </button>
+ <button
+ type="button"
+ onClick={() => bulkStar(false)}
+ disabled={bulkBusy || selected.size === 0}
+ className="px-2 py-1 text-[11px] bg-port-border hover:bg-port-border/70 text-white rounded flex items-center gap-1 disabled:opacity-40"
+ title="Unfavorite selected"
+ >
+ <StarOff className="w-3 h-3" /> Unstar
+ </button>
+ <button
+ ref={moveBtnRef}
+ type="button"
+ onClick={() => setPickerMode((m) => (m === 'move' ? null : 'move'))}
+ disabled={bulkBusy || selected.size === 0}
+ className="px-2 py-1 text-[11px] bg-port-accent/20 hover:bg-port-accent/40 text-port-accent rounded flex items-center gap-1 disabled:opacity-40"
+ title={isUnsorted ? 'File selected into a collection' : 'Move selected to another collection'}
+ >
+ <FolderInput className="w-3 h-3" /> {isUnsorted ? 'File…' : 'Move…'}
+ </button>
+ {!isUnsorted && (
+ <>
+ <button
+ ref={copyBtnRef}
+ type="button"
+ onClick={() => setPickerMode((m) => (m === 'copy' ? null : 'copy'))}
+ disabled={bulkBusy || selected.size === 0}
+ className="px-2 py-1 text-[11px] bg-port-accent/20 hover:bg-port-accent/40 text-port-accent rounded flex items-center gap-1 disabled:opacity-40"
+ title="Copy selected to another collection"
+ >
+ <Copy className="w-3 h-3" /> Copy…
+ </button>
+ <button
+ type="button"
+ onClick={bulkRemove}
+ disabled={bulkBusy || selected.size === 0}
+ className="px-2 py-1 text-[11px] bg-port-error/20 hover:bg-port-error/40 text-port-error rounded flex items-center gap-1 disabled:opacity-40"
+ title="Remove selected from this collection"
+ >
+ <Trash2 className="w-3 h-3" /> Remove
+ </button>
+ </>
+ )}
+ <button
+ type="button"
+ onClick={exitSelectMode}
+ disabled={bulkBusy}
+ className="p-1 text-gray-400 hover:text-white disabled:opacity-40"
+ title="Exit select mode"
+ aria-label="Exit select mode"
+ >
+ <X className="w-4 h-4" />
+ </button>
+ </div>
+ {pickerMode && (
+ <BulkTargetPicker
+ anchorRef={pickerMode === 'move' ? moveBtnRef : copyBtnRef}
+ excludeId={collection.id}
+ busy={bulkBusy}
+ title={`${pickerMode === 'move' ? 'Move' : 'Copy'} ${selected.size} to…`}
+ onPick={bulkMoveOrCopy}
+ onClose={() => setPickerMode(null)}
+ />
+ )}
+ </div>
+ )}
+
{items.length === 0 ? (
<div className="text-gray-500 text-sm bg-port-card border border-port-border rounded-lg p-6 text-center">
- This collection is empty. Use the folder icon on any image/video card to add items here.
+ {isUnsorted
+ ? 'Nothing unsorted — every image and video is in at least one collection.'
+ : 'This collection is empty. Use the folder icon on any image/video card to add items here.'}
</div>
) : (
<div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-3">
{items.map((item) => {
- const key = `${item.kind}:${item.kind === 'video' ? item.id : item.filename}`;
+ const key = item.key;
const isCover = collection.coverKey === key;
+ const isSelected = selected.has(key);
return (
<div key={key} className="relative">
<MediaCard
item={item}
- onPreview={setPreview}
- onRemix={item.kind === 'image' ? handleRemix : undefined}
- onSendToVideo={item.kind === 'image' ? handleSendToVideo : undefined}
- onContinue={item.kind === 'video' ? handleContinue : undefined}
- onDelete={handleRemove}
+ onPreview={selectMode ? undefined : setPreview}
+ onClick={selectMode ? () => toggleSelect(key) : undefined}
+ onRemix={!selectMode && item.kind === 'image' ? handleRemix : undefined}
+ onSendToVideo={!selectMode && item.kind === 'image' ? handleSendToVideo : undefined}
+ onContinue={!selectMode && item.kind === 'video' ? handleContinue : undefined}
+ onDelete={!selectMode ? handleDelete : undefined}
+ hideActions={selectMode}
+ selected={isSelected}
starred={!!annotations[key]?.starred}
hasNote={!!annotations[key]?.note}
- onToggleStar={toggleStar}
+ onToggleStar={!selectMode ? toggleStar : undefined}
/>
- <button
- type="button"
- onClick={() => handleSetCover(item)}
- className={`absolute top-1.5 right-1.5 w-7 h-7 rounded-full flex items-center justify-center border transition-colors ${
- isCover
- ? 'bg-port-accent text-white border-port-accent'
- : 'bg-black/60 text-gray-300 border-port-border hover:text-white'
- }`}
- title={isCover ? 'Cover (click to reset to newest)' : 'Set as cover'}
- >
- <Star className="w-3.5 h-3.5" fill={isCover ? 'currentColor' : 'none'} />
- </button>
+ {!selectMode && !isUnsorted && (
+ <button
+ type="button"
+ onClick={() => handleSetCover(item)}
+ className={`absolute top-1.5 right-1.5 w-7 h-7 rounded-full flex items-center justify-center border transition-colors ${
+ isCover
+ ? 'bg-port-accent text-white border-port-accent'
+ : 'bg-black/60 text-gray-300 border-port-border hover:text-white'
+ }`}
+ title={isCover ? 'Cover (click to reset to newest)' : 'Set as cover'}
+ >
+ <Star className="w-3.5 h-3.5" fill={isCover ? 'currentColor' : 'none'} />
+ </button>
+ )}
+ {selectMode && isSelected && (
+ <div className="absolute top-1.5 right-1.5 w-7 h-7 rounded-full bg-port-accent text-white border border-port-accent flex items-center justify-center pointer-events-none">
+ <CheckSquare className="w-4 h-4" />
+ </div>
+ )}
</div>
);
})}
diff --git a/client/src/pages/MediaCollections.jsx b/client/src/pages/MediaCollections.jsx
index 768a5a95b3..06af0c0b81 100644
--- a/client/src/pages/MediaCollections.jsx
+++ b/client/src/pages/MediaCollections.jsx
@@ -1,11 +1,12 @@
import { useEffect, useMemo, useState } from 'react';
import { Link } from 'react-router-dom';
-import { Plus, FolderOpen, Trash2, Image as ImageIcon, Film } from 'lucide-react';
+import { Plus, FolderOpen, Inbox, Trash2, Image as ImageIcon, Film } from 'lucide-react';
import toast from '../components/ui/Toast';
import {
listMediaCollections, createMediaCollection, deleteMediaCollection,
listVideoHistory, listImageGallery,
} from '../services/api';
+import { buildUnsortedCollection } from '../lib/unsorted';
// Resolve a collection's cover-thumbnail URL. Default = newest item by
// addedAt; user-pinned coverKey wins when set. We need full image/video
@@ -92,13 +93,24 @@ export default function MediaCollections() {
});
};
- const enriched = useMemo(() => collections.map((c) => {
- const counts = (c.items || []).reduce((acc, it) => {
- acc[it.kind] = (acc[it.kind] || 0) + 1;
- return acc;
- }, { image: 0, video: 0 });
- return { ...c, cover: resolveCover(c, imagesByName, videosById), counts };
- }), [collections, imagesByName, videosById]);
+ const images = useMemo(() => Array.from(imagesByName.values()), [imagesByName]);
+ const videos = useMemo(() => Array.from(videosById.values()), [videosById]);
+ const unsorted = useMemo(
+ () => buildUnsortedCollection(collections, images, videos),
+ [collections, images, videos],
+ );
+
+ const enriched = useMemo(() => {
+ // Pinned synthetic "Unsorted" entry first, then real collections.
+ const all = [unsorted, ...collections];
+ return all.map((c) => {
+ const counts = (c.items || []).reduce((acc, it) => {
+ acc[it.kind] = (acc[it.kind] || 0) + 1;
+ return acc;
+ }, { image: 0, video: 0 });
+ return { ...c, cover: resolveCover(c, imagesByName, videosById), counts };
+ });
+ }, [collections, unsorted, imagesByName, videosById]);
return (
<div className="space-y-4">
@@ -129,7 +141,10 @@ export default function MediaCollections() {
) : (
<div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 gap-3">
{enriched.map((c) => (
- <div key={c.id} className="bg-port-card border border-port-border rounded-xl overflow-hidden flex flex-col">
+ <div
+ key={c.id}
+ className={`bg-port-card border rounded-xl overflow-hidden flex flex-col ${c.synthetic ? 'border-port-accent/40' : 'border-port-border'}`}
+ >
<Link
to={`/media/collections/${encodeURIComponent(c.id)}`}
className="block aspect-square bg-port-bg relative"
@@ -138,7 +153,7 @@ export default function MediaCollections() {
<img src={c.cover} alt={c.name} className="w-full h-full object-cover" loading="lazy" />
) : (
<div className="w-full h-full flex items-center justify-center text-gray-600">
- <FolderOpen className="w-12 h-12" />
+ {c.synthetic ? <Inbox className="w-12 h-12" /> : <FolderOpen className="w-12 h-12" />}
</div>
)}
</Link>
@@ -152,14 +167,16 @@ export default function MediaCollections() {
{c.counts.image === 0 && c.counts.video === 0 && <span>Empty</span>}
</div>
<div className="flex-1" />
- <button
- type="button"
- onClick={() => handleDelete(c)}
- className="self-end px-1.5 py-1 bg-port-error/20 hover:bg-port-error/40 text-port-error text-[10px] rounded flex items-center gap-1"
- title="Delete collection"
- >
- <Trash2 className="w-3 h-3" />
- </button>
+ {!c.synthetic && (
+ <button
+ type="button"
+ onClick={() => handleDelete(c)}
+ className="self-end px-1.5 py-1 bg-port-error/20 hover:bg-port-error/40 text-port-error text-[10px] rounded flex items-center gap-1"
+ title="Delete collection"
+ >
+ <Trash2 className="w-3 h-3" />
+ </button>
+ )}
</div>
</div>
))}
diff --git a/client/src/services/apiImageVideo.js b/client/src/services/apiImageVideo.js
index f35d82a068..c7c79985b2 100644
--- a/client/src/services/apiImageVideo.js
+++ b/client/src/services/apiImageVideo.js
@@ -108,12 +108,14 @@ export const updateMediaCollection = (id, patch) => request(`/media/collections/
export const deleteMediaCollection = (id) => request(`/media/collections/${encodeURIComponent(id)}`, {
method: 'DELETE',
});
-export const addMediaCollectionItem = (id, { kind, ref }) => request(`/media/collections/${encodeURIComponent(id)}/items`, {
+export const addMediaCollectionItem = (id, { kind, ref }, { silent = false } = {}) => request(`/media/collections/${encodeURIComponent(id)}/items`, {
method: 'POST',
body: JSON.stringify({ kind, ref }),
+ silent,
});
-export const removeMediaCollectionItem = (id, key) => request(`/media/collections/${encodeURIComponent(id)}/items/${encodeURIComponent(key)}`, {
+export const removeMediaCollectionItem = (id, key, { silent = false } = {}) => request(`/media/collections/${encodeURIComponent(id)}/items/${encodeURIComponent(key)}`, {
method: 'DELETE',
+ silent,
});
// Media annotations — per-item star + free-text note, keyed by "<kind>:<ref>"