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: mood board cross-surface integration — pin affordance + creation-flow reference strip (#1455)
Adam Eivy2975733d3788
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex f8e506821f..f0e59a2380 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -6,6 +6,7 @@## Added+- **[issue-1455] Mood board cross-surface integration — "Pin to mood board" everywhere media appears, plus a reference strip in creation flows.** Follow-up to the Mood Boards core canvas (#911), wiring boards into the rest of the Create suite. **(1) Pin affordance** — every generated image/video card and the media lightbox now carries a **Pin to mood board** button (the grid-icon sibling of "Add to collection"), so you can pin from Image Gen, Video Gen, Media History, Catalog media, and inside a collection through one shared control. The popover lists your boards, toggles membership (pin/unpin), and creates-and-pins a new board inline — pinning stores the asset's `<kind>:<ref>` media-key plus its preview thumbnail as the board item's `imageUrl`, so a *video* pin renders a frame even though a `video:` key has no derivable thumbnail path. **(2) Creation-flow reference strip** — a collapsible **Mood board reference** strip now appears in the New Series form (Series Pipeline) and the Universe Builder's Starter-idea panel: pick one of your boards and its pinned reference images show inline, so collected inspiration is visible at the moment you're describing a new universe / series (it remembers the last board per flow). The pin popover reuses the existing collection-picker shell (generalized to accept an injectable data source rather than duplicating the positioning/search/create plumbing), and the board-item image resolver is now a shared `moodBoardItemSrc` helper. (`client/src/components/media/{PinToMoodBoardMenu,CollectionPickerShell,MediaCard,MediaLightbox}.jsx`, `client/src/components/moodBoard/MoodBoardReferenceStrip.jsx`, `client/src/lib/moodBoardItemSrc.js`, `client/src/pages/{Pipeline,UniverseBuilder,MoodBoardDetail}.jsx`, #1455)- **[issue-1408] LoRA training quality-of-life: vision-assisted reference-sheet slicing, caption with Claude/Codex CLI providers, and a richer training queue.** Three improvements to building character LoRAs (Create → LoRA Training). **(1) Smarter sheet slicing** — "Slice reference sheet" now offers *Auto-detect figures with a vision model*, which asks a vision model to draw a tight box around each figure on the turnaround and crops those instead of a rigid grid; it falls back to the columns×rows grid automatically when no vision model is installed or detection finds nothing, so you still get crops to prune either way. **(2) Caption with a CLI model** — the caption-model picker now also lists vision-capable CLI providers (Codex / Claude Code), so you can auto-caption a dataset with `codex` or `claude` (vision) rather than only a local LM Studio / Ollama vision model. **(3) Training queue at a glance** — the new Training queue on the LoRA Training page shows each run's loss curve (a sparkline over its checkpoints) and sample thumbnails right in the row, so you can watch a run learn — and spot a divergence — without opening it. (Part of #1227, #1408)- **[issue-1466] Editorial check flags storyboard eyeline-match breaks — the LLM-assisted sibling of the deterministic shot-continuity check.** A new **Storyboard eyeline match (gaze continuity)** LLM check (Create → Editorial Checks) reads a scene's per-issue storyboard shots and flags the eyeline mistakes a deterministic scan can't compute: two characters in conversation whose **gaze directions don't reciprocate** across the cut (both look the same way instead of toward each other), a **described eyeline that contradicts the shot's tagged screen direction** (the storyboard's own two signals disagree), and a **reverse-angle that doesn't flip the eyeline**. Where the deterministic **Storyboard shot continuity** check (#1315) reasons over the structured `shotType`/`screenDirection`/continuity-link fields for 180°-rule axis reversals and shot-type monotony, an eyeline match needs *semantic* reading of the free-text shot descriptions — so this one runs an LLM over a compact per-scene shot block (id, framing, direction, continuity link, description), built only from scenes that have two-or-more described shots to compare. Findings render as `Continuity` notes anchored to the offending shot pair + issue. Gaze is read from the free-text shot description (the `screen direction` field records where a subject *faces or moves*, which isn't always where they look), and the pass is bounded four ways (scene count, shots-per-scene, a hard total-character ceiling, and per-shot description length) with non-silent omission/truncation markers so a very large storyboard — wide, deep, or with one pathological scene — can't overflow the model context. The check skips the model call entirely when no scene qualifies. Ships a new stage prompt (`pipeline-editorial-eyeline-match`) that migrates for existing installs (117). (`server/lib/editorial/shotContinuity.js`, `server/lib/editorial/checkRegistry.js`, `data.reference/prompts/stages/pipeline-editorial-eyeline-match.md`, `scripts/migrations/117-editorial-eyeline-match-stage.js`, Part of #1283, #1466)- **[issue-1412] Editorial check classifies unmodeled proper nouns used as character names — the LLM-assisted half of roster economy.** A new **Unmodeled proper nouns used as character names** LLM check (Create → Editorial Checks) closes the gap the deterministic **roster economy** check (#1292) deliberately left open: that scan only sees canon names + aliases, so a proper noun used as an *apparent* character name that was never added to the story bible is invisible to it. This check surfaces those — and **classifies** each one, because a keyword scan can't tell a person from a place, organization, brand, or honorific. It reads the stitched manuscript plus your canon roster (names + aliases) as an exclusion list, flags capitalized proper nouns used as character names that are **absent from canon**, and calls out **throwaway one-appearance names** the reader is told to remember but who never recur — suggesting either adding them to canon or recasting them as an unnamed description. Unlike roster economy it runs even on an **empty bible** (then every named proper noun is a candidate). The LLM does only the judgment it alone can — surface a name and confirm it's a *person* — while a **deterministic pass counts each surfaced name's appearances across the whole manuscript and authors the verdict** (one-appearance throwaway vs recurring), so a long book reviewed in chunks never mislabels a name that appears in chapters 1 and 12 as a throwaway (and the same name surfaced from two chunks collapses to one finding). Findings render as `Casting` notes anchored to the issue + a verbatim quote. Ships a new stage prompt (`pipeline-editorial-unmodeled-names`) that migrates for existing installs (116). (`server/lib/editorial/checkRegistry.js`, `data.reference/prompts/stages/pipeline-editorial-unmodeled-names.md`, `scripts/migrations/116-editorial-unmodeled-names-stage.js`, Part of #1283, #1412)diff --git a/client/src/components/media/CollectionPickerShell.jsx b/client/src/components/media/CollectionPickerShell.jsxindex 8cb15fbedb..576f3524e5 100644--- a/client/src/components/media/CollectionPickerShell.jsx+++ b/client/src/components/media/CollectionPickerShell.jsx@@ -5,25 +5,32 @@ import toast from '../ui/Toast';import { listMediaCollections, createMediaCollection } from '../../services/api';import usePopoverPosition, { VIEWPORT_PADDING } from '../../hooks/usePopoverPosition.js';-// Shared popover shell for the two collection pickers:+// Shared popover shell for the list-pick-or-create pickers://// - AddToCollectionMenu (one item → many collections, toggles membership)// - BulkTargetPicker (many items → one destination, pick + dispatch)+// - PinToMoodBoardMenu (one media item → many mood boards, toggles pin)//-// Both portal a fixed-position popover into <body>, compute placement relative+// All portal a fixed-position popover into <body>, compute placement relative// to a trigger element, ship a search input above a threshold, and end with a// "create new" inline form. This shell owns all of that plumbing; the caller// provides `renderItem` for the per-row UI and `onCreated`/`onPickCreated` for// what to do after the inline create succeeds.//-// Collections data flow (per PLAN.md item 2):-// - If `collections` is provided by the parent, we never call-// `listMediaCollections()` ourselves — this lets MediaCollectionDetail-// reuse its already-fetched list instead of paying a per-mount round-trip.+// Data flow (per PLAN.md item 2):+// - If `collections` is provided by the parent, we never call `loadItems()`+// ourselves — this lets MediaCollectionDetail reuse its already-fetched+// list instead of paying a per-mount round-trip.// - If `collections` is `null`/omitted, the shell auto-loads on mount (old// AddToCollectionMenu behavior). Use `onCollectionsLoaded` if the parent// wants to learn the fetched list (e.g. for membership rendering).//+// The data source is injectable: `loadItems`/`createItem` default to the media-+// collection API so the two collection pickers need no extra wiring, but mood-+// board (or any future `{ id, name, items }`-shaped) pickers pass their own+// loader/creator + nouns. The record shape the shell assumes is minimal:+// `{ id, name }` plus whatever `renderItem` reads.+//// `excludeId` is a single-item allow-list filter so BulkTargetPicker can hide// the current collection from its move/copy target list.@@ -52,6 +59,12 @@ export default function CollectionPickerShell({onCollectionsChange,onCreated,onClose,+ // Injectable data source — defaults to the media-collection API so the two+ // collection pickers stay zero-config. `loadItems()` resolves to an array of+ // `{ id, name, ... }`; `createItem({ name })` resolves to the created record.+ loadItems = listMediaCollections,+ createItem = createMediaCollection,+ searchPlaceholder = 'Search collections…',}) {const [collectionsState, setCollectionsState] = useState(collectionsProp ?? null);const [query, setQuery] = useState('');@@ -91,7 +104,7 @@ export default function CollectionPickerShell({if (collectionsProp !== undefined) return undefined;if (!open) return undefined;let cancelled = false;- listMediaCollections().then(+ loadItems().then((data) => {if (cancelled) return;const list = Array.isArray(data) ? data : [];@@ -100,12 +113,12 @@ export default function CollectionPickerShell({},(err) => {if (cancelled) return;- toast.error(err?.message || 'Failed to load collections');+ toast.error(err?.message || 'Failed to load list');setCollectionsState([]);},);return () => { cancelled = true; };- }, [open, collectionsProp]);+ }, [open, collectionsProp, loadItems]);const filtered = useMemo(() => {if (!collectionsState) return null;@@ -146,7 +159,7 @@ export default function CollectionPickerShell({const name = newName.trim();if (!name) return;setCreating(true);- const created = await createMediaCollection({ name }).catch((err) => {+ const created = await createItem({ name }).catch((err) => {toast.error(err?.message || 'Create failed');return null;});@@ -189,7 +202,7 @@ export default function CollectionPickerShell({type="text"value={query}onChange={(e) => setQuery(e.target.value)}- placeholder="Search collections…"+ placeholder={searchPlaceholder}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/>diff --git a/client/src/components/media/MediaCard.jsx b/client/src/components/media/MediaCard.jsxindex 24245a3c95..041882b6f2 100644--- a/client/src/components/media/MediaCard.jsx+++ b/client/src/components/media/MediaCard.jsx@@ -1,6 +1,7 @@import { Trash2, Download, Film, Image as ImageIcon, Sparkles, Eye, EyeOff, Maximize2, Wand2, Star, MessageSquare } from 'lucide-react';import MediaImage from '../MediaImage';import AddToCollectionMenu from './AddToCollectionMenu';+import PinToMoodBoardMenu from './PinToMoodBoardMenu';import { loraDisplayName } from './normalize';// Single card used everywhere a generated image/video appears in a grid:@@ -24,6 +25,7 @@ export default function MediaCard({disabled = false,hideActions = false,showCollectionMenu = true,+ showMoodBoardMenu = true,starred = false,hasNote = false,onToggleStar,@@ -163,6 +165,7 @@ export default function MediaCard({</button>)}{showCollectionMenu && <AddToCollectionMenu item={item} />}+ {showMoodBoardMenu && <PinToMoodBoardMenu item={item} />}<ahref={downloadUrl}downloaddiff --git a/client/src/components/media/MediaLightbox.jsx b/client/src/components/media/MediaLightbox.jsxindex 11b61ef169..0c7e64b4a0 100644--- a/client/src/components/media/MediaLightbox.jsx+++ b/client/src/components/media/MediaLightbox.jsx@@ -5,6 +5,7 @@ import {} from 'lucide-react';import PromptRefineModal from './PromptRefineModal';import AddToCollectionMenu from './AddToCollectionMenu';+import PinToMoodBoardMenu from './PinToMoodBoardMenu';import MediaImage from '../MediaImage';import { useScrollLock } from '../../hooks/useScrollLock';import { useSwipeNav } from '../../hooks/useSwipeNav';@@ -770,6 +771,7 @@ function SettingsPane({</button>)}<AddToCollectionMenu item={item} size="md" />+ <PinToMoodBoardMenu item={item} size="md" /><ahref={item.downloadUrl}downloaddiff --git a/client/src/components/media/PinToMoodBoardMenu.jsx b/client/src/components/media/PinToMoodBoardMenu.jsxnew file mode 100644index 0000000000..f0e308a345--- /dev/null+++ b/client/src/components/media/PinToMoodBoardMenu.jsx@@ -0,0 +1,160 @@+import { useCallback, useMemo, useRef, useState } from 'react';+import { LayoutGrid, Check } from 'lucide-react';+import toast from '../ui/Toast';+import CollectionPickerShell from './CollectionPickerShell';+import {+ listMoodBoards,+ createMoodBoard,+ addMoodBoardItem,+ removeMoodBoardItem,+} from '../../services/api';++// Self-contained "Pin to mood board" popover button, the mood-board sibling of+// AddToCollectionMenu (issue #1455, follow-up to #911). It reuses the shared+// CollectionPickerShell with the mood-board API injected as the data source, so+// the popover positioning / search / inline-create plumbing isn't duplicated.+//+// `item` is the normalized MediaCard shape: `item.key` is the `<kind>:<ref>`+// media-key (e.g. `image:foo.png`, `video:job-123`) and `item.previewUrl` is a+// renderable thumbnail URL (or null). We pin as an `image`-type board item+// carrying that mediaKey for source linkage PLUS the previewUrl as `imageUrl`+// so the board renders the thumbnail directly — this is how video pins show a+// frame without the detail-page resolver needing to map a `video:` key back to+// a thumbnail filename (which it can't derive from the id alone).+//+// Membership is keyed on `mediaKey === item.key`: a board "contains" this asset+// when any of its items pins the same media-key. Pinning again removes it+// (toggle), matching the collection menu's behavior.++const SIZES = {+ sm: { button: 'px-1.5 py-1 text-[10px]', icon: 'w-3 h-3' },+ md: { button: 'px-2 py-1.5 text-xs', icon: 'w-3.5 h-3.5' },+};++// Find the board item that pins this media-key (or undefined).+const findPinned = (board, mediaKey) =>+ (Array.isArray(board?.items) ? board.items : []).find((it) => it?.mediaKey === mediaKey);++export default function PinToMoodBoardMenu({ item, size = 'sm' }) {+ const [open, setOpen] = useState(false);+ const [busyId, setBusyId] = useState(null);+ const triggerRef = useRef(null);++ const mediaKey = item.key;+ // Only http(s) / absolute app paths are valid imageUrls (matches the board+ // item schema); a missing/blob preview is dropped so we pin mediaKey-only.+ const thumbUrl = typeof item.previewUrl === 'string' && /^(https?:\/\/|\/)/.test(item.previewUrl)+ ? item.previewUrl+ : null;+ // The board item payload: the media-key for source linkage, plus the+ // thumbnail as imageUrl so a video pin (no derivable thumbnail from its key)+ // still renders. Built once so the toggle + create-and-pin paths can't drift.+ const pinPayload = useMemo(() => (thumbUrl+ ? { type: 'image', mediaKey, imageUrl: thumbUrl }+ : { type: 'image', mediaKey }), [mediaKey, thumbUrl]);++ const handleToggleOpen = (e) => {+ e.stopPropagation();+ setOpen((prev) => !prev);+ };++ const handleTogglePin = useCallback(async (board, updateBoards) => {+ const pinned = findPinned(board, mediaKey);+ setBusyId(board.id);+ if (pinned) {+ const updated = await removeMoodBoardItem(board.id, pinned.id, { silent: true }).catch((err) => {+ toast.error(err?.message || 'Unpin failed');+ return null;+ });+ setBusyId(null);+ if (!updated) return;+ updateBoards((prev) => (prev || []).map((b) => (b.id === board.id ? updated : b)));+ toast.success(`Removed from ${board.name}`);+ return;+ }+ const created = await addMoodBoardItem(board.id, pinPayload, { silent: true }).catch((err) => {+ toast.error(err?.message || 'Pin failed');+ return null;+ });+ setBusyId(null);+ if (!created) return;+ // The add endpoint returns the new item, not the board — merge it into the+ // board's items locally so the checkmark flips without a refetch.+ updateBoards((prev) => (prev || []).map((b) => (+ b.id === board.id ? { ...b, items: [...(Array.isArray(b.items) ? b.items : []), created] } : b+ )));+ toast.success(`Pinned to ${board.name}`);+ }, [mediaKey, pinPayload]);++ const renderItem = (board, { updateCollections }) => {+ const pinned = !!findPinned(board, mediaKey);+ return (+ <button+ key={board.id}+ type="button"+ disabled={busyId === board.id}+ onClick={() => handleTogglePin(board, updateCollections)}+ className="w-full flex items-center justify-between gap-2 px-2 py-1.5 text-left text-[12px] text-gray-200 hover:bg-port-border rounded disabled:opacity-50"+ role="menuitemcheckbox"+ aria-checked={pinned}+ >+ <span className="break-words min-w-0 flex-1">{board.name}</span>+ {pinned && <Check className="w-3.5 h-3.5 text-port-success shrink-0" />}+ </button>+ );+ };++ const handleCreated = useCallback(async (created, { addToCollectionsState }) => {+ // Creating a board from this popover means "pin the current item to the new+ // board." Surface the pin failure separately so the user still learns the+ // board exists if only the auto-pin failed.+ let pinError = null;+ const pinnedItem = await addMoodBoardItem(created.id, pinPayload, { silent: true }).catch((err) => {+ pinError = err;+ return null;+ });+ const withItem = pinnedItem+ ? { ...created, items: [...(Array.isArray(created.items) ? created.items : []), pinnedItem] }+ : created;+ addToCollectionsState((prev) => ([...(prev || []), withItem]));+ if (pinError) {+ toast.error(`Created "${created.name}" but failed to pin: ${pinError.message}`);+ } else {+ toast.success(`Pinned to ${created.name}`);+ }+ }, [pinPayload]);++ const sizeCls = SIZES[size] || SIZES.sm;++ return (+ <>+ <button+ ref={triggerRef}+ type="button"+ onClick={handleToggleOpen}+ className={`shrink-0 ${sizeCls.button} bg-port-border hover:bg-port-border/70 text-white rounded flex items-center justify-center`}+ title="Pin to mood board"+ aria-haspopup="menu"+ aria-expanded={open}+ >+ <LayoutGrid className={sizeCls.icon} />+ </button>+ <CollectionPickerShell+ anchorRef={triggerRef}+ open={open}+ onClose={() => setOpen(false)}+ title="Mood boards"+ width={240}+ minWidth={180}+ emptyMessage="No mood boards yet — create one below."+ newCollectionPlaceholder="New board name"+ createTitle="Create and pin"+ searchPlaceholder="Search boards…"+ renderItem={renderItem}+ onCreated={handleCreated}+ loadItems={listMoodBoards}+ createItem={createMoodBoard}+ />+ </>+ );+}diff --git a/client/src/components/media/PinToMoodBoardMenu.test.jsx b/client/src/components/media/PinToMoodBoardMenu.test.jsxnew file mode 100644index 0000000000..d5958d8b89--- /dev/null+++ b/client/src/components/media/PinToMoodBoardMenu.test.jsx@@ -0,0 +1,87 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import { render, screen, fireEvent, waitFor, act } from '@testing-library/react';+import PinToMoodBoardMenu from './PinToMoodBoardMenu';++// Mock the api surface the menu (and the shared shell) reach for.+const api = vi.hoisted(() => ({+ listMoodBoards: vi.fn(),+ createMoodBoard: vi.fn(),+ addMoodBoardItem: vi.fn(),+ removeMoodBoardItem: vi.fn(),+ // CollectionPickerShell imports these even though the mood-board path injects+ // its own loader/creator — keep them defined so the module resolves.+ listMediaCollections: vi.fn(async () => []),+ createMediaCollection: vi.fn(),+}));++vi.mock('../../services/api', () => api);+vi.mock('../ui/Toast', () => ({ default: { success: vi.fn(), error: vi.fn() } }));++const imageItem = {+ kind: 'image',+ key: 'image:hero.png',+ filename: 'hero.png',+ previewUrl: '/data/images/hero.png',+};++beforeEach(() => {+ vi.clearAllMocks();+});++describe('PinToMoodBoardMenu', () => {+ it('lists boards and pins the media-key (with previewUrl thumbnail) on click', async () => {+ api.listMoodBoards.mockResolvedValue([{ id: 'b1', name: 'Refs', items: [] }]);+ api.addMoodBoardItem.mockResolvedValue({ id: 'mbi-1', type: 'image', mediaKey: 'image:hero.png' });++ render(<PinToMoodBoardMenu item={imageItem} />);+ fireEvent.click(screen.getByTitle('Pin to mood board'));++ const row = await screen.findByRole('menuitemcheckbox', { name: /Refs/ });+ expect(row).toHaveAttribute('aria-checked', 'false');++ await act(async () => { fireEvent.click(row); });++ expect(api.addMoodBoardItem).toHaveBeenCalledWith(+ 'b1',+ { type: 'image', mediaKey: 'image:hero.png', imageUrl: '/data/images/hero.png' },+ { silent: true },+ );+ // Membership flips locally without a refetch.+ await waitFor(() => expect(row).toHaveAttribute('aria-checked', 'true'));+ });++ it('unpins when the board already contains the media-key (toggle)', async () => {+ api.listMoodBoards.mockResolvedValue([+ { id: 'b1', name: 'Refs', items: [{ id: 'mbi-9', type: 'image', mediaKey: 'image:hero.png' }] },+ ]);+ api.removeMoodBoardItem.mockResolvedValue({ id: 'b1', name: 'Refs', items: [] });++ render(<PinToMoodBoardMenu item={imageItem} />);+ fireEvent.click(screen.getByTitle('Pin to mood board'));++ const row = await screen.findByRole('menuitemcheckbox', { name: /Refs/ });+ expect(row).toHaveAttribute('aria-checked', 'true');++ await act(async () => { fireEvent.click(row); });++ expect(api.removeMoodBoardItem).toHaveBeenCalledWith('b1', 'mbi-9', { silent: true });+ expect(api.addMoodBoardItem).not.toHaveBeenCalled();+ await waitFor(() => expect(row).toHaveAttribute('aria-checked', 'false'));+ });++ it('pins mediaKey-only when previewUrl is a non-renderable (blob) URL', async () => {+ api.listMoodBoards.mockResolvedValue([{ id: 'b1', name: 'Refs', items: [] }]);+ api.addMoodBoardItem.mockResolvedValue({ id: 'mbi-2', type: 'image', mediaKey: 'video:job-7' });++ render(<PinToMoodBoardMenu item={{ kind: 'video', key: 'video:job-7', previewUrl: null }} />);+ fireEvent.click(screen.getByTitle('Pin to mood board'));+ const row = await screen.findByRole('menuitemcheckbox', { name: /Refs/ });+ await act(async () => { fireEvent.click(row); });++ expect(api.addMoodBoardItem).toHaveBeenCalledWith(+ 'b1',+ { type: 'image', mediaKey: 'video:job-7' },+ { silent: true },+ );+ });+});diff --git a/client/src/components/moodBoard/MoodBoardReferenceStrip.jsx b/client/src/components/moodBoard/MoodBoardReferenceStrip.jsxnew file mode 100644index 0000000000..0d7caa3e02--- /dev/null+++ b/client/src/components/moodBoard/MoodBoardReferenceStrip.jsx@@ -0,0 +1,166 @@+/**+ * Mood Board reference strip (issue #1455, follow-up to #911 part 2).+ *+ * A compact, collapsible reference-image strip for creation flows (New Series,+ * New Universe, scene/treatment entry). It lets the user pick one of their mood+ * boards and see its pinned reference images inline, so collected inspiration is+ * visible at the moment they're describing a new thing — per the original #911+ * spec ("surface relevant board reference images in those entry flows").+ *+ * Read-only on purpose: this is a glance-at-your-inspiration affordance, not a+ * second editor. Clicking a thumbnail opens the full board in a new tab. The+ * pinning direction (media → board) lives in PinToMoodBoardMenu.+ *+ * Self-contained: loads the board list lazily on first expand, remembers the+ * last-picked board per `storageKey` in localStorage so it persists across+ * creation sessions. Renders nothing heavy until expanded.+ */++import { useCallback, useEffect, useMemo, useState } from 'react';+import { LayoutGrid, ChevronDown, ChevronRight, ExternalLink, ImageIcon } from 'lucide-react';+import { listMoodBoards, getMoodBoard } from '../../services/api';+import { moodBoardItemSrc } from '../../lib/moodBoardItemSrc';++const MAX_THUMBS = 12;++export default function MoodBoardReferenceStrip({ storageKey = 'create', className = '' }) {+ const lsKey = `portos.moodBoardRef.${storageKey}`;+ const [expanded, setExpanded] = useState(false);+ const [boards, setBoards] = useState(null); // null = not loaded, [] = loaded-empty+ const [selectedId, setSelectedId] = useState(() => {+ try { return localStorage.getItem(lsKey) || ''; } catch { return ''; }+ });+ const [detail, setDetail] = useState(null); // full board (with items) for selectedId+ const [loadingDetail, setLoadingDetail] = useState(false);++ // Load the board list lazily the first time the strip is expanded.+ useEffect(() => {+ if (!expanded || boards !== null) return undefined;+ let cancelled = false;+ listMoodBoards({ silent: true }).then(+ (data) => { if (!cancelled) setBoards(Array.isArray(data) ? data : []); },+ () => { if (!cancelled) setBoards([]); },+ );+ return () => { cancelled = true; };+ }, [expanded, boards]);++ // Once we have the list, default the selection to the first board when the+ // remembered id is gone (deleted board) or never set.+ useEffect(() => {+ if (!Array.isArray(boards) || boards.length === 0) return;+ if (selectedId && boards.some((b) => b.id === selectedId)) return;+ setSelectedId(boards[0].id);+ }, [boards, selectedId]);++ // Fetch the selected board's full record (the list payload already carries+ // items, but a board could be picked before the list loads on a remembered+ // id; getMoodBoard guarantees the freshest items).+ useEffect(() => {+ if (!expanded || !selectedId) { setDetail(null); return undefined; }+ // Fast path: the list entry already has items — show it immediately.+ const fromList = Array.isArray(boards) ? boards.find((b) => b.id === selectedId) : null;+ if (fromList && Array.isArray(fromList.items)) setDetail(fromList);+ let cancelled = false;+ setLoadingDetail(true);+ getMoodBoard(selectedId, { silent: true }).then(+ (data) => { if (!cancelled && data) setDetail(data); },+ () => { /* keep the list fallback */ },+ ).finally(() => { if (!cancelled) setLoadingDetail(false); });+ return () => { cancelled = true; };+ }, [expanded, selectedId, boards]);++ const handleSelect = useCallback((id) => {+ setSelectedId(id);+ try { if (id) localStorage.setItem(lsKey, id); } catch { /* ignore quota/denied */ }+ }, [lsKey]);++ const thumbs = useMemo(() => {+ const items = Array.isArray(detail?.items) ? detail.items : [];+ return items+ .map((it) => ({ id: it.id, src: moodBoardItemSrc(it), caption: it.caption || '' }))+ .filter((t) => t.src)+ .slice(0, MAX_THUMBS);+ }, [detail]);++ return (+ <div className={`bg-port-bg border border-port-border rounded ${className}`}>+ <button+ type="button"+ onClick={() => setExpanded((v) => !v)}+ className="w-full flex items-center gap-2 px-2.5 py-2 text-xs text-gray-300 hover:text-white"+ aria-expanded={expanded}+ >+ {expanded+ ? <ChevronDown className="w-3.5 h-3.5 shrink-0" aria-hidden="true" />+ : <ChevronRight className="w-3.5 h-3.5 shrink-0" aria-hidden="true" />}+ <LayoutGrid className="w-3.5 h-3.5 text-port-accent shrink-0" aria-hidden="true" />+ <span>Mood board reference</span>+ </button>++ {expanded && (+ <div className="px-2.5 pb-2.5 space-y-2">+ {boards === null ? (+ <p className="text-[11px] text-gray-500">Loading boards…</p>+ ) : boards.length === 0 ? (+ <p className="text-[11px] text-gray-500">+ No mood boards yet.{' '}+ <a href="/mood-boards" target="_blank" rel="noopener noreferrer" className="text-port-accent hover:underline">+ Create one+ </a>{' '}+ to collect reference images.+ </p>+ ) : (+ <>+ <div className="flex items-center gap-2">+ <label htmlFor={`mb-ref-${storageKey}`} className="text-[11px] text-gray-500 shrink-0">Board</label>+ <select+ id={`mb-ref-${storageKey}`}+ value={selectedId}+ onChange={(e) => handleSelect(e.target.value)}+ className="flex-1 min-w-0 bg-port-card border border-port-border rounded px-2 py-1 text-[12px] text-white focus:outline-none focus:border-port-accent"+ >+ {boards.map((b) => (+ <option key={b.id} value={b.id}>{b.name}</option>+ ))}+ </select>+ {selectedId && (+ <a+ href={`/mood-boards/${encodeURIComponent(selectedId)}`}+ target="_blank"+ rel="noopener noreferrer"+ title="Open board in new tab"+ className="shrink-0 p-1 text-gray-400 hover:text-port-accent"+ >+ <ExternalLink className="w-3.5 h-3.5" aria-hidden="true" />+ </a>+ )}+ </div>++ {thumbs.length === 0 ? (+ <div className="flex items-center gap-1.5 text-[11px] text-gray-500 py-2">+ <ImageIcon className="w-3.5 h-3.5" aria-hidden="true" />+ {loadingDetail ? 'Loading reference images…' : 'No reference images pinned on this board yet.'}+ </div>+ ) : (+ <div className="grid grid-cols-4 sm:grid-cols-6 gap-1.5">+ {thumbs.map((t) => (+ <a+ key={t.id}+ href={`/mood-boards/${encodeURIComponent(selectedId)}`}+ target="_blank"+ rel="noopener noreferrer"+ title={t.caption || 'Open board'}+ className="block aspect-square rounded overflow-hidden bg-port-card border border-port-border hover:border-port-accent"+ >+ <img src={t.src} alt={t.caption} loading="lazy" className="w-full h-full object-cover" />+ </a>+ ))}+ </div>+ )}+ </>+ )}+ </div>+ )}+ </div>+ );+}diff --git a/client/src/lib/README.md b/client/src/lib/README.mdindex 3bb64b6df6..2c8313669b 100644--- a/client/src/lib/README.md+++ b/client/src/lib/README.md@@ -85,6 +85,7 @@ grep -i "what you want to do" client/src/lib/README.md| `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. || `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. || `sameJsonShape.js` | `sameJsonShape(prev, next)` — JSON.stringify-based equality for `useAutoRefetch`'s `compare` option on small, deterministically-shaped poll payloads. || `unsorted.js` | Synthetic "Unsorted" collection from media not filed in any real collection. || `upsertByIdPrepend.js` | Newest-first upsert into an id-keyed list. |diff --git a/client/src/lib/index.js b/client/src/lib/index.jsindex 4f6fb36d99..2fe46c6bf9 100644--- a/client/src/lib/index.js+++ b/client/src/lib/index.js@@ -56,6 +56,7 @@ export * from './manuscriptAnchors.js';export * from './manuscriptFormat.js';export * from './mediaNavigation.js';export * from './mediaSearch.js';+export * from './moodBoardItemSrc.js';export * from './sameJsonShape.js';export * from './unsorted.js';export * from './upsertByIdPrepend.js';diff --git a/client/src/lib/moodBoardItemSrc.js b/client/src/lib/moodBoardItemSrc.jsnew file mode 100644index 0000000000..96359976c6--- /dev/null+++ b/client/src/lib/moodBoardItemSrc.js@@ -0,0 +1,22 @@+// Resolve a mood-board item to a display image src (issue #911 / #1455).+//+// A board item is renderable as an image when it carries either an explicit+// `imageUrl` (external or absolute app path) or a pinned `image:<file>`+// media-key — the served bytes live at `/data/images/<file>`. A `video:<id>`+// media-key has no derivable thumbnail path (the id isn't the thumbnail+// filename), so a video pin renders only when the pin also stored an+// `imageUrl` thumbnail (the cross-surface pin flow does this). Returns null+// when there's nothing renderable.+//+// Shared by MoodBoardDetail (the canvas) and MoodBoardReferenceStrip (the+// creation-flow picker) so the two can't diverge on how a pin resolves.++const IMAGE_PREFIX = 'image:';++export function moodBoardItemSrc(item) {+ if (item?.imageUrl) return item.imageUrl;+ if (typeof item?.mediaKey === 'string' && item.mediaKey.startsWith(IMAGE_PREFIX)) {+ return `/data/images/${encodeURIComponent(item.mediaKey.slice(IMAGE_PREFIX.length))}`;+ }+ return null;+}diff --git a/client/src/lib/moodBoardItemSrc.test.js b/client/src/lib/moodBoardItemSrc.test.jsnew file mode 100644index 0000000000..c16eb218c7--- /dev/null+++ b/client/src/lib/moodBoardItemSrc.test.js@@ -0,0 +1,29 @@+import { describe, it, expect } from 'vitest';+import { moodBoardItemSrc } from './moodBoardItemSrc';++describe('moodBoardItemSrc', () => {+ it('prefers an explicit imageUrl', () => {+ expect(moodBoardItemSrc({ imageUrl: 'https://x/y.png', mediaKey: 'image:z.png' }))+ .toBe('https://x/y.png');+ });++ it('resolves an image: media-key to the served bytes (URL-encoded)', () => {+ expect(moodBoardItemSrc({ mediaKey: 'image:my render.png' }))+ .toBe('/data/images/my%20render.png');+ });++ it('returns null for a video: media-key with no imageUrl (no derivable thumbnail)', () => {+ expect(moodBoardItemSrc({ mediaKey: 'video:job-123' })).toBeNull();+ });++ it('renders a video pin when an imageUrl thumbnail was stored alongside the key', () => {+ expect(moodBoardItemSrc({ mediaKey: 'video:job-123', imageUrl: '/data/video-thumbnails/t.jpg' }))+ .toBe('/data/video-thumbnails/t.jpg');+ });++ it('returns null for a text item / empty item', () => {+ expect(moodBoardItemSrc({ type: 'text', text: 'hi' })).toBeNull();+ expect(moodBoardItemSrc(null)).toBeNull();+ expect(moodBoardItemSrc({})).toBeNull();+ });+});diff --git a/client/src/pages/MoodBoardDetail.jsx b/client/src/pages/MoodBoardDetail.jsxindex cab48ac87f..6932aa9119 100644--- a/client/src/pages/MoodBoardDetail.jsx+++ b/client/src/pages/MoodBoardDetail.jsx@@ -21,17 +21,7 @@ import {updateMoodBoardItem,removeMoodBoardItem,} from '../services/api';--// Resolve an item to a display image src: a pinned mediaKey `image:<file>` maps-// to the served bytes; otherwise the stored external/app URL. Returns null when-// there's nothing renderable (e.g. a video media-key we don't thumbnail in v1).-function imageSrc(item) {- if (item?.imageUrl) return item.imageUrl;- if (typeof item?.mediaKey === 'string' && item.mediaKey.startsWith('image:')) {- return `/data/images/${encodeURIComponent(item.mediaKey.slice('image:'.length))}`;- }- return null;-}+import { moodBoardItemSrc } from '../lib/moodBoardItemSrc';export default function MoodBoardDetail() {const { id } = useParams();@@ -272,7 +262,7 @@ export default function MoodBoardDetail() {) : (<div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-3">{items.map((item) => {- const src = imageSrc(item);+ const src = moodBoardItemSrc(item);return (<div key={item.id} className="bg-port-card border border-port-border rounded-md overflow-hidden flex flex-col">{item.type === 'image' ? (diff --git a/client/src/pages/Pipeline.jsx b/client/src/pages/Pipeline.jsxindex 5a1fd08a51..3e935bfc07 100644--- a/client/src/pages/Pipeline.jsx+++ b/client/src/pages/Pipeline.jsx@@ -30,6 +30,7 @@ import {} from '../services/api';import { ArcShapePicker, ArcShapeSparkline, getStoryShape } from '../components/pipeline/StoryShapes';import AuthorPicker from '../components/pipeline/AuthorPicker';+import MoodBoardReferenceStrip from '../components/moodBoard/MoodBoardReferenceStrip';import { buildImporterLink } from '../lib/importerDeepLink';const emptyForm = () => ({@@ -403,6 +404,7 @@ export default function Pipeline() {/></div></div>+ <MoodBoardReferenceStrip storageKey="pipeline-series" /><div className="flex gap-2"><buttontype="submit"diff --git a/client/src/pages/UniverseBuilder.jsx b/client/src/pages/UniverseBuilder.jsxindex d84f6b270f..0872913621 100644--- a/client/src/pages/UniverseBuilder.jsx+++ b/client/src/pages/UniverseBuilder.jsx@@ -39,6 +39,7 @@ import { RUNNER_FAMILIES, loraCompatKey } from '../lib/runnerFamilies';import ShareToButton from '../components/sharing/ShareToButton';import SyncToPeerButton from '../components/sharing/SyncToPeerButton';import OriginBadge from '../components/sharing/OriginBadge';+import MoodBoardReferenceStrip from '../components/moodBoard/MoodBoardReferenceStrip';import UniverseCanonSection from '../components/universe/UniverseCanonSection';import StyleProbeImage from '../components/universe/StyleProbeImage';import EntryCard from '../components/universe/EntryCard';@@ -2901,6 +2902,8 @@ function BibleTab({</div></div>+ <MoodBoardReferenceStrip storageKey="universe-builder" />+<div className="flex items-center gap-2 flex-wrap"><buttononClick={handleExpand}