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): compose a board style and render its poster

[._.]/ Adam Eivy40591ab3a190
diff --git a/client/src/components/moodBoard/MoodBoardStylePanel.jsx b/client/src/components/moodBoard/MoodBoardStylePanel.jsx
new file mode 100644
index 0000000000..36ba6edf22
--- /dev/null
+++ b/client/src/components/moodBoard/MoodBoardStylePanel.jsx
@@ -0,0 +1,376 @@
+/**
+ * Board-level prompt-from-media, composite style, and canonical poster.
+ *
+ * Each pin already has its own prompt-from-media action. This panel is the
+ * board's: it runs that same analysis on gallery items that don't have one
+ * yet, then asks for one composite still-image prompt from the stored
+ * analyses (no second look at the pixels). The poster renders that prompt on
+ * any enabled image service and is the board's reference image — the same
+ * role a universe's base-style probe plays.
+ */
+import { useCallback, useRef, useState } from 'react';
+import { ScanEye, Sparkles, ImageIcon } from 'lucide-react';
+import ProviderModelSelector from '../ProviderModelSelector';
+import MediaJobThumb from '../pipeline/MediaJobThumb';
+import toast from '../ui/Toast';
+import useMounted from '../../hooks/useMounted';
+import useProviderModels from '../../hooks/useProviderModels';
+import useVisionModelIds from '../../hooks/useVisionModelIds';
+import useImageRenderSettings from '../../hooks/useImageRenderSettings';
+import useSingleImageRender from '../../hooks/useSingleImageRender';
+import { promptFromMedia, updateMoodBoard, updateMoodBoardItem, composeMoodBoardPrompt } from '../../services/api';
+import { isVisionCapableCliProvider, visionLocalModelFilter } from '../../utils/providers';
+import { formatCount } from '../../utils/formatters';
+import { moodBoardItemAnalysisSource, moodBoardPosterSrc } from '../../lib/moodBoardItemSrc';
+import {
+ boardAnalyzePlan,
+ boardPosterRenderCfg,
+ moodBoardAnalysisFromResult,
+ posterStyleKey,
+} from '../../lib/moodBoardAnalysis';
+import { modeLabel } from '../../lib/imageGenBackends';
+
+const visionProviderFilter = (p) => p.enabled && (p.type === 'api' || isVisionCapableCliProvider(p));
+
+export default function MoodBoardStylePanel({ board, onBoardChange }) {
+ const mountedRef = useMounted();
+ const items = Array.isArray(board?.items) ? board.items : [];
+ const plan = boardAnalyzePlan(items);
+ const posterSrc = moodBoardPosterSrc(board);
+ const savedPrompt = board?.style?.prompt || '';
+ const savedNegative = board?.style?.negativePrompt || '';
+
+ const styleIdentity = `${board?.style?.composedAt || ''}\0${savedPrompt}\0${savedNegative}`;
+ const [seenStyle, setSeenStyle] = useState(styleIdentity);
+ const [prompt, setPrompt] = useState(savedPrompt);
+ const [negative, setNegative] = useState(savedNegative);
+ if (seenStyle !== styleIdentity) {
+ setSeenStyle(styleIdentity);
+ setPrompt(savedPrompt);
+ setNegative(savedNegative);
+ }
+
+ const [busy, setBusy] = useState(false);
+ const [progress, setProgress] = useState('');
+ const [savingStyle, setSavingStyle] = useState(false);
+ const [rendererMode, setRendererMode] = useState('');
+ const capturedKeyRef = useRef(null);
+
+ const { idsByProvider: visionIds } = useVisionModelIds(true);
+ const modelFilter = useCallback(
+ (id, provider) => visionLocalModelFilter(id, provider, visionIds),
+ [visionIds],
+ );
+ const {
+ providers,
+ selectedProviderId,
+ selectedModel,
+ availableModels,
+ setSelectedProviderId,
+ setSelectedModel,
+ loading: providersLoading,
+ } = useProviderModels({
+ filter: visionProviderFilter,
+ silent: true,
+ withEffort: true,
+ modelFilter,
+ });
+
+ const { imageCfg, backends } = useImageRenderSettings({ includeExternal: true });
+ const resolvedMode = rendererMode || imageCfg?.mode || '';
+ const rendererOptions = backends.some((b) => b.id === resolvedMode) || !resolvedMode
+ ? backends
+ : [{ id: resolvedMode, label: modeLabel(resolvedMode) }, ...backends];
+
+ const styleDirty = prompt.trim() !== savedPrompt.trim()
+ || negative.trim() !== savedNegative.trim();
+ const canRender = Boolean(board?.id) && Boolean(savedPrompt.trim()) && !styleDirty && !busy;
+
+ const onPosterComplete = async (filename) => {
+ if (!board?.id || !filename) return;
+ const captured = capturedKeyRef.current;
+ capturedKeyRef.current = null;
+ if (captured == null || captured !== posterStyleKey(board.style)) {
+ toast.error('Board style changed while the poster rendered — generate it again');
+ return;
+ }
+ const updated = await updateMoodBoard(board.id, { posterImageRef: filename }, { silent: true }).catch(() => null);
+ if (!mountedRef.current) return;
+ if (!updated) {
+ toast.error('Poster rendered but could not be saved on the board');
+ return;
+ }
+ onBoardChange(updated);
+ toast.success('Board poster saved');
+ };
+
+ const { jobId, render: queueRender, handleComplete } = useSingleImageRender({
+ buildPrompt: () => {
+ const text = (board?.style?.prompt || '').trim();
+ if (!text) return null;
+ return { prompt: text, negativePrompt: (board?.style?.negativePrompt || '').trim() };
+ },
+ onComplete: onPosterComplete,
+ onError: (err) => toast.error(err?.message || 'Poster render failed'),
+ scopeId: board?.id,
+ });
+
+ const replaceItem = (item) => {
+ onBoardChange((prev) => (prev
+ ? { ...prev, items: (prev.items || []).map((it) => (it.id === item.id ? item : it)) }
+ : prev));
+ };
+
+ const compose = async () => {
+ const updated = await composeMoodBoardPrompt(board.id, {
+ providerId: selectedProviderId || undefined,
+ model: selectedModel || undefined,
+ }, { silent: true }).catch((err) => {
+ if (mountedRef.current) toast.error(err?.message || 'Could not compose a board style from the item analyses');
+ return null;
+ });
+ if (!mountedRef.current || !updated) return null;
+ if (!updated.style?.prompt) {
+ toast.error('Could not compose a board style from the item analyses');
+ return null;
+ }
+ onBoardChange(updated);
+ toast.success('Board style composed from item analyses');
+ return updated;
+ };
+
+ const analyzeBoard = async () => {
+ if (!board?.id || busy) return;
+ if (!selectedProviderId) {
+ toast.error('Select a vision-capable provider to analyze the board');
+ return;
+ }
+ setBusy(true);
+ let failures = 0;
+ const pending = plan.pending;
+ for (let i = 0; i < pending.length; i += 1) {
+ const item = pending[i];
+ const source = moodBoardItemAnalysisSource(item);
+ if (!source) continue;
+ setProgress(`Analyzing ${formatCount(i + 1)} of ${formatCount(pending.length)}`);
+ const data = await promptFromMedia({
+ sourceKind: source.kind === 'video' ? 'video' : 'image',
+ filename: source.filename,
+ targets: source.kind === 'video' ? ['image', 'video'] : ['image'],
+ providerId: selectedProviderId,
+ model: selectedModel || undefined,
+ }, { silent: true }).catch(() => null);
+ if (!mountedRef.current) return;
+ const analysis = moodBoardAnalysisFromResult(item, data);
+ if (!analysis) {
+ failures += 1;
+ continue;
+ }
+ const saved = await updateMoodBoardItem(board.id, item.id, { analysis }, { silent: true }).catch(() => null);
+ if (!mountedRef.current) return;
+ if (!saved) {
+ failures += 1;
+ continue;
+ }
+ replaceItem(saved);
+ }
+ setProgress('');
+ const analyzedNow = plan.analyzed + (pending.length - failures);
+ if (analyzedNow < 1) {
+ setBusy(false);
+ toast.error('No item could be analyzed, so the board style was not composed');
+ return;
+ }
+ if (failures > 0) {
+ toast.error(`${formatCount(failures)} item${failures === 1 ? '' : 's'} could not be analyzed`);
+ }
+ await compose();
+ if (mountedRef.current) setBusy(false);
+ };
+
+ const composeOnly = async () => {
+ if (!board?.id || busy) return;
+ setBusy(true);
+ await compose();
+ if (mountedRef.current) setBusy(false);
+ };
+
+ const saveStyle = async () => {
+ const nextPrompt = prompt.trim();
+ if (!nextPrompt) {
+ toast.error('The board style prompt can’t be empty');
+ return;
+ }
+ setSavingStyle(true);
+ const style = {
+ prompt: nextPrompt,
+ negativePrompt: negative.trim() || null,
+ rationale: board.style?.rationale || null,
+ analyzedItemCount: board.style?.analyzedItemCount || 0,
+ providerId: board.style?.providerId || null,
+ model: board.style?.model || null,
+ composedAt: board.style?.composedAt || new Date().toISOString(),
+ };
+ const updated = await updateMoodBoard(board.id, { style }, { silent: true }).catch(() => null);
+ if (!mountedRef.current) return;
+ setSavingStyle(false);
+ if (!updated) {
+ toast.error('Failed to save the board style');
+ return;
+ }
+ onBoardChange(updated);
+ toast.success('Board style saved');
+ };
+
+ const renderPoster = async () => {
+ if (styleDirty) {
+ toast.error('Save the board style before generating the poster');
+ return;
+ }
+ if (!savedPrompt.trim()) {
+ toast.error('Compose a board style before generating the poster');
+ return;
+ }
+ const key = posterStyleKey(board.style);
+ const queued = await queueRender(boardPosterRenderCfg(imageCfg, resolvedMode));
+ if (queued) capturedKeyRef.current = key;
+ };
+
+ const showAnalyze = plan.pending.length > 0;
+ const showCompose = plan.analyzed > 0;
+
+ return (
+ <section className="bg-port-card border border-port-border rounded-md p-4 mb-6">
+ <div className="flex items-center gap-2 mb-1">
+ <ScanEye className="w-4 h-4 text-port-accent" aria-hidden="true" />
+ <h2 className="text-sm font-medium text-white">Board style</h2>
+ </div>
+ <p className="text-[11px] text-gray-500 mb-3">
+ Prompt from media for each gallery item, then one composite style from those prompts. The poster is this board’s canonical reference image.
+ </p>
+ <div className="flex flex-col sm:flex-row gap-4">
+ <div className="w-full sm:w-56 shrink-0">
+ <div className="aspect-[3/2] w-full rounded-md overflow-hidden border border-port-border bg-port-bg">
+ {jobId ? (
+ <MediaJobThumb jobId={jobId} onFilename={handleComplete} size="fill" label="Board poster" />
+ ) : posterSrc ? (
+ <img src={posterSrc} alt="Board poster" className="w-full h-full object-cover" />
+ ) : (
+ <div className="w-full h-full flex flex-col items-center justify-center text-gray-600 gap-1">
+ <ImageIcon className="w-6 h-6" aria-hidden="true" />
+ <span className="text-[11px]">No poster yet</span>
+ </div>
+ )}
+ </div>
+ </div>
+ <div className="flex-1 min-w-0 space-y-3">
+ <ProviderModelSelector
+ providers={providers}
+ selectedProviderId={selectedProviderId}
+ selectedModel={selectedModel}
+ availableModels={availableModels}
+ onProviderChange={setSelectedProviderId}
+ onModelChange={setSelectedModel}
+ disabled={busy || providersLoading}
+ layout="stacked"
+ />
+ {providers.length === 0 && !providersLoading ? (
+ <p className="text-xs text-port-warning">No vision-capable provider is enabled. Add one under Settings → Providers to analyze items. Composing from analyses you already have still works.</p>
+ ) : null}
+ <div className="flex flex-wrap items-center gap-2">
+ {showAnalyze ? (
+ <button
+ type="button"
+ onClick={analyzeBoard}
+ disabled={busy || !selectedProviderId}
+ className="inline-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"
+ >
+ <ScanEye className="w-4 h-4" aria-hidden="true" />
+ {busy && progress ? progress : 'Analyze board'}
+ </button>
+ ) : null}
+ {showCompose ? (
+ <button
+ type="button"
+ onClick={composeOnly}
+ disabled={busy}
+ className="inline-flex items-center gap-1.5 px-3 py-1.5 text-sm rounded bg-port-bg border border-port-border text-gray-200 hover:text-white disabled:opacity-50 transition-colors"
+ >
+ Compose board style
+ </button>
+ ) : null}
+ {!showAnalyze && !showCompose ? (
+ <p className="text-xs text-gray-500">Pin a gallery image or video to analyze this board. External links can’t be read.</p>
+ ) : null}
+ </div>
+ {plan.skipped > 0 ? (
+ <p className="text-[11px] text-gray-500">
+ {formatCount(plan.skipped)} pin{plan.skipped === 1 ? '' : 's'} {plan.skipped === 1 ? 'is' : 'are'} an external link and can’t be analyzed.
+ </p>
+ ) : null}
+ <div>
+ <label htmlFor="board-style-prompt" className="block text-xs text-gray-400 mb-1">Style prompt</label>
+ <textarea
+ id="board-style-prompt"
+ value={prompt}
+ rows={4}
+ maxLength={8000}
+ onChange={(e) => setPrompt(e.target.value)}
+ placeholder="Compose a style from the item analyses, or write one."
+ 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>
+ <label htmlFor="board-style-negative" className="block text-xs text-gray-400 mb-1">Negative prompt</label>
+ <textarea
+ id="board-style-negative"
+ value={negative}
+ rows={2}
+ maxLength={8000}
+ onChange={(e) => setNegative(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>
+ {board?.style?.rationale ? (
+ <p className="text-xs text-gray-400">{board.style.rationale}</p>
+ ) : null}
+ <div className="flex flex-wrap items-end gap-2">
+ <div className="min-w-0">
+ <label htmlFor="board-poster-renderer" className="block text-xs text-gray-400 mb-1">Image renderer</label>
+ <select
+ id="board-poster-renderer"
+ value={resolvedMode}
+ onChange={(e) => setRendererMode(e.target.value)}
+ disabled={Boolean(jobId) || rendererOptions.length === 0}
+ className="bg-port-bg border border-port-border rounded px-2 py-1.5 text-white text-sm focus:border-port-accent outline-none max-w-full"
+ >
+ {rendererOptions.length === 0 ? <option value="">Loading renderers…</option> : null}
+ {rendererOptions.map((backend) => (
+ <option key={backend.id} value={backend.id}>{backend.label}</option>
+ ))}
+ </select>
+ </div>
+ <button
+ type="button"
+ onClick={saveStyle}
+ disabled={!styleDirty || savingStyle || busy}
+ className="px-3 py-1.5 text-sm rounded bg-port-bg border border-port-border text-gray-200 hover:text-white disabled:opacity-50 transition-colors"
+ >
+ {savingStyle ? 'Saving…' : 'Save style'}
+ </button>
+ <button
+ type="button"
+ onClick={renderPoster}
+ disabled={!canRender || Boolean(jobId)}
+ title={styleDirty ? 'Save the board style first' : (savedPrompt.trim() ? 'Render the poster on the selected image service' : 'Compose a board style first')}
+ className="inline-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"
+ >
+ <Sparkles className="w-4 h-4" aria-hidden="true" />
+ {posterSrc ? 'Regenerate poster' : 'Generate poster'}
+ </button>
+ </div>
+ </div>
+ </div>
+ </section>
+ );
+}
diff --git a/client/src/components/moodBoard/MoodBoardStylePanel.test.jsx b/client/src/components/moodBoard/MoodBoardStylePanel.test.jsx
new file mode 100644
index 0000000000..304ccf71bb
--- /dev/null
+++ b/client/src/components/moodBoard/MoodBoardStylePanel.test.jsx
@@ -0,0 +1,140 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { render, screen, waitFor } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import { IMAGE_GEN_MODE } from '../../lib/imageGenModes';
+import { BOARD_POSTER_SIZE } from '../../lib/moodBoardAnalysis';
+
+const {
+ mockRender, mockCompose, mockPrompt, mockUpdateItem, mockUpdateBoard,
+} = vi.hoisted(() => ({
+ mockRender: vi.fn(async () => 'job-9'),
+ mockCompose: vi.fn(),
+ mockPrompt: vi.fn(),
+ mockUpdateItem: vi.fn(),
+ mockUpdateBoard: vi.fn(),
+}));
+
+vi.mock('../../services/api', () => ({
+ promptFromMedia: (...args) => mockPrompt(...args),
+ composeMoodBoardPrompt: (...args) => mockCompose(...args),
+ updateMoodBoardItem: (...args) => mockUpdateItem(...args),
+ updateMoodBoard: (...args) => mockUpdateBoard(...args),
+}));
+
+vi.mock('../ui/Toast', () => ({
+ default: { success: vi.fn(), error: vi.fn(), warning: vi.fn() },
+}));
+
+vi.mock('../ProviderModelSelector', () => ({ default: () => <div>provider</div> }));
+vi.mock('../pipeline/MediaJobThumb', () => ({ default: () => <div>rendering</div> }));
+
+vi.mock('../../hooks/useVisionModelIds', () => ({ default: () => ({ idsByProvider: {} }) }));
+vi.mock('../../hooks/useProviderModels', () => ({
+ default: () => ({
+ providers: [{ id: 'vision-1', name: 'Vision', type: 'api', enabled: true }],
+ selectedProviderId: 'vision-1',
+ selectedModel: 'vlm',
+ availableModels: ['vlm'],
+ setSelectedProviderId: vi.fn(),
+ setSelectedModel: vi.fn(),
+ loading: false,
+ }),
+}));
+vi.mock('../../hooks/useImageRenderSettings', () => ({
+ default: () => ({
+ imageCfg: { mode: IMAGE_GEN_MODE.GROK, modelId: 'flux', inheritedBackend: true, width: 1024, height: 1536 },
+ backends: [{ id: IMAGE_GEN_MODE.GROK, label: 'Grok' }, { id: IMAGE_GEN_MODE.LOCAL, label: 'Local' }],
+ }),
+}));
+
+let lastRenderOpts = null;
+vi.mock('../../hooks/useSingleImageRender', () => ({
+ default: (opts) => {
+ lastRenderOpts = opts;
+ return { jobId: null, render: mockRender, handleComplete: vi.fn() };
+ },
+}));
+
+import MoodBoardStylePanel from './MoodBoardStylePanel';
+
+const analyzedBoard = {
+ id: 'mb-1',
+ items: [{ id: 'a', type: 'image', mediaKey: 'image:a.png', analysis: { prompt: 'ink wash' } }],
+ style: {
+ prompt: 'dusty ink wash',
+ negativePrompt: 'gloss',
+ rationale: 'tactile',
+ analyzedItemCount: 1,
+ composedAt: '2026-08-14T00:00:00.000Z',
+ },
+};
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ lastRenderOpts = null;
+ mockCompose.mockResolvedValue({
+ ...analyzedBoard,
+ style: { ...analyzedBoard.style, prompt: 'composed ink' },
+ });
+ mockPrompt.mockResolvedValue({ imagePrompt: 'a pin in ink', imageNegativePrompt: 'gloss', providerId: 'vision-1', model: 'vlm' });
+ mockUpdateItem.mockImplementation(async (_id, _itemId, patch) => ({
+ id: 'b', type: 'image', mediaKey: 'image:b.png', analysis: patch.analysis,
+ }));
+ mockUpdateBoard.mockImplementation(async (_id, patch) => ({ ...analyzedBoard, ...patch }));
+});
+
+describe('MoodBoardStylePanel', () => {
+ it('composes from saved analyses without running prompt-from-media again', async () => {
+ const onBoardChange = vi.fn();
+ render(<MoodBoardStylePanel board={analyzedBoard} onBoardChange={onBoardChange} />);
+ expect(screen.queryByRole('button', { name: 'Analyze board' })).toBeNull();
+ await userEvent.click(screen.getByRole('button', { name: 'Compose board style' }));
+ await waitFor(() => expect(mockCompose).toHaveBeenCalledWith('mb-1', { providerId: 'vision-1', model: 'vlm' }, { silent: true }));
+ expect(mockPrompt).not.toHaveBeenCalled();
+ expect(onBoardChange).toHaveBeenCalledWith(expect.objectContaining({
+ style: expect.objectContaining({ prompt: 'composed ink' }),
+ }));
+ });
+
+ it('analyzes unread gallery pins, then composes the board style', async () => {
+ const board = {
+ id: 'mb-1',
+ items: [{ id: 'b', type: 'image', mediaKey: 'image:b.png' }],
+ };
+ render(<MoodBoardStylePanel board={board} onBoardChange={vi.fn()} />);
+ expect(screen.queryByRole('button', { name: 'Compose board style' })).toBeNull();
+ await userEvent.click(screen.getByRole('button', { name: 'Analyze board' }));
+ await waitFor(() => expect(mockCompose).toHaveBeenCalled());
+ expect(mockPrompt).toHaveBeenCalledWith(expect.objectContaining({
+ sourceKind: 'image',
+ filename: 'b.png',
+ targets: ['image'],
+ providerId: 'vision-1',
+ }), { silent: true });
+ expect(mockUpdateItem).toHaveBeenCalledWith('mb-1', 'b', expect.objectContaining({
+ analysis: expect.objectContaining({ prompt: 'a pin in ink' }),
+ }), { silent: true });
+ });
+
+ it('renders the poster on the selected image service and pins the filename', async () => {
+ const onBoardChange = vi.fn();
+ render(<MoodBoardStylePanel board={analyzedBoard} onBoardChange={onBoardChange} />);
+ await userEvent.click(screen.getByRole('button', { name: 'Generate poster' }));
+ await waitFor(() => expect(mockRender).toHaveBeenCalledWith(expect.objectContaining({
+ mode: IMAGE_GEN_MODE.GROK,
+ inheritedBackend: false,
+ width: BOARD_POSTER_SIZE.width,
+ height: BOARD_POSTER_SIZE.height,
+ modelId: null,
+ })));
+ await lastRenderOpts.onComplete('poster.png');
+ expect(mockUpdateBoard).toHaveBeenCalledWith('mb-1', { posterImageRef: 'poster.png' }, { silent: true });
+ expect(onBoardChange).toHaveBeenCalled();
+ });
+
+ it('shows a saved poster', () => {
+ render(<MoodBoardStylePanel board={{ ...analyzedBoard, posterImageRef: 'poster.png' }} onBoardChange={vi.fn()} />);
+ expect(screen.getByAltText('Board poster').getAttribute('src')).toBe('/data/images/poster.png');
+ expect(screen.getByRole('button', { name: 'Regenerate poster' })).toBeEnabled();
+ });
+});
diff --git a/client/src/hooks/README.md b/client/src/hooks/README.md
index 47a4f62928..173542381e 100644
--- a/client/src/hooks/README.md
+++ b/client/src/hooks/README.md
@@ -79,7 +79,7 @@ grep -i "what you want to do" client/src/hooks/README.md
| `useImageGenQueue` | Work-scoped live queue of in-flight image renders. | Pages that show per-work image-gen queue state. |
| `useLocalImageRuntime` | The local image runtime's verdict for one model — `{ runtime, loading, refresh }` — from `GET /api/image-gen/status?mode=local&modelId=…`, the same `diagnoseLocalRuntime` the renderer refuses against. `runtime` carries `readiness`, `reason` and a one-button `remedy`. Pass `null` while the host is still resolving which model it renders on. | Any surface whose renders can be blocked by an unhealthy local runtime: pair it with `LocalRuntimeStatus` to show the verdict and its fix, and read `readiness` to stand the surface's own Render button down. |
| `useDeckRenderTarget` | What a deck's next card render runs on — `{ backends, size, summary, localRuntime, blocked }` — resolving the `RENDER_TARGET.DECK` pin ladder, the card trim, and the local runtime's verdict in one call. | Any deck surface that queues a render or names the options it will use (the render bar, the card grid's per-card re-render) — resolve it once on the page and pass it down rather than probing per consumer. |
-| `useImageRenderSettings` | Load settings and project shared record → target → install render preferences; returns `{ imageCfg, backends }`. `imageCfg.inheritedBackend` distinguishes inherited display/runtime preferences from explicit form overrides; local model admission stays server-side. | Single-image render slots; pass record and target, and retain the owning record tag on submission. |
+| `useImageRenderSettings` | Load settings and project shared record → target → install render preferences; returns `{ imageCfg, backends }`. `imageCfg.inheritedBackend` distinguishes inherited display/runtime preferences from explicit form overrides; local model admission stays server-side. Pass `includeExternal` to also list an enabled external image service. | Single-image render slots; pass record and target, and retain the owning record tag on submission. |
| `useUserTimezone` | Resolve the user's configured IANA timezone (`settings.timezone`) once, falling back to the browser zone then UTC; returns the tz string. | A date-scoped surface that must derive "today" the same way the server does (POST launcher/history day keys, #2681). |
| `useSingleImageRender` | Queue-one-render / wait-for-completion jobId lifecycle: builds opts from `imageCfg`, calls `buildPrompt`, POSTs `generateImage`, tracks the `jobId` head, and runs a once-per-`(key, filename)` completion guard before `onComplete`. | Single-image render slots driven by `EntryThumbSlot`/`MediaJobThumb` (style probe, characters step). Completion SSE stays in the thumb. |
diff --git a/client/src/hooks/useImageRenderSettings.js b/client/src/hooks/useImageRenderSettings.js
index b5e24cd4da..86cbdd730b 100644
--- a/client/src/hooks/useImageRenderSettings.js
+++ b/client/src/hooks/useImageRenderSettings.js
@@ -19,11 +19,15 @@ import { deriveAvailableBackends } from '../lib/imageGenBackends';
* @param {object} [opts]
* @param {object|null} [opts.record] - Record whose `imageMode`/`imageModelId` pin wins.
* @param {string|null} [opts.target] - RENDER_TARGET id whose `renderDefaults` pin is next.
+ * @param {boolean} [opts.includeExternal] - Also list an enabled external SDAPI
+ * backend. Default false; the mood-board poster opts in so the user can pick
+ * any configured image service.
* @returns {{ imageCfg: object, backends: Array<{id:string,label:string}> }} —
- * `backends` is the enabled, non-external list the pin ladder was gated on
- * (empty until settings land), for callers that also render a backend picker.
+ * `backends` is the enabled list the pin ladder was gated on (external omitted
+ * unless `includeExternal`; empty until settings land), for callers that also
+ * render a backend picker.
*/
-export default function useImageRenderSettings({ record = null, target = null } = {}) {
+export default function useImageRenderSettings({ record = null, target = null, includeExternal = false } = {}) {
// `null` = not fetched yet (or the fetch failed), which is NOT the same as a
// settings blob with no backends enabled. Holding the raw blob (rather than a
// derived cfg seeded with the defaults and an `[]` backend list) keeps the two
@@ -38,11 +42,11 @@ export default function useImageRenderSettings({ record = null, target = null }
// a freshly-fetched draft object on every save, and re-deriving an identical
// cfg would churn the render opts for every consumer downstream.
return useMemo(() => {
- const backends = settings ? deriveAvailableBackends(settings, { excludeExternal: true }) : [];
+ const backends = settings ? deriveAvailableBackends(settings, { excludeExternal: !includeExternal }) : [];
return {
backends,
// Display projection only; tagged submissions retain server inheritance.
imageCfg: resolveRenderCfg(settings, { record, target }),
};
- }, [settings, target, record?.imageMode, record?.imageModelId]);
+ }, [settings, target, includeExternal, record?.imageMode, record?.imageModelId]);
}
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index beba2715da..a969d12560 100644
--- a/client/src/lib/README.md
+++ b/client/src/lib/README.md
@@ -183,7 +183,8 @@ grep -i "what you want to do" client/src/lib/README.md
| `ports.js` | `PORTS` + `DEFAULT_PEER_PORT`, re-exported from the pure leaf `server/lib/ports.js` (which `ports.test.js` pins against `ecosystem.config.cjs`, the source of truth — see docs/PORTS.md). Use these instead of re-hardcoding a port literal in a form default, a copy-paste help string, or a cross-machine URL. |
| `providerManagement.js` | What every AI Providers surface shares about a service instance (#7567, #8014): `catalogSummary` reads its catalog state honestly (keeps `unknown` / `known`-and-empty / `failed`-with-retained-models distinct), `serviceReadinessCopy` / `SERVICE_READINESS_COPY` give one phrasing per `readiness` value (badge tone + label, and the predicate the compose popover and compatibility matrix append to the service's name), `draftFromTransports` / `transportsFromDraft` round-trip its `transports` map through a text form, dropping a blank endpoint rather than sending an empty one, and `classifyServiceCategory` / `SERVICE_CATEGORIES` / `serviceMatchesQuery` / `sortServices` / `servicePresetAction` group the Services view by what the definition offers (not the instance's selected plan) and decide whether a card may start a derived preset. |
| `morsePractice.js` | Pure deterministic adaptive Morse sampler — `selectMorsePrompt` combines bounded weak-character/confusion weighting with a non-zero exploration floor and only emits material valid for the active Koch pool; `canAdvanceMorseLevel` guards level advancement on sample count, accuracy, and effective speed. |
-| `moodBoardItemSrc.js` | `moodBoardItemSrc(item)` resolves a mood-board item to a display image/poster src (`imageUrl` → served `image:<file>` bytes → derived video thumbnail → null); `moodBoardItemVideoSrc(item)` resolves a `type:'video'` item's playback URL; `moodBoardItemAnalysisSource(item)` resolves an item to a prompt-from-media source (null when not a local gallery asset). Shared by MoodBoardDetail + MoodBoardReferenceStrip. |
+| `moodBoardAnalysis.js` | `moodBoardAnalysisFromResult(item, result)` picks the type-matched prompt-from-media payload stored on a pin; `boardAnalyzePlan(items)` splits pins into already-analyzed, still-readable, and skipped; `boardPosterRenderCfg(imageCfg, mode)` builds the explicit landscape poster render (any chosen image service) and `posterStyleKey(style)` detects a style change while that render is in flight. |
+| `moodBoardItemSrc.js` | `moodBoardItemSrc(item)` resolves a mood-board item to a display image/poster src (`imageUrl` → served `image:<file>` bytes → derived video thumbnail → null); `moodBoardPosterSrc(board)` resolves the board's canonical poster filename to `/data/images/…`; `moodBoardItemVideoSrc(item)` resolves a `type:'video'` item's playback URL; `moodBoardItemAnalysisSource(item)` resolves an item to a prompt-from-media source (null when not a local gallery asset). Shared by MoodBoardDetail + MoodBoardReferenceStrip. |
| `rapidReaderPosition.js` | Cursor-to-word mapping plus privacy-preserving Rapid Reader progress persistence keyed by a text fingerprint; stores position/settings without storing pasted source text. |
| `registerServiceWorker.js` | `registerServiceWorker()` / `unregisterServiceWorkers()` — wires up the offline app-shell + low-bandwidth asset-caching service worker (`public/sw.js`). Registers only in a production secure context (HTTPS or localhost); no-ops over plain-HTTP Tailnet and tears down any stale SW in dev. Called once from `main.jsx`. |
| `safeStorage.js` | `safeReadStorage` / `safeReadJsonStorage` / `safeWriteStorage` / `safeWriteJsonStorage` / `safeRemoveStorage` — guarded `localStorage` access that swallows throws (Safari private mode, blocked storage), with fallback-safe JSON parsing for structured entries. Use instead of touching `localStorage` inline so a storage failure never crashes init or a write path (#2387). Consumed by `useTheme`, `useNavWorkingSet`, and the command palette. Also `safeReadJsonSession` / `safeWriteJsonSession` / `safeRemoveSession` — the same guarantees over `sessionStorage`, for tab-scoped crash-recovery buffers of edits the server has not accepted yet (QuotaBurn's unsaved-patch stash). |
diff --git a/client/src/lib/index.js b/client/src/lib/index.js
index a188a8ddcc..6ead875113 100644
--- a/client/src/lib/index.js
+++ b/client/src/lib/index.js
@@ -144,6 +144,7 @@ export * from './assetProvenance.js';
export * from './mediaNavigation.js';
export * from './mediaSearch.js';
export * from './morsePractice.js';
+export * from './moodBoardAnalysis.js';
export * from './moodBoardItemSrc.js';
export * from './ports.js';
export * from './providerManagement.js';
diff --git a/client/src/lib/moodBoardAnalysis.js b/client/src/lib/moodBoardAnalysis.js
new file mode 100644
index 0000000000..c93aa3fc79
--- /dev/null
+++ b/client/src/lib/moodBoardAnalysis.js
@@ -0,0 +1,92 @@
+// Mood-board analysis helpers shared by the per-item prompt-from-media flow
+// and the board-level "analyze, then compose a poster" flow.
+//
+// Pure: no React, no fetches. The page persists whatever `moodBoardAnalysisFromResult`
+// returns; the style panel uses `boardAnalyzePlan` to decide whether the next
+// click runs vision or only composes from prompts already stored on the items.
+
+import { moodBoardItemAnalysisSource } from './moodBoardItemSrc';
+import { IMAGE_GEN_MODE } from './imageGenModes';
+
+// Landscape 3:2 — a board poster, not a portrait character sheet. The image
+// service is whichever backend the caller resolved; only the frame is fixed.
+export const BOARD_POSTER_SIZE = Object.freeze({ width: 1536, height: 1024 });
+
+/**
+ * The analysis object stored on a media item after one prompt-from-media run.
+ * Prefers the prompt that matches the item's own type (video items keep the
+ * video prompt) and falls back to the other target when the model only filled
+ * one. Returns null when neither prompt is usable.
+ */
+export function moodBoardAnalysisFromResult(item, result) {
+ if (!result) return null;
+ const preferVideo = item?.type === 'video';
+ const primary = preferVideo ? result.videoPrompt : result.imagePrompt;
+ const fallback = preferVideo ? result.imagePrompt : result.videoPrompt;
+ const usedPrimary = primary != null && primary !== '';
+ const prompt = usedPrimary ? primary : fallback;
+ if (!prompt) return null;
+ const negative = usedPrimary
+ ? (preferVideo ? result.videoNegativePrompt : result.imageNegativePrompt)
+ : (preferVideo ? result.imageNegativePrompt : result.videoNegativePrompt);
+ return {
+ prompt,
+ negativePrompt: negative || null,
+ rationale: result.rationale || null,
+ providerId: result.providerId || null,
+ model: result.model || null,
+ };
+}
+
+/**
+ * Split a board's items into the ones prompt-from-media can still read and
+ * the ones that already carry a prompt. External URL pins can't be read, so
+ * they count as skipped rather than pending.
+ */
+export function boardAnalyzePlan(items) {
+ const list = Array.isArray(items) ? items : [];
+ const pending = [];
+ let analyzed = 0;
+ let skipped = 0;
+ for (const item of list) {
+ const stored = item?.analysis?.prompt;
+ if (typeof stored === 'string' && stored.trim()) {
+ analyzed += 1;
+ continue;
+ }
+ if (item?.type !== 'image' && item?.type !== 'video') continue;
+ if (moodBoardItemAnalysisSource(item)) pending.push(item);
+ else skipped += 1;
+ }
+ return { pending, analyzed, skipped };
+}
+
+// Stable key for the style a poster was queued against, so a completion that
+// lands after the user composed a different prompt is not pinned.
+export function posterStyleKey(style) {
+ return JSON.stringify({
+ prompt: typeof style?.prompt === 'string' ? style.prompt.trim() : '',
+ negative: typeof style?.negativePrompt === 'string' ? style.negativePrompt.trim() : '',
+ });
+}
+
+/**
+ * Render config for the board poster. `mode` (when set) overrides the resolved
+ * install default so the poster can run on any enabled image service. The
+ * override is explicit (`inheritedBackend: false`) — a mood board has no
+ * universe/music-video tag that would re-resolve the backend server-side.
+ * Switching off local drops the local model id so it is not sent to a cloud CLI.
+ */
+export function boardPosterRenderCfg(imageCfg, mode) {
+ const chosen = mode || imageCfg?.mode;
+ const local = chosen === IMAGE_GEN_MODE.LOCAL;
+ return {
+ ...(imageCfg || {}),
+ mode: chosen,
+ inheritedBackend: false,
+ modelId: local ? (imageCfg?.modelId || null) : null,
+ cloudModel: null,
+ width: BOARD_POSTER_SIZE.width,
+ height: BOARD_POSTER_SIZE.height,
+ };
+}
diff --git a/client/src/lib/moodBoardAnalysis.test.js b/client/src/lib/moodBoardAnalysis.test.js
new file mode 100644
index 0000000000..2dbc69c20f
--- /dev/null
+++ b/client/src/lib/moodBoardAnalysis.test.js
@@ -0,0 +1,78 @@
+import { describe, expect, it } from 'vitest';
+import { IMAGE_GEN_MODE } from './imageGenModes';
+import {
+ BOARD_POSTER_SIZE,
+ boardAnalyzePlan,
+ boardPosterRenderCfg,
+ moodBoardAnalysisFromResult,
+ posterStyleKey,
+} from './moodBoardAnalysis';
+
+describe('moodBoardAnalysisFromResult', () => {
+ it('stores the image prompt for an image pin and falls back to the video prompt', () => {
+ expect(moodBoardAnalysisFromResult(
+ { type: 'image' },
+ { imagePrompt: 'ink wash', imageNegativePrompt: 'gloss', rationale: 'tactile', providerId: 'ollama', model: 'vlm' },
+ )).toEqual({
+ prompt: 'ink wash',
+ negativePrompt: 'gloss',
+ rationale: 'tactile',
+ providerId: 'ollama',
+ model: 'vlm',
+ });
+ expect(moodBoardAnalysisFromResult(
+ { type: 'image' },
+ { videoPrompt: 'a pan across ink' },
+ ).prompt).toBe('a pan across ink');
+ });
+
+ it('prefers the video prompt for a video pin', () => {
+ expect(moodBoardAnalysisFromResult(
+ { type: 'video' },
+ { imagePrompt: 'still', videoPrompt: 'a slow push', videoNegativePrompt: 'cuts' },
+ ).prompt).toBe('a slow push');
+ });
+
+ it('returns null when the run produced no prompt', () => {
+ expect(moodBoardAnalysisFromResult({ type: 'image' }, {})).toBeNull();
+ expect(moodBoardAnalysisFromResult({ type: 'image' }, null)).toBeNull();
+ });
+});
+
+describe('boardAnalyzePlan', () => {
+ it('splits analyzed pins, readable pins, and external links', () => {
+ const plan = boardAnalyzePlan([
+ { id: 'a', type: 'image', mediaKey: 'image:a.png', analysis: { prompt: 'already' } },
+ { id: 'b', type: 'image', mediaKey: 'image:b.png' },
+ { id: 'c', type: 'image', imageUrl: 'https://example.com/c.png' },
+ { id: 'd', type: 'text', text: 'a note' },
+ ]);
+ expect(plan.analyzed).toBe(1);
+ expect(plan.pending.map((it) => it.id)).toEqual(['b']);
+ expect(plan.skipped).toBe(1);
+ });
+});
+
+describe('boardPosterRenderCfg', () => {
+ const imageCfg = { mode: IMAGE_GEN_MODE.GROK, modelId: 'flux', cloudModel: 'grok-imagine', inheritedBackend: true, width: 1024, height: 1536 };
+
+ it('pins an explicit landscape frame on the chosen image service', () => {
+ expect(boardPosterRenderCfg(imageCfg, IMAGE_GEN_MODE.LOCAL)).toMatchObject({
+ mode: IMAGE_GEN_MODE.LOCAL,
+ inheritedBackend: false,
+ modelId: 'flux',
+ cloudModel: null,
+ width: BOARD_POSTER_SIZE.width,
+ height: BOARD_POSTER_SIZE.height,
+ });
+ });
+
+ it('drops a local model id when the chosen service is not local', () => {
+ expect(boardPosterRenderCfg(imageCfg, IMAGE_GEN_MODE.GROK).modelId).toBeNull();
+ });
+
+ it('keys the poster on the saved prompt so a later compose is not pinned', () => {
+ expect(posterStyleKey({ prompt: 'ink', negativePrompt: 'gloss' }))
+ .not.toBe(posterStyleKey({ prompt: 'oil', negativePrompt: 'gloss' }));
+ });
+});
diff --git a/client/src/lib/moodBoardItemSrc.js b/client/src/lib/moodBoardItemSrc.js
index cc46f4220b..8e398fb775 100644
--- a/client/src/lib/moodBoardItemSrc.js
+++ b/client/src/lib/moodBoardItemSrc.js
@@ -18,6 +18,15 @@
const IMAGE_PREFIX = 'image:';
const VIDEO_PREFIX = 'video:';
+// The board's canonical poster, served from the gallery. Null when the board
+// has not been rendered yet. The filename is a basename (the write schema
+// rejects separators); encode it so a space in a gallery name still resolves.
+export function moodBoardPosterSrc(board) {
+ const name = typeof board?.posterImageRef === 'string' ? board.posterImageRef.trim() : '';
+ if (!name || name.includes('/') || name.includes('\\')) return null;
+ return `/data/images/${encodeURIComponent(name)}`;
+}
+
export function moodBoardItemSrc(item) {
if (item?.imageUrl) return item.imageUrl;
if (typeof item?.mediaKey === 'string' && item.mediaKey.startsWith(IMAGE_PREFIX)) {
diff --git a/client/src/lib/moodBoardItemSrc.test.js b/client/src/lib/moodBoardItemSrc.test.js
index 9807b2fb34..928b20fffa 100644
--- a/client/src/lib/moodBoardItemSrc.test.js
+++ b/client/src/lib/moodBoardItemSrc.test.js
@@ -1,5 +1,5 @@
import { describe, it, expect } from 'vitest';
-import { moodBoardItemSrc, moodBoardItemVideoSrc, moodBoardItemAnalysisSource } from './moodBoardItemSrc';
+import { moodBoardItemSrc, moodBoardItemVideoSrc, moodBoardItemAnalysisSource, moodBoardPosterSrc } from './moodBoardItemSrc';
describe('moodBoardItemSrc', () => {
it('prefers an explicit imageUrl', () => {
@@ -83,4 +83,16 @@ describe('moodBoardItemAnalysisSource (#4188 Phase 3)', () => {
expect(moodBoardItemAnalysisSource(null)).toBeNull();
});
});
+
+describe('moodBoardPosterSrc', () => {
+ it('serves the canonical poster from the gallery', () => {
+ expect(moodBoardPosterSrc({ posterImageRef: 'board poster.png' }))
+ .toBe('/data/images/board%20poster.png');
+ });
+ it('returns null when there is no poster or the name is a path', () => {
+ expect(moodBoardPosterSrc({})).toBeNull();
+ expect(moodBoardPosterSrc({ posterImageRef: 'a/b.png' })).toBeNull();
+ expect(moodBoardPosterSrc(null)).toBeNull();
+ });
+});
// @vitest-environment node
diff --git a/client/src/pages/MoodBoardDetail.jsx b/client/src/pages/MoodBoardDetail.jsx
index 73f120170c..9fd6506563 100644
--- a/client/src/pages/MoodBoardDetail.jsx
+++ b/client/src/pages/MoodBoardDetail.jsx
@@ -19,6 +19,7 @@ import InlineConfirmRow from '../components/ui/InlineConfirmRow';
import GalleryImagePicker from '../components/imageGen/GalleryImagePicker';
import GalleryVideoPicker from '../components/videoGen/GalleryVideoPicker';
import { PromptFromMediaModal } from '../components/media/PromptFromMedia';
+import MoodBoardStylePanel from '../components/moodBoard/MoodBoardStylePanel';
import { copyToClipboard } from '../lib/clipboard';
import {
getMoodBoard,
@@ -32,6 +33,7 @@ import {
importMoodBoardXPost,
} from '../services/api';
import { moodBoardItemSrc, moodBoardItemVideoSrc, moodBoardItemAnalysisSource } from '../lib/moodBoardItemSrc';
+import { moodBoardAnalysisFromResult } from '../lib/moodBoardAnalysis';
import { timeAgo } from '../utils/formatters';
import useMounted from '../hooks/useMounted';
@@ -200,22 +202,8 @@ function MoodBoardEditor({ id }) {
// matches the item's own type, falling back to whichever was generated.
const persistAnalysis = async (item, result) => {
if (!mountedRef.current) return;
- const preferVideo = item.type === 'video';
- const primary = preferVideo ? result.videoPrompt : result.imagePrompt;
- const fallback = preferVideo ? result.imagePrompt : result.videoPrompt;
- const usedPrimary = primary != null && primary !== '';
- const prompt = usedPrimary ? primary : fallback;
- if (!prompt) return;
- const negative = usedPrimary
- ? (preferVideo ? result.videoNegativePrompt : result.imageNegativePrompt)
- : (preferVideo ? result.imageNegativePrompt : result.videoNegativePrompt);
- const analysis = {
- prompt,
- negativePrompt: negative || null,
- rationale: result.rationale || null,
- providerId: result.providerId || null,
- model: result.model || null,
- };
+ const analysis = moodBoardAnalysisFromResult(item, result);
+ if (!analysis) return;
const updated = await updateMoodBoardItem(id, item.id, { analysis }, { silent: true }).catch(() => null);
if (!mountedRef.current) return;
if (!updated) { toast.error('Analysis ran but could not be saved to the item'); return; }
@@ -401,6 +389,8 @@ function MoodBoardEditor({ id }) {
</div>
</div>
+ <MoodBoardStylePanel board={board} onBoardChange={setBoard} />
+
{/* Pinterest link + sync */}
<div className="bg-port-card border border-port-border rounded-md p-4 mb-6">
<div className="flex items-center gap-2 mb-3">
@@ -693,8 +683,8 @@ function MoodBoardEditor({ id }) {
<button
type="button"
onClick={() => setAnalyzeItemId(item.id)}
- title={item.analysis ? 'View AI analysis' : 'Analyze with AI'}
- aria-label={item.analysis ? 'View AI analysis' : 'Analyze with AI'}
+ title={item.analysis ? 'View prompt from media' : 'Prompt from media'}
+ aria-label={item.analysis ? 'View prompt from media' : 'Prompt from media'}
className={`min-h-[44px] min-w-[44px] inline-flex items-center justify-center p-1 transition-colors ${item.analysis ? 'text-port-accent hover:text-port-accent/80' : 'text-gray-500 hover:text-white'}`}
>
<ScanEye className="w-3.5 h-3.5" aria-hidden="true" />
diff --git a/client/src/pages/MoodBoardDetail.test.jsx b/client/src/pages/MoodBoardDetail.test.jsx
index 0275b96a3e..f5cbad6c2c 100644
--- a/client/src/pages/MoodBoardDetail.test.jsx
+++ b/client/src/pages/MoodBoardDetail.test.jsx
@@ -38,6 +38,10 @@ vi.mock('../components/ui/Toast', () => ({
// test is the page's own wiring (open, persist via onResult, stored-analysis
// children), not the analyzer internals, which have their own suite.
let analysisDelay = null;
+vi.mock('../components/moodBoard/MoodBoardStylePanel', () => ({
+ default: () => <div data-testid="board-style-panel" />,
+}));
+
vi.mock('../components/media/PromptFromMedia', () => ({
PromptFromMediaModal: ({ open, item, onResult, children }) => (open && item ? (
<div data-testid="pfm-modal">
@@ -350,7 +354,7 @@ describe('MoodBoardDetail item analysis (#4188 Phase 3)', () => {
.mockResolvedValueOnce({ id: 'b', name: 'Board B', items: [] });
const { rerender } = renderPage();
await waitFor(() => expect(boardNameValue()).toBe('Board A'));
- fireEvent.click(screen.getByRole('button', { name: 'Analyze with AI' }));
+ fireEvent.click(screen.getByRole('button', { name: 'Prompt from media' }));
fireEvent.click(screen.getByRole('button', { name: 'mock-generate' }));
currentId = 'b';
@@ -378,7 +382,7 @@ describe('MoodBoardDetail item analysis (#4188 Phase 3)', () => {
// One analyzable item → exactly one analyze button; the text item and the
// external-URL pin get none.
- expect(screen.getAllByRole('button', { name: 'Analyze with AI' })).toHaveLength(1);
+ expect(screen.getAllByRole('button', { name: 'Prompt from media' })).toHaveLength(1);
});
it('persists a run onto the item and flips the card to its analyzed state', async () => {
@@ -398,7 +402,7 @@ describe('MoodBoardDetail item analysis (#4188 Phase 3)', () => {
renderPage();
await waitFor(() => expect(boardNameValue()).toBe('Board A'));
- fireEvent.click(screen.getByRole('button', { name: 'Analyze with AI' }));
+ fireEvent.click(screen.getByRole('button', { name: 'Prompt from media' }));
expect(screen.getByTestId('pfm-modal')).toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: 'mock-generate' }));
@@ -416,7 +420,7 @@ describe('MoodBoardDetail item analysis (#4188 Phase 3)', () => {
// The persisted item flows back into board state: the card badge flips and
// the modal now shows the stored analysis.
- await screen.findByRole('button', { name: 'View AI analysis' });
+ await screen.findByRole('button', { name: 'View prompt from media' });
expect(screen.getByLabelText('Saved analysis prompt')).toHaveValue('a moody castle at dusk');
});
@@ -433,11 +437,11 @@ describe('MoodBoardDetail item analysis (#4188 Phase 3)', () => {
renderPage();
await waitFor(() => expect(boardNameValue()).toBe('Board A'));
- fireEvent.click(screen.getByRole('button', { name: 'View AI analysis' }));
+ fireEvent.click(screen.getByRole('button', { name: 'View prompt from media' }));
fireEvent.click(screen.getByRole('button', { name: 'Remove' }));
await waitFor(() => {
expect(mockUpdateMoodBoardItem).toHaveBeenCalledWith('a', 'i1', { analysis: null }, { silent: true });
});
- await screen.findByRole('button', { name: 'Analyze with AI' });
+ await screen.findByRole('button', { name: 'Prompt from media' });
});
});
diff --git a/client/src/pages/MoodBoards.jsx b/client/src/pages/MoodBoards.jsx
index 0e68e4f8f5..b17395d005 100644
--- a/client/src/pages/MoodBoards.jsx
+++ b/client/src/pages/MoodBoards.jsx
@@ -17,7 +17,7 @@ import InlineConfirmRow from '../components/ui/InlineConfirmRow';
import EmptyState from '../components/EmptyState';
import { timeAgo } from '../utils/formatters';
import { listMoodBoards, createMoodBoard, deleteMoodBoard } from '../services/api';
-import { moodBoardItemSrc } from '../lib/moodBoardItemSrc';
+import { moodBoardItemSrc, moodBoardPosterSrc } from '../lib/moodBoardItemSrc';
const itemCounts = (board) => {
const items = Array.isArray(board?.items) ? board.items : [];
@@ -50,9 +50,13 @@ function MoodBoardCard({ board, onDelete, isConfirming, onConfirmDelete, onCance
.filter((it) => Boolean(it.src));
}, [board]);
- const coverItem = visualItems[0] || null;
- const subThumbnails = visualItems.slice(1, 1 + MAX_THUMBNAILS);
- const remainingVisualsCount = visualItems.length - (1 + subThumbnails.length);
+ const posterSrc = moodBoardPosterSrc(board);
+ const coverSrc = posterSrc || visualItems[0]?.src || null;
+ // A rendered poster is the cover, so the pinned stills all stay in the strip.
+ // Without one, the first still is the cover and drops out of the strip.
+ const stripItems = posterSrc ? visualItems : visualItems.slice(1);
+ const subThumbnails = stripItems.slice(0, MAX_THUMBNAILS);
+ const remainingVisualsCount = stripItems.length - subThumbnails.length;
return (
<li className="bg-port-card border border-port-border rounded-xl overflow-hidden flex flex-col hover:border-port-accent/40 transition-colors">
@@ -71,9 +75,9 @@ function MoodBoardCard({ board, onDelete, isConfirming, onConfirmDelete, onCance
className="block bg-port-bg border-b border-port-border/60 group relative"
>
<div className="aspect-[16/10] w-full overflow-hidden relative bg-port-bg flex items-center justify-center">
- {coverItem ? (
+ {coverSrc ? (
<img
- src={coverItem.src}
+ src={coverSrc}
alt={board.name}
loading="lazy"
className="w-full h-full object-cover group-hover:scale-105 transition-transform duration-200"
diff --git a/client/src/pages/MoodBoards.test.jsx b/client/src/pages/MoodBoards.test.jsx
index 2fbf274bf9..fb69f479f9 100644
--- a/client/src/pages/MoodBoards.test.jsx
+++ b/client/src/pages/MoodBoards.test.jsx
@@ -78,6 +78,24 @@ describe('MoodBoards index', () => {
expect(screen.getByText('7 items')).toBeInTheDocument();
});
+ it('uses the canonical poster as the cover and keeps the first pin in the strip', async () => {
+ listMoodBoards.mockResolvedValue([
+ {
+ id: 'board-2',
+ name: 'Ink',
+ description: '',
+ posterImageRef: 'board poster.png',
+ items: [
+ { id: 'it-1', type: 'image', imageUrl: '/data/images/pin.png', caption: 'First pin' },
+ ],
+ updatedAt: '2026-01-01T00:00:00.000Z',
+ },
+ ]);
+ await renderPage();
+ expect((await screen.findByAltText('Ink')).getAttribute('src')).toBe('/data/images/board%20poster.png');
+ expect(screen.getByAltText('First pin')).toBeInTheDocument();
+ });
+
it('allows deleting a board with confirmation', async () => {
listMoodBoards.mockResolvedValue([
{ id: 'board-1', name: 'Board To Delete', items: [], updatedAt: '2026-01-01T00:00:00.000Z' },
diff --git a/client/src/services/README.md b/client/src/services/README.md
index cb5b85a325..58f7208772 100644
--- a/client/src/services/README.md
+++ b/client/src/services/README.md
@@ -84,7 +84,7 @@ toasts on throw). **Custom catch ⇒ `silent: true`** — otherwise toasts fire
| `apiHealth.js` | Apple Health. |
| `apiMeatspace.js` | MeatSpace health, genome, POST, memory-practice, and atomic POST training-run APIs. |
| `apiMortalLoom.js` | Mortality tracking. |
-| `apiMoodBoard.js` | Mood boards (inspiration canvas + items), plus `listMoodBoardNames()` for pickers. |
+| `apiMoodBoard.js` | Mood boards (inspiration canvas + items), `listMoodBoardNames()` for pickers, and `composeMoodBoardPrompt()` which stores the board's composite style prompt. |
| `apiTribe.js` | Tribe people (relationship rings + contacts), plus `getTribeDuplicateIdentifiers()` (`GET /tribe/duplicate-identifiers`): a non-blocking report of emails/phones shared by more than one person. |
| `apiTimeline.js` | Human-activity timeline: `/timeline/day`. |
| `apiCalendar.js` | Calendar events. |
diff --git a/client/src/services/apiMoodBoard.js b/client/src/services/apiMoodBoard.js
index 7313d03196..14b9be674b 100644
--- a/client/src/services/apiMoodBoard.js
+++ b/client/src/services/apiMoodBoard.js
@@ -49,6 +49,15 @@ export const removeMoodBoardItem = (id, itemId, options) =>
...options,
});
+// Distill stored per-item analyses into the board's own composite style prompt
+// and persist it on the board (`style`). Resolves to the updated board.
+export const composeMoodBoardPrompt = (id, { providerId, model } = {}, options = {}) =>
+ request(`/mood-boards/${encodeURIComponent(id)}/compose-prompt`, {
+ method: 'POST',
+ body: JSON.stringify({ providerId, model }),
+ ...options,
+ });
+
// Board → universe style synthesis (#4188 Phase 4). Stateless review step:
// sends the universe's CURRENT style context (styleNotes/influences/locked)
// plus the chosen LLM; resolves to `{ proposed, diff, rationale, llm }`.
diff --git a/docs/features/product-surfaces.md b/docs/features/product-surfaces.md
index c94f83918a..2d05a3ec26 100644
--- a/docs/features/product-surfaces.md
+++ b/docs/features/product-surfaces.md
@@ -97,7 +97,7 @@ An end-to-end creative production suite for authors, worldbuilders, filmmakers,
| **Universes & Canon** | `/universes`, `/universes/:id` | Worldbuilding bibles: sci-fi/fantasy lore, style templates, canon entries, characters, settings, and visual consistency anchors. | — |
| **Creative Catalog** | `/catalog`, `/catalog?settings=1` | Searchable relational entity database (characters, places, objects, lore, scenes) with vector search and taxonomy management. | [STORAGE.md](../STORAGE.md) |
| **Catalog Ingest** | `/catalog/ingest` | Paste unstructured scraps, scenes, or notes to automatically extract structured catalog ingredients. | — |
-| **Mood Boards** | `/mood-boards` | Visual pinboards, style canvases, color palettes, and conceptual reference collections. | — |
+| **Mood Boards** | `/mood-boards` | Visual pinboards and reference collections. Each pin and the whole board can be turned into a prompt; the board composes those prompts into one style and can render it as a canonical poster on any configured image service. | — |
| **Media Gen (Image & Video)** | `/media`, `/media/image`, `/media/video` | Local and federated text-to-image (Stable Diffusion, FLUX, MFLUX) and text-to-video (LTX-Video, MiniMax H3) generation. | [Video Speed Profiles](./video-speed-profiles.md), [Video Text Encoders](./video-text-encoders.md) |
| **Media History & Timeline** | `/media/history`, `/media/timeline` | Asset gallery, multi-track video timeline editor, clip trimming, audio overlay, and video stitching. | — |
| **Image Annotation** | `/media/annotate` | Canvas drawing, sketch-over, visual markup, and region labeling for image conditioning. | — |
diff --git a/server/lib/README.md b/server/lib/README.md
index 6b659c6417..0321072430 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -781,5 +781,5 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `databaseWriterRegistry.js` | `createDatabaseWriterRegistry(dataDir?)` supplies durable detached launch reservations and inventory observations (reservation, POSIX launcher group, job PID, abandonment, completion) plus `retire(id, archiveDir?)` for proven-quiescent records; `reserveDatabaseWriter` is the mandatory `spawnDetached` admission boundary. `classifyWriterQuiescence(row, processes)` classifies a row against a process-table snapshot (quiescent / running / orphaned / pending / ambiguous) without probing PIDs. Legacy compacted history and Windows completions stay unresolved. |
| `musicVideoCreativeContext.js` | `musicVideoCreativeContext(concept)` composes the selected universe style and authored cast/place/object bible for planning and generation. |
-| `moodBoardStyleContext.js` | `collectBoardStyleContext(board)` bounds a board's notes, captions and analyzed style for creative prompts. |
+| `moodBoardStyleContext.js` | `collectBoardStyleContext(board)` bounds a board's notes, captions, analyzed prompts, and composite style for creative prompts. `moodBoardImageCandidates(board, resolveItem)` lists the poster first, then pinned local images. |
| `musicVideoAutomation.js` | Music Video automation brief: `MUSIC_VIDEO_AUTOMATION_TOOLS` (image/video backends derived from `generationModes.js` plus `code:render`, each flagged `metered`), `MUSIC_VIDEO_AUTOMATION_TOOL_IDS`, and `normalizeMusicVideoAutomation(patch, current)` (per-sub-field merge, catalog-ordered tools, `budgetUsd: null` = no cap). Dependency-free; the client create drawer imports it. |
diff --git a/server/lib/conflictJournal.js b/server/lib/conflictJournal.js
index 20615fcb71..f465fca9be 100644
--- a/server/lib/conflictJournal.js
+++ b/server/lib/conflictJournal.js
@@ -528,13 +528,15 @@ export const RESTORABLE_FIELDS = Object.freeze({
creativeDirectorProject: ['name', 'status', 'styleSpec', 'userStory', 'treatment', 'aspectRatio', 'quality', 'modelId', 'targetDurationSeconds', 'disableAudio', 'autoAcceptScenes', 'startingImageFile'],
// Mood boards (#1564): the user-authored fields the merge can restore. `items[]`
// (the pinned image/text references) carries the bulk of the work, alongside
- // name/description. Server-owned / structural fields are excluded — `id`/
- // `createdAt`/the LWW-tombstone trio. The whole record is hashed for DETECTION
- // by contentHashForRecord (no scalar narrowing); this set is what the Conflicts
- // UI offers for restore. `moodBoard` matches the record kind, and the resolver
- // routes restore through restoreBoard → applyBoardRestore (which accepts items,
- // unlike the route's applyBoardPatch).
- moodBoard: ['name', 'description', 'items'],
+ // name/description. `style` is the composite board prompt and `posterImageRef`
+ // is the canonical poster filename — both user-triggered, so a restore must
+ // be able to bring them back. Server-owned / structural fields are excluded —
+ // `id`/`createdAt`/the LWW-tombstone trio. The whole record is hashed for
+ // DETECTION by contentHashForRecord (no scalar narrowing); this set is what
+ // the Conflicts UI offers for restore. `moodBoard` matches the record kind,
+ // and the resolver routes restore through restoreBoard → applyBoardRestore
+ // (which accepts items, unlike the route's applyBoardPatch).
+ moodBoard: ['name', 'description', 'items', 'style', 'posterImageRef'],
// Writers Room works (#1565): the user-authored manifest fields the merge can
// restore through `updateWork` (which accepts exactly this set + the liveMode
// partial-merge). Server-owned / structural fields are excluded — `id`/
diff --git a/server/lib/moodBoardStyleContext.js b/server/lib/moodBoardStyleContext.js
index 94ff3f0d27..18a1dd1e67 100644
--- a/server/lib/moodBoardStyleContext.js
+++ b/server/lib/moodBoardStyleContext.js
@@ -62,10 +62,47 @@ export function collectBoardStyleContext(board) {
totalChars += entrySize;
fragments.push({ kind: it.type, ...entry });
}
+ // The board's own composite prompt is the distilled through-line. It is one
+ // field, so it gets the description budget rather than the per-item cap —
+ // clipping it to 600 would drop the look downstream renders are asked to match.
+ const style = board?.style;
+ const stylePrompt = trimTo(style?.prompt, 2000) || null;
+ const styleNegative = trimTo(style?.negativePrompt, 2000) || null;
return {
name: trimTo(board?.name, 200) || null,
description: trimTo(board?.description, 2000) || null,
+ stylePrompt,
+ styleNegative,
items: fragments,
droppedItems: dropped,
};
}
+
+/**
+ * Local image references a board contributes, poster first. `resolveItem`
+ * is `boardItemLocalImage` (injected so this module stays free of the board
+ * store). The canonical poster is the board's style reference — the same role
+ * a universe's style-probe image plays — and pinned item images follow it.
+ * Duplicate filenames are dropped so a poster that was also pinned ships once.
+ */
+export function moodBoardImageCandidates(board, resolveItem) {
+ const candidates = [];
+ const seen = new Set();
+ const push = (kind, filename, label) => {
+ if (kind !== 'image' && kind !== 'image-ref') return;
+ if (typeof filename !== 'string' || !filename.trim()) return;
+ const key = `${kind}:${filename.trim()}`;
+ if (seen.has(key)) return;
+ seen.add(key);
+ candidates.push({ kind, filename: filename.trim(), label });
+ };
+ push('image', board?.posterImageRef, 'Mood board poster');
+ const items = Array.isArray(board?.items) ? board.items : [];
+ for (const item of items) {
+ const asset = typeof resolveItem === 'function' ? resolveItem(item) : null;
+ if (!asset) continue;
+ const caption = typeof item?.caption === 'string' ? item.caption.trim() : '';
+ push(asset.kind, asset.filename, caption || asset.filename);
+ }
+ return candidates;
+}
diff --git a/server/lib/moodBoardValidation.js b/server/lib/moodBoardValidation.js
index b50f2f62e6..7a43bf6eb8 100644
--- a/server/lib/moodBoardValidation.js
+++ b/server/lib/moodBoardValidation.js
@@ -53,11 +53,38 @@ export const moodBoardCreateSchema = z.object({
description: z.string().max(5000).optional(),
}).strict();
+// Gallery filename for the board's canonical poster. Same traversal rule as
+// the asset manifest (`sanitizeAssetFilename`): separators and `.` / `..`
+// are rejected; an image extension is required so a video ref can't be
+// stored as the still the poster slot renders.
+const posterFilenameSchema = z.string().trim().min(1).max(255).refine(
+ (v) => !v.includes('/') && !v.includes('\\') && v !== '.' && v !== '..'
+ && /\.(png|jpe?g|gif|webp)$/i.test(v),
+ 'posterImageRef must be a gallery image filename',
+);
+
+// Composite board style — one ready-to-render prompt distilled from the
+// per-item prompt-from-media analyses. Written by POST /compose-prompt and
+// editable from the board page. `null` on the PATCH clears it. Additive on
+// the wire (whole-record LWW); bounds match the per-item analysis caps.
+export const moodBoardStyleSchema = z.object({
+ prompt: z.string().trim().min(1).max(8000),
+ negativePrompt: z.string().max(8000).nullable().optional(),
+ rationale: z.string().max(1200).nullable().optional(),
+ analyzedItemCount: z.number().int().min(0).max(500).optional(),
+ providerId: z.string().max(128).nullable().optional(),
+ model: z.string().max(256).nullable().optional(),
+ composedAt: z.string().datetime({ offset: true }).nullable().optional(),
+}).strict();
+
// Board PATCH — only the editable board-level fields. items[] is managed via
-// the dedicated item endpoints, never a bulk board PATCH.
+// the dedicated item endpoints, never a bulk board PATCH. `style` /
+// `posterImageRef` are the composite prompt and the canonical poster.
export const moodBoardUpdateSchema = z.object({
name: z.string().trim().min(1).max(200).optional(),
description: z.string().max(5000).optional(),
+ style: moodBoardStyleSchema.nullable().optional(),
+ posterImageRef: posterFilenameSchema.nullable().optional(),
}).strict();
// Add-item. An `image` item requires at least one of mediaKey / imageUrl; a
diff --git a/server/lib/moodBoardValidation.test.js b/server/lib/moodBoardValidation.test.js
index dbc13ede0a..e06962fbf0 100644
--- a/server/lib/moodBoardValidation.test.js
+++ b/server/lib/moodBoardValidation.test.js
@@ -8,6 +8,7 @@ import { describe, it, expect } from 'vitest';
import {
moodBoardCreateSchema,
moodBoardUpdateSchema,
+ moodBoardStyleSchema,
moodBoardItemCreateSchema,
moodBoardItemUpdateSchema,
moodBoardXPostImportSchema,
@@ -31,6 +32,24 @@ describe('moodBoardUpdateSchema', () => {
it('accepts a partial patch', () => {
expect(moodBoardUpdateSchema.parse({ description: '' }).description).toBe('');
});
+ it('accepts a composite style and a poster filename, and null clears both', () => {
+ const style = moodBoardStyleSchema.parse({
+ prompt: 'ink wash dusk',
+ negativePrompt: 'gloss',
+ analyzedItemCount: 2,
+ composedAt: '2026-08-14T00:00:00.000Z',
+ });
+ expect(style.prompt).toBe('ink wash dusk');
+ const patch = moodBoardUpdateSchema.parse({ style, posterImageRef: 'poster.png' });
+ expect(patch.posterImageRef).toBe('poster.png');
+ expect(moodBoardUpdateSchema.parse({ style: null, posterImageRef: null })).toEqual({ style: null, posterImageRef: null });
+ });
+ it('rejects a poster path and a style with no prompt', () => {
+ expect(moodBoardUpdateSchema.safeParse({ posterImageRef: '../x.png' }).success).toBe(false);
+ expect(moodBoardUpdateSchema.safeParse({ posterImageRef: 'notes.txt' }).success).toBe(false);
+ expect(moodBoardStyleSchema.safeParse({ prompt: ' ' }).success).toBe(false);
+ expect(moodBoardStyleSchema.safeParse({ prompt: 'ok', extra: true }).success).toBe(false);
+ });
});
describe('moodBoardXPostImportSchema', () => {
diff --git a/server/lib/schemaVersions.js b/server/lib/schemaVersions.js
index 232726e08d..916cd159da 100644
--- a/server/lib/schemaVersions.js
+++ b/server/lib/schemaVersions.js
@@ -528,6 +528,10 @@ export const PORTOS_SCHEMA_VERSIONS = Object.freeze({
// the ahead-version push until it upgrades. Video bytes ride the existing
// asset manifest (`video:<filename>` ref → PATHS.videos, receiver regenerates
// the poster thumbnail on pull).
+ // A board's composite `style` prompt and `posterImageRef` are additive on
+ // that same v2 record: whole-record LWW plus every local mutator spreads the
+ // board, so an older peer preserves both keys and does not execute against
+ // them. The poster file rides the asset manifest as a gallery image. No bump.
moodBoards: 2,
// v1 = Writers Room works (PostgreSQL `writers_room_works` + decomposed
// `writers_room_draft_versions`) federated via the per-record peer-sync push
diff --git a/server/lib/styleSourcePrompt.js b/server/lib/styleSourcePrompt.js
index f2ee5e26fd..e8e8ef74b6 100644
--- a/server/lib/styleSourcePrompt.js
+++ b/server/lib/styleSourcePrompt.js
@@ -31,6 +31,12 @@ export function moodBoardSection(board) {
if (!board) return '';
const lines = [`Mood board: "${board.name || 'Untitled board'}" — distill its through-line (palette, texture, lighting, rhythm, mood), not any single item.`];
if (isNonBlankStr(board.description)) lines.push(`Board description: ${board.description}`);
+ // The composite prompt is the board's canonical look, already distilled from
+ // per-item analyses. Lead with it so a later item fragment can't outrank it.
+ if (isNonBlankStr(board.stylePrompt)) {
+ lines.push(`Composite board style (the canonical look distilled from the item analyses): ${board.stylePrompt}`);
+ }
+ if (isNonBlankStr(board.styleNegative)) lines.push(`Composite board style to avoid: ${board.styleNegative}`);
const fragments = (board.items || []).map((item) => {
const parts = [];
if (item.note) parts.push(`note: ${item.note}`);
diff --git a/server/lib/styleSourcePrompt.test.js b/server/lib/styleSourcePrompt.test.js
new file mode 100644
index 0000000000..4818a9d066
--- /dev/null
+++ b/server/lib/styleSourcePrompt.test.js
@@ -0,0 +1,17 @@
+import { describe, expect, it } from 'vitest';
+import { moodBoardSection } from './styleSourcePrompt.js';
+
+describe('moodBoardSection', () => {
+ it('leads with the composite style prompt when the board has one', () => {
+ const text = moodBoardSection({
+ name: 'Foundry',
+ description: 'Dusty.',
+ stylePrompt: 'granular ink wash, dusty ochre light',
+ styleNegative: 'gloss, neon',
+ items: [{ analyzedPrompt: 'one pin' }],
+ });
+ expect(text.indexOf('Composite board style')).toBeLessThan(text.indexOf('one pin'));
+ expect(text).toContain('granular ink wash');
+ expect(text).toContain('gloss, neon');
+ });
+});
diff --git a/server/routes/moodBoard.js b/server/routes/moodBoard.js
index 5f2cdda520..9b6b2ae0f8 100644
--- a/server/routes/moodBoard.js
+++ b/server/routes/moodBoard.js
@@ -23,6 +23,7 @@ import {
} from '../lib/validation.js';
import { influencesSchema, lockedSchema } from './universeBuilder/shared.js';
import { synthesizeBoardStyle } from '../services/moodBoardStyleSynthesis.js';
+import { composeBoardPrompt } from '../services/moodBoardCompositeStyle.js';
import { STYLE_NOTES_MAX } from '../services/universeBuilder.js';
import {
listBoards,
@@ -118,6 +119,21 @@ router.post('/:id/synthesize-style', asyncHandler(async (req, res) => {
res.json(await synthesizeBoardStyle({ board, ...body }));
}));
+// Board-level composite prompt. Reads the per-item analyses already stored on
+// the board (prompt-from-media), distills one still-image prompt, and persists
+// it as `board.style`. The page then renders that prompt as the poster.
+const composePromptSchema = z.object({
+ providerId: z.string().trim().max(128).optional(),
+ model: z.string().trim().max(256).optional(),
+}).strict();
+router.post('/:id/compose-prompt', asyncHandler(async (req, res) => {
+ const body = validateRequest(composePromptSchema, req.body ?? {});
+ const board = await getBoard(req.params.id);
+ if (!board) throw new ServerError('Mood board not found', { status: 404, code: 'NOT_FOUND' });
+ const style = await composeBoardPrompt({ board, ...body });
+ res.json(await updateBoard(req.params.id, { style }));
+}));
+
// Link the board to a public Pinterest board's RSS feed.
router.put('/:id/pinterest', asyncHandler(async (req, res) => {
const data = validateRequest(moodBoardPinterestLinkSchema, req.body);
diff --git a/server/routes/moodBoard.test.js b/server/routes/moodBoard.test.js
index 8f6e3841aa..d6c243b825 100644
--- a/server/routes/moodBoard.test.js
+++ b/server/routes/moodBoard.test.js
@@ -27,8 +27,13 @@ vi.mock('../services/moodBoardStyleSynthesis.js', () => ({
synthesizeBoardStyle: vi.fn(),
}));
+vi.mock('../services/moodBoardCompositeStyle.js', () => ({
+ composeBoardPrompt: vi.fn(),
+}));
+
import * as svc from '../services/moodBoard/index.js';
import { synthesizeBoardStyle } from '../services/moodBoardStyleSynthesis.js';
+import { composeBoardPrompt } from '../services/moodBoardCompositeStyle.js';
import moodBoardRoutes from './moodBoard.js';
const makeApp = () => {
@@ -127,6 +132,34 @@ describe('mood-board routes', () => {
});
});
+ describe('POST /:id/compose-prompt', () => {
+ it('404s when the board is missing', async () => {
+ svc.getBoard.mockResolvedValueOnce(null);
+ const res = await request(makeApp()).post('/api/mood-boards/nope/compose-prompt').send({});
+ expect(res.status).toBe(404);
+ expect(composeBoardPrompt).not.toHaveBeenCalled();
+ });
+
+ it('persists the composed style on the board', async () => {
+ const board = { id: 'mb-1', name: 'A', items: [] };
+ const style = { prompt: 'ink wash dusk', negativePrompt: null, rationale: 'tactile', analyzedItemCount: 1, providerId: 'ollama', model: 'qwen', composedAt: '2026-08-14T00:00:00.000Z' };
+ svc.getBoard.mockResolvedValueOnce(board);
+ composeBoardPrompt.mockResolvedValueOnce(style);
+ svc.updateBoard.mockResolvedValueOnce({ ...board, style });
+ const res = await request(makeApp()).post('/api/mood-boards/mb-1/compose-prompt').send({ providerId: 'ollama', model: 'qwen' });
+ expect(res.status).toBe(200);
+ expect(composeBoardPrompt).toHaveBeenCalledWith({ board, providerId: 'ollama', model: 'qwen' });
+ expect(svc.updateBoard).toHaveBeenCalledWith('mb-1', { style });
+ expect(res.body.style.prompt).toBe('ink wash dusk');
+ });
+
+ it('400s on an unknown body key', async () => {
+ const res = await request(makeApp()).post('/api/mood-boards/mb-1/compose-prompt').send({ effort: 'high' });
+ expect(res.status).toBe(400);
+ expect(composeBoardPrompt).not.toHaveBeenCalled();
+ });
+ });
+
describe('POST /:id/x-post', () => {
it('validates the body and passes it to the service', async () => {
svc.importXPost.mockResolvedValueOnce({ board: { id: 'mb-1' }, added: 2 });
diff --git a/server/services/creativeStyleSources.js b/server/services/creativeStyleSources.js
index dd740d5ba8..246ae88a3d 100644
--- a/server/services/creativeStyleSources.js
+++ b/server/services/creativeStyleSources.js
@@ -120,18 +120,18 @@ export async function resolveUniverseStyleSource(universeId, { imageSlots, narra
*/
export async function resolveMoodBoardStyleSource(moodBoardId, { imageSlots }) {
if (!moodBoardId) return { board: null, images: [] };
- const [{ getBoard }, { collectBoardStyleContext }, { boardItemLocalImage }] = await Promise.all([
+ const [{ getBoard }, { collectBoardStyleContext, moodBoardImageCandidates }, { boardItemLocalImage }] = await Promise.all([
import('./moodBoard/db.js'),
import('./moodBoard/styleContext.js'),
import('./moodBoard/logic.js'),
]);
const board = await getBoard(moodBoardId);
if (!board) throw new ServerError('Mood board not found', { status: 404, code: 'NOT_FOUND' });
- // Text items, videos, and external pins attach nothing — they still
- // contribute their caption/analysis text through the board context.
- const candidates = (board.items || []).map((item) => () => {
- const asset = boardItemLocalImage(item);
- return asset ? localReference(asset.kind, asset.filename, trimTo(item.caption, 120) || asset.filename, 'mood-board') : null;
- });
+ // The canonical poster leads, then pinned gallery stills. Text items, videos,
+ // and external pins attach nothing — they still contribute their caption and
+ // analysis text through the board context.
+ const candidates = moodBoardImageCandidates(board, boardItemLocalImage).map((candidate) => () => (
+ localReference(candidate.kind, candidate.filename, trimTo(candidate.label, 120) || candidate.filename, 'mood-board')
+ ));
return { board: collectBoardStyleContext(board), images: fillReferences(candidates, imageSlots) };
}
diff --git a/server/services/moodBoard/db.js b/server/services/moodBoard/db.js
index 4f3a8e11fa..d57b678481 100644
--- a/server/services/moodBoard/db.js
+++ b/server/services/moodBoard/db.js
@@ -146,7 +146,7 @@ export async function updateBoard(id, patch) {
}
/**
- * Faithful conflict-restore (RESTORABLE_FIELDS.moodBoard = name/description/items)
+ * Faithful conflict-restore (RESTORABLE_FIELDS.moodBoard = name/description/items/style/posterImageRef)
* wired into conflictJournalResolver. Goes through the row lock + tombstone guard
* like every other mutator, but uses applyBoardRestore so a "restore my whole
* version" also brings back items[] (applyBoardPatch only touches name/description).
diff --git a/server/services/moodBoard/logic.js b/server/services/moodBoard/logic.js
index 92563b3ae2..1841c93baa 100644
--- a/server/services/moodBoard/logic.js
+++ b/server/services/moodBoard/logic.js
@@ -148,13 +148,32 @@ export function boardItemLocalImage(item) {
return imageUrlToAppAsset(item.imageUrl);
}
-// 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.
+// Stored shape of the board's composite style prompt. Absent optionals become
+// explicit nulls; `composedAt` is stamped when the writer didn't send one.
+// `null` clears the style (the poster render has nothing to pin to).
+export function normalizeBoardStyle(style, now = nowIso()) {
+ if (!style) return null;
+ return {
+ prompt: style.prompt,
+ negativePrompt: style.negativePrompt ?? null,
+ rationale: style.rationale ?? null,
+ analyzedItemCount: Number.isInteger(style.analyzedItemCount) ? style.analyzedItemCount : 0,
+ providerId: style.providerId ?? null,
+ model: style.model ?? null,
+ composedAt: style.composedAt ?? now,
+ };
+}
+
+// Apply a PATCH to board-level fields (name/description/style/poster). Absent
+// keys preserve the original; a present empty string clears description, and
+// `null` clears style or the poster filename. `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;
+ if (patch.style !== undefined) next.style = normalizeBoardStyle(patch.style);
+ if (patch.posterImageRef !== undefined) next.posterImageRef = patch.posterImageRef ?? null;
next.updatedAt = nowIso();
return next;
}
@@ -270,10 +289,11 @@ export function removeItem(board, itemId) {
}
// Faithful conflict-restore of the restorable board fields (RESTORABLE_FIELDS.
-// moodBoard = name/description/items). Unlike applyBoardPatch — the route PATCH
-// path, which only touches name/description because items are managed through
-// the dedicated item ops — a "restore my whole version" must bring back the
-// board's items[]. The conflict resolver narrows `patch` to the allowed fields
+// moodBoard = name/description/items/style/posterImageRef). Unlike applyBoardPatch
+// — the route PATCH path, which does not touch items because they are managed
+// through the dedicated item ops — a "restore my whole version" must bring back
+// the board's items[], and the composite style + poster when the journaled
+// version had them. The conflict resolver narrows `patch` to the allowed fields
// (via `pick`), so this just spreads the present ones and bumps updatedAt so the
// restore wins LWW and re-propagates. Mirrors creativeDirector's
// applyProjectPatch wholesale-spread restore path.
@@ -282,6 +302,8 @@ export function applyBoardRestore(board, patch) {
if (patch.name !== undefined) next.name = patch.name;
if (patch.description !== undefined) next.description = patch.description;
if (Array.isArray(patch.items)) next.items = patch.items;
+ if (patch.style !== undefined) next.style = normalizeBoardStyle(patch.style);
+ if (patch.posterImageRef !== undefined) next.posterImageRef = patch.posterImageRef ?? null;
next.updatedAt = nowIso();
return next;
}
diff --git a/server/services/moodBoard/logic.test.js b/server/services/moodBoard/logic.test.js
index b2994cdf14..5526bad937 100644
--- a/server/services/moodBoard/logic.test.js
+++ b/server/services/moodBoard/logic.test.js
@@ -9,6 +9,7 @@ import {
buildBoardRecord,
applyBoardPatch,
applyBoardRestore,
+ normalizeBoardStyle,
addItem,
updateItem,
removeItem,
@@ -56,6 +57,24 @@ describe('applyBoardPatch', () => {
it('preserves description when the key is absent', () => {
expect(applyBoardPatch(base, { name: 'B' }).description).toBe('old');
});
+ it('stores a composite style and poster, and null clears both', () => {
+ const style = { prompt: 'ink wash dusk', negativePrompt: 'gloss', analyzedItemCount: 2 };
+ const withStyle = applyBoardPatch(base, { style, posterImageRef: 'poster.png' });
+ expect(withStyle.style.prompt).toBe('ink wash dusk');
+ expect(withStyle.style.negativePrompt).toBe('gloss');
+ expect(withStyle.style.analyzedItemCount).toBe(2);
+ expect(withStyle.style.composedAt).toEqual(expect.any(String));
+ expect(withStyle.posterImageRef).toBe('poster.png');
+ const cleared = applyBoardPatch(withStyle, { style: null, posterImageRef: null });
+ expect(cleared.style).toBeNull();
+ expect(cleared.posterImageRef).toBeNull();
+ });
+ it('leaves style and poster in place when the patch omits them', () => {
+ const styled = { ...base, style: normalizeBoardStyle({ prompt: 'keep' }, 't1'), posterImageRef: 'poster.png' };
+ const next = applyBoardPatch(styled, { name: 'B' });
+ expect(next.style.prompt).toBe('keep');
+ expect(next.posterImageRef).toBe('poster.png');
+ });
});
describe('addItem', () => {
@@ -287,6 +306,16 @@ describe('applyBoardRestore', () => {
const base = { ...buildBoardRecord({ name: 'A' }, { id: 'mb-1', now: 't0' }), items: [{ id: 'x' }] };
expect(applyBoardRestore(base, { items: 'nope' }).items).toEqual([{ id: 'x' }]);
});
+ it('restores the composite style and poster when the journaled version had them', () => {
+ const base = { ...buildBoardRecord({ name: 'A' }, { id: 'mb-1', now: 't0' }), style: null, posterImageRef: 'new.png' };
+ const next = applyBoardRestore(base, {
+ style: { prompt: 'restored ink', analyzedItemCount: 1, composedAt: '2026-08-14T00:00:00.000Z' },
+ posterImageRef: 'old.png',
+ });
+ expect(next.style.prompt).toBe('restored ink');
+ expect(next.style.composedAt).toBe('2026-08-14T00:00:00.000Z');
+ expect(next.posterImageRef).toBe('old.png');
+ });
});
describe('applyPinterestLink', () => {
diff --git a/server/services/moodBoard/styleContext.js b/server/services/moodBoard/styleContext.js
index 8955384f8d..5883c71976 100644
--- a/server/services/moodBoard/styleContext.js
+++ b/server/services/moodBoard/styleContext.js
@@ -1,2 +1,2 @@
// Compatibility entrypoint; pure context is shared with creative setup clients.
-export { collectBoardStyleContext } from '../../lib/moodBoardStyleContext.js';
+export { collectBoardStyleContext, moodBoardImageCandidates } from '../../lib/moodBoardStyleContext.js';
diff --git a/server/services/moodBoard/styleContext.test.js b/server/services/moodBoard/styleContext.test.js
index 9ce29270a0..4e8af386eb 100644
--- a/server/services/moodBoard/styleContext.test.js
+++ b/server/services/moodBoard/styleContext.test.js
@@ -1,5 +1,5 @@
import { describe, expect, it } from 'vitest';
-import { collectBoardStyleContext } from './styleContext.js';
+import { collectBoardStyleContext, moodBoardImageCandidates } from './styleContext.js';
const boardWith = (items) => ({
id: 'mb-1',
@@ -38,6 +38,28 @@ describe('collectBoardStyleContext', () => {
});
expect(ctx.items[1]).toMatchObject({ kind: 'text', note: 'lean grim and spiritual' });
expect(ctx.droppedItems).toBe(0);
+ expect(ctx.stylePrompt).toBeNull();
+ });
+
+ it('carries the composite style prompt and lists the poster ahead of pinned images', () => {
+ const board = {
+ ...boardWith([analyzedItem]),
+ style: { prompt: 'the shared ink-wash look', negativePrompt: 'gloss' },
+ posterImageRef: 'poster.png',
+ };
+ const ctx = collectBoardStyleContext(board);
+ expect(ctx.stylePrompt).toBe('the shared ink-wash look');
+ expect(ctx.styleNegative).toBe('gloss');
+ const candidates = moodBoardImageCandidates(board, (item) => (
+ item.mediaKey === 'image:ref.png' ? { kind: 'image', filename: 'ref.png' } : null
+ ));
+ expect(candidates.map((c) => c.filename)).toEqual(['poster.png', 'ref.png']);
+ });
+
+ it('does not list the poster twice when a pin is the same file', () => {
+ const board = { posterImageRef: 'ref.png', items: [{ caption: 'same', mediaKey: 'image:ref.png' }] };
+ const candidates = moodBoardImageCandidates(board, () => ({ kind: 'image', filename: 'ref.png' }));
+ expect(candidates).toEqual([{ kind: 'image', filename: 'ref.png', label: 'Mood board poster' }]);
});
it('caps the fragment list and reports the overflow', () => {
diff --git a/server/services/moodBoardCompositeStyle.js b/server/services/moodBoardCompositeStyle.js
new file mode 100644
index 0000000000..c8151c12fd
--- /dev/null
+++ b/server/services/moodBoardCompositeStyle.js
@@ -0,0 +1,127 @@
+/**
+ * Mood board composite style prompt.
+ *
+ * Per-item prompt-from-media already decomposes each pin into a render prompt.
+ * This run does not look at pixels again: it distills those stored prompts
+ * (plus captions and notes) into ONE still-image prompt — the board's
+ * canonical look — and the board page renders that prompt on whatever image
+ * service the user picks. Nothing here calls a vision model.
+ */
+
+import { parseLLMJSON, resolveAPIProvider } from './aiProvider.js';
+import { ServerError } from '../lib/errorHandler.js';
+import { assertProvider, runPromptThroughProvider } from './promptRunner.js';
+import { trimTo } from '../lib/textUtils.js';
+import { collectBoardStyleContext } from './moodBoard/styleContext.js';
+
+const PROMPT_MAX = 8000;
+const REASON_MAX = 1200;
+
+function analyzedItems(board) {
+ const items = Array.isArray(board?.items) ? board.items : [];
+ return items.filter((it) => it?.analysis && typeof it.analysis.prompt === 'string' && it.analysis.prompt.trim());
+}
+
+// Analyses first so the context budget spends itself on decomposed prompts
+// before captions and notes. The stored board order is not rewritten.
+function withAnalysesFirst(board) {
+ const items = Array.isArray(board?.items) ? board.items : [];
+ const analyzed = [];
+ const rest = [];
+ for (const it of items) {
+ if (it?.analysis && typeof it.analysis.prompt === 'string' && it.analysis.prompt.trim()) analyzed.push(it);
+ else rest.push(it);
+ }
+ return { ...board, items: [...analyzed, ...rest] };
+}
+
+const contentPrompt = (text) => trimTo(text, PROMPT_MAX)
+ .replace(/^(?:please\s+)?(?:create|generate|render|make)\s+(?:(?:an?|the)\s+(?:image|picture|poster)\s+(?:of|showing|depicting)\s+)?/i, '')
+ .trim();
+
+export function buildCompositeStylePrompt({ context, analyzedItemCount }) {
+ const payload = JSON.stringify({ board: context, analyzedItemCount });
+ return `You are a senior prompt engineer. Compose ONE ready-to-render still-image prompt that captures the shared visual style of a mood board.
+
+The board's items have already been decomposed: each "analyzedPrompt" is a render prompt reverse-engineered from that pin. Treat those prompts as the source of truth. Captions and notes are supporting context only. Find the through-line — medium, mark-making, palette, light, texture, lens, composition, mood — and write a single prompt for a canonical reference image of that style. The image is a poster for the board itself: an editorial style reference a viewer would recognize as this board's look, not a collage that restates every item's subject, and not a description of one pin.
+
+Do not invent named characters, brands, logos, or copyrighted-artist attribution that the analyses do not already state.
+
+Mood board:
+${payload}
+
+Return JSON only:
+{
+ "prompt": "<complete ready-to-render still-image prompt>",
+ "negativePrompt": "<what the image model should avoid, or empty string>",
+ "rationale": "<one concise sentence naming the through-line>"
+}
+
+Rules:
+- Output ONLY valid JSON.
+- prompt is the COMPLETE render text, paragraph-style. Start with the subject or scene. Never prefix it with Create, Generate, Make, or Render an image of.
+- No motion language. This prompt is for a still poster.
+- An empty negativePrompt is valid when the analyses share no consistent avoid.`;
+}
+
+export async function composeBoardPrompt({ board, providerId, model } = {}) {
+ const analyzed = analyzedItems(board);
+ if (!analyzed.length) {
+ throw new ServerError(
+ 'Analyze at least one item with prompt-from-media before composing a board style. The composite is built from those prompts.',
+ { status: 400, code: 'NOTHING_ANALYZED' },
+ );
+ }
+
+ const context = collectBoardStyleContext(withAnalysesFirst(board));
+ const fed = context.items.filter((it) => it.analyzedPrompt).length;
+ if (!fed) {
+ throw new ServerError(
+ 'The item analyses did not fit the style context. Remove some notes and compose again.',
+ { status: 400, code: 'NOTHING_ANALYZED' },
+ );
+ }
+
+ const provider = await resolveAPIProvider(providerId);
+ assertProvider(provider, {
+ message: 'Composing a board style needs an API-based provider. Configure one under Settings → Providers.',
+ code: 'NO_API_PROVIDER',
+ status: 503,
+ });
+
+ const result = await runPromptThroughProvider({
+ provider,
+ prompt: buildCompositeStylePrompt({ context, analyzedItemCount: fed }),
+ source: 'mood-board-composite-style',
+ model: model || undefined,
+ });
+ let parsed;
+ try {
+ parsed = parseLLMJSON(result.text || '');
+ } catch (error) {
+ throw new ServerError(`The model returned invalid board style: ${error.message}`, {
+ status: 502,
+ code: 'COMPOSITE_BAD_JSON',
+ });
+ }
+
+ const prompt = contentPrompt(parsed?.prompt);
+ if (!prompt) {
+ throw new ServerError('The model returned an empty board style prompt', {
+ status: 502,
+ code: 'COMPOSITE_BAD_JSON',
+ });
+ }
+ const negative = trimTo(parsed?.negativePrompt, PROMPT_MAX);
+
+ return {
+ prompt,
+ negativePrompt: negative || null,
+ rationale: trimTo(parsed?.rationale, REASON_MAX) || null,
+ analyzedItemCount: fed,
+ providerId: result.provider?.id || provider.id || null,
+ model: result.model || null,
+ composedAt: new Date().toISOString(),
+ };
+}
+
diff --git a/server/services/moodBoardCompositeStyle.test.js b/server/services/moodBoardCompositeStyle.test.js
new file mode 100644
index 0000000000..18796a8041
--- /dev/null
+++ b/server/services/moodBoardCompositeStyle.test.js
@@ -0,0 +1,72 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+vi.mock('./aiProvider.js', async (importActual) => {
+ const actual = await importActual();
+ return { ...actual, resolveAPIProvider: vi.fn() };
+});
+vi.mock('./promptRunner.js', async (importActual) => {
+ const actual = await importActual();
+ return { ...actual, runPromptThroughProvider: vi.fn() };
+});
+
+const aiProvider = await import('./aiProvider.js');
+const promptRunner = await import('./promptRunner.js');
+const { buildCompositeStylePrompt, composeBoardPrompt } = await import('./moodBoardCompositeStyle.js');
+
+const apiProvider = { id: 'ollama', type: 'api', defaultModel: 'qwen' };
+const composedText = JSON.stringify({
+ prompt: 'Create an image of a weathered foundry in granular ink wash, dusty ochre light, tactile paper grain',
+ negativePrompt: 'gloss, neon, plastic',
+ rationale: 'Every pin trades polish for a tactile mark.',
+});
+
+const analyzed = {
+ id: 'i1',
+ type: 'image',
+ analysis: { prompt: 'a weathered foundry in granular ink wash', negativePrompt: 'gloss, neon' },
+};
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ aiProvider.resolveAPIProvider.mockResolvedValue(apiProvider);
+ promptRunner.runPromptThroughProvider.mockResolvedValue({ text: composedText, model: 'qwen', provider: apiProvider });
+});
+
+describe('composeBoardPrompt', () => {
+ it('refuses a board whose items have not been decomposed into prompts', async () => {
+ await expect(composeBoardPrompt({
+ board: { id: 'mb-1', name: 'Empty', items: [{ id: 'i1', type: 'image', mediaKey: 'image:a.png', caption: 'a caption' }] },
+ })).rejects.toMatchObject({ code: 'NOTHING_ANALYZED', status: 400 });
+ expect(promptRunner.runPromptThroughProvider).not.toHaveBeenCalled();
+ });
+
+ it('distills stored item prompts into one still-image style and strips an imperative prefix', async () => {
+ const style = await composeBoardPrompt({
+ board: {
+ id: 'mb-1',
+ name: 'Foundry',
+ description: 'Dusty painted sci-fi.',
+ items: [analyzed, { id: 'i2', type: 'text', text: 'lean and grim' }],
+ },
+ providerId: 'ollama',
+ model: 'qwen',
+ });
+ const sent = promptRunner.runPromptThroughProvider.mock.calls[0][0].prompt;
+ expect(sent).toContain('granular ink wash');
+ expect(sent).toContain('Dusty painted sci-fi.');
+ expect(buildCompositeStylePrompt({ context: { items: [] }, analyzedItemCount: 1 })).toContain('analyzedPrompt');
+ expect(style.prompt.startsWith('a weathered foundry')).toBe(true);
+ expect(style.negativePrompt).toBe('gloss, neon, plastic');
+ expect(style.analyzedItemCount).toBe(1);
+ expect(style.providerId).toBe('ollama');
+ expect(style.model).toBe('qwen');
+ expect(style.rationale).toContain('tactile');
+ });
+
+ it('rejects an empty model prompt', async () => {
+ promptRunner.runPromptThroughProvider.mockResolvedValueOnce({ text: '{"prompt":" ","negativePrompt":""}', model: 'qwen' });
+ await expect(composeBoardPrompt({
+ board: { id: 'mb-1', items: [analyzed] },
+ })).rejects.toMatchObject({ code: 'COMPOSITE_BAD_JSON', status: 502 });
+ });
+});
diff --git a/server/services/sharing/peerSyncAssets.js b/server/services/sharing/peerSyncAssets.js
index aace9c815a..09e2b41c3d 100644
--- a/server/services/sharing/peerSyncAssets.js
+++ b/server/services/sharing/peerSyncAssets.js
@@ -657,6 +657,11 @@ export async function buildBoardAssetManifest(board) {
export function referenceBoardAssetManifest(board) {
const dedup = new Map();
+ // The canonical poster is a gallery still, same as a pinned image. A poster
+ // that is also pinned dedups onto one manifest entry. A missing local file
+ // is dropped later by the hash step, same as any other image ref.
+ const poster = imageAssetReference(board?.posterImageRef);
+ if (poster) dedup.set(`${poster.kind}:${poster.filename}`, poster);
for (const it of Array.isArray(board?.items) ? board.items : []) {
// `video` items (#4188) carry a `video:<filename>` mediaKey (the ref IS
// the on-disk filename, so collectionVideoRefToFilename passes it through
diff --git a/server/services/sharing/peerSyncAssets.test.js b/server/services/sharing/peerSyncAssets.test.js
index 9517f30527..19d9f2e411 100644
--- a/server/services/sharing/peerSyncAssets.test.js
+++ b/server/services/sharing/peerSyncAssets.test.js
@@ -343,6 +343,26 @@ describe('buildBoardAssetManifest — video items (#4188)', () => {
expect(manifest).toContainEqual(expect.objectContaining({ filename: 'clip.mp4', kind: 'video', sha256: sha(videoBytes) }));
expect(manifest).toHaveLength(2);
});
+
+ it('bundles the canonical poster and dedups it against the same pinned file', async () => {
+ const posterBytes = Buffer.from('poster-bytes');
+ const otherBytes = Buffer.from('other-bytes');
+ writeImage('poster.png', posterBytes);
+ writeImage('other.png', otherBytes);
+ const withPoster = await buildBoardAssetManifest({
+ posterImageRef: 'poster.png',
+ items: [{ id: 'i1', type: 'image', mediaKey: 'image:other.png', imageUrl: null }],
+ });
+ expect(withPoster).toContainEqual(expect.objectContaining({ filename: 'poster.png', kind: 'image', sha256: sha(posterBytes) }));
+ expect(withPoster).toContainEqual(expect.objectContaining({ filename: 'other.png', kind: 'image', sha256: sha(otherBytes) }));
+ const deduped = await buildBoardAssetManifest({
+ posterImageRef: 'poster.png',
+ items: [{ id: 'i1', type: 'image', mediaKey: 'image:poster.png', imageUrl: null }],
+ });
+ expect(deduped.filter((entry) => entry.filename === 'poster.png')).toHaveLength(1);
+ const missing = await buildBoardAssetManifest({ posterImageRef: 'never-written.png', items: [] });
+ expect(missing).toEqual([]);
+ });
});
describe('buildFableLoomAssetManifest — scene renders', () => {