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: order and badge the collection picker rows like the collections grid (#3312)
[._.]/ Adam Eivyb88fdd9bbf32
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 48309dd434..6ac9123762 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -128,6 +128,7 @@## Media Collections- **[issue-3311] A collection now records who created it instead of the grid guessing from its name.** The "auto-generated" ordering and badge shipped in #3283 reverse-engineered provenance on the client from four independent clues — a name prefix, an `Auto-…` description, a `uc-`/`sc-` id, or a universe/series link — so every new machine-created bucket quietly sorted as if you had made it yourself until someone remembered to extend that list. Collections are now stamped `auto` or `user` when they are created, existing ones were classified once by a migration, and the old clue-matching only runs for a record a peer on an older version has not stamped yet.+- **[issue-3312] The "file this into a collection" picker got the same treatment as the grid.** The popover you actually use to file an image or video still listed every collection in raw order with the full prefixed name in each row, so filing something meant scrolling a wall of identical `Creative Director: …` entries in a 240px-wide dropdown. Rows now use the same ordering as `/media/collections` — collections holding something sort above the auto-generated empties — and each row lifts the shared creator prefix into a small badge so the part of the name that tells them apart gets the full row width. Search matches its words in any order instead of demanding one contiguous substring. Empty collections are still listed, since filing *into* an empty collection is the whole point.## UI Consistencydiff --git a/client/src/components/media/AddToCollectionMenu.jsx b/client/src/components/media/AddToCollectionMenu.jsxindex 1887c8942e..83ddcdfd59 100644--- a/client/src/components/media/AddToCollectionMenu.jsx+++ b/client/src/components/media/AddToCollectionMenu.jsx@@ -2,6 +2,7 @@ import { useCallback, useRef, useState } from 'react';import { FolderPlus, Check } from 'lucide-react';import toast from '../ui/Toast';import CollectionPickerShell from './CollectionPickerShell';+import CollectionRowLabel from './CollectionRowLabel';import { addMediaCollectionItem, removeMediaCollectionItem } from '../../services/api';// Self-contained popover button used by MediaCard. The popover is portalled@@ -62,7 +63,7 @@ export default function AddToCollectionMenu({ item, size = 'sm' }) {role="menuitemcheckbox"aria-checked={inIt}>- <span className="break-words min-w-0 flex-1">{c.name}</span>+ <CollectionRowLabel name={c.name} />{inIt && <Check className="w-3.5 h-3.5 text-port-success shrink-0" />}</button>);diff --git a/client/src/components/media/AddToCollectionMenu.test.jsx b/client/src/components/media/AddToCollectionMenu.test.jsxnew file mode 100644index 0000000000..3fad5b8aa5--- /dev/null+++ b/client/src/components/media/AddToCollectionMenu.test.jsx@@ -0,0 +1,99 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import { render, screen, fireEvent, act } from '@testing-library/react';+import AddToCollectionMenu from './AddToCollectionMenu';++// Covers the picker's list presentation (#3312): CollectionPickerShell orders+// rows with the shared `applyCollectionView` and each row renders the+// prefix-stripped title with the auto-creator prefix lifted into a badge, the+// same as the /media/collections grid (#3283).++const api = vi.hoisted(() => ({+ listMediaCollections: vi.fn(),+ createMediaCollection: vi.fn(),+ addMediaCollectionItem: vi.fn(),+ removeMediaCollectionItem: vi.fn(),+}));++vi.mock('../../services/api', () => api);+vi.mock('../ui/Toast', () => ({ default: { success: vi.fn(), error: vi.fn() } }));++const item = { kind: 'image', key: 'image:hero.png', filename: 'hero.png' };++// Six collections so the shell's search input renders (SEARCH_THRESHOLD).+// Deliberately shuffled relative to the expected display order, and the auto+// empties carry the NEWEST timestamps so a raw "recently updated" sort alone+// would float them to the top.+const collections = [+ { id: 'cd-1', name: 'Creative Director: Zephyr Drift', source: 'auto', items: [], updatedAt: '2026-01-05T00:00:00Z' },+ { id: 'c-keep', name: 'Keepers', source: 'user', items: [], updatedAt: '2026-01-01T00:00:00Z' },+ { id: 'cd-2', name: 'Creative Director: Amber Loop', source: 'auto', items: [{ kind: 'image', ref: 'a.png' }], updatedAt: '2026-01-04T00:00:00Z' },+ { id: 'uc-1', name: 'Universe: Example Universe', source: 'auto', items: [], updatedAt: '2026-01-03T00:00:00Z' },+ { id: 'c-ref', name: 'Reference Shots', source: 'user', items: [{ kind: 'image', ref: 'b.png' }], updatedAt: '2026-01-02T00:00:00Z' },+ { id: 'c-wall', name: 'Wallpapers', source: 'user', items: [], updatedAt: '2025-12-31T00:00:00Z' },+];++const openMenu = async () => {+ render(<AddToCollectionMenu item={item} />);+ fireEvent.click(screen.getByTitle('Add to collection'));+ await screen.findByRole('menuitemcheckbox', { name: /Keepers/ });+};++const rowTitles = () =>+ screen.getAllByRole('menuitemcheckbox').map((el) => el.textContent.trim());++beforeEach(() => {+ vi.clearAllMocks();+ api.listMediaCollections.mockResolvedValue(collections);+});++describe('AddToCollectionMenu row presentation', () => {+ it('sinks auto-created empties below everything else, newest-updated first within a bucket', async () => {+ await openMenu();++ expect(rowTitles()).toEqual([+ 'Creative DirectorAmber Loop', // auto but has items → stays in the top bucket+ 'Reference Shots',+ 'Keepers',+ 'Wallpapers',+ 'Creative DirectorZephyr Drift', // auto + empty → bottom bucket despite newest updatedAt+ 'UniverseExample Universe',+ ]);+ });++ it('lifts the auto-creator prefix into a badge and keeps the full name as the tooltip', async () => {+ await openMenu();++ const row = screen.getByRole('menuitemcheckbox', { name: /Zephyr Drift/ });+ expect(row.querySelector('[title]')).toHaveAttribute('title', 'Creative Director: Zephyr Drift');+ // The badge is its own element so the distinguishing tail owns the row width.+ expect(screen.getAllByText('Creative Director')).toHaveLength(2);+ expect(screen.getByText('Zephyr Drift')).toBeInTheDocument();+ });++ it('still lists empty collections — filing INTO an empty collection is the point', async () => {+ await openMenu();++ expect(screen.getByRole('menuitemcheckbox', { name: /Wallpapers/ })).toBeInTheDocument();+ expect(screen.getByRole('menuitemcheckbox', { name: /Example Universe/ })).toBeInTheDocument();+ });++ it('matches search tokens in any order (AND-token, not a single substring)', async () => {+ await openMenu();++ await act(async () => {+ fireEvent.change(screen.getByPlaceholderText('Search collections…'), { target: { value: 'loop amber' } });+ });++ expect(rowTitles()).toEqual(['Creative DirectorAmber Loop']);+ });++ it('keeps matching a plain substring of the prefixed name', async () => {+ await openMenu();++ await act(async () => {+ fireEvent.change(screen.getByPlaceholderText('Search collections…'), { target: { value: 'wallpaper' } });+ });++ expect(rowTitles()).toEqual(['Wallpapers']);+ });+});diff --git a/client/src/components/media/BulkTargetPicker.jsx b/client/src/components/media/BulkTargetPicker.jsxindex 7694c664b4..b223d36fe5 100644--- a/client/src/components/media/BulkTargetPicker.jsx+++ b/client/src/components/media/BulkTargetPicker.jsx@@ -1,5 +1,6 @@import { useCallback } from 'react';import CollectionPickerShell from './CollectionPickerShell';+import CollectionRowLabel from './CollectionRowLabel';// Single-target picker used by MediaCollectionDetail's bulk-action bar.// AddToCollectionMenu toggles membership for one item across many collections;@@ -33,7 +34,7 @@ export default function BulkTargetPicker({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>+ <CollectionRowLabel name={c.name} /><span className="text-[10px] text-gray-500 shrink-0">{c.items?.length ?? 0}</span></button>), [busy, onPick]);diff --git a/client/src/components/media/CollectionPickerShell.jsx b/client/src/components/media/CollectionPickerShell.jsxindex 42d90c4091..9254c89c3a 100644--- a/client/src/components/media/CollectionPickerShell.jsx+++ b/client/src/components/media/CollectionPickerShell.jsx@@ -4,6 +4,7 @@ import { Plus, Search } from 'lucide-react';import toast from '../ui/Toast';import { listMediaCollections, createMediaCollection } from '../../services/api';import usePopoverPosition, { VIEWPORT_PADDING } from '../../hooks/usePopoverPosition.js';+import { applyCollectionView } from '../../lib/mediaCollectionList.js';// Shared popover shell for the list-pick-or-create pickers://@@ -120,11 +121,22 @@ export default function CollectionPickerShell({return () => { cancelled = true; };}, [open, collectionsProp, loadItems]);+ // Search + ordering come from the same helper the /media/collections grid uses+ // (#3283), so the picker and the grid agree on what a query matches and what+ // order rows land in — auto-generated empties sink to the bottom instead of+ // burying the real collections in the raw list order (#3312).+ //+ // "Hide empty" is deliberately NOT applied here: filing an item INTO an empty+ // collection is the picker's main job, so the empties are ordered last, never+ // removed. The AND-token matcher replaces the old single-substring filter —+ // it's a strict superset (every token of a query is itself a substring of that+ // query), so nothing that matched before stops matching, and multi-word+ // queries now match in any order, which matters once the shared+ // "Creative Director: " prefix lives in a badge and users type only the tail.const filtered = useMemo(() => {if (!collectionsState) return null;const base = excludeId ? collectionsState.filter((c) => c.id !== excludeId) : collectionsState;- const q = query.trim().toLowerCase();- return q ? base.filter((c) => c.name.toLowerCase().includes(q)) : base;+ return applyCollectionView(base, { query });}, [collectionsState, query, excludeId]);// Close on outside-click / Escape — placement and scroll/resize reflow are@@ -176,7 +188,9 @@ export default function CollectionPickerShell({if (!open) return null;const showSearch = (collectionsState?.length || 0) >= SEARCH_THRESHOLD;- const list = filtered ?? collectionsState;+ // `filtered` is null only while the list is still loading (same sentinel as+ // `collectionsState`), so it is the single render source once loaded.+ const list = filtered;return createPortal(<divdiff --git a/client/src/components/media/CollectionRowLabel.jsx b/client/src/components/media/CollectionRowLabel.jsxnew file mode 100644index 0000000000..c9b5a271c5--- /dev/null+++ b/client/src/components/media/CollectionRowLabel.jsx@@ -0,0 +1,28 @@+import { splitCollectionName } from '../../lib/mediaCollectionList.js';++// Collection name as rendered inside a CollectionPickerShell row (#3312) — the+// dropdown twin of the MediaCollections card title (#3283).+//+// Every Creative Director project / Writers Room batch / universe / series+// render bucket auto-files itself as a collection named+// "<Creator>: <the part that actually differs>". Rendered flat in a ~240px+// popover row those all read as the same clipped prefix, so `splitCollectionName`+// lifts the prefix into a small badge above the title and the distinguishing+// tail gets the full row width. User-named collections (and mood boards) have no+// prefix and render as a plain title, exactly as before.+//+// The full original name stays reachable as the `title` tooltip, matching the+// card.+export default function CollectionRowLabel({ name }) {+ const { badge, title } = splitCollectionName(name);+ return (+ <span className="min-w-0 flex-1 flex flex-col items-start gap-0.5" title={name}>+ {badge && (+ <span className="text-[9px] uppercase tracking-wide text-gray-400 bg-port-bg border border-port-border rounded px-1 py-px leading-tight">+ {badge}+ </span>+ )}+ <span className="break-words text-left">{title}</span>+ </span>+ );+}diff --git a/client/src/lib/README.md b/client/src/lib/README.mdindex 4479c65376..37297ead07 100644--- a/client/src/lib/README.md+++ b/client/src/lib/README.md@@ -103,7 +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 ordering for the Media Collections grid (#3283): `applyCollectionView(collections, { query, sort })` filters via `mediaSearch.js`'s AND-token matcher over name+description 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); keys are derived once per record, not per comparison. "Hide empty" is deliberately NOT a parameter — the page owns that one predicate (`collectionItemCount(c) > 0`) because it also needs the pre-filter count. `isAutoCollection(c)` recognizes a machine-created collection from ANY of four independent markers (`AUTO_NAME_PREFIXES`, `Auto-created…`/`Auto-generated…` description, `uc-`/`sc-` id, universe/series link) so a record predating a given marker still classifies; `splitCollectionName(name)` lifts the shared `Creative Director: ` / `Writers Room: ` / `Universe: ` / `Series: ` prefix into a badge label so the distinguishing tail survives truncation, and name sorting uses that stripped title. **Adding a server-side auto-creator means adding its prefix here** or its collections silently rank as user-created. Pure — no React. |+| `mediaCollectionList.js` | Search / sort ordering for the Media Collections grid (#3283) and the `CollectionPickerShell` dropdown (#3312): `applyCollectionView(collections, { query, sort })` filters via `mediaSearch.js`'s AND-token matcher over name+description 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); keys are derived once per record, not per comparison. "Hide empty" is deliberately NOT a parameter — the page owns that one predicate (`collectionItemCount(c) > 0`) because it also needs the pre-filter count. `isAutoCollection(c)` recognizes a machine-created collection from ANY of four independent markers (`AUTO_NAME_PREFIXES`, `Auto-created…`/`Auto-generated…` description, `uc-`/`sc-` id, universe/series link) so a record predating a given marker still classifies; `splitCollectionName(name)` lifts the shared `Creative Director: ` / `Writers Room: ` / `Universe: ` / `Series: ` prefix into a badge label so the distinguishing tail survives truncation, and name sorting uses that stripped title. **Adding a server-side auto-creator means adding its prefix here** or its collections silently rank as user-created. 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`. |