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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat: filter the gallery image picker by universe/collection and entry type (#3479)
[._.]/ Adam Eivy783d804b9aef
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 85aef4d8c1..dc5a8539a4 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -71,3 +71,5 @@- **The CoS prompt-builder suite let the contributor's own global `CLAUDE.md` decide its results, so its suppression checks had never actually run on CI.** `buildAgentPrompt` reads `~/.claude/CLAUDE.md` off the real filesystem and splices it verbatim into the prompt, and `agentPromptBuilder.test.js` then asserts the prompt does *not* contain things like `gh pr merge`. That made every negative assertion in the file unsound in both directions: it false-failed on a machine whose personal global instructions happened to mention the string, and — worse — false-passed on a machine with no such file at all, which is exactly what CI is, so the suppression those assertions exist to prove was never exercised there. `homedir()` is now stubbed to a path that cannot exist, making the global section deterministically empty, and a new fixture-backed test closes the gap from the other side: it points the stub at a throwaway home whose global `CLAUDE.md` deliberately *does* contain the suppressed strings, asserts the fixture really is spliced in verbatim, and then asserts every section the builder itself authored still omits them on the reasoning-only path. Verified by breaking the suppression and watching the new test fail (#3475).- **`completeAgent` had three addresses, and the four callers that most needed one address were using the wrong one.** Continuing #3450's sequencing: `agentManagement.js`, `agentLifecycle.js`, `agentFinalization.js` and `agentCliSpawning.js` all reached the completion transition through the `cosAgents.js` barrel. These four are the callers the "move the caller above the facade" recipe cannot reach — the first two DEFINE transitions `agentOrchestrator.js` re-exports, so importing the facade from either is the cycle itself, and the other two are leaves those two must call to spawn and to finalize. So the rule they follow is the other half of the same property: above the facade's closure a transition comes from the facade, inside it from the module that DECLARES it (`cosAgentLifecycle.js`), and never from a barrel. `cleanupOrphanedAgents`'s `await import('./cos.js')` went with it — it was pulling `completeAgent` and `getAgents` through the `cos.js` re-export block while the module was already a static import three lines up, so the deferral bought no cycle protection at all. The new guard in `agentImportCycles.test.js` derives the transition names from the facade's export blocks and walks re-export edges to work out which modules forward them, so a barrel added later is covered without being named; it catches a named import, a renamed one, a namespace property read, a destructure off a namespace handle, and the three deferred spellings of the same reaches — including `const { completeAgent } = await import('./cos.js')`, the exact pattern this change deleted. Each bypass-probed.++- **The "Pick from Gallery" picker could only be narrowed by typing, so finding one object in one universe meant recalling a word from its prompt.** It now carries two dropdowns beside the search box: a scope select that groups every universe and media collection under `<optgroup>`s, and a type select built from the `entryCategory`/`entryKind` tags the Universe Builder stamps onto sidecars, labelled through the same `humanizeCategory` the Builder uses. All three filters AND-combine, and both dropdowns list only universes/collections/types that actually match an image currently in the picker — a scope that can only ever produce an empty grid isn't offered, and a selection that stops matching resets itself to "All" rather than silently blanking the grid. Collection membership is matched on the stored `{ kind, ref }` pair (the same `<kind>:<ref>` string `normalizeImage` puts on `item.key`), not on a bare filename, so a collection holding video refs alongside images filters correctly. Both option fetches are best-effort: if the collections or universes call fails the picker keeps working, falling back to the universe name stamped on each sidecar (#3479).diff --git a/client/src/components/imageGen/GalleryImagePicker.jsx b/client/src/components/imageGen/GalleryImagePicker.jsxindex 4a42b9bc6a..638535b03c 100644--- a/client/src/components/imageGen/GalleryImagePicker.jsx+++ b/client/src/components/imageGen/GalleryImagePicker.jsx@@ -5,6 +5,9 @@// same as MediaHistory) and click a thumbnail to pick it. Calls `onSelect(item)`// with the normalized media item (item.filename + item.previewUrl) then closes.//+// Two dropdowns narrow the grid further: a grouped Universe/Collection scope+// and an entry Type. Both AND-combine with the text query.+//// With `allowUpload`, a header "Upload" button lets the user pick a file off// disk: it's saved into the gallery via POST /api/image-gen/upload (so the// stored `/data/images/<f>` URL syncs to peers, unlike a generic upload) and@@ -19,22 +22,38 @@ import Modal from '../ui/Modal';import FilePickerButton from '../ui/FilePickerButton';import MediaCard from '../media/MediaCard';import { normalizeImage } from '../media/normalize';-import { listImageGallery } from '../../services/apiImageVideo';+import { listImageGallery, listMediaCollections } from '../../services/apiImageVideo';+import { listUniverses } from '../../services/apiUniverseBuilder';import { uploadGalleryImage } from '../../services/apiSystem';import { readFileAsBase64 } from '../../utils/fileUpload';import { buildMediaHaystack, tokenizeQuery, matchHaystack } from '../../lib/mediaSearch';+import { humanizeCategory } from '../../lib/universeBuilderShared';import toast from '../ui/Toast';+// Scope-select values are prefixed so one <select> can carry both option kinds.+const UNI_PREFIX = 'uni:';+const COL_PREFIX = 'col:';+// A collection stores membership as `{ kind, ref }` (server/lib/mediaItemKey.js),+// which serializes to the same `<kind>:<ref>` string `normalizeImage` puts on+// `item.key` — so membership is a set lookup, not a filename comparison.+const membershipKey = (it) => `${it?.kind}:${it?.ref}`;+const byLabel = (a, b) => a.label.localeCompare(b.label);+export default function GalleryImagePicker({ open, onClose, onSelect, allowUpload = false }) {const [items, setItems] = useState([]);const [loading, setLoading] = useState(false);const [uploading, setUploading] = useState(false);const [query, setQuery] = useState('');+ const [collections, setCollections] = useState([]);+ const [universes, setUniverses] = useState([]);+ // '' = All. Otherwise `uni:<id>` or `col:<id>`.+ const [scope, setScope] = useState('');+ const [type, setType] = useState('');// Fetch the gallery each time the picker opens so newly generated images show// up without a page reload. Reset the search on close so a re-open starts clean.useEffect(() => {- if (!open) { setQuery(''); return; }+ if (!open) { setQuery(''); setScope(''); setType(''); return; }let cancelled = false;setLoading(true);listImageGallery()@@ -51,14 +70,90 @@ export default function GalleryImagePicker({ open, onClose, onSelect, allowUploareturn () => { cancelled = true; };}, [open]);+ // Filter sources are best-effort: either fetch failing just drops that group+ // from the scope dropdown, leaving text + type filtering intact. `silent`+ // because the empty-list fallback below is this caller's error UI.+ useEffect(() => {+ if (!open) return undefined;+ let cancelled = false;+ listMediaCollections({ silent: true })+ .then((list) => { if (!cancelled) setCollections(Array.isArray(list) ? list : []); })+ .catch(() => { if (!cancelled) setCollections([]); });+ listUniverses({ silent: true })+ .then((list) => { if (!cancelled) setUniverses(Array.isArray(list) ? list : []); })+ .catch(() => { if (!cancelled) setUniverses([]); });+ return () => { cancelled = true; };+ }, [open]);+// Cache each item's haystack per fetched list; keystrokes then only re-run the// cheap token match instead of rebuilding every haystack (mirrors MediaHistory).const haystacks = useMemo(() => items.map(buildMediaHaystack), [items]);const tokens = useMemo(() => tokenizeQuery(query), [query]);- const filtered = useMemo(- () => tokens.length === 0 ? items : items.filter((_, idx) => matchHaystack(haystacks[idx], tokens)),- [items, haystacks, tokens],- );++ // Universes are seeded from the images' own `universeId`/`universeName` stamps+ // so the group still populates when listUniverses fails; the fetched record+ // only supplies a fresher display name for a universe that was renamed after+ // the sidecar was written. Universes with no image here are dropped — a scope+ // that can only ever yield an empty grid isn't worth an option row.+ const universeOptions = useMemo(() => {+ const present = new Map();+ for (const it of items) {+ if (it.universeId && !present.has(it.universeId)) present.set(it.universeId, it.universeName || it.universeId);+ }+ for (const u of universes) {+ if (u?.id && u.name && present.has(u.id)) present.set(u.id, u.name);+ }+ return [...present.entries()]+ .map(([id, label]) => ({ value: `${UNI_PREFIX}${id}`, label }))+ .sort(byLabel);+ }, [items, universes]);++ const galleryKeys = useMemo(() => new Set(items.map((it) => it.key)), [items]);++ // Same "must match something" rule as universes. A collection also holds video+ // refs, which this image-only picker can never surface.+ const collectionOptions = useMemo(() => collections+ .filter((c) => Array.isArray(c?.items) && c.items.some((it) => galleryKeys.has(membershipKey(it))))+ .map((c) => ({ value: `${COL_PREFIX}${c.id}`, label: c.name || c.id }))+ .sort(byLabel), [collections, galleryKeys]);++ const typeOptions = useMemo(() => {+ const seen = new Set();+ for (const it of items) {+ if (it.entryCategory) seen.add(it.entryCategory);+ if (it.entryKind) seen.add(it.entryKind);+ }+ return [...seen].map((value) => ({ value, label: humanizeCategory(value) })).sort(byLabel);+ }, [items]);++ // Membership set for the selected collection — `null` whenever no collection+ // is scoped, which is the signal the filter uses to skip the check entirely.+ const scopedCollectionKeys = useMemo(() => {+ if (!scope.startsWith(COL_PREFIX)) return null;+ const collection = collections.find((c) => c?.id === scope.slice(COL_PREFIX.length));+ return new Set((collection?.items || []).map(membershipKey));+ }, [scope, collections]);++ // A selection that survived a gallery/collection refetch but no longer has an+ // option row would silently filter everything out — drop it back to "All".+ useEffect(() => {+ if (scope && ![...universeOptions, ...collectionOptions].some((o) => o.value === scope)) setScope('');+ }, [scope, universeOptions, collectionOptions]);+ useEffect(() => {+ if (type && !typeOptions.some((o) => o.value === type)) setType('');+ }, [type, typeOptions]);++ const filtered = useMemo(() => {+ const universeId = scope.startsWith(UNI_PREFIX) ? scope.slice(UNI_PREFIX.length) : null;+ if (tokens.length === 0 && !universeId && !scopedCollectionKeys && !type) return items;+ return items.filter((item, idx) => {+ if (tokens.length > 0 && !matchHaystack(haystacks[idx], tokens)) return false;+ if (universeId && item.universeId !== universeId) return false;+ if (scopedCollectionKeys && !scopedCollectionKeys.has(item.key)) return false;+ if (type && item.entryCategory !== type && item.entryKind !== type) return false;+ return true;+ });+ }, [items, haystacks, tokens, scope, scopedCollectionKeys, type]);// Upload a file off disk into the gallery, then select it like any gallery// image. Saving goes through the peer-syncable `/data/images/` upload so the@@ -94,50 +189,95 @@ export default function GalleryImagePicker({ open, onClose, onSelect, allowUploapanelClassName="bg-port-card border border-port-border rounded-xl max-h-[85vh] flex flex-col"ariaLabel="Pick an image from your gallery">- <div className="flex items-center justify-between gap-3 p-3 border-b border-port-border">- <h2 className="text-sm font-medium text-white shrink-0">Pick from gallery</h2>- <div className="relative flex-1 max-w-md">- <Search className="absolute left-2 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-gray-500" />- <input- type="text"- value={query}- onChange={(e) => setQuery(e.target.value)}- placeholder="Search prompt, model, seed, LoRA…"- className="w-full pl-7 pr-7 py-1.5 text-xs bg-port-bg border border-port-border rounded-lg text-white placeholder-gray-500 focus:outline-none focus:border-port-accent"- autoFocus- />- {query && (+ <div className="p-3 border-b border-port-border space-y-2">+ <div className="flex items-center justify-between gap-3">+ <h2 className="text-sm font-medium text-white shrink-0">Pick from gallery</h2>+ <div className="flex items-center gap-2 shrink-0">+ {allowUpload && (+ <FilePickerButton+ accept="image/png,image/jpeg,image/webp,image/gif"+ onChange={handleUpload}+ disabled={uploading}+ title="Upload an image from your device"+ className="inline-flex shrink-0 items-center gap-1.5 rounded-lg border border-port-border bg-port-bg px-2.5 py-1.5 text-xs text-gray-300 hover:border-port-accent hover:text-white"+ >+ {uploading+ ? <><RefreshCw className="h-3.5 w-3.5 animate-spin" /> Uploading…</>+ : <><Upload className="h-3.5 w-3.5" /> Upload</>}+ </FilePickerButton>+ )}<buttontype="button"- onClick={() => setQuery('')}- className="absolute right-2 top-1/2 -translate-y-1/2 text-gray-500 hover:text-white"- aria-label="Clear search"+ onClick={onClose}+ className="shrink-0 p-1.5 text-gray-400 hover:text-white rounded min-h-[44px] min-w-[44px] flex items-center justify-center"+ aria-label="Close">- <X className="w-3.5 h-3.5" />+ <X className="w-4 h-4" /></button>+ </div>+ </div>+ <div className="flex flex-col sm:flex-row sm:items-center gap-2">+ <div className="relative flex-1 min-w-0">+ <label htmlFor="gallery-picker-search" className="sr-only">Search gallery</label>+ <Search className="absolute left-2 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-gray-500" />+ <input+ id="gallery-picker-search"+ type="text"+ value={query}+ onChange={(e) => setQuery(e.target.value)}+ placeholder="Search prompt, model, seed, LoRA…"+ className="w-full pl-7 pr-7 py-1.5 text-xs bg-port-bg border border-port-border rounded-lg text-white placeholder-gray-500 focus:outline-none focus:border-port-accent"+ autoFocus+ />+ {query && (+ <button+ type="button"+ onClick={() => setQuery('')}+ className="absolute right-2 top-1/2 -translate-y-1/2 text-gray-500 hover:text-white"+ aria-label="Clear search"+ >+ <X className="w-3.5 h-3.5" />+ </button>+ )}+ </div>+ {(universeOptions.length > 0 || collectionOptions.length > 0) && (+ <div className="sm:w-44">+ <label htmlFor="gallery-picker-scope" className="sr-only">Filter by universe or collection</label>+ <select+ id="gallery-picker-scope"+ value={scope}+ onChange={(e) => setScope(e.target.value)}+ className="w-full bg-port-bg border border-port-border rounded-lg px-2 py-1.5 text-xs text-white focus:outline-none focus:border-port-accent"+ >+ <option value="">All universes & collections</option>+ {universeOptions.length > 0 && (+ <optgroup label="Universes">+ {universeOptions.map((o) => <option key={o.value} value={o.value}>{o.label}</option>)}+ </optgroup>+ )}+ {collectionOptions.length > 0 && (+ <optgroup label="Collections">+ {collectionOptions.map((o) => <option key={o.value} value={o.value}>{o.label}</option>)}+ </optgroup>+ )}+ </select>+ </div>+ )}+ {typeOptions.length > 0 && (+ <div className="sm:w-36">+ <label htmlFor="gallery-picker-type" className="sr-only">Filter by type</label>+ <select+ id="gallery-picker-type"+ value={type}+ onChange={(e) => setType(e.target.value)}+ className="w-full bg-port-bg border border-port-border rounded-lg px-2 py-1.5 text-xs text-white focus:outline-none focus:border-port-accent"+ >+ <option value="">All types</option>+ {typeOptions.map((o) => <option key={o.value} value={o.value}>{o.label}</option>)}+ </select>+ </div>)}</div>- {allowUpload && (- <FilePickerButton- accept="image/png,image/jpeg,image/webp,image/gif"- onChange={handleUpload}- disabled={uploading}- title="Upload an image from your device"- className="inline-flex shrink-0 items-center gap-1.5 rounded-lg border border-port-border bg-port-bg px-2.5 py-1.5 text-xs text-gray-300 hover:border-port-accent hover:text-white"- >- {uploading- ? <><RefreshCw className="h-3.5 w-3.5 animate-spin" /> Uploading…</>- : <><Upload className="h-3.5 w-3.5" /> Upload</>}- </FilePickerButton>- )}- <button- type="button"- onClick={onClose}- className="shrink-0 p-1.5 text-gray-400 hover:text-white rounded min-h-[44px] min-w-[44px] flex items-center justify-center"- aria-label="Close"- >- <X className="w-4 h-4" />- </button></div><div className="flex-1 overflow-y-auto p-3">@@ -147,7 +287,7 @@ export default function GalleryImagePicker({ open, onClose, onSelect, allowUploa</div>) : filtered.length === 0 ? (<div className="text-xs text-gray-500 py-10 text-center">- {items.length === 0 ? 'No images in your gallery yet.' : 'No images match your search.'}+ {items.length === 0 ? 'No images in your gallery yet.' : 'No images match your search or filters.'}</div>) : (<div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 gap-3">diff --git a/client/src/components/imageGen/GalleryImagePicker.test.jsx b/client/src/components/imageGen/GalleryImagePicker.test.jsxindex d2373ec867..db73e2ef73 100644--- a/client/src/components/imageGen/GalleryImagePicker.test.jsx+++ b/client/src/components/imageGen/GalleryImagePicker.test.jsx@@ -3,8 +3,19 @@ import { render, screen, fireEvent, waitFor } from '@testing-library/react';import GalleryImagePicker from './GalleryImagePicker';const listImageGallery = vi.fn();+const listMediaCollections = vi.fn();vi.mock('../../services/apiImageVideo', () => ({listImageGallery: (...args) => listImageGallery(...args),+ listMediaCollections: (...args) => listMediaCollections(...args),+}));++const listUniverses = vi.fn();+// universeBuilderShared imports the WORLD_CATEGORY_* constants from this module,+// so the mock has to carry them or the shared lib loads with undefined values.+vi.mock('../../services/apiUniverseBuilder', () => ({+ listUniverses: (...args) => listUniverses(...args),+ WORLD_CATEGORIES: ['landscapes', 'environments', 'structures', 'vehicles'],+ WORLD_CATEGORY_KEY_MAX: 64,}));const uploadGalleryImage = vi.fn();@@ -19,14 +30,40 @@ vi.mock('../../utils/fileUpload', () => ({vi.mock('../ui/Toast', () => ({ default: { error: vi.fn(), success: vi.fn() } }));const GALLERY = [- { filename: 'neon.png', path: '/data/images/neon.png', prompt: 'a neon sunset', modelId: 'flux2', seed: 1 },- { filename: 'forest.png', path: '/data/images/forest.png', prompt: 'a quiet forest', modelId: 'sdxl', seed: 2 },+ {+ filename: 'neon.png', path: '/data/images/neon.png', prompt: 'a neon sunset', modelId: 'flux2', seed: 1,+ universeId: 'uni-a', universeName: 'Stale Name', entryCategory: 'characters', entryKind: 'canon',+ },+ {+ filename: 'forest.png', path: '/data/images/forest.png', prompt: 'a quiet forest', modelId: 'sdxl', seed: 2,+ universeId: 'uni-b', universeName: 'Second Universe', entryCategory: 'landscapes', entryKind: 'variation',+ },+ {+ filename: 'mecha.png', path: '/data/images/mecha.png', prompt: 'a chrome mecha', modelId: 'flux2', seed: 3,+ universeId: 'uni-a', universeName: 'Stale Name', entryCategory: 'vehicles', entryKind: 'canon',+ },+];++// `items` are `{ kind, ref }` pairs, not bare filenames — the same shape the+// server persists (server/lib/mediaItemKey.js).+const COLLECTIONS = [+ { id: 'col-1', name: 'Mood Board', items: [{ kind: 'image', ref: 'forest.png' }, { kind: 'video', ref: 'clip-1' }] },+ { id: 'col-2', name: 'Video Only', items: [{ kind: 'video', ref: 'clip-2' }] },];+const UNIVERSES = [{ id: 'uni-a', name: 'Renamed Universe' }];++const scopeSelect = () => screen.getByLabelText(/universe or collection/i);+const typeSelect = () => screen.getByLabelText(/filter by type/i);+describe('GalleryImagePicker', () => {beforeEach(() => {listImageGallery.mockReset();listImageGallery.mockResolvedValue(GALLERY);+ listMediaCollections.mockReset();+ listMediaCollections.mockResolvedValue(COLLECTIONS);+ listUniverses.mockReset();+ listUniverses.mockResolvedValue(UNIVERSES);});it('does not fetch or render while closed', () => {@@ -88,4 +125,110 @@ describe('GalleryImagePicker', () => {expect(onSelect.mock.calls[0][0]).toMatchObject({ filename: 'upload-abcd1234.png', previewUrl: '/data/images/upload-abcd1234.png' });expect(onClose).toHaveBeenCalledTimes(1);});++ it('filters by universe, preferring the fetched record name over the stamped one', async () => {+ render(<GalleryImagePicker open onClose={vi.fn()} onSelect={vi.fn()} />);+ await screen.findByAltText('a neon sunset');+ await waitFor(() => expect(screen.getByRole('option', { name: 'Renamed Universe' })).toBeTruthy());+ expect(screen.queryByRole('option', { name: 'Stale Name' })).toBeNull();++ fireEvent.change(scopeSelect(), { target: { value: 'uni:uni-a' } });+ await waitFor(() => expect(screen.queryByAltText('a quiet forest')).toBeNull());+ expect(screen.getByAltText('a neon sunset')).toBeTruthy();+ expect(screen.getByAltText('a chrome mecha')).toBeTruthy();+ });++ it('filters by collection membership and omits collections with no image in the gallery', async () => {+ render(<GalleryImagePicker open onClose={vi.fn()} onSelect={vi.fn()} />);+ await screen.findByAltText('a neon sunset');+ await waitFor(() => expect(screen.getByRole('option', { name: 'Mood Board' })).toBeTruthy());+ // 'Video Only' holds a video ref, which this image picker can never show.+ expect(screen.queryByRole('option', { name: 'Video Only' })).toBeNull();++ fireEvent.change(scopeSelect(), { target: { value: 'col:col-1' } });+ await waitFor(() => expect(screen.queryByAltText('a neon sunset')).toBeNull());+ expect(screen.getByAltText('a quiet forest')).toBeTruthy();+ expect(screen.queryByAltText('a chrome mecha')).toBeNull();+ });++ it('filters by type across entryCategory and entryKind, with humanized labels', async () => {+ render(<GalleryImagePicker open onClose={vi.fn()} onSelect={vi.fn()} />);+ await screen.findByAltText('a neon sunset');+ expect(screen.getByRole('option', { name: 'Vehicles' })).toBeTruthy();+ expect(screen.getByRole('option', { name: 'Canon' })).toBeTruthy();++ fireEvent.change(typeSelect(), { target: { value: 'vehicles' } });+ await waitFor(() => expect(screen.queryByAltText('a neon sunset')).toBeNull());+ expect(screen.getByAltText('a chrome mecha')).toBeTruthy();++ // entryKind is matched by the same select — 'variation' only tags forest.+ fireEvent.change(typeSelect(), { target: { value: 'variation' } });+ await waitFor(() => expect(screen.queryByAltText('a chrome mecha')).toBeNull());+ expect(screen.getByAltText('a quiet forest')).toBeTruthy();+ });++ it('AND-combines the filters with the text query', async () => {+ render(<GalleryImagePicker open onClose={vi.fn()} onSelect={vi.fn()} />);+ await screen.findByAltText('a neon sunset');+ await waitFor(() => expect(screen.getByRole('option', { name: 'Renamed Universe' })).toBeTruthy());++ fireEvent.change(scopeSelect(), { target: { value: 'uni:uni-a' } });+ fireEvent.change(screen.getByPlaceholderText(/Search prompt/i), { target: { value: 'mecha' } });+ await waitFor(() => expect(screen.queryByAltText('a neon sunset')).toBeNull());+ expect(screen.getByAltText('a chrome mecha')).toBeTruthy();++ // Query that matches only an out-of-scope image yields nothing, not a fallback.+ fireEvent.change(screen.getByPlaceholderText(/Search prompt/i), { target: { value: 'forest' } });+ await waitFor(() => expect(screen.queryByAltText('a chrome mecha')).toBeNull());+ expect(screen.queryByAltText('a quiet forest')).toBeNull();+ expect(screen.getByText(/No images match your search or filters/i)).toBeTruthy();+ });++ it('restores the full grid when the filters are cleared back to All', async () => {+ render(<GalleryImagePicker open onClose={vi.fn()} onSelect={vi.fn()} />);+ await screen.findByAltText('a neon sunset');+ await waitFor(() => expect(screen.getByRole('option', { name: 'Mood Board' })).toBeTruthy());++ fireEvent.change(scopeSelect(), { target: { value: 'col:col-1' } });+ fireEvent.change(typeSelect(), { target: { value: 'variation' } });+ await waitFor(() => expect(screen.queryByAltText('a neon sunset')).toBeNull());++ fireEvent.change(scopeSelect(), { target: { value: '' } });+ fireEvent.change(typeSelect(), { target: { value: '' } });+ await waitFor(() => expect(screen.getByAltText('a neon sunset')).toBeTruthy());+ expect(screen.getByAltText('a quiet forest')).toBeTruthy();+ expect(screen.getByAltText('a chrome mecha')).toBeTruthy();+ });++ it('degrades to image-derived universes and no collections when those fetches fail', async () => {+ listMediaCollections.mockRejectedValue(new Error('nope'));+ listUniverses.mockRejectedValue(new Error('nope'));+ render(<GalleryImagePicker open onClose={vi.fn()} onSelect={vi.fn()} />);+ await screen.findByAltText('a neon sunset');++ // Universe options fall back to the name stamped on the sidecar.+ await waitFor(() => expect(screen.getByRole('option', { name: 'Stale Name' })).toBeTruthy());+ expect(screen.queryByRole('option', { name: 'Mood Board' })).toBeNull();++ fireEvent.change(scopeSelect(), { target: { value: 'uni:uni-b' } });+ await waitFor(() => expect(screen.queryByAltText('a neon sunset')).toBeNull());+ expect(screen.getByAltText('a quiet forest')).toBeTruthy();+ });++ it('passes silent:true so the picker owns its own filter-fetch failure handling', async () => {+ render(<GalleryImagePicker open onClose={vi.fn()} onSelect={vi.fn()} />);+ await screen.findByAltText('a neon sunset');+ expect(listMediaCollections).toHaveBeenCalledWith({ silent: true });+ expect(listUniverses).toHaveBeenCalledWith({ silent: true });+ });++ it('does not render the filter selects when nothing is filterable', async () => {+ listImageGallery.mockResolvedValue([{ filename: 'plain.png', path: '/data/images/plain.png', prompt: 'plain' }]);+ listMediaCollections.mockResolvedValue([]);+ listUniverses.mockResolvedValue([]);+ render(<GalleryImagePicker open onClose={vi.fn()} onSelect={vi.fn()} />);+ await screen.findByAltText('plain');+ expect(screen.queryByLabelText(/universe or collection/i)).toBeNull();+ expect(screen.queryByLabelText(/filter by type/i)).toBeNull();+ });});