Skip to content

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

feat: Mood Boards — inspiration canvas for the Create suite (#911)

Adam Eivy5e77a9add700
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index a986c196a7..3bd495c042 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -2,6 +2,8 @@
## Added
+- **[issue-911] Mood Boards — an inspiration canvas that feeds the Create suite.** A new **Mood Boards** page (Create → Mood Boards, deep-linkable at `/mood-boards` and `/mood-boards/:id`, reachable via ⌘K / voice as "mood board" / "inspiration" / "references") for collecting visual + textual references, distinct from raw Media History. Create named boards with a description, then pin items: an **image** (external/pinned URL, or an app path like `/data/images/…`) or a **text note**, each with an optional caption and source backref. Items live inline in the board record; the canvas renders an image grid with inline-editable captions and an inline-confirm delete. Boards are **db-primary and local-only** — one row per board in the new `mood_boards` Postgres table (full record in `data` JSONB, modeled on `creative_director_projects`: no sync cursor/tombstone in v1), provisioned by both the boot-time `ensureSchema()` upgrade and `init-db.sql` with an audit trigger, registered via migration 108. Every write locks the board row (`SELECT … FOR UPDATE`) so concurrent add/edit affordances can't clobber each other. Cross-surface "Pin to mood board" affordances and a board picker in the universe/scene/treatment creation flows are tracked as a follow-up. (`server/services/moodBoard/`, `server/routes/moodBoard.js`, `server/lib/moodBoardValidation.js`, `client/src/pages/{MoodBoards,MoodBoardDetail}.jsx`, `client/src/services/apiMoodBoard.js`, #911)
+
- **The series pipeline list now shows a cover thumbnail on each series card.** Like the reference-image thumbnail on the Universe list, each series in **Pipeline** now leads with a small thumbnail of its graphic-novel cover — the first rendered **volume (trade-paperback) cover**, falling back to the earliest rendered **issue cover** — so you can recognize a series at a glance instead of reading names. The thumbnail filename is **persisted onto the series record** (`series.coverImage`) rather than computed at list time, so the list stays cheap (no per-series issue scan): the two cover filename hooks stamp it when a cover render completes, and a one-time, marker-gated boot backfill (`data/series-cover-backfill.applied.json`) derives it for series whose covers rendered before this shipped. Volume covers come straight off the series record (free); the issue fallback is only scanned when no volume cover exists. The field is wire-gated (`pipelineSeries` schema v5) so an older peer can't strip-then-LWW the pointer back, and the card falls back to a book icon when no cover exists yet (or 404s on a peer that synced the pointer but not the bytes). (`server/services/pipeline/seriesCoverImage.js`, `server/services/pipeline/series.js`, `server/services/pipeline/{comicPagesFilenameHook,seasonCoverFilenameHook}.js`, `server/scripts/backfillSeriesCoverImages.js`, `client/src/pages/Pipeline.jsx`)
- **Enrich a Universe noun — and refine a Universe style — from a reference image.** The Universe Bible's "Describe from image" modal now takes reference images from your **gallery** as well as uploads, and for **characters** it can do more than write the descriptor paragraph: a new **Build character details** action has a vision model read the reference image(s) and *propose* values for the character's still-blank structured fields (pronouns, age, visual notes, color palette, expressions, …). The proposals are shown for review — uncheck any, edit the text inline — and applied through the normal entry-patch path, so existing values are never overwritten (no-clobber, characters-only). Separately, the **Refine Prompts** form gains an optional **style-reference image**: pick one from the gallery and the refiner runs through a vision-capable provider, folding the image's palette/lighting/mood into the universe's `influences` + `styleNotes`. Both vision paths require an API provider with a vision model and reject a silent fallback to a non-vision provider rather than hallucinating from text alone; the vision provider/model pickers scope local (Ollama/LM Studio) backends to vision-capable models. Relatedly, a **model-not-found error no longer benches the whole provider** — that's a bad model id in one request, not a provider outage, so (like a content refusal) the single call still falls back but the provider stays available for its other working models (previously one bad model id could take Ollama offline for 30 minutes). (`server/services/universeVisionExpand.js`, `server/services/universeBuilderRefine.js`, `server/routes/universeBuilder.js`, `server/lib/promptRunner.js`, `client/src/components/universe/VisionDescribeModal.jsx`, `client/src/pages/UniverseBuilder.jsx`)
diff --git a/client/src/App.jsx b/client/src/App.jsx
index be9a6a6bd3..85c1782a0a 100644
--- a/client/src/App.jsx
+++ b/client/src/App.jsx
@@ -58,6 +58,8 @@ const VideoTimeline = lazyWithReload(() => import('./pages/VideoTimeline'));
const VideoTimelineEditor = lazyWithReload(() => import('./pages/VideoTimelineEditor'));
const CreativeDirector = lazyWithReload(() => import('./pages/CreativeDirector'));
const CreativeDirectorDetail = lazyWithReload(() => import('./pages/CreativeDirectorDetail'));
+const MoodBoards = lazyWithReload(() => import('./pages/MoodBoards'));
+const MoodBoardDetail = lazyWithReload(() => import('./pages/MoodBoardDetail'));
const CreateApp = lazyWithReload(() => import('./pages/CreateApp'));
const Templates = lazyWithReload(() => import('./pages/Templates'));
const PromptManager = lazyWithReload(() => import('./pages/PromptManager'));
@@ -296,6 +298,8 @@ export default function App() {
<Route path="catalog" element={<Catalog />} />
<Route path="catalog/ingest" element={<CatalogIngest />} />
<Route path="catalog/:type/:id" element={<CatalogIngredient />} />
+ <Route path="mood-boards" element={<MoodBoards />} />
+ <Route path="mood-boards/:id" element={<MoodBoardDetail />} />
<Route path="universes" element={<Universes />} />
<Route path="universes/new" element={<UniverseBuilder />} />
<Route path="universes/:universeId" element={<UniverseBuilder />} />
diff --git a/client/src/components/Layout.jsx b/client/src/components/Layout.jsx
index bde2a1e6cf..96b3d38f54 100644
--- a/client/src/components/Layout.jsx
+++ b/client/src/components/Layout.jsx
@@ -204,6 +204,7 @@ const navItems = [
{ to: '/pipeline/editorial-checks', label: 'Editorial Checks', icon: ListChecks },
{ to: '/importer', label: 'Importer', icon: FileInput },
{ to: '/media', label: 'Media Gen', icon: Layers },
+ { to: '/mood-boards', label: 'Mood Boards', icon: Palette },
{ to: '/pipeline', label: 'Series Pipeline', icon: WorkflowIcon, dynamic: 'pipelineSeries' },
{ to: '/sharing', label: 'Sharing', icon: Share2 },
{ to: '/songs', label: 'Songs', icon: Music },
diff --git a/client/src/pages/MoodBoardDetail.jsx b/client/src/pages/MoodBoardDetail.jsx
new file mode 100644
index 0000000000..cab48ac87f
--- /dev/null
+++ b/client/src/pages/MoodBoardDetail.jsx
@@ -0,0 +1,333 @@
+/**
+ * Mood Board canvas (issue #911).
+ *
+ * The board editor: rename/describe the board, and pin/edit/remove reference
+ * items. v1 items are an external image URL (or app path) or a text note, each
+ * with an optional caption + source backref. The board's JSONB also stores a
+ * `mediaKey` for items pinned from elsewhere in PortOS (the cross-surface "Pin
+ * to mood board" flow is a follow-up — see issue trailer); this page renders a
+ * `mediaKey` image item if one exists, but the in-page add form uses URL/text.
+ */
+
+import { useEffect, useState, useCallback } from 'react';
+import { useParams, useNavigate, Link } from 'react-router-dom';
+import { ArrowLeft, ImageIcon, FileText, Trash2, Plus, Save } from 'lucide-react';
+import toast from '../components/ui/Toast';
+import InlineConfirmRow from '../components/ui/InlineConfirmRow';
+import {
+ getMoodBoard,
+ updateMoodBoard,
+ addMoodBoardItem,
+ 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;
+}
+
+export default function MoodBoardDetail() {
+ const { id } = useParams();
+ const navigate = useNavigate();
+ const [board, setBoard] = useState(null);
+ const [loading, setLoading] = useState(true);
+ const [name, setName] = useState('');
+ const [description, setDescription] = useState('');
+ const [savingMeta, setSavingMeta] = useState(false);
+ const [confirmingItemId, setConfirmingItemId] = useState(null);
+
+ // Add-item form.
+ const [itemType, setItemType] = useState('image');
+ const [imageUrl, setImageUrl] = useState('');
+ const [text, setText] = useState('');
+ const [caption, setCaption] = useState('');
+ const [source, setSource] = useState('');
+ const [adding, setAdding] = useState(false);
+
+ const load = useCallback(async () => {
+ setLoading(true);
+ const data = await getMoodBoard(id, { silent: true }).catch(() => null);
+ if (data) {
+ setBoard(data);
+ setName(data.name || '');
+ setDescription(data.description || '');
+ } else {
+ toast.error('Mood board not found');
+ }
+ setLoading(false);
+ }, [id]);
+
+ useEffect(() => { load(); }, [load]);
+
+ const metaDirty = board && (name.trim() !== (board.name || '') || description !== (board.description || ''));
+
+ const handleSaveMeta = async () => {
+ if (!name.trim()) { toast.error('Board name is required'); return; }
+ setSavingMeta(true);
+ const updated = await updateMoodBoard(id, { name: name.trim(), description }, { silent: true }).catch(() => null);
+ setSavingMeta(false);
+ if (!updated) { toast.error('Failed to save board'); return; }
+ setBoard(updated);
+ toast.success('Board saved');
+ };
+
+ const resetAddForm = () => {
+ setImageUrl(''); setText(''); setCaption(''); setSource('');
+ };
+
+ const handleAddItem = async () => {
+ const payload = { type: itemType, caption: caption || null, source: source || null };
+ if (itemType === 'image') {
+ if (!imageUrl.trim()) { toast.error('Enter an image URL'); return; }
+ payload.imageUrl = imageUrl.trim();
+ } else {
+ if (!text.trim()) { toast.error('Enter some text'); return; }
+ payload.text = text.trim();
+ }
+ setAdding(true);
+ const item = await addMoodBoardItem(id, payload, { silent: true }).catch(() => null);
+ setAdding(false);
+ if (!item) { toast.error('Failed to add item'); return; }
+ setBoard((prev) => (prev ? { ...prev, items: [...(prev.items || []), item] } : prev));
+ resetAddForm();
+ };
+
+ const handleUpdateCaption = async (itemId, nextCaption) => {
+ const item = await updateMoodBoardItem(id, itemId, { caption: nextCaption || null }, { silent: true }).catch(() => null);
+ if (!item) { toast.error('Failed to update caption'); return; }
+ setBoard((prev) => (prev
+ ? { ...prev, items: (prev.items || []).map((it) => (it.id === itemId ? item : it)) }
+ : prev));
+ };
+
+ const handleRemoveItem = async (itemId) => {
+ setConfirmingItemId(null);
+ const updated = await removeMoodBoardItem(id, itemId, { silent: true }).catch(() => null);
+ if (!updated) { toast.error('Failed to remove item'); return; }
+ setBoard((prev) => (prev ? { ...prev, items: (prev.items || []).filter((it) => it.id !== itemId) } : prev));
+ };
+
+ if (loading) {
+ return <div className="text-gray-400 text-sm py-8 text-center">Loading…</div>;
+ }
+ if (!board) {
+ return (
+ <div className="max-w-4xl mx-auto text-center py-12">
+ <p className="text-gray-400 mb-4">This mood board doesn’t exist.</p>
+ <Link to="/mood-boards" className="text-port-accent hover:underline">Back to boards</Link>
+ </div>
+ );
+ }
+
+ const items = Array.isArray(board.items) ? board.items : [];
+
+ return (
+ <div className="max-w-5xl mx-auto">
+ <button
+ type="button"
+ onClick={() => navigate('/mood-boards')}
+ className="flex items-center gap-1 text-sm text-gray-400 hover:text-white mb-4 transition-colors"
+ >
+ <ArrowLeft className="w-4 h-4" aria-hidden="true" /> Boards
+ </button>
+
+ {/* Board metadata */}
+ <div className="bg-port-card border border-port-border rounded-md p-4 mb-6">
+ <div className="space-y-3">
+ <div>
+ <label htmlFor="board-name" className="block text-xs text-gray-400 mb-1">Name</label>
+ <input
+ id="board-name"
+ type="text"
+ value={name}
+ maxLength={200}
+ onChange={(e) => setName(e.target.value)}
+ className="w-full bg-port-bg border border-port-border rounded px-2 py-1.5 text-white text-sm focus:border-port-accent outline-none"
+ />
+ </div>
+ <div>
+ <label htmlFor="board-description" className="block text-xs text-gray-400 mb-1">Description</label>
+ <textarea
+ id="board-description"
+ value={description}
+ maxLength={5000}
+ rows={2}
+ onChange={(e) => setDescription(e.target.value)}
+ className="w-full bg-port-bg border border-port-border rounded px-2 py-1.5 text-white text-sm focus:border-port-accent outline-none resize-y"
+ />
+ </div>
+ <div className="flex justify-end">
+ <button
+ type="button"
+ onClick={handleSaveMeta}
+ disabled={!metaDirty || savingMeta}
+ className="flex items-center gap-1.5 px-3 py-1.5 text-sm rounded bg-port-accent text-white hover:bg-port-accent/80 disabled:opacity-50 transition-colors"
+ >
+ <Save className="w-4 h-4" aria-hidden="true" /> Save
+ </button>
+ </div>
+ </div>
+ </div>
+
+ {/* Add item */}
+ <div className="bg-port-card border border-port-border rounded-md p-4 mb-6">
+ <div className="flex items-center gap-2 mb-3" role="tablist" aria-label="Item type">
+ <button
+ type="button"
+ role="tab"
+ aria-selected={itemType === 'image'}
+ onClick={() => setItemType('image')}
+ className={`flex items-center gap-1.5 px-3 py-1.5 text-sm rounded transition-colors ${itemType === 'image' ? 'bg-port-accent text-white' : 'bg-port-bg text-gray-400 hover:text-white'}`}
+ >
+ <ImageIcon className="w-4 h-4" aria-hidden="true" /> Image
+ </button>
+ <button
+ type="button"
+ role="tab"
+ aria-selected={itemType === 'text'}
+ onClick={() => setItemType('text')}
+ className={`flex items-center gap-1.5 px-3 py-1.5 text-sm rounded transition-colors ${itemType === 'text' ? 'bg-port-accent text-white' : 'bg-port-bg text-gray-400 hover:text-white'}`}
+ >
+ <FileText className="w-4 h-4" aria-hidden="true" /> Note
+ </button>
+ </div>
+
+ <div className="space-y-3">
+ {itemType === 'image' ? (
+ <div>
+ <label htmlFor="item-image-url" className="block text-xs text-gray-400 mb-1">Image URL</label>
+ <input
+ id="item-image-url"
+ type="text"
+ value={imageUrl}
+ maxLength={2048}
+ placeholder="https://… or /data/images/…"
+ onChange={(e) => setImageUrl(e.target.value)}
+ className="w-full bg-port-bg border border-port-border rounded px-2 py-1.5 text-white text-sm focus:border-port-accent outline-none"
+ />
+ </div>
+ ) : (
+ <div>
+ <label htmlFor="item-text" className="block text-xs text-gray-400 mb-1">Note</label>
+ <textarea
+ id="item-text"
+ value={text}
+ maxLength={10000}
+ rows={2}
+ onChange={(e) => setText(e.target.value)}
+ className="w-full bg-port-bg border border-port-border rounded px-2 py-1.5 text-white text-sm focus:border-port-accent outline-none resize-y"
+ />
+ </div>
+ )}
+ <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
+ <div>
+ <label htmlFor="item-caption" className="block text-xs text-gray-400 mb-1">Caption (optional)</label>
+ <input
+ id="item-caption"
+ type="text"
+ value={caption}
+ maxLength={2000}
+ onChange={(e) => setCaption(e.target.value)}
+ className="w-full bg-port-bg border border-port-border rounded px-2 py-1.5 text-white text-sm focus:border-port-accent outline-none"
+ />
+ </div>
+ <div>
+ <label htmlFor="item-source" className="block text-xs text-gray-400 mb-1">Source (optional)</label>
+ <input
+ id="item-source"
+ type="text"
+ value={source}
+ maxLength={2048}
+ placeholder="where it came from"
+ onChange={(e) => setSource(e.target.value)}
+ className="w-full bg-port-bg border border-port-border rounded px-2 py-1.5 text-white text-sm focus:border-port-accent outline-none"
+ />
+ </div>
+ </div>
+ <div className="flex justify-end">
+ <button
+ type="button"
+ onClick={handleAddItem}
+ disabled={adding}
+ className="flex items-center gap-1.5 px-3 py-1.5 text-sm rounded bg-port-success text-white hover:bg-port-success/80 disabled:opacity-50 transition-colors"
+ >
+ <Plus className="w-4 h-4" aria-hidden="true" /> Pin to board
+ </button>
+ </div>
+ </div>
+ </div>
+
+ {/* Items grid */}
+ {items.length === 0 ? (
+ <div className="text-gray-400 text-sm py-12 text-center border border-dashed border-port-border rounded">
+ No items yet. Pin an image or note above.
+ </div>
+ ) : (
+ <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-3">
+ {items.map((item) => {
+ const src = imageSrc(item);
+ return (
+ <div key={item.id} className="bg-port-card border border-port-border rounded-md overflow-hidden flex flex-col">
+ {item.type === 'image' ? (
+ src ? (
+ <img src={src} alt={item.caption || ''} loading="lazy" className="w-full aspect-square object-cover bg-port-bg" />
+ ) : (
+ <div className="w-full aspect-square flex items-center justify-center bg-port-bg text-gray-600">
+ <ImageIcon className="w-8 h-8" aria-hidden="true" />
+ </div>
+ )
+ ) : (
+ <div className="w-full aspect-square p-3 overflow-y-auto bg-port-bg text-sm text-gray-200 whitespace-pre-wrap">
+ {item.text}
+ </div>
+ )}
+ <div className="p-2 flex flex-col gap-1">
+ <input
+ type="text"
+ defaultValue={item.caption || ''}
+ placeholder="Add a caption…"
+ maxLength={2000}
+ onBlur={(e) => {
+ const next = e.target.value.trim();
+ if (next !== (item.caption || '')) handleUpdateCaption(item.id, next);
+ }}
+ className="w-full bg-transparent border-0 border-b border-transparent focus:border-port-border text-xs text-gray-300 px-0 py-0.5 outline-none"
+ />
+ <div className="flex items-center justify-between">
+ {item.source ? (
+ <span className="text-[10px] text-gray-500 truncate" title={item.source}>{item.source}</span>
+ ) : <span />}
+ <button
+ type="button"
+ onClick={() => setConfirmingItemId(item.id)}
+ title="Remove item"
+ aria-label="Remove item"
+ className="p-1 text-gray-500 hover:text-port-error transition-colors"
+ >
+ <Trash2 className="w-3.5 h-3.5" aria-hidden="true" />
+ </button>
+ </div>
+ {confirmingItemId === item.id ? (
+ <InlineConfirmRow
+ question="Remove this item?"
+ confirmText="Remove"
+ onConfirm={() => handleRemoveItem(item.id)}
+ onCancel={() => setConfirmingItemId(null)}
+ />
+ ) : null}
+ </div>
+ </div>
+ );
+ })}
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/client/src/pages/MoodBoards.jsx b/client/src/pages/MoodBoards.jsx
new file mode 100644
index 0000000000..c0a879bd9a
--- /dev/null
+++ b/client/src/pages/MoodBoards.jsx
@@ -0,0 +1,145 @@
+/**
+ * Mood Boards page — board index (issue #911).
+ *
+ * Lists every mood board (an inspiration/reference canvas that feeds the Create
+ * suite) and lets the user create, open, or delete one. The heavy canvas lives
+ * at `/mood-boards/:id`; "New Board" creates a blank board and drops into it.
+ * Mirrors the Universes index (list/table → detail editor) but simpler — boards
+ * are local-only with no sync/duplicate machinery.
+ */
+
+import { useEffect, useState, useCallback } from 'react';
+import { Link, useNavigate } from 'react-router-dom';
+import { Plus, Palette, Trash2, ImageIcon, FileText } from 'lucide-react';
+import toast from '../components/ui/Toast';
+import InlineConfirmRow from '../components/ui/InlineConfirmRow';
+import { timeAgo } from '../utils/formatters';
+import { listMoodBoards, createMoodBoard, deleteMoodBoard } from '../services/api';
+
+const itemCounts = (board) => {
+ const items = Array.isArray(board?.items) ? board.items : [];
+ let images = 0;
+ let texts = 0;
+ for (const it of items) {
+ if (it?.type === 'image') images += 1;
+ else if (it?.type === 'text') texts += 1;
+ }
+ return { images, texts, total: items.length };
+};
+
+export default function MoodBoards() {
+ const navigate = useNavigate();
+ const [boards, setBoards] = useState([]);
+ const [loading, setLoading] = useState(true);
+ const [creating, setCreating] = useState(false);
+ const [confirmingId, setConfirmingId] = useState(null);
+
+ const load = useCallback(async () => {
+ setLoading(true);
+ const data = await listMoodBoards({ silent: true }).catch(() => null);
+ if (data) setBoards(Array.isArray(data) ? data : []);
+ else toast.error('Failed to load mood boards');
+ setLoading(false);
+ }, []);
+
+ useEffect(() => { load(); }, [load]);
+
+ const handleCreate = async () => {
+ setCreating(true);
+ const board = await createMoodBoard({ name: 'Untitled board' }, { silent: true }).catch(() => null);
+ setCreating(false);
+ if (!board) { toast.error('Failed to create board'); return; }
+ navigate(`/mood-boards/${board.id}`);
+ };
+
+ const handleDelete = async (id) => {
+ setConfirmingId(null);
+ const ok = await deleteMoodBoard(id, { silent: true }).then(() => true).catch(() => false);
+ if (!ok) { toast.error('Failed to delete board'); return; }
+ setBoards((prev) => prev.filter((b) => b.id !== id));
+ toast.success('Board deleted');
+ };
+
+ return (
+ <div className="max-w-5xl mx-auto">
+ <div className="flex items-center justify-between mb-4">
+ <div className="flex items-center gap-2">
+ <Palette className="w-6 h-6 text-port-accent" aria-hidden="true" />
+ <h1 className="text-xl font-semibold text-white">Mood Boards</h1>
+ </div>
+ <button
+ type="button"
+ onClick={handleCreate}
+ disabled={creating}
+ className="flex items-center gap-1.5 px-3 py-1.5 text-sm rounded bg-port-accent text-white hover:bg-port-accent/80 disabled:opacity-50 transition-colors"
+ >
+ <Plus className="w-4 h-4" aria-hidden="true" />
+ New Board
+ </button>
+ </div>
+
+ <p className="text-sm text-gray-400 mb-4">
+ Collect visual and textual references for your universes, scenes, and treatments.
+ </p>
+
+ {loading ? (
+ <div className="text-gray-400 text-sm py-8 text-center">Loading…</div>
+ ) : boards.length === 0 ? (
+ <div className="text-gray-400 text-sm py-12 text-center border border-dashed border-port-border rounded">
+ No mood boards yet. Create one to start pinning references.
+ </div>
+ ) : (
+ <ul className="space-y-2">
+ {boards.map((board) => {
+ const { images, texts, total } = itemCounts(board);
+ return (
+ <li
+ key={board.id}
+ className="bg-port-card border border-port-border rounded-md overflow-hidden"
+ >
+ {confirmingId === board.id ? (
+ <InlineConfirmRow
+ variant="separator"
+ question={`Delete "${board.name}"? This can't be undone.`}
+ onConfirm={() => handleDelete(board.id)}
+ onCancel={() => setConfirmingId(null)}
+ />
+ ) : null}
+ <div className="flex items-center gap-3 p-3">
+ <Link
+ to={`/mood-boards/${board.id}`}
+ className="flex-1 min-w-0"
+ >
+ <div className="text-white font-medium truncate">{board.name}</div>
+ {board.description ? (
+ <div className="text-xs text-gray-400 truncate">{board.description}</div>
+ ) : null}
+ <div className="flex items-center gap-3 mt-1 text-xs text-gray-500">
+ <span className="flex items-center gap-1">
+ <ImageIcon className="w-3 h-3" aria-hidden="true" /> {images}
+ </span>
+ <span className="flex items-center gap-1">
+ <FileText className="w-3 h-3" aria-hidden="true" /> {texts}
+ </span>
+ <span>{total} item{total === 1 ? '' : 's'}</span>
+ <span>· {timeAgo(board.updatedAt)}</span>
+ </div>
+ </Link>
+ <button
+ type="button"
+ onClick={() => setConfirmingId(board.id)}
+ title="Delete board"
+ aria-label={`Delete ${board.name}`}
+ className="p-1.5 text-gray-500 hover:text-port-error transition-colors"
+ >
+ <Trash2 className="w-4 h-4" aria-hidden="true" />
+ </button>
+ </div>
+ </li>
+ );
+ })}
+ </ul>
+ )}
+ </div>
+ );
+}
diff --git a/client/src/services/README.md b/client/src/services/README.md
index 0055600480..fd7b66cca6 100644
--- a/client/src/services/README.md
+++ b/client/src/services/README.md
@@ -72,6 +72,7 @@ toasts on throw). **Custom catch ⇒ `silent: true`** — otherwise toasts fire
| `apiHealth.js` | Apple Health. |
| `apiMeatspace.js` | MeatSpace (genome + location). |
| `apiMortalLoom.js` | Mortality tracking. |
+| `apiMoodBoard.js` | Mood boards (inspiration canvas + items). |
| `apiCalendar.js` | Calendar events. |
| `apiMessages.js` | Messages / notifications. |
| `apiPersonalities.js` | Agent personality profiles. |
diff --git a/client/src/services/api.js b/client/src/services/api.js
index d35292cee5..7bb8aa5ecc 100644
--- a/client/src/services/api.js
+++ b/client/src/services/api.js
@@ -54,6 +54,7 @@ export * from './apiSongs.js';
export * from './apiPeerSync.js';
export * from './apiSyncReview.js';
export * from './apiCreativeDirector.js';
+export * from './apiMoodBoard.js';
export * from './apiImporter.js';
export * from './apiStoryBuilder.js';
export * from './apiVoice.js';
diff --git a/client/src/services/apiMoodBoard.js b/client/src/services/apiMoodBoard.js
new file mode 100644
index 0000000000..a124f711ea
--- /dev/null
+++ b/client/src/services/apiMoodBoard.js
@@ -0,0 +1,47 @@
+import { request } from './apiCore.js';
+
+// Mood boards (issue #911) — inspiration/reference canvases that feed the
+// Create suite. Boards are db-primary, local-only; items live inline.
+// `options` is forwarded to the request helper so callers that own their own
+// error UI (useAsyncAction / custom catch) can pass `{ silent: true }`.
+
+export const listMoodBoards = (options) => request('/mood-boards', options);
+
+export const getMoodBoard = (id, options) =>
+ request(`/mood-boards/${encodeURIComponent(id)}`, options);
+
+export const createMoodBoard = (data, options) => request('/mood-boards', {
+ method: 'POST',
+ body: JSON.stringify(data),
+ ...options,
+});
+
+export const updateMoodBoard = (id, patch, options) => request(`/mood-boards/${encodeURIComponent(id)}`, {
+ method: 'PATCH',
+ body: JSON.stringify(patch),
+ ...options,
+});
+
+export const deleteMoodBoard = (id, options) => request(`/mood-boards/${encodeURIComponent(id)}`, {
+ method: 'DELETE',
+ ...options,
+});
+
+export const addMoodBoardItem = (id, item, options) => request(`/mood-boards/${encodeURIComponent(id)}/items`, {
+ method: 'POST',
+ body: JSON.stringify(item),
+ ...options,
+});
+
+export const updateMoodBoardItem = (id, itemId, patch, options) =>
+ request(`/mood-boards/${encodeURIComponent(id)}/items/${encodeURIComponent(itemId)}`, {
+ method: 'PATCH',
+ body: JSON.stringify(patch),
+ ...options,
+ });
+
+export const removeMoodBoardItem = (id, itemId, options) =>
+ request(`/mood-boards/${encodeURIComponent(id)}/items/${encodeURIComponent(itemId)}`, {
+ method: 'DELETE',
+ ...options,
+ });
diff --git a/scripts/migrations/108-mood-boards-table.js b/scripts/migrations/108-mood-boards-table.js
new file mode 100644
index 0000000000..fdfff9e138
--- /dev/null
+++ b/scripts/migrations/108-mood-boards-table.js
@@ -0,0 +1,25 @@
+/**
+ * Registration stub for the mood_boards table (issue #911).
+ *
+ * The actual DDL — `CREATE TABLE IF NOT EXISTS mood_boards` plus its
+ * `idx_mood_boards_updated` index and the `trg_mood_boards_audit` trigger — is
+ * idempotent and lives in `ensureSchema()` (`server/lib/db.js`) and the
+ * fresh-install seed (`server/scripts/init-db.sql`), both of which run at server
+ * boot AFTER the DB pool is up. The `scripts/migrations/` runner executes BEFORE
+ * the pool is initialized, so a DB-table create cannot live here — the same
+ * reason migrations 048–052 are boot-time + stub-registered.
+ *
+ * This stub exists so the new-table change is *registered the standard way*: it
+ * lands in `data/migrations.applied.json` so the migration ledger and `git log`
+ * show when the mood_boards table was introduced. The table is additive (a
+ * brand-new, local-only db-primary store), so there is no data backfill —
+ * the moodBoard service populates it lazily on the first board create.
+ *
+ * No-op + idempotent: nothing to do here.
+ */
+
+export default {
+ async up() {
+ console.log('🎨 mood_boards: table created idempotently by ensureSchema at boot; nothing to do in the file runner');
+ },
+};
diff --git a/server/index.js b/server/index.js
index a0c1a21129..6c6236db44 100644
--- a/server/index.js
+++ b/server/index.js
@@ -106,6 +106,7 @@ import videoGenRoutes from './routes/videoGen.js';
import videoTimelineRoutes from './routes/videoTimeline.js';
import mediaJobsRoutes from './routes/mediaJobs.js';
import creativeDirectorRoutes from './routes/creativeDirector.js';
+import moodBoardRoutes from './routes/moodBoard.js';
import writersRoomRoutes from './routes/writersRoom.js';
import universeBuilderRoutes from './routes/universeBuilder.js';
import authorsRoutes from './routes/authors.js';
@@ -526,6 +527,7 @@ app.use('/api/video-gen', videoGenRoutes);
app.use('/api/video-timeline', videoTimelineRoutes);
app.use('/api/media-jobs', mediaJobsRoutes);
app.use('/api/creative-director', creativeDirectorRoutes);
+app.use('/api/mood-boards', moodBoardRoutes);
app.use('/api/writers-room', writersRoomRoutes);
app.use('/api/universe-builder', universeBuilderRoutes);
app.use('/api/authors', authorsRoutes);
diff --git a/server/lib/README.md b/server/lib/README.md
index b772e586f6..7b68ba6d5c 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -33,6 +33,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `identityValidation.js` | Identity section + chronotype + scheduling schemas. |
| `meatspaceValidation.js` | Meatspace (location/health log) schemas. |
| `memoryValidation.js` | Memory record + retrieval schemas. |
+| `moodBoardValidation.js` | Mood board + board-item create/update schemas. |
| `notesValidation.js` | Notes route schemas + safe-relative-path guard. |
| `peerSyncValidation.js` | Federated peer-sync wire/request schemas (push payload, subscribe, sync-now, pull-metadata). |
| `postValidation.js` | Social post schemas. |
diff --git a/server/lib/db.js b/server/lib/db.js
index 21460524ac..aac38098f3 100644
--- a/server/lib/db.js
+++ b/server/lib/db.js
@@ -823,6 +823,27 @@ async function ensureSchemaImpl() {
updated_at TIMESTAMPTZ DEFAULT NOW()
)`,
+ // Mood boards (issue #911). A dedicated inspiration/mood-board canvas,
+ // distinct from raw Media History, for collecting visual + textual
+ // references that feed the Create suite. One row per board, the full record
+ // (name/description/items[]) in `data` JSONB. Items (image-by-media-key or
+ // external URL, or a text note + optional caption/source backref) live
+ // inline in the board's JSONB rather than a child table — a board is read/
+ // written whole, has a small bounded item list, and there are no cross-board
+ // item queries. `name` mirrors a column for the live-list sort. Mood boards
+ // are db-primary and LOCAL-ONLY (no sync_sequence/tombstone) — like
+ // creative_director_projects, they don't federate to peers in v1. Mirrors
+ // the mood_boards block in init-db.sql.
+ `CREATE TABLE IF NOT EXISTS mood_boards (
+ id TEXT PRIMARY KEY,
+ name TEXT NOT NULL,
+ data JSONB NOT NULL DEFAULT '{}'::jsonb,
+ created_at TIMESTAMPTZ DEFAULT NOW(),
+ updated_at TIMESTAMPTZ DEFAULT NOW()
+ )`,
+ // updated_at DESC is the board-list "recently touched" sort.
+ `CREATE INDEX IF NOT EXISTS idx_mood_boards_updated ON mood_boards (updated_at DESC)`,
+
// Media asset index (Phase 3.2, issue #1000). One row per generated image
// or video; the bytes stay on disk (data/images, data/videos) and the
// sidecar/.json history files remain authoritative — this table is a
@@ -1199,8 +1220,8 @@ async function ensureSchemaImpl() {
'universes', 'universe_runs', 'pipeline_series', 'pipeline_issues',
'story_builder_sessions', 'writers_room_works', 'writers_room_folders',
'writers_room_draft_versions', 'catalog_ingredients', 'catalog_scraps',
- 'catalog_user_types', 'creative_director_projects', 'lora_training_runs',
- 'authors', 'tribe_people', 'tribe_touchpoints',
+ 'catalog_user_types', 'creative_director_projects', 'mood_boards',
+ 'lora_training_runs', 'authors', 'tribe_people', 'tribe_touchpoints',
];
for (const t of auditedTables) {
catalogDDL.push(`DROP TRIGGER IF EXISTS trg_${t}_audit ON ${t}`);
diff --git a/server/lib/index.js b/server/lib/index.js
index ec8d46af3a..697dcf80e7 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -25,6 +25,7 @@ export * as genomeValidation from './genomeValidation.js';
export * as identityValidation from './identityValidation.js';
export * as meatspaceValidation from './meatspaceValidation.js';
export * as memoryValidation from './memoryValidation.js';
+export * as moodBoardValidation from './moodBoardValidation.js';
export * as notesValidation from './notesValidation.js';
export * as peerSyncValidation from './peerSyncValidation.js';
export * as postValidation from './postValidation.js';
diff --git a/server/lib/moodBoardValidation.js b/server/lib/moodBoardValidation.js
new file mode 100644
index 0000000000..8a8eaa67a9
--- /dev/null
+++ b/server/lib/moodBoardValidation.js
@@ -0,0 +1,83 @@
+import { z } from 'zod';
+
+// =============================================================================
+// MOOD BOARD SCHEMAS (issue #911)
+// =============================================================================
+// A mood board collects visual + textual references that feed the Create suite.
+// Boards are db-primary, local-only records; items live inline in the board's
+// JSONB. validation.js re-exports everything here so deep imports keep working.
+
+export const MOOD_BOARD_ITEM_TYPES = Object.freeze(['image', 'text']);
+
+// A media-key references an indexed asset as `<kind>:<ref>` (see mediaItemKey.js)
+// — e.g. `image:my-render.png` or `video:job-123`. Kept permissive (the index is
+// the source of truth); just bound the length and require the `<kind>:<ref>` shape.
+const mediaKeySchema = z.string().trim().min(3).max(512).regex(
+ /^[a-z]+:.+$/,
+ 'mediaKey must be in `<kind>:<ref>` form',
+);
+
+// External/pinned image URL. http(s) or a same-origin app path (e.g. a served
+// `/data/images/...` URL). Bounded; the UI renders it in an <img>, so no exotic
+// schemes.
+const imageUrlSchema = z.string().trim().min(1).max(2048).refine(
+ (v) => /^https?:\/\//.test(v) || v.startsWith('/'),
+ 'imageUrl must be an http(s) URL or an absolute app path',
+);
+
+const captionSchema = z.string().max(2000).nullable().optional();
+const sourceSchema = z.string().max(2048).nullable().optional();
+
+// Board create. description optional (defaults to '' in the record builder).
+export const moodBoardCreateSchema = z.object({
+ name: z.string().trim().min(1).max(200),
+ description: z.string().max(5000).optional(),
+}).strict();
+
+// Board PATCH — only the editable board-level fields. items[] is managed via
+// the dedicated item endpoints, never a bulk board PATCH.
+export const moodBoardUpdateSchema = z.object({
+ name: z.string().trim().min(1).max(200).optional(),
+ description: z.string().max(5000).optional(),
+}).strict();
+
+// Add-item. An `image` item requires at least one of mediaKey / imageUrl; a
+// `text` item requires non-empty text. The cross-field rule is enforced with a
+// superRefine so the failure is specific.
+export const moodBoardItemCreateSchema = z.object({
+ type: z.enum(MOOD_BOARD_ITEM_TYPES),
+ mediaKey: mediaKeySchema.nullable().optional(),
+ imageUrl: imageUrlSchema.nullable().optional(),
+ text: z.string().trim().max(10000).nullable().optional(),
+ caption: captionSchema,
+ source: sourceSchema,
+}).strict().superRefine((val, ctx) => {
+ if (val.type === 'image') {
+ if (!val.mediaKey && !val.imageUrl) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ message: 'an image item requires mediaKey or imageUrl',
+ path: ['imageUrl'],
+ });
+ }
+ } else if (val.type === 'text') {
+ if (!val.text || !val.text.trim()) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ message: 'a text item requires non-empty text',
+ path: ['text'],
+ });
+ }
+ }
+});
+
+// Item PATCH — caption/source on any item, plus the type-appropriate body
+// field. No `type` switch (an item's kind is fixed at creation); every field
+// optional so a partial edit validates.
+export const moodBoardItemUpdateSchema = z.object({
+ caption: captionSchema,
+ source: sourceSchema,
+ text: z.string().trim().max(10000).nullable().optional(),
+ imageUrl: imageUrlSchema.nullable().optional(),
+ mediaKey: mediaKeySchema.nullable().optional(),
+}).strict();
diff --git a/server/lib/moodBoardValidation.test.js b/server/lib/moodBoardValidation.test.js
new file mode 100644
index 0000000000..c29edf2669
--- /dev/null
+++ b/server/lib/moodBoardValidation.test.js
@@ -0,0 +1,68 @@
+/**
+ * Schema tests for mood board validation (issue #911). Locks the cross-field
+ * item rules (image requires mediaKey|imageUrl; text requires non-empty text)
+ * and the URL/media-key shape guards the route boundary relies on.
+ */
+
+import { describe, it, expect } from 'vitest';
+import {
+ moodBoardCreateSchema,
+ moodBoardUpdateSchema,
+ moodBoardItemCreateSchema,
+ moodBoardItemUpdateSchema,
+} from './moodBoardValidation.js';
+
+describe('moodBoardCreateSchema', () => {
+ it('accepts a name + optional description', () => {
+ expect(moodBoardCreateSchema.parse({ name: 'Refs' }).name).toBe('Refs');
+ expect(moodBoardCreateSchema.parse({ name: 'Refs', description: 'd' }).description).toBe('d');
+ });
+ it('rejects an empty name', () => {
+ expect(moodBoardCreateSchema.safeParse({ name: '' }).success).toBe(false);
+ });
+ it('rejects unknown keys (strict)', () => {
+ expect(moodBoardCreateSchema.safeParse({ name: 'x', items: [] }).success).toBe(false);
+ });
+});
+
+describe('moodBoardUpdateSchema', () => {
+ it('accepts a partial patch', () => {
+ expect(moodBoardUpdateSchema.parse({ description: '' }).description).toBe('');
+ });
+});
+
+describe('moodBoardItemCreateSchema', () => {
+ it('accepts an image item with imageUrl', () => {
+ expect(moodBoardItemCreateSchema.safeParse({ type: 'image', imageUrl: 'https://x/y.png' }).success).toBe(true);
+ });
+ it('accepts an image item with an app-path imageUrl', () => {
+ expect(moodBoardItemCreateSchema.safeParse({ type: 'image', imageUrl: '/data/images/a.png' }).success).toBe(true);
+ });
+ it('accepts an image item with a mediaKey', () => {
+ expect(moodBoardItemCreateSchema.safeParse({ type: 'image', mediaKey: 'image:a.png' }).success).toBe(true);
+ });
+ it('rejects an image item with neither mediaKey nor imageUrl', () => {
+ expect(moodBoardItemCreateSchema.safeParse({ type: 'image' }).success).toBe(false);
+ });
+ it('rejects a bad imageUrl scheme', () => {
+ expect(moodBoardItemCreateSchema.safeParse({ type: 'image', imageUrl: 'javascript:alert(1)' }).success).toBe(false);
+ });
+ it('rejects a malformed mediaKey', () => {
+ expect(moodBoardItemCreateSchema.safeParse({ type: 'image', mediaKey: 'no-colon' }).success).toBe(false);
+ });
+ it('accepts a text item with text', () => {
+ expect(moodBoardItemCreateSchema.safeParse({ type: 'text', text: 'note' }).success).toBe(true);
+ });
+ it('rejects a text item with blank text', () => {
+ expect(moodBoardItemCreateSchema.safeParse({ type: 'text', text: ' ' }).success).toBe(false);
+ });
+});
+
+describe('moodBoardItemUpdateSchema', () => {
+ it('accepts a caption-only patch', () => {
+ expect(moodBoardItemUpdateSchema.parse({ caption: 'c' }).caption).toBe('c');
+ });
+ it('accepts a null caption (clear)', () => {
+ expect(moodBoardItemUpdateSchema.parse({ caption: null }).caption).toBeNull();
+ });
+});
diff --git a/server/lib/navManifest.js b/server/lib/navManifest.js
index 2aac26d8f9..8ab39242a4 100644
--- a/server/lib/navManifest.js
+++ b/server/lib/navManifest.js
@@ -19,6 +19,7 @@ export const NAV_COMMANDS = [
{ id: 'nav.media.history', path: '/media/history', label: 'Media History', section: 'Create', aliases: ['media-history', 'video-history'], keywords: ['videos', 'gallery', 'stitch'] },
{ id: 'nav.media.collections', path: '/media/collections', label: 'Collections', section: 'Create', aliases: ['collections', 'media-collections', 'stacks', 'projects'], keywords: ['bucket', 'group', 'project', 'album', 'organize'] },
{ id: 'nav.media.creative-director', path: '/media/creative-director', label: 'Creative Director', section: 'Create', aliases: ['creative-director', 'creative', 'director', 'long-form', 'episode'], keywords: ['story', 'episode', 'narrative', 'agent', 'auto-video', 'long-form'] },
+ { id: 'nav.create.mood-boards', path: '/mood-boards', label: 'Mood Boards', section: 'Create', aliases: ['mood-boards', 'mood-board', 'moodboard', 'mood', 'inspiration', 'references'], keywords: ['inspiration', 'reference', 'pin', 'visual', 'canvas', 'collect', 'pinboard', 'palette', 'ideas'] },
{ id: 'nav.media.timeline', path: '/media/timeline', label: 'Timeline', section: 'Create', aliases: ['timeline', 'video-timeline', 'editor'], keywords: ['edit', 'trim', 'composite', 'stitch', 'cut', 'compose'] },
{ id: 'nav.media.models', path: '/media/models', label: 'Media Models', section: 'Create', aliases: ['media-models', 'image-models', 'video-models', 'huggingface'], keywords: ['hf cache', 'model storage', 'disk'] },
{ id: 'nav.create.authors', path: '/authors', label: 'Authors', section: 'Create', aliases: ['authors', 'author', 'byline', 'author-persona', 'writer-persona'], keywords: ['author', 'byline', 'pen name', 'persona', 'writing style', 'bio', 'headshot', 'cover', 'book author'] },
diff --git a/server/lib/validation.js b/server/lib/validation.js
index b85fd351a8..54ddabf39e 100644
--- a/server/lib/validation.js
+++ b/server/lib/validation.js
@@ -1784,3 +1784,4 @@ export const legacyExportSchema = z.object({
export * from './peerSyncValidation.js';
export * from './creativeDirectorValidation.js';
export * from './storyBuilderValidation.js';
+export * from './moodBoardValidation.js';
diff --git a/server/routes/moodBoard.js b/server/routes/moodBoard.js
new file mode 100644
index 0000000000..19adeb4426
--- /dev/null
+++ b/server/routes/moodBoard.js
@@ -0,0 +1,77 @@
+/**
+ * Mood Board Routes — REST surface for board CRUD + inline item ops (issue #911).
+ *
+ * A board collects visual + textual references that feed the Create suite.
+ * Items live inline in the board record, so they're managed through dedicated
+ * sub-routes (add/update/remove) rather than a bulk board PATCH — each op locks
+ * the board row server-side so concurrent affordances can't clobber each other.
+ */
+
+import { Router } from 'express';
+import { asyncHandler, ServerError } from '../lib/errorHandler.js';
+import {
+ validateRequest,
+ moodBoardCreateSchema,
+ moodBoardUpdateSchema,
+ moodBoardItemCreateSchema,
+ moodBoardItemUpdateSchema,
+} from '../lib/validation.js';
+import {
+ listBoards,
+ getBoard,
+ createBoard,
+ updateBoard,
+ deleteBoard,
+ addBoardItem,
+ updateBoardItem,
+ removeBoardItem,
+} from '../services/moodBoard/index.js';
+
+const router = Router();
+
+router.get('/', asyncHandler(async (_req, res) => {
+ res.json(await listBoards());
+}));
+
+router.get('/:id', asyncHandler(async (req, res) => {
+ const board = await getBoard(req.params.id);
+ if (!board) throw new ServerError('Mood board not found', { status: 404, code: 'NOT_FOUND' });
+ res.json(board);
+}));
+
+router.post('/', asyncHandler(async (req, res) => {
+ const data = validateRequest(moodBoardCreateSchema, req.body);
+ const board = await createBoard(data);
+ res.status(201).json(board);
+}));
+
+router.patch('/:id', asyncHandler(async (req, res) => {
+ const data = validateRequest(moodBoardUpdateSchema, req.body);
+ const updated = await updateBoard(req.params.id, data);
+ res.json(updated);
+}));
+
+router.delete('/:id', asyncHandler(async (req, res) => {
+ await deleteBoard(req.params.id);
+ res.json({ ok: true });
+}));
+
+// Pin an item to the board (image-by-media-key/URL or text note).
+router.post('/:id/items', asyncHandler(async (req, res) => {
+ const data = validateRequest(moodBoardItemCreateSchema, req.body);
+ const item = await addBoardItem(req.params.id, data);
+ res.status(201).json(item);
+}));
+
+router.patch('/:id/items/:itemId', asyncHandler(async (req, res) => {
+ const data = validateRequest(moodBoardItemUpdateSchema, req.body);
+ const item = await updateBoardItem(req.params.id, req.params.itemId, data);
+ res.json(item);
+}));
+
+router.delete('/:id/items/:itemId', asyncHandler(async (req, res) => {
+ const board = await removeBoardItem(req.params.id, req.params.itemId);
+ res.json(board);
+}));
+
+export default router;
diff --git a/server/scripts/init-db.sql b/server/scripts/init-db.sql
index ad17929b3c..8834c4c40e 100644
--- a/server/scripts/init-db.sql
+++ b/server/scripts/init-db.sql
@@ -648,6 +648,26 @@ CREATE TABLE IF NOT EXISTS creative_director_projects (
updated_at TIMESTAMPTZ DEFAULT NOW()
);
+-- Mood boards (issue #911). A dedicated inspiration/mood-board canvas, distinct
+-- from raw Media History, for collecting visual + textual references that feed
+-- the Create suite. One row per board, the full record (name/description/items[])
+-- in `data` JSONB. Each item carries an image (media-key or external URL) or a
+-- text note, optional caption, and an optional source backref — kept inline in
+-- the board's JSONB rather than a child table because a board is read/written
+-- whole (a small bounded item list, no cross-board item queries). `name` mirrors
+-- a column for the live-list sort. Mood boards are db-primary and LOCAL-ONLY
+-- (no sync_sequence/tombstone) — like creative_director_projects, they don't
+-- federate to peers in v1. Mirrors the mood_boards block in db.js ensureSchema().
+CREATE TABLE IF NOT EXISTS mood_boards (
+ id TEXT PRIMARY KEY,
+ name TEXT NOT NULL,
+ data JSONB NOT NULL DEFAULT '{}'::jsonb,
+ created_at TIMESTAMPTZ DEFAULT NOW(),
+ updated_at TIMESTAMPTZ DEFAULT NOW()
+);
+-- updated_at DESC is the board-list "recently touched" sort.
+CREATE INDEX IF NOT EXISTS idx_mood_boards_updated ON mood_boards (updated_at DESC);
+
-- Media asset index (Phase 3.2, issue #1000). One row per generated image or
-- video. The bytes stay on disk (data/images, data/videos) and the image
-- sidecars + data/video-history.json remain authoritative — this table is a
@@ -1011,6 +1031,8 @@ DROP TRIGGER IF EXISTS trg_catalog_user_types_audit ON catalog_user_types;
CREATE TRIGGER trg_catalog_user_types_audit AFTER UPDATE OR DELETE ON catalog_user_types FOR EACH ROW EXECUTE FUNCTION record_audit_log();
DROP TRIGGER IF EXISTS trg_creative_director_projects_audit ON creative_director_projects;
CREATE TRIGGER trg_creative_director_projects_audit AFTER UPDATE OR DELETE ON creative_director_projects FOR EACH ROW EXECUTE FUNCTION record_audit_log();
+DROP TRIGGER IF EXISTS trg_mood_boards_audit ON mood_boards;
+CREATE TRIGGER trg_mood_boards_audit AFTER UPDATE OR DELETE ON mood_boards FOR EACH ROW EXECUTE FUNCTION record_audit_log();
DROP TRIGGER IF EXISTS trg_lora_training_runs_audit ON lora_training_runs;
CREATE TRIGGER trg_lora_training_runs_audit AFTER UPDATE OR DELETE ON lora_training_runs FOR EACH ROW EXECUTE FUNCTION record_audit_log();
DROP TRIGGER IF EXISTS trg_authors_audit ON authors;
diff --git a/server/services/moodBoard/db.js b/server/services/moodBoard/db.js
new file mode 100644
index 0000000000..1b7e0a03f4
--- /dev/null
+++ b/server/services/moodBoard/db.js
@@ -0,0 +1,137 @@
+/**
+ * Mood Board — PostgreSQL-backed store (issue #911).
+ *
+ * One row per board in `mood_boards`: id / name / created_at / updated_at as
+ * columns, the full record (name/description/items[]) in `data` JSONB. Mood
+ * boards are db-primary and local-only (no federation in v1), modeled on the
+ * creativeDirector projectsDB store.
+ *
+ * Concurrency: the trust model is single-user, but a board has more than one
+ * write path that can touch the SAME board (board PATCH + item add/update/remove
+ * fired from different UI affordances), and a read-modify-write spanning two
+ * pool round-trips would lose updates. So every mutator runs inside
+ * withTransaction + `SELECT … FOR UPDATE` — the row lock serializes concurrent
+ * writes to one board without blocking writes to other boards.
+ *
+ * All mutation semantics live in logic.js so the transforms stay unit-testable
+ * without a live DB; this module only does row I/O + locking.
+ */
+
+import { randomUUID } from 'crypto';
+import { query, withTransaction } from '../../lib/db.js';
+import { ServerError } from '../../lib/errorHandler.js';
+import { mirrorTimestamp } from '../../lib/pgTimestamp.js';
+import {
+ buildBoardRecord,
+ applyBoardPatch,
+ addItem,
+ updateItem,
+ removeItem,
+} from './logic.js';
+
+// `data` JSONB is the whole record; name/created_at/updated_at mirror into
+// columns (kept in lockstep on every write) for the live-list sort. Reads
+// always return `data` verbatim so consumers see the exact stored shape.
+function rowToBoard(row) {
+ if (!row) return null;
+ return row.data;
+}
+
+async function persist(exec, board) {
+ const now = new Date().toISOString();
+ const createdAt = mirrorTimestamp(board.createdAt, now);
+ await exec(
+ `INSERT INTO mood_boards (id, name, data, created_at, updated_at)
+ VALUES ($1, $2, $3::jsonb, $4, $5)
+ ON CONFLICT (id) DO UPDATE SET
+ name = EXCLUDED.name,
+ data = EXCLUDED.data,
+ updated_at = EXCLUDED.updated_at`,
+ [
+ board.id,
+ board.name,
+ JSON.stringify(board),
+ createdAt,
+ mirrorTimestamp(board.updatedAt, createdAt),
+ ],
+ );
+ return board;
+}
+
+export async function listBoards() {
+ // updated_at DESC — most-recently-touched first (the board grid's default).
+ const result = await query(
+ `SELECT data FROM mood_boards ORDER BY updated_at DESC`,
+ );
+ return result.rows.map(rowToBoard);
+}
+
+export async function getBoard(id) {
+ const result = await query(`SELECT data FROM mood_boards WHERE id = $1`, [id]);
+ return rowToBoard(result.rows[0]);
+}
+
+export async function createBoard(input) {
+ const id = `mb-${randomUUID()}`;
+ const board = buildBoardRecord(input, { id });
+ await persist(query, board);
+ console.log(`🎨 Created mood board: ${id} (${input.name})`);
+ return board;
+}
+
+// Lock the row, apply `mutate(board)`, persist (unless skipPersist), and return
+// the mutator's continuation. Throws NOT_FOUND when the row is absent.
+async function withLockedBoard(id, mutate) {
+ return withTransaction(async (client) => {
+ const sel = await client.query(
+ `SELECT data FROM mood_boards WHERE id = $1 FOR UPDATE`,
+ [id],
+ );
+ const board = rowToBoard(sel.rows[0]);
+ if (!board) {
+ throw new ServerError('Mood board not found', { status: 404, code: 'NOT_FOUND' });
+ }
+ const { board: next, result, skipPersist } = mutate(board);
+ if (!skipPersist) await persist(client.query.bind(client), next);
+ return { board: next, result };
+ });
+}
+
+export async function updateBoard(id, patch) {
+ const { board } = await withLockedBoard(id, (b) => ({ board: applyBoardPatch(b, patch) }));
+ return board;
+}
+
+export async function deleteBoard(id) {
+ const result = await query(`DELETE FROM mood_boards WHERE id = $1`, [id]);
+ if (result.rowCount === 0) {
+ throw new ServerError('Mood board not found', { status: 404, code: 'NOT_FOUND' });
+ }
+ return { ok: true };
+}
+
+export async function addBoardItem(id, itemInput) {
+ const { result } = await withLockedBoard(id, (b) => {
+ const { board, item } = addItem(b, itemInput);
+ return { board, result: item };
+ });
+ return result;
+}
+
+export async function updateBoardItem(id, itemId, patch) {
+ const { result } = await withLockedBoard(id, (b) => {
+ const { board, item } = updateItem(b, itemId, patch);
+ return { board, result: item };
+ });
+ return result;
+}
+
+export async function removeBoardItem(id, itemId) {
+ // Unknown itemId → skip the write entirely (no-op, no updated_at bump). The
+ // route still 200s — removing an already-gone item is idempotent.
+ const { board } = await withLockedBoard(id, (b) => {
+ const { board: next, removed } = removeItem(b, itemId);
+ return { board: next, skipPersist: !removed };
+ });
+ return board;
+}
diff --git a/server/services/moodBoard/db.test.js b/server/services/moodBoard/db.test.js
new file mode 100644
index 0000000000..1e92214c6f
--- /dev/null
+++ b/server/services/moodBoard/db.test.js
@@ -0,0 +1,101 @@
+/**
+ * Postgres-backed round-trip for the mood board store (issue #911).
+ *
+ * Like projectsDB.test.js / mediaAssetIndex/db.test.js, this needs a live
+ * PostgreSQL with the schema applied. If no DB is reachable (CI, fresh
+ * checkout), it SKIPS cleanly rather than failing red. When a DB IS reachable it
+ * exercises create/list/get/update + the item add/update/remove ops, cleaning up
+ * its own rows after (only rows it created — no global table mutation).
+ */
+
+import { describe, it, expect, afterAll, beforeAll } from 'vitest';
+import { checkHealth, ensureSchema, query, close } from '../../lib/db.js';
+
+let dbReady = false;
+let skipReason = '';
+{
+ const health = await checkHealth().catch((e) => ({ connected: false, error: e?.message }));
+ if (!health.connected) {
+ skipReason = `Postgres not reachable (${health.error || 'no connection'})`;
+ } else {
+ await ensureSchema().catch(() => {});
+ const probe = await query(
+ `SELECT EXISTS(SELECT 1 FROM information_schema.tables WHERE table_name = 'mood_boards') AS ok`,
+ ).catch(() => ({ rows: [{ ok: false }] }));
+ if (probe.rows?.[0]?.ok) dbReady = true;
+ else skipReason = 'mood_boards table not present';
+ }
+}
+
+if (!dbReady) console.log(`⏭️ moodBoard/db.test.js skipped: ${skipReason}`);
+
+describe.skipIf(!dbReady)('mood board DB round-trip', () => {
+ let db;
+ const created = [];
+ beforeAll(async () => {
+ db = await import('./db.js');
+ });
+ afterAll(async () => {
+ for (const id of created) {
+ await query(`DELETE FROM mood_boards WHERE id = $1`, [id]).catch(() => {});
+ }
+ await close();
+ });
+
+ it('creates, lists, and gets a board (lossless data)', async () => {
+ const board = await db.createBoard({ name: 'Test board', description: 'd' });
+ created.push(board.id);
+ expect(board.id).toMatch(/^mb-/);
+ expect(board.items).toEqual([]);
+
+ const fetched = await db.getBoard(board.id);
+ expect(fetched.name).toBe('Test board');
+ expect(fetched.description).toBe('d');
+
+ const list = await db.listBoards();
+ expect(list.some((b) => b.id === board.id)).toBe(true);
+ });
+
+ it('updates board metadata', async () => {
+ const board = await db.createBoard({ name: 'Rename me' });
+ created.push(board.id);
+ const updated = await db.updateBoard(board.id, { name: 'Renamed' });
+ expect(updated.name).toBe('Renamed');
+ expect((await db.getBoard(board.id)).name).toBe('Renamed');
+ });
+
+ it('adds, updates, and removes items', async () => {
+ const board = await db.createBoard({ name: 'Items' });
+ created.push(board.id);
+
+ const item = await db.addBoardItem(board.id, { type: 'image', imageUrl: 'https://x/y.png' });
+ expect(item.id).toMatch(/^mbi-/);
+ expect((await db.getBoard(board.id)).items).toHaveLength(1);
+
+ const patched = await db.updateBoardItem(board.id, item.id, { caption: 'cap' });
+ expect(patched.caption).toBe('cap');
+
+ const afterRemove = await db.removeBoardItem(board.id, item.id);
+ expect(afterRemove.items).toHaveLength(0);
+ });
+
+ it('removeBoardItem is a no-op for an unknown item id', async () => {
+ const board = await db.createBoard({ name: 'Noop' });
+ created.push(board.id);
+ const result = await db.removeBoardItem(board.id, 'mbi-nope');
+ expect(result.items).toEqual([]);
+ });
+
+ it('throws NOT_FOUND for a missing board on get/update/delete', async () => {
+ expect(await db.getBoard('mb-missing')).toBeNull();
+ await expect(db.updateBoard('mb-missing', { name: 'x' })).rejects.toThrow(/not found/i);
+ await expect(db.deleteBoard('mb-missing')).rejects.toThrow(/not found/i);
+ });
+
+ it('deletes a board', async () => {
+ const board = await db.createBoard({ name: 'Delete me' });
+ const result = await db.deleteBoard(board.id);
+ expect(result.ok).toBe(true);
+ expect(await db.getBoard(board.id)).toBeNull();
+ });
+});
diff --git a/server/services/moodBoard/index.js b/server/services/moodBoard/index.js
new file mode 100644
index 0000000000..b326f23d97
--- /dev/null
+++ b/server/services/moodBoard/index.js
@@ -0,0 +1,19 @@
+/**
+ * Mood Board service — public entry (issue #911).
+ *
+ * Mood boards are db-primary, local-only records (no file backend, no
+ * federation in v1), so the public surface is just the Postgres store. The
+ * pure transforms live in logic.js (unit-tested without a DB); db.js does the
+ * row I/O + per-board row locking. Routes import from here.
+ */
+
+export {
+ listBoards,
+ getBoard,
+ createBoard,
+ updateBoard,
+ deleteBoard,
+ addBoardItem,
+ updateBoardItem,
+ removeBoardItem,
+} from './db.js';
diff --git a/server/services/moodBoard/logic.js b/server/services/moodBoard/logic.js
new file mode 100644
index 0000000000..5a61f800b1
--- /dev/null
+++ b/server/services/moodBoard/logic.js
@@ -0,0 +1,111 @@
+/**
+ * Mood Board — pure record transforms (issue #911).
+ *
+ * Storage-agnostic mutation semantics, mirroring the creativeDirector
+ * projectsLogic split: each function takes a plain board record and returns the
+ * next record (or throws a ServerError on a validation failure), leaving the
+ * load/persist to the db module. A board holds a small bounded `items[]` inline
+ * — image refs (media-key or external URL) or text notes — that feed the Create
+ * suite. No file backend exists (mood boards are db-primary, local-only), so
+ * this module has a single consumer (db.js); it stays a separate pure module so
+ * the transforms are unit-testable without a live database.
+ */
+
+import { randomUUID } from 'crypto';
+import { ServerError } from '../../lib/errorHandler.js';
+
+// Bound the inline items[] so a single board row's JSONB can't grow without
+// limit (a board is loaded/serialized whole on every read/write). Far above any
+// realistic hand-curated board. Enforced in addItem (the add route surfaces the
+// BOARD_FULL error); the item schema validates a single item, not the count.
+export const MAX_ITEMS_PER_BOARD = 500;
+
+function nowIso() {
+ return new Date().toISOString();
+}
+
+// Build a fresh board record from a validated create input. `id`/`now` are
+// injected by the caller (db.js) so this stays pure and testable.
+export function buildBoardRecord(input, { id, now = nowIso() } = {}) {
+ return {
+ id,
+ name: input.name,
+ description: input.description ?? '',
+ items: [],
+ createdAt: now,
+ updatedAt: now,
+ };
+}
+
+// Apply a PATCH to board-level fields (name/description). Absent keys preserve
+// the original; a present empty string clears (description). `items` is managed
+// only through the dedicated item ops below, never a bulk board PATCH.
+export function applyBoardPatch(board, patch) {
+ const next = { ...board };
+ if (patch.name !== undefined) next.name = patch.name;
+ if (patch.description !== undefined) next.description = patch.description;
+ next.updatedAt = nowIso();
+ return next;
+}
+
+// Normalize a validated item input into the stored item shape. An image item
+// carries a `mediaKey` (an indexed `<kind>:<ref>` asset) OR an `imageUrl`
+// (external/pinned), never required to have both; a text item carries `text`.
+// `caption`/`source` are optional on both. The route schema guarantees the
+// type-appropriate field is present, so this only fills the shared shape.
+function normalizeItem(input, { id, now = nowIso() } = {}) {
+ return {
+ id,
+ type: input.type,
+ mediaKey: input.type === 'image' ? (input.mediaKey ?? null) : null,
+ imageUrl: input.type === 'image' ? (input.imageUrl ?? null) : null,
+ text: input.type === 'text' ? input.text : null,
+ caption: input.caption ?? null,
+ source: input.source ?? null,
+ createdAt: now,
+ };
+}
+
+export function addItem(board, itemInput) {
+ const items = Array.isArray(board.items) ? board.items : [];
+ if (items.length >= MAX_ITEMS_PER_BOARD) {
+ throw new ServerError(`Board is full (max ${MAX_ITEMS_PER_BOARD} items)`, {
+ status: 400,
+ code: 'BOARD_FULL',
+ });
+ }
+ const item = normalizeItem(itemInput, { id: `mbi-${randomUUID()}` });
+ const next = { ...board, items: [...items, item], updatedAt: nowIso() };
+ return { board: next, item };
+}
+
+// PATCH a single item's editable fields (caption/source/text/imageUrl/mediaKey).
+// Absent keys preserve; throws NOT_FOUND when the item id isn't on the board.
+export function updateItem(board, itemId, patch) {
+ const items = Array.isArray(board.items) ? board.items : [];
+ const idx = items.findIndex((it) => it && it.id === itemId);
+ if (idx === -1) {
+ throw new ServerError('Item not found', { status: 404, code: 'NOT_FOUND' });
+ }
+ const current = items[idx];
+ const updated = { ...current };
+ for (const key of ['caption', 'source', 'text', 'imageUrl', 'mediaKey']) {
+ if (patch[key] !== undefined) updated[key] = patch[key];
+ }
+ const nextItems = [...items];
+ nextItems[idx] = updated;
+ const next = { ...board, items: nextItems, updatedAt: nowIso() };
+ return { board: next, item: updated };
+}
+
+// Remove an item by id. Returns `removed: false` (no write) when the id is
+// absent so the db layer can skip a wasted row rewrite.
+export function removeItem(board, itemId) {
+ const items = Array.isArray(board.items) ? board.items : [];
+ const nextItems = items.filter((it) => !(it && it.id === itemId));
+ if (nextItems.length === items.length) {
+ return { board, removed: false };
+ }
+ const next = { ...board, items: nextItems, updatedAt: nowIso() };
+ return { board: next, removed: true };
+}
diff --git a/server/services/moodBoard/logic.test.js b/server/services/moodBoard/logic.test.js
new file mode 100644
index 0000000000..0eccf0b015
--- /dev/null
+++ b/server/services/moodBoard/logic.test.js
@@ -0,0 +1,112 @@
+/**
+ * Pure record-transform tests for the mood board logic (issue #911). No I/O —
+ * these lock the create/patch/item semantics the db store depends on, so the
+ * two never drift without a live database.
+ */
+
+import { describe, it, expect } from 'vitest';
+import {
+ buildBoardRecord,
+ applyBoardPatch,
+ addItem,
+ updateItem,
+ removeItem,
+ MAX_ITEMS_PER_BOARD,
+} from './logic.js';
+
+describe('buildBoardRecord', () => {
+ it('builds a board with empty items and mirrored timestamps', () => {
+ const board = buildBoardRecord({ name: 'Refs' }, { id: 'mb-1', now: 't0' });
+ expect(board).toEqual({
+ id: 'mb-1',
+ name: 'Refs',
+ description: '',
+ items: [],
+ createdAt: 't0',
+ updatedAt: 't0',
+ });
+ });
+ it('keeps a provided description', () => {
+ expect(buildBoardRecord({ name: 'Refs', description: 'd' }, { id: 'mb-1', now: 't0' }).description).toBe('d');
+ });
+});
+
+describe('applyBoardPatch', () => {
+ const base = buildBoardRecord({ name: 'A', description: 'old' }, { id: 'mb-1', now: 't0' });
+ it('updates only present fields and bumps updatedAt', () => {
+ const next = applyBoardPatch(base, { name: 'B' });
+ expect(next.name).toBe('B');
+ expect(next.description).toBe('old');
+ expect(next.updatedAt).not.toBe('t0');
+ });
+ it('treats an empty-string description as a clear', () => {
+ expect(applyBoardPatch(base, { description: '' }).description).toBe('');
+ });
+ it('preserves description when the key is absent', () => {
+ expect(applyBoardPatch(base, { name: 'B' }).description).toBe('old');
+ });
+});
+
+describe('addItem', () => {
+ const base = buildBoardRecord({ name: 'A' }, { id: 'mb-1', now: 't0' });
+ it('normalizes an image item with imageUrl', () => {
+ const { board, item } = addItem(base, { type: 'image', imageUrl: 'https://x/y.png', caption: 'c' });
+ expect(item.type).toBe('image');
+ expect(item.imageUrl).toBe('https://x/y.png');
+ expect(item.text).toBeNull();
+ expect(item.caption).toBe('c');
+ expect(item.id).toMatch(/^mbi-/);
+ expect(board.items).toHaveLength(1);
+ });
+ it('normalizes an image item with mediaKey', () => {
+ const { item } = addItem(base, { type: 'image', mediaKey: 'image:a.png' });
+ expect(item.mediaKey).toBe('image:a.png');
+ expect(item.imageUrl).toBeNull();
+ });
+ it('normalizes a text item and nulls image fields', () => {
+ const { item } = addItem(base, { type: 'text', text: 'note' });
+ expect(item.text).toBe('note');
+ expect(item.mediaKey).toBeNull();
+ expect(item.imageUrl).toBeNull();
+ });
+ it('throws BOARD_FULL at the item cap', () => {
+ const full = { ...base, items: Array.from({ length: MAX_ITEMS_PER_BOARD }, (_, i) => ({ id: `i${i}` })) };
+ expect(() => addItem(full, { type: 'text', text: 'x' })).toThrow(/full/i);
+ });
+});
+
+describe('updateItem', () => {
+ const withItem = (() => {
+ const { board } = addItem(buildBoardRecord({ name: 'A' }, { id: 'mb-1', now: 't0' }), { type: 'text', text: 'orig' });
+ return board;
+ })();
+ const itemId = withItem.items[0].id;
+
+ it('patches present fields only', () => {
+ const { item } = updateItem(withItem, itemId, { caption: 'new' });
+ expect(item.caption).toBe('new');
+ expect(item.text).toBe('orig');
+ });
+ it('throws NOT_FOUND for an unknown item id', () => {
+ expect(() => updateItem(withItem, 'nope', { caption: 'x' })).toThrow(/not found/i);
+ });
+});
+
+describe('removeItem', () => {
+ const withItem = (() => {
+ const { board } = addItem(buildBoardRecord({ name: 'A' }, { id: 'mb-1', now: 't0' }), { type: 'text', text: 'orig' });
+ return board;
+ })();
+ const itemId = withItem.items[0].id;
+
+ it('removes a present item', () => {
+ const { board, removed } = removeItem(withItem, itemId);
+ expect(removed).toBe(true);
+ expect(board.items).toHaveLength(0);
+ });
+ it('returns removed:false (no write) for an absent id', () => {
+ const { board, removed } = removeItem(withItem, 'nope');
+ expect(removed).toBe(false);
+ expect(board).toBe(withItem);
+ });
+});