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([issue-4188]): persist a universe's linked mood board on the record

[._.]/ Adam Eivy248bca7341b4
diff --git a/.changelog/next/added-issue-4188.md b/.changelog/next/added-issue-4188.md
new file mode 100644
index 0000000000..e992e20da3
--- /dev/null
+++ b/.changelog/next/added-issue-4188.md
@@ -0,0 +1 @@
+- Universes can now link a mood board directly on the record: pick or create a board from the Universe Bible tab and the link survives reload, stays per-universe, and syncs to your other machines (previously the reference strip only remembered one board per browser).
diff --git a/client/src/components/moodBoard/MoodBoardReferenceStrip.jsx b/client/src/components/moodBoard/MoodBoardReferenceStrip.jsx
index 83632bfccb..0a4d298a50 100644
--- a/client/src/components/moodBoard/MoodBoardReferenceStrip.jsx
+++ b/client/src/components/moodBoard/MoodBoardReferenceStrip.jsx
@@ -14,21 +14,39 @@
* 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.
+ *
+ * Controlled mode (#4188): pass `value` (a board id, or '' for none) +
+ * `onChange` and the selection is owned by the caller instead of localStorage —
+ * the Universe Builder persists the pick on the universe record (`moodBoardId`)
+ * so it survives reload, is per-universe, and syncs to peers. Controlled mode
+ * never falls back to the first board (an unset link stays visibly unset) and
+ * offers a "New board" button when `newBoardName` is provided, creating a board
+ * named for the caller's record and selecting it in one step.
*/
import { useCallback, useEffect, useMemo, useState } from 'react';
-import { LayoutGrid, ChevronDown, ChevronRight, ExternalLink, ImageIcon } from 'lucide-react';
-import { listMoodBoards, getMoodBoard } from '../../services/api';
+import { LayoutGrid, ChevronDown, ChevronRight, ExternalLink, ImageIcon, Plus, Loader2 } from 'lucide-react';
+import toast from '../ui/Toast';
+import { listMoodBoards, getMoodBoard, createMoodBoard } from '../../services/api';
import { moodBoardItemSrc } from '../../lib/moodBoardItemSrc';
import { safeReadStorage, safeWriteStorage } from '../../lib/safeStorage';
const MAX_THUMBS = 12;
-export default function MoodBoardReferenceStrip({ storageKey = 'create', className = '' }) {
+export default function MoodBoardReferenceStrip({
+ storageKey = 'create',
+ className = '',
+ value = undefined,
+ onChange = null,
+ newBoardName = '',
+}) {
+ const controlled = value !== undefined;
const lsKey = `portos.moodBoardRef.${storageKey}`;
const [expanded, setExpanded] = useState(false);
const [boards, setBoards] = useState(null); // null = not loaded, [] = loaded-empty
- const [selectedId, setSelectedId] = useState(() => safeReadStorage(lsKey) || '');
+ const [localId, setLocalId] = useState(() => (controlled ? '' : safeReadStorage(lsKey) || ''));
+ const selectedId = controlled ? (value || '') : localId;
+ const [creating, setCreating] = useState(false);
const [detail, setDetail] = useState(null); // full board (with items) for selectedId
const [loadingDetail, setLoadingDetail] = useState(false);
@@ -43,14 +61,20 @@ export default function MoodBoardReferenceStrip({ storageKey = 'create', classNa
return () => { cancelled = true; };
}, [expanded, boards]);
- // The board actually shown: the user's pick when it's still in the list, else
- // the first board. Derived (not state) so display drives off it immediately —
- // no render tick where the <select> value matches no option (which would log
- // a controlled-select warning and flash the empty state before an effect
- // catches up). The remembered id is persisted only on an explicit pick.
- const effectiveId = (Array.isArray(boards) && boards.length > 0)
- ? ((selectedId && boards.some((b) => b.id === selectedId)) ? selectedId : boards[0].id)
- : '';
+ // The board actually shown. Uncontrolled: the user's pick when it's still in
+ // the list, else the first board. Derived (not state) so display drives off
+ // it immediately — no render tick where the <select> value matches no option
+ // (which would log a controlled-select warning and flash the empty state
+ // before an effect catches up). The remembered id is persisted only on an
+ // explicit pick. Controlled: the caller's value is the truth — a missing or
+ // deleted board shows as unset rather than silently falling back to another
+ // board (the persisted link must never drift from what's displayed).
+ const inList = (id) => Array.isArray(boards) && boards.some((b) => b.id === id);
+ const effectiveId = controlled
+ ? ((selectedId && inList(selectedId)) ? selectedId : '')
+ : ((Array.isArray(boards) && boards.length > 0)
+ ? (inList(selectedId) ? selectedId : boards[0].id)
+ : '');
// Fetch the shown board's full record (the list payload already carries
// items, but getMoodBoard guarantees the freshest items).
@@ -69,9 +93,31 @@ export default function MoodBoardReferenceStrip({ storageKey = 'create', classNa
}, [expanded, effectiveId, boards]);
const handleSelect = useCallback((id) => {
- setSelectedId(id);
+ if (controlled) {
+ onChange?.(id);
+ return;
+ }
+ setLocalId(id);
if (id) safeWriteStorage(lsKey, id);
- }, [lsKey]);
+ }, [controlled, onChange, lsKey]);
+
+ // Create-and-link (controlled mode with a suggested name): one click makes a
+ // board named for the caller's record and selects it.
+ const handleCreate = useCallback(async () => {
+ if (creating) return;
+ setCreating(true);
+ try {
+ const created = await createMoodBoard({ name: newBoardName || 'Untitled board' }, { silent: true });
+ if (created?.id) {
+ setBoards((prev) => (Array.isArray(prev) ? [created, ...prev] : [created]));
+ onChange?.(created.id);
+ }
+ } catch {
+ toast.error('Could not create mood board');
+ } finally {
+ setCreating(false);
+ }
+ }, [creating, newBoardName, onChange]);
const thumbs = useMemo(() => {
const items = Array.isArray(detail?.items) ? detail.items : [];
@@ -101,13 +147,26 @@ export default function MoodBoardReferenceStrip({ storageKey = 'create', classNa
{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 flex-wrap">
+ <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>
+ {controlled && newBoardName && (
+ <button
+ type="button"
+ onClick={handleCreate}
+ disabled={creating}
+ className="flex items-center gap-1 px-2 py-1 text-[11px] text-port-accent border border-port-accent/40 rounded hover:bg-port-accent/15 disabled:opacity-50"
+ >
+ {creating ? <Loader2 className="w-3 h-3 animate-spin" aria-hidden="true" /> : <Plus className="w-3 h-3" aria-hidden="true" />}
+ New board “{newBoardName}”
+ </button>
+ )}
+ </div>
) : (
<>
<div className="flex items-center gap-2">
@@ -118,10 +177,23 @@ export default function MoodBoardReferenceStrip({ storageKey = 'create', classNa
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"
>
+ {controlled && <option value="">— no board linked —</option>}
{boards.map((b) => (
<option key={b.id} value={b.id}>{b.name}</option>
))}
</select>
+ {controlled && newBoardName && (
+ <button
+ type="button"
+ onClick={handleCreate}
+ disabled={creating}
+ title={`Create a board named “${newBoardName}” and link it`}
+ className="shrink-0 flex items-center gap-1 px-2 py-1 text-[11px] text-port-accent border border-port-accent/40 rounded hover:bg-port-accent/15 disabled:opacity-50"
+ >
+ {creating ? <Loader2 className="w-3 h-3 animate-spin" aria-hidden="true" /> : <Plus className="w-3 h-3" aria-hidden="true" />}
+ New
+ </button>
+ )}
{effectiveId && (
<a
href={`/mood-boards/${encodeURIComponent(effectiveId)}`}
@@ -138,7 +210,9 @@ export default function MoodBoardReferenceStrip({ storageKey = 'create', classNa
{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.'}
+ {!effectiveId
+ ? 'No board linked — pick one above to surface its references here.'
+ : 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">
diff --git a/client/src/components/moodBoard/MoodBoardReferenceStrip.test.jsx b/client/src/components/moodBoard/MoodBoardReferenceStrip.test.jsx
new file mode 100644
index 0000000000..61b36b1ab1
--- /dev/null
+++ b/client/src/components/moodBoard/MoodBoardReferenceStrip.test.jsx
@@ -0,0 +1,98 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { render, screen, fireEvent, waitFor, act } from '@testing-library/react';
+import MoodBoardReferenceStrip from './MoodBoardReferenceStrip';
+import * as api from '../../services/api';
+
+vi.mock('../../services/api', () => ({
+ listMoodBoards: vi.fn(),
+ getMoodBoard: vi.fn(),
+ createMoodBoard: vi.fn(),
+}));
+
+const BOARDS = [
+ { id: 'mb-1', name: 'Board One', items: [] },
+ { id: 'mb-2', name: 'Board Two', items: [] },
+];
+
+const expand = () => fireEvent.click(screen.getByRole('button', { name: /mood board reference/i }));
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ localStorage.clear();
+ api.listMoodBoards.mockResolvedValue(BOARDS);
+ api.getMoodBoard.mockImplementation((id) => Promise.resolve(BOARDS.find((b) => b.id === id) || null));
+});
+
+describe('MoodBoardReferenceStrip — uncontrolled (localStorage) mode', () => {
+ it('falls back to the first board when nothing is remembered', async () => {
+ render(<MoodBoardReferenceStrip storageKey="test" />);
+ expand();
+ const select = await screen.findByLabelText('Board');
+ expect(select.value).toBe('mb-1');
+ // No "none" placeholder in uncontrolled mode.
+ expect(screen.queryByRole('option', { name: /no board linked/i })).toBeNull();
+ });
+
+ it('persists an explicit pick to localStorage', async () => {
+ render(<MoodBoardReferenceStrip storageKey="test" />);
+ expand();
+ const select = await screen.findByLabelText('Board');
+ fireEvent.change(select, { target: { value: 'mb-2' } });
+ expect(localStorage.getItem('portos.moodBoardRef.test')).toBe('mb-2');
+ await act(async () => {}); // settle the board-detail fetch the pick kicked off
+ });
+});
+
+describe('MoodBoardReferenceStrip — controlled (persisted link) mode', () => {
+ it('shows the caller value and never falls back to the first board', async () => {
+ render(<MoodBoardReferenceStrip storageKey="u" value="" onChange={() => {}} />);
+ expand();
+ const select = await screen.findByLabelText('Board');
+ expect(select.value).toBe('');
+ expect(screen.getByRole('option', { name: /no board linked/i })).toBeTruthy();
+ expect(screen.getByText(/No board linked — pick one above/)).toBeTruthy();
+ });
+
+ it('reports picks through onChange and does not touch localStorage', async () => {
+ const onChange = vi.fn();
+ render(<MoodBoardReferenceStrip storageKey="u" value="" onChange={onChange} />);
+ expand();
+ const select = await screen.findByLabelText('Board');
+ fireEvent.change(select, { target: { value: 'mb-2' } });
+ expect(onChange).toHaveBeenCalledWith('mb-2');
+ expect(localStorage.getItem('portos.moodBoardRef.u')).toBeNull();
+ });
+
+ it('treats a deleted/unknown linked board as unset instead of drifting to another board', async () => {
+ render(<MoodBoardReferenceStrip storageKey="u" value="mb-gone" onChange={() => {}} />);
+ expand();
+ const select = await screen.findByLabelText('Board');
+ expect(select.value).toBe('');
+ });
+
+ it('creates a board named for the record and links it via onChange', async () => {
+ const onChange = vi.fn();
+ api.createMoodBoard.mockResolvedValue({ id: 'mb-new', name: 'Example Universe', items: [] });
+ render(
+ <MoodBoardReferenceStrip storageKey="u" value="" onChange={onChange} newBoardName="Example Universe" />,
+ );
+ expand();
+ await screen.findByLabelText('Board');
+ fireEvent.click(screen.getByRole('button', { name: /^New$/ }));
+ await waitFor(() => expect(onChange).toHaveBeenCalledWith('mb-new'));
+ expect(api.createMoodBoard).toHaveBeenCalledWith({ name: 'Example Universe' }, { silent: true });
+ });
+
+ it('offers create-and-link even when no boards exist yet', async () => {
+ const onChange = vi.fn();
+ api.listMoodBoards.mockResolvedValue([]);
+ api.createMoodBoard.mockResolvedValue({ id: 'mb-first', name: 'Example Universe', items: [] });
+ render(
+ <MoodBoardReferenceStrip storageKey="u" value="" onChange={onChange} newBoardName="Example Universe" />,
+ );
+ expand();
+ const btn = await screen.findByRole('button', { name: /New board/ });
+ fireEvent.click(btn);
+ await waitFor(() => expect(onChange).toHaveBeenCalledWith('mb-first'));
+ });
+});
diff --git a/client/src/components/universeBuilder/UniverseBibleTab.jsx b/client/src/components/universeBuilder/UniverseBibleTab.jsx
index 00981a284c..ba62948516 100644
--- a/client/src/components/universeBuilder/UniverseBibleTab.jsx
+++ b/client/src/components/universeBuilder/UniverseBibleTab.jsx
@@ -166,7 +166,15 @@ export default function BibleTab({
</div>
</div>
- <MoodBoardReferenceStrip storageKey="universe-builder" />
+ {/* Persisted per-universe link (#4188): the pick lives on the record
+ (`moodBoardId`) and rides the normal draft Save — not localStorage —
+ so it survives reload, is per-universe, and syncs to peers. */}
+ <MoodBoardReferenceStrip
+ storageKey="universe-builder"
+ value={draft.moodBoardId || ''}
+ onChange={(id) => updateDraft({ moodBoardId: id || null })}
+ newBoardName={draft.name?.trim() || ''}
+ />
<div className="flex items-center gap-2 flex-wrap">
<button
diff --git a/client/src/hooks/useUniverseDraft.js b/client/src/hooks/useUniverseDraft.js
index fb348f10b9..b3afde840c 100644
--- a/client/src/hooks/useUniverseDraft.js
+++ b/client/src/hooks/useUniverseDraft.js
@@ -45,6 +45,7 @@ export const createEmptyUniverseDraft = () => ({
logline: '',
premise: '',
styleNotes: '',
+ moodBoardId: null,
categories: ensureDraftCategories(),
compositeSheets: [],
influences: { embrace: [], avoid: [] },
@@ -62,6 +63,7 @@ export const universeDraftSnapshot = (draft = {}) => JSON.stringify({
logline: draft.logline || '',
premise: draft.premise || '',
styleNotes: draft.styleNotes || '',
+ moodBoardId: draft.moodBoardId || null,
categories: draft.categories || {},
compositeSheets: draft.compositeSheets || [],
influences: ensureInfluences(draft.influences),
@@ -250,6 +252,7 @@ export default function useUniverseDraft({ selectedId, goToWorld }) {
logline: universe.logline || '',
premise: universe.premise || '',
styleNotes: universe.styleNotes || '',
+ moodBoardId: universe.moodBoardId || null,
influences: ensureInfluences(universe.influences),
styleReferences: universe.styleReferences || [],
locked: universe.locked || {},
@@ -275,6 +278,9 @@ export default function useUniverseDraft({ selectedId, goToWorld }) {
logline: draft.logline || '',
premise: draft.premise || '',
styleNotes: draft.styleNotes || '',
+ // Linked mood board (#4188) — null clears server-side; the field always
+ // ships so Save carries the full intended state like other scalars.
+ moodBoardId: draft.moodBoardId || null,
categories: draft.categories,
compositeSheets: draft.compositeSheets || [],
influences: ensureInfluences(draft.influences),
diff --git a/server/lib/schemaVersions.js b/server/lib/schemaVersions.js
index 9c8e474df5..c1b1420854 100644
--- a/server/lib/schemaVersions.js
+++ b/server/lib/schemaVersions.js
@@ -62,7 +62,12 @@ export const PORTOS_SCHEMA_VERSIONS = Object.freeze({
// `universes` gate above already protects the canonical (embedded) copy.
// v8 adds shared styleReferences[]. Older peers must not sanitize the field
// away and LWW-sync that loss back to a newer install.
- universes: 8,
+ // v9 = `moodBoardId` added (#4188) — the universe's linked mood board. The
+ // pointer rides the wire (mood boards federate, so the id resolves on peers);
+ // same rationale as v6/v7/v8: additive + gracefully degrading, but an older
+ // peer that re-sanitizes a universe through its moodBoardId-unaware
+ // `sanitizeTemplate` would silently strip the link and LWW the loss back.
+ universes: 9,
// v1 = post-split. Migrations 035/036 introduced the pipeline collection
// layout for issues and series.
// v2 = `stages.audio.audioMode` + `stages.audio.cues[]` added (whole-episode
diff --git a/server/lib/schemaVersions.test.js b/server/lib/schemaVersions.test.js
index b4f3a4d728..81f5cc9dcb 100644
--- a/server/lib/schemaVersions.test.js
+++ b/server/lib/schemaVersions.test.js
@@ -19,9 +19,10 @@ describe('PORTOS_SCHEMA_VERSIONS', () => {
// must ship alongside it. The test exists to make a layout bump a
// deliberate two-file edit.
// v6 = canon characters gained relationshipLinks[] (#1287); v7 = canon
- // objects gained attachments[] (#1288); v8 adds styleReferences[]. These
- // are additive + version-gated so an older peer cannot strip-then-LWW them.
- expect(PORTOS_SCHEMA_VERSIONS.universes).toBe(8);
+ // objects gained attachments[] (#1288); v8 adds styleReferences[]; v9 adds
+ // moodBoardId (#4188). These are additive + version-gated so an older peer
+ // cannot strip-then-LWW them.
+ expect(PORTOS_SCHEMA_VERSIONS.universes).toBe(9);
});
it('declares pipeline collection layout versions', () => {
@@ -45,14 +46,14 @@ describe('buildPortosMeta', () => {
it('returns { portosVersion, schemaVersions } with the live registry', async () => {
const meta = await buildPortosMeta();
expect(meta.portosVersion).toMatch(/^\d+\.\d+\.\d+/);
- expect(meta.schemaVersions.universes).toBe(8);
+ expect(meta.schemaVersions.universes).toBe(9);
expect(meta.schemaVersions.pipelineIssues).toBe(2);
expect(meta.schemaVersions.pipelineSeries).toBe(12);
});
it('overrides merge into schemaVersions', async () => {
const meta = await buildPortosMeta({ schemaVersions: { future: 1 } });
- expect(meta.schemaVersions.universes).toBe(8);
+ expect(meta.schemaVersions.universes).toBe(9);
expect(meta.schemaVersions.future).toBe(1);
});
});
@@ -200,7 +201,7 @@ describe('scopeVersionDiff', () => {
// Sender is ahead on mediaCollections only; a universe transfer scopes to
// ['universes'] and stays compatible even though the union diff is not.
const union = compareSchemaVersions(
- { universes: 8, pipelineSeries: 2, pipelineIssues: 2, mediaCollections: 2 },
+ { universes: 9, pipelineSeries: 2, pipelineIssues: 2, mediaCollections: 2 },
PORTOS_SCHEMA_VERSIONS,
);
expect(union.compatible).toBe(false); // mediaCollections 2 > 1
diff --git a/server/routes/universeBuilder/crud.js b/server/routes/universeBuilder/crud.js
index 6513c3ee79..2fcd38254e 100644
--- a/server/routes/universeBuilder/crud.js
+++ b/server/routes/universeBuilder/crud.js
@@ -38,6 +38,8 @@ const createSchema = z.object({
logline: z.string().trim().max(svc.LOGLINE_MAX).optional().default(''),
premise: z.string().trim().max(svc.PREMISE_MAX).optional().default(''),
styleNotes: z.string().trim().max(svc.STYLE_NOTES_MAX).optional().default(''),
+ // Linked mood board pointer (#4188) — null/'' clears, absent preserves.
+ moodBoardId: z.string().trim().max(svc.MOOD_BOARD_ID_MAX).nullable().optional(),
categories: categoriesSchema.optional(),
compositeSheets: z.array(compositeSheetSchema).max(svc.COMPOSITE_SHEETS_MAX).optional(),
influences: influencesSchema.optional(),
@@ -75,6 +77,8 @@ const patchSchema = z.object({
logline: z.string().trim().max(svc.LOGLINE_MAX).optional(),
premise: z.string().trim().max(svc.PREMISE_MAX).optional(),
styleNotes: z.string().trim().max(svc.STYLE_NOTES_MAX).optional(),
+ // Linked mood board pointer (#4188) — null/'' clears, absent preserves.
+ moodBoardId: z.string().trim().max(svc.MOOD_BOARD_ID_MAX).nullable().optional(),
categories: categoriesSchema.optional(),
compositeSheets: z.array(compositeSheetSchema).max(svc.COMPOSITE_SHEETS_MAX).optional(),
influences: influencesSchema.optional(),
diff --git a/server/services/dataSync.pipelineUniverse.test.js b/server/services/dataSync.pipelineUniverse.test.js
index dea163adb3..2789400820 100644
--- a/server/services/dataSync.pipelineUniverse.test.js
+++ b/server/services/dataSync.pipelineUniverse.test.js
@@ -163,19 +163,19 @@ describe('dataSync — universe category', () => {
const snap = await dataSync.getSnapshot('universe');
expect(snap.portosMeta).toBeDefined();
expect(typeof snap.portosMeta.portosVersion).toBe('string');
- expect(snap.portosMeta.schemaVersions.universes).toBe(8);
+ expect(snap.portosMeta.schemaVersions.universes).toBe(9);
});
it('applyRemote rejects when sender schemaVersions are AHEAD of local code', async () => {
writeUniverseState({ universes: [], runs: [] });
const result = await dataSync.applyRemote('universe', {
universes: [{ id: 'u-new', name: 'Foundry', updatedAt: '2026-05-17T10:00:00Z' }],
- }, { portosMeta: { portosVersion: '99.0.0', schemaVersions: { universes: 9 } } });
+ }, { portosMeta: { portosVersion: '99.0.0', schemaVersions: { universes: 10 } } });
expect(result.applied).toBe(false);
expect(result.count).toBe(0);
expect(result.blockedBySchema).toBeDefined();
expect(result.blockedBySchema.ahead).toEqual([
- { category: 'universes', senderV: 9, receiverV: 8 },
+ { category: 'universes', senderV: 10, receiverV: 9 },
]);
expect(result.blockedBySchema.senderPortosVersion).toBe('99.0.0');
// Nothing was written.
diff --git a/server/services/sharing/integration.test.js b/server/services/sharing/integration.test.js
index 3931f3aa95..981798c978 100644
--- a/server/services/sharing/integration.test.js
+++ b/server/services/sharing/integration.test.js
@@ -2312,7 +2312,7 @@ describe('sharing round-trip', () => {
const exp = await exporter.exportSeries(s.id, bucket.id);
const manifest = JSON.parse(readFileSync(join(tempBucket, 'manifests', exp.filename), 'utf-8'));
expect(manifest.portosSchemaVersions).toBeDefined();
- expect(manifest.portosSchemaVersions.universes).toBe(8);
+ expect(manifest.portosSchemaVersions.universes).toBe(9);
});
it('importer rejects a manifest when the sender is AHEAD on a category the manifest CARRIES', async () => {
diff --git a/server/services/sharing/peerSync.test.js b/server/services/sharing/peerSync.test.js
index 9e54fb64a6..6dcb8dcd54 100644
--- a/server/services/sharing/peerSync.test.js
+++ b/server/services/sharing/peerSync.test.js
@@ -3594,17 +3594,17 @@ describe('peerSync', () => {
describe('receiver — applyIncomingPush', () => {
it('rejects when sender schemaVersions.universes is AHEAD of local code', async () => {
- // Local code is at universes:8 (see server/lib/schemaVersions.js).
- // A push from a sender on universes:9 must NOT touch local state.
+ // Local code is at universes:9 (see server/lib/schemaVersions.js).
+ // A push from a sender on universes:10 must NOT touch local state.
const rejection = await applyIncomingPush({
kind: 'universe',
record: { id: 'u1', name: 'Foo' },
assetManifest: [],
sourceInstanceId: 'peer-a',
- portosMeta: { portosVersion: '99.0.0', schemaVersions: { universes: 9 } },
+ portosMeta: { portosVersion: '99.0.0', schemaVersions: { universes: 10 } },
}).catch((err) => err);
expect(rejection.code).toBe('PEER_SYNC_SCHEMA_VERSION_AHEAD');
- expect(rejection.details.ahead).toEqual([{ category: 'universes', senderV: 9, receiverV: 8 }]);
+ expect(rejection.details.ahead).toEqual([{ category: 'universes', senderV: 10, receiverV: 9 }]);
expect(rejection.details.senderPortosVersion).toBe('99.0.0');
// Receiver MUST stamp its OWN PortOS version so the sender can show
// the user "peer X is on PortOS vY" — without this, the sender would
@@ -3845,7 +3845,7 @@ describe('peerSync', () => {
expect(call).toBeDefined();
const body = JSON.parse(call[1].body);
expect(body.portosMeta).toBeDefined();
- expect(body.portosMeta.schemaVersions.universes).toBe(8);
+ expect(body.portosMeta.schemaVersions.universes).toBe(9);
expect(typeof body.portosMeta.portosVersion).toBe('string');
});
diff --git a/server/services/universeBuilder.test.js b/server/services/universeBuilder.test.js
index 6813b43424..dd1d7158a2 100644
--- a/server/services/universeBuilder.test.js
+++ b/server/services/universeBuilder.test.js
@@ -2647,6 +2647,40 @@ describe("universeBuilder service", () => {
});
});
+ describe("moodBoardId (linked mood board, #4188)", () => {
+ it("persists through create and is absent when never set", async () => {
+ const linked = await svc.createUniverse({ name: "Linked", moodBoardId: "mb-abc123" });
+ expect(linked.moodBoardId).toBe("mb-abc123");
+ const bare = await svc.createUniverse({ name: "Bare" });
+ expect("moodBoardId" in bare).toBe(false);
+ });
+
+ it("PATCH sets, preserves-on-absent, and clears on ''/null", async () => {
+ const w = await svc.createUniverse({ name: "W" });
+ const set = await svc.updateUniverse(w.id, { moodBoardId: "mb-1" });
+ expect(set.moodBoardId).toBe("mb-1");
+ // A patch that doesn't carry the key preserves the link.
+ const untouched = await svc.updateUniverse(w.id, { logline: "still linked" });
+ expect(untouched.moodBoardId).toBe("mb-1");
+ // Key-present with '' clears — the field drops back to absent.
+ const cleared = await svc.updateUniverse(w.id, { moodBoardId: "" });
+ expect("moodBoardId" in cleared).toBe(false);
+ const setAgain = await svc.updateUniverse(w.id, { moodBoardId: "mb-2" });
+ expect(setAgain.moodBoardId).toBe("mb-2");
+ const nulled = await svc.updateUniverse(w.id, { moodBoardId: null });
+ expect("moodBoardId" in nulled).toBe(false);
+ });
+
+ it("sanitizes a non-string value to absent on read", async () => {
+ await seedState({
+ universes: [{ id: "w-mb", name: "X", moodBoardId: 42, createdAt: "2024-01-01T00:00:00Z" }],
+ runs: [],
+ });
+ const list = await svc.listUniverses();
+ expect("moodBoardId" in list[0]).toBe(false);
+ });
+ });
+
describe("insertUniverseWithId", () => {
it("preserves the caller-supplied id", async () => {
const u = await svc.insertUniverseWithId({
diff --git a/server/services/universeBuilder/crud.js b/server/services/universeBuilder/crud.js
index 75ce5389a2..36b77798c7 100644
--- a/server/services/universeBuilder/crud.js
+++ b/server/services/universeBuilder/crud.js
@@ -236,6 +236,7 @@ export async function createUniverse(input = {}) {
logline: input.logline || '',
premise: input.premise || '',
styleNotes: input.styleNotes || '',
+ moodBoardId: input.moodBoardId || '',
categories: input.categories || {},
compositeSheets: input.compositeSheets || [],
influences: input.influences || {},
@@ -469,6 +470,9 @@ export async function updateUniverse(id, patchOrMutator = {}, options = {}) {
const PATCHABLE_SCALARS = [
'name', 'starterPrompt',
'logline', 'premise', 'styleNotes', 'compositeSheets',
+ // Linked mood board pointer (#4188). Key-present with ''/null clears
+ // (sanitizeTemplate drops the field); key-absent preserves.
+ 'moodBoardId',
// Uploaded, analyzed bible references — patched wholesale.
'styleReferences',
// Base style-probe render refs — patched wholesale (sanitizer re-caps).
diff --git a/server/services/universeBuilder/sanitize.js b/server/services/universeBuilder/sanitize.js
index ba4bf99850..5239204039 100644
--- a/server/services/universeBuilder/sanitize.js
+++ b/server/services/universeBuilder/sanitize.js
@@ -70,6 +70,8 @@ export const LOGLINE_MAX = 500;
// an abbreviation ledger.
export const PREMISE_MAX = 20000;
export const STYLE_NOTES_MAX = 4000;
+// Linked mood board pointer (`mb-<uuid>`, #4188) — generous cap for the id.
+export const MOOD_BOARD_ID_MAX = 80;
export const VARIATIONS_PER_CATEGORY_MAX = 50;
export const COMPOSITE_SHEETS_MAX = 50;
export const COMPOSITE_SHEET_KINDS = Object.freeze([
@@ -707,6 +709,7 @@ export const sanitizeTemplate = (raw) => {
const logline = trimTo(raw.logline, LOGLINE_MAX);
const premise = trimTo(raw.premise, PREMISE_MAX);
const styleNotes = trimTo(raw.styleNotes, STYLE_NOTES_MAX);
+ const moodBoardId = trimTo(raw.moodBoardId, MOOD_BOARD_ID_MAX);
const categories = sanitizeCategories(raw.categories || {});
const compositeSheets = sanitizeCompositeSheets(raw.compositeSheets || []);
const influences = resolveInfluences(raw);
@@ -764,6 +767,12 @@ export const sanitizeTemplate = (raw) => {
// discovered by federation/export asset collection so the image bytes
// travel with the universe.
styleReferences: sanitizeStyleReferences(raw.styleReferences),
+ // Linked mood board (#4188) — the board feeding this universe's style
+ // tools. A plain pointer (`mb-<uuid>`): boards are standalone federated
+ // records, so the id resolves on peers. Persisted only when set (so every
+ // existing universe keeps its on-disk shape) and kept ON the wire —
+ // `universes` v9 gates it against strip-then-LWW by older peers.
+ ...(moodBoardId ? { moodBoardId } : {}),
// Base "style probe" renders — images generated from the raw style preset
// (influences embrace/avoid + styleNotes) with NO subject, so the user can
// see the world's base visual emphasis. Additive + regenerable; sanitized