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

fix([issue-3283]): keep empty auto-collections from burying real ones in Media Collections

[._.]/ Adam Eivy5c10496f76c2
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index 75379f4870..5d705cb329 100644
--- a/client/src/lib/README.md
+++ b/client/src/lib/README.md
@@ -103,6 +103,7 @@ grep -i "what you want to do" client/src/lib/README.md
| `manuscriptAnchors.js` | `locateFind` / `locateAnchors` / `buildHighlightSegments` — resolve editorial-comment `anchorQuote`s to spans in manuscript text and tile the text into plain + highlighted (severity-toned) segments for the Manuscript editor's in-context feedback. Mirrors the nearest-occurrence `locateFind` in `server/services/pipeline/manuscriptFix.js`. |
| `manuscriptFormat.js` | `formatManuscript(text, stageId)` / `REFLOW_STAGES` — normalize a manuscript section's text for the editor's "Format" button: undo PDF-paste artifacts (stylized drop-cap split onto its own line, hyphen-split words, trailing whitespace, runaway blank lines) for every stage, and additionally reflow soft-wrapped lines back into paragraphs for `prose` only (scripts keep their structural line breaks). Pure/DOM-free. |
| `mediaNavigation.js` | `getAdjacentMedia(items, item)` — prev/next computation for lightboxes. |
+| `mediaCollectionList.js` | Search / sort / hide-empty helpers for the Media Collections grid (#3283): `applyCollectionView(collections, { query, sort, hideEmpty })` filters by AND-token name/description search and orders synthetic "Unsorted" → non-empty-or-user-created → auto-generated empties, then by `COLLECTION_SORTS` (`updated` / `name` / `count`, `normalizeCollectionSort` coerces an unknown/URL value). `isAutoCollection(c)` recognizes a machine-created collection from ANY of four independent markers (name prefix, `Auto-created for project …` description, `uc-`/`sc-` id, universe/series link) so pre-marker records still classify; `splitCollectionName(name)` lifts the shared `Creative Director: ` prefix into a badge label so the distinguishing tail survives truncation, and name sorting uses that stripped title. Pure — no React. |
| `mediaSearch.js` | `buildMediaHaystack`, `tokenizeQuery`, `matchHaystack`, `filterByQuery` — client-side AND-token search over normalized media items (prompt/model/seed/LoRA/universe tags). Shared by MediaHistory + the Image Gen gallery picker. |
| `moodBoardItemSrc.js` | `moodBoardItemSrc(item)` resolves a mood-board item to a display image src (`imageUrl` → served `image:<file>` bytes → null). Shared by MoodBoardDetail + MoodBoardReferenceStrip. |
| `registerServiceWorker.js` | `registerServiceWorker()` / `unregisterServiceWorkers()` — wires up the offline app-shell + low-bandwidth asset-caching service worker (`public/sw.js`). Registers only in a production secure context (HTTPS or localhost); no-ops over plain-HTTP Tailnet and tears down any stale SW in dev. Called once from `main.jsx`. |
diff --git a/client/src/lib/index.js b/client/src/lib/index.js
index dfdf9c9eb4..0fa0e41b1e 100644
--- a/client/src/lib/index.js
+++ b/client/src/lib/index.js
@@ -77,6 +77,7 @@ export * from './localLlmTargetKey.js';
export * from './loopbackHost.js';
export * from './manuscriptAnchors.js';
export * from './manuscriptFormat.js';
+export * from './mediaCollectionList.js';
export * from './mediaNavigation.js';
export * from './mediaSearch.js';
export * from './moodBoardItemSrc.js';
diff --git a/client/src/lib/mediaCollectionList.js b/client/src/lib/mediaCollectionList.js
new file mode 100644
index 0000000000..6eacdebc3b
--- /dev/null
+++ b/client/src/lib/mediaCollectionList.js
@@ -0,0 +1,145 @@
+// Search / sort / hide-empty helpers for the Media Collections grid (#3283).
+//
+// The grid is dominated by collections nothing created on purpose: every
+// Creative Director project and every universe/series render bucket auto-files
+// itself as a collection, so a user with a handful of real collections scrolls
+// past dozens of empty auto-generated ones to find them. These helpers give the
+// page one definition of "auto-generated", "empty", and the display ordering
+// that keeps real collections on top.
+//
+// Pure — no React, no I/O. The page and its tests share them.
+
+// Shared name prefixes that auto-creators stamp onto every collection they
+// make. Rendered as a badge above the card title instead of inside it, so the
+// distinguishing tail (usually a project name + date) isn't what gets clipped.
+// Keep in sync with the server-side creators
+// (`server/services/creativeDirector/projects{DB,File}.js`).
+export const AUTO_NAME_PREFIXES = ['Creative Director: '];
+
+// Description stamped by the auto-creators. A user can't produce this by
+// accident through the UI (the create form takes a name only).
+const AUTO_DESCRIPTION_PREFIX = 'Auto-created for project ';
+
+// Deterministic id prefixes for the universe-/series-linked render buckets the
+// pipeline files into (see `mediaCollections.js` — `uc-<universeId>` /
+// `sc-<seriesId>`).
+const AUTO_ID_PREFIXES = ['uc-', 'sc-'];
+
+/**
+ * Split a collection name into its auto-creator prefix and the remaining
+ * title. Returns `{ badge: null, title: name }` for a user-named collection.
+ * @param {string} name
+ * @returns {{ badge: string|null, title: string }}
+ */
+export function splitCollectionName(name) {
+ const str = typeof name === 'string' ? name : '';
+ for (const prefix of AUTO_NAME_PREFIXES) {
+ if (str.startsWith(prefix) && str.length > prefix.length) {
+ // Trim the trailing separator off the badge label ("Creative Director").
+ return { badge: prefix.replace(/[:\s]+$/, ''), title: str.slice(prefix.length) };
+ }
+ }
+ return { badge: null, title: str };
+}
+
+/**
+ * True when a collection was created by an automated flow rather than by the
+ * user. Any one of the four independent markers is sufficient — an install can
+ * hold records from before a given marker existed, so this must not require all
+ * of them to agree.
+ * @param {object} collection
+ * @returns {boolean}
+ */
+export function isAutoCollection(collection) {
+ if (!collection || collection.synthetic) return false;
+ if (splitCollectionName(collection.name).badge) return true;
+ const description = typeof collection.description === 'string' ? collection.description : '';
+ if (description.startsWith(AUTO_DESCRIPTION_PREFIX)) return true;
+ const id = typeof collection.id === 'string' ? collection.id : '';
+ if (AUTO_ID_PREFIXES.some((p) => id.startsWith(p))) return true;
+ return Boolean(collection.universeId || collection.seriesId);
+}
+
+/** Item count for a collection (0 for a malformed/absent items array). */
+export function collectionItemCount(collection) {
+ return Array.isArray(collection?.items) ? collection.items.length : 0;
+}
+
+// The sort control's options, in menu order. First entry is the default.
+export const COLLECTION_SORTS = [
+ { id: 'updated', label: 'Recently updated' },
+ { id: 'name', label: 'Name' },
+ { id: 'count', label: 'Item count' },
+];
+
+export const DEFAULT_COLLECTION_SORT = COLLECTION_SORTS[0].id;
+
+/** Coerce a stored/URL sort id to a known one (unknown → the default). */
+export function normalizeCollectionSort(raw) {
+ return COLLECTION_SORTS.some((s) => s.id === raw) ? raw : DEFAULT_COLLECTION_SORT;
+}
+
+// Ordering bucket: synthetic ("Unsorted") is pinned first, then anything with
+// items or a user-chosen name, then the auto-generated empties that motivated
+// this. Within a bucket the caller's sort applies.
+const orderBucket = (collection) => {
+ if (collection?.synthetic) return 0;
+ if (collectionItemCount(collection) > 0) return 1;
+ return isAutoCollection(collection) ? 2 : 1;
+};
+
+// Sort timestamp. `null`/absent means "never stamped" — distinct from a real
+// epoch-0 date — and sorts last rather than pretending to be the oldest record.
+const updatedTime = (collection) => {
+ const raw = collection?.updatedAt || collection?.createdAt;
+ const ms = raw ? Date.parse(raw) : NaN;
+ return Number.isFinite(ms) ? ms : null;
+};
+
+// Name sorting uses the PREFIX-STRIPPED title, so the Creative Director
+// entries interleave by their real project names instead of all clumping under
+// "C" — the same reason the prefix moves to a badge in the card.
+const sortName = (collection) => splitCollectionName(collection?.name).title.toLowerCase();
+
+const compareBy = (sort) => (a, b) => {
+ if (sort === 'name') return sortName(a).localeCompare(sortName(b));
+ if (sort === 'count') {
+ const delta = collectionItemCount(b) - collectionItemCount(a);
+ if (delta !== 0) return delta;
+ return sortName(a).localeCompare(sortName(b));
+ }
+ const ta = updatedTime(a);
+ const tb = updatedTime(b);
+ if (ta === tb) return sortName(a).localeCompare(sortName(b));
+ if (ta === null) return 1;
+ if (tb === null) return -1;
+ return tb - ta;
+};
+
+// AND semantics across whitespace-separated tokens, matched against the name
+// and description (substring, any order) — same shape as `mediaSearch.js`, but
+// over collection records rather than normalized media items.
+const matchesQuery = (collection, tokens) => {
+ if (tokens.length === 0) return true;
+ const haystack = `${collection?.name || ''} ${collection?.description || ''}`.toLowerCase();
+ return tokens.every((t) => haystack.includes(t));
+};
+
+/**
+ * Filter + order the collection grid.
+ * @param {object[]} collections - Enriched collections (synthetic entry included)
+ * @param {object} view
+ * @param {string} [view.query] - Free-text name/description search
+ * @param {string} [view.sort] - One of COLLECTION_SORTS ids
+ * @param {boolean} [view.hideEmpty] - Drop item-less collections
+ * @returns {object[]} A new array; the input is not mutated
+ */
+export function applyCollectionView(collections, { query = '', sort = DEFAULT_COLLECTION_SORT, hideEmpty = false } = {}) {
+ const tokens = String(query || '').trim().toLowerCase().split(/\s+/).filter(Boolean);
+ const filtered = (collections || []).filter((c) => {
+ if (hideEmpty && collectionItemCount(c) === 0) return false;
+ return matchesQuery(c, tokens);
+ });
+ const comparator = compareBy(normalizeCollectionSort(sort));
+ return filtered.sort((a, b) => (orderBucket(a) - orderBucket(b)) || comparator(a, b));
+}
diff --git a/client/src/lib/mediaCollectionList.test.js b/client/src/lib/mediaCollectionList.test.js
new file mode 100644
index 0000000000..0325a54857
--- /dev/null
+++ b/client/src/lib/mediaCollectionList.test.js
@@ -0,0 +1,136 @@
+import { describe, it, expect } from 'vitest';
+import {
+ applyCollectionView, splitCollectionName, isAutoCollection, collectionItemCount,
+ normalizeCollectionSort, DEFAULT_COLLECTION_SORT, COLLECTION_SORTS,
+} from './mediaCollectionList.js';
+
+const item = (n) => Array.from({ length: n }, (_, i) => ({ kind: 'image', ref: `${i}.png` }));
+
+const unsorted = { id: 'unsorted', name: 'Unsorted', synthetic: true, items: item(3) };
+const userFull = { id: 'u1', name: 'Concept Art', items: item(5), updatedAt: '2026-07-01T00:00:00Z' };
+const userEmpty = { id: 'u2', name: 'Zeppelins', items: [], updatedAt: '2026-07-05T00:00:00Z' };
+const autoFull = {
+ id: 'p1', name: 'Creative Director: Nightly Surreal — 2026-07-30', items: item(2),
+ description: 'Auto-created for project p1', updatedAt: '2026-07-30T00:00:00Z',
+};
+const autoEmpty = {
+ id: 'p2', name: 'Creative Director: Nightly Surreal — 2026-08-01', items: [],
+ description: 'Auto-created for project p2', updatedAt: '2026-08-01T00:00:00Z',
+};
+
+const ids = (list) => list.map((c) => c.id);
+
+describe('splitCollectionName', () => {
+ it('lifts the shared auto-creator prefix into a badge label', () => {
+ expect(splitCollectionName('Creative Director: Nightly Surreal — 2026-08-01'))
+ .toEqual({ badge: 'Creative Director', title: 'Nightly Surreal — 2026-08-01' });
+ });
+
+ it('leaves a user-named collection alone', () => {
+ expect(splitCollectionName('Concept Art')).toEqual({ badge: null, title: 'Concept Art' });
+ });
+
+ it('does not strip a name that is nothing but the prefix', () => {
+ expect(splitCollectionName('Creative Director: ').badge).toBe(null);
+ });
+
+ it('tolerates a missing name', () => {
+ expect(splitCollectionName(undefined)).toEqual({ badge: null, title: '' });
+ });
+});
+
+describe('isAutoCollection', () => {
+ it('recognizes each marker independently', () => {
+ expect(isAutoCollection({ id: 'x', name: 'Creative Director: Foo' })).toBe(true);
+ expect(isAutoCollection({ id: 'x', name: 'Foo', description: 'Auto-created for project x' })).toBe(true);
+ expect(isAutoCollection({ id: 'uc-universe-1', name: 'Foo' })).toBe(true);
+ expect(isAutoCollection({ id: 'sc-series-1', name: 'Foo' })).toBe(true);
+ expect(isAutoCollection({ id: 'x', name: 'Foo', universeId: 'u1' })).toBe(true);
+ expect(isAutoCollection({ id: 'x', name: 'Foo', seriesId: 's1' })).toBe(true);
+ });
+
+ it('is false for a user-created collection and for the synthetic Unsorted entry', () => {
+ expect(isAutoCollection(userEmpty)).toBe(false);
+ expect(isAutoCollection(unsorted)).toBe(false);
+ expect(isAutoCollection(null)).toBe(false);
+ });
+});
+
+describe('collectionItemCount', () => {
+ it('treats a missing/malformed items array as empty', () => {
+ expect(collectionItemCount({ items: null })).toBe(0);
+ expect(collectionItemCount(undefined)).toBe(0);
+ expect(collectionItemCount({ items: item(4) })).toBe(4);
+ });
+});
+
+describe('normalizeCollectionSort', () => {
+ it('accepts every advertised sort id', () => {
+ for (const s of COLLECTION_SORTS) expect(normalizeCollectionSort(s.id)).toBe(s.id);
+ });
+
+ it('coerces an unknown/absent value to the default', () => {
+ expect(normalizeCollectionSort('bogus')).toBe(DEFAULT_COLLECTION_SORT);
+ expect(normalizeCollectionSort(null)).toBe(DEFAULT_COLLECTION_SORT);
+ });
+});
+
+describe('applyCollectionView', () => {
+ const all = [unsorted, userFull, userEmpty, autoFull, autoEmpty];
+
+ it('pins Unsorted first, then non-empty/user-created, then auto-generated empties', () => {
+ const out = applyCollectionView(all, { hideEmpty: false });
+ expect(out[0].id).toBe('unsorted');
+ // autoEmpty is the newest by updatedAt but still sorts last — its bucket wins.
+ expect(out[out.length - 1].id).toBe('p2');
+ // A user's own empty collection is NOT demoted with the auto empties.
+ expect(out.indexOf(userEmpty)).toBeLessThan(out.length - 1);
+ });
+
+ it('drops every empty collection when hideEmpty is set', () => {
+ expect(ids(applyCollectionView(all, { hideEmpty: true }))).toEqual(['unsorted', 'p1', 'u1']);
+ });
+
+ it('does not mutate the input array', () => {
+ const input = [...all];
+ applyCollectionView(input, { sort: 'name' });
+ expect(input).toEqual(all);
+ });
+
+ it('searches name and description with AND-token semantics', () => {
+ expect(ids(applyCollectionView(all, { query: 'nightly 08-01', hideEmpty: false }))).toEqual(['p2']);
+ expect(ids(applyCollectionView(all, { query: 'project p1', hideEmpty: false }))).toEqual(['p1']);
+ expect(applyCollectionView(all, { query: 'nothing matches this' })).toEqual([]);
+ });
+
+ it('ignores case and surrounding whitespace in the query', () => {
+ expect(ids(applyCollectionView(all, { query: ' CONCEPT ', hideEmpty: false }))).toEqual(['u1']);
+ });
+
+ it('sorts by name using the prefix-stripped title so auto entries interleave', () => {
+ const out = applyCollectionView([userFull, autoFull], { sort: 'name' });
+ // "Nightly…" < "Concept…" would be false on the raw names ("Creative
+ // Director: Nightly" sorts before "Concept Art"), so this asserts the strip.
+ expect(ids(out)).toEqual(['u1', 'p1']);
+ });
+
+ it('sorts by descending item count', () => {
+ expect(ids(applyCollectionView([autoFull, userFull], { sort: 'count' }))).toEqual(['u1', 'p1']);
+ });
+
+ it('sorts a never-stamped record last rather than treating it as the oldest', () => {
+ const noStamp = { id: 'n1', name: 'No timestamps', items: item(1) };
+ const out = applyCollectionView([noStamp, userFull], { sort: 'updated' });
+ expect(ids(out)).toEqual(['u1', 'n1']);
+ });
+
+ it('falls back to the default sort for an unknown sort id', () => {
+ expect(ids(applyCollectionView(all, { sort: 'bogus', hideEmpty: true })))
+ .toEqual(ids(applyCollectionView(all, { sort: DEFAULT_COLLECTION_SORT, hideEmpty: true })));
+ });
+
+ it('handles an absent list', () => {
+ expect(applyCollectionView(undefined, {})).toEqual([]);
+ expect(applyCollectionView([])).toEqual([]);
+ });
+});
diff --git a/client/src/pages/MediaCollections.jsx b/client/src/pages/MediaCollections.jsx
index 88c0476f03..aa60d6f89d 100644
--- a/client/src/pages/MediaCollections.jsx
+++ b/client/src/pages/MediaCollections.jsx
@@ -1,16 +1,27 @@
-import { useEffect, useMemo, useState } from 'react';
-import { Link, useNavigate } from 'react-router-dom';
-import { Plus, FolderOpen, Inbox, Trash2, Image as ImageIcon, Film } from 'lucide-react';
+import { useCallback, useEffect, useMemo, useState } from 'react';
+import { Link, useNavigate, useSearchParams } from 'react-router-dom';
+import { Plus, FolderOpen, Inbox, Trash2, Image as ImageIcon, Film, Search } from 'lucide-react';
import toast from '../components/ui/Toast';
import {
listMediaCollections, createMediaCollection, deleteMediaCollection,
listVideoHistory, listImageGallery,
} from '../services/api';
import { buildUnsortedCollection } from '../lib/unsorted';
+import {
+ applyCollectionView, splitCollectionName, collectionItemCount,
+ COLLECTION_SORTS, DEFAULT_COLLECTION_SORT, normalizeCollectionSort,
+} from '../lib/mediaCollectionList';
+import { middleTruncate } from '../utils/formatters';
import MediaImage from '../components/MediaImage';
import SyncBadge from '../components/sync/SyncBadge';
import { useSyncIntegrity, syncBadgeStatus } from '../hooks/useSyncIntegrity';
+// Cap for the card title AFTER the auto-creator prefix moves to its badge.
+// Middle-truncating at this length keeps the trailing date/qualifier — the only
+// thing distinguishing sibling auto-generated names — visible, which a plain
+// end-clip (`line-clamp`) always eats.
+const TITLE_MAX_CHARS = 34;
+
// Resolve a collection's cover-thumbnail URL. Default = newest item by
// addedAt; user-pinned coverKey wins when set. We need full image/video
// records to build the thumbnail src, so the page fetches both lists once
@@ -51,6 +62,7 @@ const resolveCover = (collection, imagesByName, videosById) => {
export default function MediaCollections() {
const navigate = useNavigate();
+ const [searchParams, setSearchParams] = useSearchParams();
const [collections, setCollections] = useState([]);
const [loading, setLoading] = useState(true);
const [creating, setCreating] = useState(false);
@@ -116,10 +128,53 @@ export default function MediaCollections() {
acc[it.kind] = (acc[it.kind] || 0) + 1;
return acc;
}, { image: 0, video: 0 });
- return { ...c, cover: resolveCover(c, imagesByName, videosById), counts };
+ // Lift the shared auto-creator prefix ("Creative Director: ") out of the
+ // title into its own badge, then middle-truncate what's left — otherwise
+ // every auto-generated card renders the same clipped prefix and the
+ // trailing project name/date that tells them apart is what gets cut.
+ const { badge, title } = splitCollectionName(c.name);
+ return {
+ ...c,
+ cover: resolveCover(c, imagesByName, videosById),
+ counts,
+ badge,
+ displayTitle: middleTruncate(title, TITLE_MAX_CHARS),
+ };
});
}, [collections, unsorted, imagesByName, videosById]);
+ // Filter/sort state lives in the URL so a filtered grid is shareable and
+ // survives a back-navigation from a collection. `empty=1` OPTS IN to showing
+ // empty collections — the default (param absent) hides them, because an empty
+ // auto-created collection has nothing to open.
+ const query = searchParams.get('q') || '';
+ const sort = normalizeCollectionSort(searchParams.get('sort'));
+ const hideEmpty = searchParams.get('empty') !== '1';
+
+ const updateParams = useCallback((patch, { replace = false } = {}) => {
+ setSearchParams((prev) => {
+ const next = new URLSearchParams(prev);
+ for (const [k, v] of Object.entries(patch)) {
+ if (v == null || v === '') next.delete(k);
+ else next.set(k, v);
+ }
+ return next;
+ }, { replace });
+ }, [setSearchParams]);
+
+ // Search + sort first, then apply "hide empty" as a slice of that result, so
+ // the "N empty hidden" count only ever names rows the toggle removed — not
+ // rows the search already dropped.
+ const matching = useMemo(
+ () => applyCollectionView(enriched, { query, sort, hideEmpty: false }),
+ [enriched, query, sort],
+ );
+ const visible = useMemo(
+ () => (hideEmpty ? matching.filter((c) => collectionItemCount(c) > 0) : matching),
+ [matching, hideEmpty],
+ );
+ const hiddenEmptyCount = matching.length - visible.length;
+
return (
<div className="space-y-4">
<form onSubmit={handleCreate} className="flex gap-2 items-center">
@@ -141,65 +196,134 @@ export default function MediaCollections() {
</button>
</form>
+ {/* Filter row. Stacks under `sm` so the search box keeps a usable width
+ on a phone instead of sharing one line with the sort + toggle. */}
+ <div className="flex flex-col sm:flex-row gap-2 sm:items-center">
+ <div className="relative flex-1">
+ <Search size={14} className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-500" aria-hidden="true" />
+ <label htmlFor="collection-search" className="sr-only">Search collections</label>
+ <input
+ id="collection-search"
+ type="search"
+ value={query}
+ onChange={(e) => updateParams({ q: e.target.value }, { replace: true })}
+ placeholder="Search collections…"
+ className="w-full pl-9 pr-3 py-2 bg-port-card border border-port-border rounded-lg text-white text-sm focus:outline-none focus:border-port-accent"
+ />
+ </div>
+ <label htmlFor="collection-sort" className="sr-only">Sort collections</label>
+ <select
+ id="collection-sort"
+ value={sort}
+ onChange={(e) => updateParams({ sort: e.target.value === DEFAULT_COLLECTION_SORT ? '' : e.target.value })}
+ className="bg-port-card border border-port-border rounded-lg px-3 py-2 text-sm text-white focus:outline-none focus:border-port-accent"
+ >
+ {COLLECTION_SORTS.map((s) => (
+ <option key={s.id} value={s.id}>{s.label}</option>
+ ))}
+ </select>
+ <label className="flex items-center gap-2 text-sm text-gray-400 px-1 py-2 cursor-pointer whitespace-nowrap">
+ <input
+ type="checkbox"
+ checked={hideEmpty}
+ onChange={(e) => updateParams({ empty: e.target.checked ? '' : '1' })}
+ className="accent-port-accent"
+ />
+ Hide empty
+ </label>
+ </div>
+
{loading ? (
<div className="text-gray-500 text-sm">Loading…</div>
) : enriched.length === 0 ? (
<div className="text-gray-500 text-sm bg-port-card border border-port-border rounded-lg p-6 text-center">
No collections yet. Create one above, or use the folder icon on any image/video card to start a new collection.
</div>
- ) : (
- <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 rounded-xl overflow-hidden flex flex-col ${c.synthetic ? 'border-port-accent/40' : 'border-port-border'}`}
+ ) : visible.length === 0 ? (
+ <div className="text-gray-500 text-sm bg-port-card border border-port-border rounded-lg p-6 text-center space-y-2">
+ <div>
+ {hiddenEmptyCount > 0
+ ? `No collections with items match${query ? ' that search' : ''}.`
+ : 'No collections match that search.'}
+ </div>
+ {hiddenEmptyCount > 0 && (
+ <button
+ type="button"
+ onClick={() => updateParams({ empty: '1' })}
+ className="text-port-accent hover:underline"
>
- <Link
- to={`/media/collections/${encodeURIComponent(c.id)}`}
- className="block aspect-square bg-port-bg relative"
+ Show {hiddenEmptyCount} empty {hiddenEmptyCount === 1 ? 'collection' : 'collections'}
+ </button>
+ )}
+ </div>
+ ) : (
+ <div className="space-y-2">
+ {hiddenEmptyCount > 0 && (
+ <div className="text-xs text-gray-500">
+ {hiddenEmptyCount} empty {hiddenEmptyCount === 1 ? 'collection' : 'collections'} hidden.{' '}
+ <button type="button" onClick={() => updateParams({ empty: '1' })} className="text-port-accent hover:underline">
+ Show
+ </button>
+ </div>
+ )}
+ <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 gap-3">
+ {visible.map((c) => (
+ <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'}`}
>
- {c.cover ? (
- // A cover can point at a pruned video thumbnail or an unpulled
- // peer asset; MediaImage degrades to the syncing tile instead
- // of the browser's broken-image icon.
- <MediaImage 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">
- {c.synthetic ? <Inbox className="w-12 h-12" /> : <FolderOpen className="w-12 h-12" />}
- </div>
- )}
- </Link>
- <div className="p-2 space-y-1.5 flex-1 flex flex-col">
- <Link to={`/media/collections/${encodeURIComponent(c.id)}`} className="text-sm text-white hover:text-port-accent line-clamp-1" title={c.name}>
- {c.name}
- </Link>
- <div className="flex items-center gap-2 text-[10px] text-gray-500">
- {c.counts.image > 0 && <span className="flex items-center gap-1"><ImageIcon className="w-3 h-3" />{c.counts.image}</span>}
- {c.counts.video > 0 && <span className="flex items-center gap-1"><Film className="w-3 h-3" />{c.counts.video}</span>}
- {c.counts.image === 0 && c.counts.video === 0 && <span>Empty</span>}
- </div>
- <div className="flex-1" />
- <div className="flex items-center justify-between gap-1">
- {!c.synthetic && (
- <SyncBadge
- status={syncBadgeStatus(sync, c.id)}
- onClick={() => navigate(`/media/collections/${encodeURIComponent(c.id)}/sync`)}
- />
+ <Link
+ to={`/media/collections/${encodeURIComponent(c.id)}`}
+ className="block aspect-square bg-port-bg relative"
+ >
+ {c.cover ? (
+ // A cover can point at a pruned video thumbnail or an unpulled
+ // peer asset; MediaImage degrades to the syncing tile instead
+ // of the browser's broken-image icon.
+ <MediaImage 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">
+ {c.synthetic ? <Inbox className="w-12 h-12" /> : <FolderOpen className="w-12 h-12" />}
+ </div>
)}
- {!c.synthetic && (
- <button
- type="button"
- onClick={() => handleDelete(c)}
- className="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>
+ </Link>
+ <div className="p-2 space-y-1.5 flex-1 flex flex-col">
+ {c.badge && (
+ <span className="inline-block self-start text-[9px] uppercase tracking-wide text-gray-400 bg-port-bg border border-port-border rounded px-1.5 py-0.5">
+ {c.badge}
+ </span>
)}
+ <Link to={`/media/collections/${encodeURIComponent(c.id)}`} className="text-sm text-white hover:text-port-accent break-words" title={c.name}>
+ {c.displayTitle}
+ </Link>
+ <div className="flex items-center gap-2 text-[10px] text-gray-500">
+ {c.counts.image > 0 && <span className="flex items-center gap-1"><ImageIcon className="w-3 h-3" />{c.counts.image}</span>}
+ {c.counts.video > 0 && <span className="flex items-center gap-1"><Film className="w-3 h-3" />{c.counts.video}</span>}
+ {c.counts.image === 0 && c.counts.video === 0 && <span>Empty</span>}
+ </div>
+ <div className="flex-1" />
+ <div className="flex items-center justify-between gap-1">
+ {!c.synthetic && (
+ <SyncBadge
+ status={syncBadgeStatus(sync, c.id)}
+ onClick={() => navigate(`/media/collections/${encodeURIComponent(c.id)}/sync`)}
+ />
+ )}
+ {!c.synthetic && (
+ <button
+ type="button"
+ onClick={() => handleDelete(c)}
+ className="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>
</div>
- </div>
- ))}
+ ))}
+ </div>
</div>
)}
</div>
diff --git a/client/src/pages/MediaCollections.test.jsx b/client/src/pages/MediaCollections.test.jsx
index 45ca479f80..3501620551 100644
--- a/client/src/pages/MediaCollections.test.jsx
+++ b/client/src/pages/MediaCollections.test.jsx
@@ -1,5 +1,6 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { render, screen, waitFor } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
import { MemoryRouter } from 'react-router-dom';
// ── Mock API calls ───────────────────────────────────────────────────────────
@@ -7,6 +8,12 @@ vi.mock('../services/api', () => ({
listMediaCollections: vi.fn().mockResolvedValue([
{ id: 'col-1', name: 'Alpha', items: [{ kind: 'image', ref: 'img1.png', addedAt: '2024-01-01' }] },
{ id: 'col-2', name: 'Beta', items: [] },
+ {
+ id: 'col-3',
+ name: 'Creative Director: Nightly Surreal Landscapes — 2026-08-01',
+ description: 'Auto-created for project col-3',
+ items: [],
+ },
]),
createMediaCollection: vi.fn(),
deleteMediaCollection: vi.fn(),
@@ -39,16 +46,16 @@ vi.mock('../lib/unsorted', () => ({
buildUnsortedCollection: () => ({
id: '__unsorted__',
name: 'Unsorted',
- items: [],
+ items: [{ kind: 'image', ref: 'loose.png', addedAt: '2024-01-02' }],
synthetic: true,
}),
}));
import MediaCollections from './MediaCollections';
-function renderPage() {
+function renderPage(entry = '/media/collections') {
return render(
- <MemoryRouter initialEntries={['/media/collections']}>
+ <MemoryRouter initialEntries={[entry]}>
<MediaCollections />
</MemoryRouter>,
);
@@ -57,16 +64,15 @@ function renderPage() {
describe('MediaCollections', () => {
beforeEach(() => { vi.clearAllMocks(); });
- it('renders collection names after loading', async () => {
+ it('renders non-empty collection names after loading', async () => {
renderPage();
await waitFor(() => {
expect(screen.getByText('Alpha')).toBeInTheDocument();
- expect(screen.getByText('Beta')).toBeInTheDocument();
});
});
- it('renders a SyncBadge per non-synthetic collection row', async () => {
- renderPage();
+ it('renders a SyncBadge per visible non-synthetic collection row', async () => {
+ renderPage('/media/collections?empty=1');
await waitFor(() => screen.getByText('Alpha'));
// 'in-parity' badge on col-1, 'diverged' on col-2
expect(screen.getByText('In sync')).toBeInTheDocument();
@@ -74,11 +80,58 @@ describe('MediaCollections', () => {
});
it('does not render a SyncBadge for the synthetic Unsorted collection', async () => {
- renderPage();
+ renderPage('/media/collections?empty=1');
await waitFor(() => screen.getByText('Alpha'));
- // Unsorted is synthetic — only 2 badges for the 2 real collections
+ // Unsorted is synthetic — only the real collections with a known sync
+ // status get a badge (col-1 in-parity, col-2 diverged; col-3 has none).
const badges = screen.getAllByRole('button', { name: /in sync|diverged|assets missing|local only|on peer only|not syncing/i });
- // Should be exactly 2 (one per real collection)
expect(badges.length).toBe(2);
});
+
+ it('hides empty collections by default and says how many it hid', async () => {
+ renderPage();
+ await waitFor(() => screen.getByText('Alpha'));
+ expect(screen.queryByText('Beta')).not.toBeInTheDocument();
+ expect(screen.getByText(/2 empty collections hidden/)).toBeInTheDocument();
+ });
+
+ it('reveals the empty collections from the "Show" affordance', async () => {
+ const user = userEvent.setup();
+ renderPage();
+ await waitFor(() => screen.getByText('Alpha'));
+ await user.click(screen.getByRole('button', { name: 'Show' }));
+ expect(await screen.findByText('Beta')).toBeInTheDocument();
+ });
+
+ it('honours ?empty=1 so a shared filtered URL restores the view', async () => {
+ renderPage('/media/collections?empty=1');
+ expect(await screen.findByText('Beta')).toBeInTheDocument();
+ });
+
+ it('filters by the search box', async () => {
+ const user = userEvent.setup();
+ renderPage('/media/collections?empty=1');
+ await waitFor(() => screen.getByText('Alpha'));
+ await user.type(screen.getByLabelText('Search collections'), 'beta');
+ await waitFor(() => expect(screen.queryByText('Alpha')).not.toBeInTheDocument());
+ expect(screen.getByText('Beta')).toBeInTheDocument();
+ });
+
+ it('lifts the shared auto-creator prefix into a badge and keeps the name tail visible', async () => {
+ renderPage('/media/collections?empty=1');
+ await waitFor(() => screen.getByText('Alpha'));
+ expect(screen.getByText('Creative Director')).toBeInTheDocument();
+ // The trailing date survives — an end-clip would have eaten it.
+ expect(screen.getByText(/2026-08-01$/)).toBeInTheDocument();
+ // The full name is still available on hover.
+ expect(screen.getByTitle('Creative Director: Nightly Surreal Landscapes — 2026-08-01')).toBeInTheDocument();
+ });
+
+ it('offers the three sort options', async () => {
+ renderPage();
+ await waitFor(() => screen.getByText('Alpha'));
+ const select = screen.getByLabelText('Sort collections');
+ expect([...select.options].map((o) => o.textContent))
+ .toEqual(['Recently updated', 'Name', 'Item count']);
+ });
});
diff --git a/client/src/utils/README.md b/client/src/utils/README.md
index d58d05136d..8a9b5109f9 100644
--- a/client/src/utils/README.md
+++ b/client/src/utils/README.md
@@ -22,7 +22,7 @@ grep -i "what you want to do" client/src/utils/README.md
| Module | Purpose |
|---|---|
-| `formatters` | Date/time/duration/byte/word formatters (`formatBytes`, `formatCompactCount`, `timeAgo`, `formatTimecode`, `formatDurationMs`, `formatDateShort`, `parseTimeoutMs`, `formatCooldown`, `parseSizeGb`, `recommendedRamGb`, `nameFromImageFilename`, …) plus timeout-input bounds and `getAppName`. Do not re-define formatters inside components. |
+| `formatters` | Date/time/duration/byte/word formatters (`formatBytes`, `formatCompactCount`, `timeAgo`, `formatTimecode`, `formatDurationMs`, `formatDateShort`, `parseTimeoutMs`, `formatCooldown`, `parseSizeGb`, `recommendedRamGb`, `nameFromImageFilename`, `middleTruncate` — clip a long string from the MIDDLE so its distinguishing tail survives, where CSS `line-clamp`/`text-overflow` always eats the end — …) plus timeout-input bounds and `getAppName`. Do not re-define formatters inside components. |
| `cronHelpers` | Cron preset list, `isCronExpression` detection, and `describeCron` human-readable rendering. |
| `timeWindow` | Time-of-day window math (`isInTimeWindow`, `timeStringToMinutes`) and morning-layout auto-switch helpers (`pickActiveLayoutId`, `recordManualLayoutPick`). |
| `timezone` | Timezone day-key helpers (`dayKeyInTimezone`, `todayKeyInTimezone`) — browser mirror of the server's `todayInTimezone`, so date-scoped POST surfaces derive "today" in the user's configured timezone and agree with the server (#2681). |
diff --git a/client/src/utils/formatters.js b/client/src/utils/formatters.js
index f74de06a9d..8359a0e837 100644
--- a/client/src/utils/formatters.js
+++ b/client/src/utils/formatters.js
@@ -391,6 +391,29 @@ export function nameFromImageFilename(filename, fallback = 'Untitled 3D model')
return name || fallback;
}
+/**
+ * Truncate from the MIDDLE so the distinguishing tail of a long string stays
+ * readable — the failure mode of CSS `line-clamp`/`text-overflow`, which always
+ * eats the end. Use it wherever a list renders many strings that share a long
+ * prefix (auto-generated names, dated run labels, deep paths), where clipping
+ * the end collapses every row to the same visible text.
+ * @param {string} value - Source string (non-strings coerce; nullish → '')
+ * @param {number} [max=48] - Maximum length of the RESULT, ellipsis included
+ * @param {string} [ellipsis='…'] - Joiner placed between head and tail
+ * @returns {string} `value` when it already fits, else `head…tail`
+ */
+export function middleTruncate(value, max = 48, ellipsis = '…') {
+ const str = value == null ? '' : String(value);
+ // A max that can't fit the ellipsis plus one char on each side has no
+ // meaningful middle-truncation; fall back to a plain head slice.
+ if (!Number.isFinite(max) || max < ellipsis.length + 2) return str.slice(0, Math.max(0, max));
+ if (str.length <= max) return str;
+ const keep = max - ellipsis.length;
+ const head = Math.ceil(keep / 2);
+ const tail = keep - head;
+ return `${str.slice(0, head)}${ellipsis}${tail > 0 ? str.slice(str.length - tail) : ''}`;
+}
+
/**
* Format a cooldown countdown in milliseconds as "M:SS" (e.g., "1:05", "0:09").
* @param {number} ms - Remaining milliseconds (negative values clamp to 0:00)
diff --git a/client/src/utils/formatters.test.js b/client/src/utils/formatters.test.js
index b1a1d0dc0a..a3e8c8a5c8 100644
--- a/client/src/utils/formatters.test.js
+++ b/client/src/utils/formatters.test.js
@@ -1,7 +1,7 @@
import { describe, it, expect } from 'vitest';
import {
formatContextLength, formatDurationMin, formatDurationMs, formatEventDateTime, timeAgo,
- formatCooldown, parseSizeGb, recommendedRamGb, parseTimeoutMs, formatDurationSec,
+ formatCooldown, parseSizeGb, recommendedRamGb, parseTimeoutMs, formatDurationSec, middleTruncate,
} from './formatters.js';
describe('formatDurationSec', () => {
@@ -252,3 +252,28 @@ describe('parseTimeoutMs', () => {
expect(parseTimeoutMs('30000')).toBe(30000);
});
});
+
+describe('middleTruncate', () => {
+ it('returns the string untouched when it already fits', () => {
+ expect(middleTruncate('short name', 20)).toBe('short name');
+ expect(middleTruncate('exactly-ten', 11)).toBe('exactly-ten');
+ });
+
+ it('keeps the distinguishing tail that an end-clip would eat', () => {
+ const a = middleTruncate('Nightly Surreal Landscapes — 2026-08-01', 24);
+ const b = middleTruncate('Nightly Surreal Landscapes — 2026-08-02', 24);
+ expect(a).not.toBe(b);
+ expect(a.endsWith('2026-08-01')).toBe(true);
+ expect(a.length).toBe(24);
+ });
+
+ it('coerces nullish input to an empty string', () => {
+ expect(middleTruncate(null, 10)).toBe('');
+ expect(middleTruncate(undefined, 10)).toBe('');
+ });
+
+ it('falls back to a head slice when max cannot fit a middle', () => {
+ expect(middleTruncate('abcdef', 2)).toBe('ab');
+ expect(middleTruncate('abcdef', 0)).toBe('');
+ });
+});