Skip to content

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

feat([issue-4188]): per-item AI prompt analysis on mood boards (Phase 3)

[._.]/ Adam Eivydde2bf04ad8b
diff --git a/.changelog/next/added-issue-4188.md b/.changelog/next/added-issue-4188.md
index b5e7a04752..a94a436c57 100644
--- a/.changelog/next/added-issue-4188.md
+++ b/.changelog/next/added-issue-4188.md
@@ -1,2 +1,3 @@
- Universes can now link a mood board directly on the record: pick or create a board from the Universe Bible tab and the link survives reload, stays per-universe, and syncs to your other machines (previously the reference strip only remembered one board per browser).
- Mood boards can now pull items straight from your galleries: pick images from the image gallery, pick or upload videos, and video items play right on the board with a poster thumbnail. Uploaded videos land in the shared video gallery, so board items sync to your other machines like any other media.
+- Mood board items can now be analyzed with AI: an "Analyze with AI" action on gallery-backed items runs the same Prompt-from-media flow as the video page (your choice of vision provider) and saves the resulting prompt, negative prompt, and rationale onto the item — shown with a highlighted badge, viewable/copyable/removable from the item, and synced to your other machines with the board.
diff --git a/client/src/components/media/PromptFromMedia.jsx b/client/src/components/media/PromptFromMedia.jsx
index 5a2c4386f8..58624a20e8 100644
--- a/client/src/components/media/PromptFromMedia.jsx
+++ b/client/src/components/media/PromptFromMedia.jsx
@@ -51,6 +51,8 @@ function SourceThumb({ source }) {
* `kindDefault` seeds the target checkboxes (`image` / `video` / `both`).
* When `setPrompt` is passed (Image Gen / Video Gen), Apply fills the host
* form. Otherwise the result offers "Open in Image Gen / Video Gen".
+ * `onResult` (optional) fires with the full analysis payload after each
+ * successful run, so a host (e.g. a mood-board item — #4188) can persist it.
*/
export default function PromptFromMedia({
kindDefault = 'both',
@@ -60,6 +62,7 @@ export default function PromptFromMedia({
initialSource = null,
disabled = false,
alwaysOpen = false,
+ onResult,
}) {
const navigate = useNavigate();
const idPrefix = useId();
@@ -174,6 +177,7 @@ export default function PromptFromMedia({
if (!data) return;
setResult(data);
toast.success('Prompts ready');
+ if (onResult) onResult(data);
};
const apply = (kind) => {
@@ -389,7 +393,10 @@ function PromptResultField({ label, value, negative, onCopy, onApply, applyLabel
);
}
-export function PromptFromMediaModal({ item, open, onClose }) {
+// `kindDefault` / `onResult` pass through to PromptFromMedia; `children`
+// render above the analyzer in the scroll area — a host can slot in the
+// item's stored analysis (mood boards — #4188).
+export function PromptFromMediaModal({ item, open, onClose, kindDefault = 'both', onResult, children }) {
if (!open || !item) return null;
return (
<Modal
@@ -416,10 +423,12 @@ export function PromptFromMediaModal({ item, open, onClose }) {
</button>
</header>
<div className="flex-1 overflow-y-auto p-4">
+ {children}
<PromptFromMedia
- kindDefault="both"
+ kindDefault={kindDefault}
initialSource={item}
alwaysOpen
+ onResult={onResult}
/>
</div>
</Modal>
diff --git a/client/src/components/media/PromptFromMedia.test.jsx b/client/src/components/media/PromptFromMedia.test.jsx
index 1a5165d01e..dc7d510e17 100644
--- a/client/src/components/media/PromptFromMedia.test.jsx
+++ b/client/src/components/media/PromptFromMedia.test.jsx
@@ -110,6 +110,38 @@ describe('PromptFromMedia', () => {
expect(screen.getByText('the camera dollies past the subject')).toBeInTheDocument();
});
+ it('notifies the host via onResult and sends a filename-only clip without a videoId (#4188)', async () => {
+ const onResult = vi.fn();
+ const payload = {
+ videoPrompt: 'a slow dolly through fog',
+ videoNegativePrompt: 'jitter',
+ rationale: 'Foggy push-in.',
+ providerId: 'openai',
+ model: 'gpt-4o',
+ };
+ vi.mocked(api.promptFromMedia).mockResolvedValue(payload);
+
+ renderPanel({
+ kindDefault: 'video',
+ applyKind: undefined,
+ onResult,
+ // A mood-board video item resolves by on-disk filename — no history id.
+ initialSource: { kind: 'video', filename: 'clip.mp4', previewUrl: '/data/video-thumbnails/clip.jpg' },
+ });
+
+ fireEvent.click(screen.getByRole('button', { name: /create prompt/i }));
+
+ await waitFor(() => {
+ expect(api.promptFromMedia).toHaveBeenCalledWith(expect.objectContaining({
+ sourceKind: 'video',
+ videoId: undefined,
+ filename: 'clip.mp4',
+ targets: ['video'],
+ }));
+ });
+ expect(onResult).toHaveBeenCalledWith(payload);
+ });
+
it('skips the disclosure toggle when hosted as an always-open card', () => {
renderPanel({ alwaysOpen: true, initialSource: null });
expect(screen.queryByRole('button', { name: /toggle prompt from media/i })).toBeNull();
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index fa4c918e15..f8589b4541 100644
--- a/client/src/lib/README.md
+++ b/client/src/lib/README.md
@@ -114,7 +114,7 @@ grep -i "what you want to do" client/src/lib/README.md
| `mediaNavigation.js` | `getAdjacentMedia(items, item)` — prev/next computation for lightboxes. |
| `mediaCollectionList.js` | Search / sort ordering for the Media Collections grid (#3283) and the `CollectionPickerShell` dropdown (#3312): `applyCollectionView(collections, { query, sort })` filters via `mediaSearch.js`'s AND-token matcher over name+description and orders synthetic "Unsorted" → non-empty-or-user-created → auto-generated empties, then by `COLLECTION_SORTS` (`updated` / `name` / `count`, `normalizeCollectionSort` coerces an unknown/URL value); keys are derived once per record, not per comparison. "Hide empty" is deliberately NOT a parameter — the page owns that one predicate (`collectionItemCount(c) > 0`) because it also needs the pre-filter count. `isAutoCollection(c)` recognizes a machine-created collection from ANY of four independent markers (`AUTO_NAME_PREFIXES`, `Auto-created…`/`Auto-generated…` description, `uc-`/`sc-` id, universe/series link) so a record predating a given marker still classifies; `splitCollectionName(name)` lifts the shared `Creative Director: ` / `Writers Room: ` / `Universe: ` / `Series: ` prefix into a badge label so the distinguishing tail survives truncation, and name sorting uses that stripped title. **Adding a server-side auto-creator means adding its prefix here** or its collections silently rank as user-created. Pure — no React. |
| `mediaSearch.js` | `buildMediaHaystack`, `tokenizeQuery`, `matchHaystack`, `filterByQuery` — client-side AND-token search over normalized media items (prompt/model/seed/LoRA/universe tags). Shared by MediaHistory + the Image Gen gallery picker. |
-| `moodBoardItemSrc.js` | `moodBoardItemSrc(item)` resolves a mood-board item to a display image/poster src (`imageUrl` → served `image:<file>` bytes → derived video thumbnail → null); `moodBoardItemVideoSrc(item)` resolves a `type:'video'` item's playback URL. Shared by MoodBoardDetail + MoodBoardReferenceStrip. |
+| `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. |
| `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`, `useCitySettings`, `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). |
| `sameJsonShape.js` | `sameJsonShape(prev, next)` — JSON.stringify-based equality for `useAutoRefetch`'s `compare` option on small, deterministically-shaped poll payloads. |
diff --git a/client/src/lib/moodBoardItemSrc.js b/client/src/lib/moodBoardItemSrc.js
index cd66221e5a..47341212c8 100644
--- a/client/src/lib/moodBoardItemSrc.js
+++ b/client/src/lib/moodBoardItemSrc.js
@@ -30,6 +30,35 @@ export function moodBoardItemSrc(item) {
return null;
}
+// Resolve a board item to a prompt-from-media source (#4188 Phase 3) — the
+// gallery-item shape PromptFromMedia's `initialSource` expects. Returns null
+// when the item's media isn't a local gallery asset the analyzer can read:
+// text items, external-URL pins, and legacy `video:<id>` pins on image items.
+// A video item resolves by FILENAME (`kind:'video'` with no id — the server
+// accepts filename in place of the history id); an image item resolves by its
+// `image:<file>` media-key or a `/data/images/<file>` app-path imageUrl.
+export function moodBoardItemAnalysisSource(item) {
+ if (item?.type === 'video') {
+ if (typeof item?.mediaKey === 'string' && item.mediaKey.startsWith(VIDEO_PREFIX)) {
+ const filename = item.mediaKey.slice(VIDEO_PREFIX.length);
+ if (filename) return { kind: 'video', filename, previewUrl: moodBoardItemSrc(item) };
+ }
+ return null;
+ }
+ if (item?.type !== 'image') return null;
+ if (typeof item?.mediaKey === 'string' && item.mediaKey.startsWith(IMAGE_PREFIX)) {
+ const filename = item.mediaKey.slice(IMAGE_PREFIX.length);
+ if (filename) return { filename, previewUrl: moodBoardItemSrc(item) };
+ }
+ const GALLERY_PREFIX = '/data/images/';
+ if (typeof item?.imageUrl === 'string' && item.imageUrl.startsWith(GALLERY_PREFIX)) {
+ let filename = item.imageUrl.slice(GALLERY_PREFIX.length);
+ try { filename = decodeURIComponent(filename); } catch { /* keep raw */ }
+ if (filename && !filename.includes('/')) return { filename, previewUrl: item.imageUrl };
+ }
+ return null;
+}
+
// Playback URL for a `type: 'video'` item; null for anything else (including
// legacy `video:<id>` pins on image items, whose ref is not a filename).
export function moodBoardItemVideoSrc(item) {
diff --git a/client/src/lib/moodBoardItemSrc.test.js b/client/src/lib/moodBoardItemSrc.test.js
index c2e8f5a222..efb073a6d6 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 } from './moodBoardItemSrc';
+import { moodBoardItemSrc, moodBoardItemVideoSrc, moodBoardItemAnalysisSource } from './moodBoardItemSrc';
describe('moodBoardItemSrc', () => {
it('prefers an explicit imageUrl', () => {
@@ -51,3 +51,24 @@ describe('moodBoardItemVideoSrc', () => {
expect(moodBoardItemVideoSrc(null)).toBeNull();
});
});
+
+describe('moodBoardItemAnalysisSource (#4188 Phase 3)', () => {
+ it('resolves a video item to a filename video source with its poster', () => {
+ expect(moodBoardItemAnalysisSource({
+ type: 'video', mediaKey: 'video:clip.mp4', imageUrl: '/data/video-thumbnails/clip.jpg',
+ })).toEqual({ kind: 'video', filename: 'clip.mp4', previewUrl: '/data/video-thumbnails/clip.jpg' });
+ });
+ it('resolves an image item by media-key or a /data/images app path (decoded)', () => {
+ expect(moodBoardItemAnalysisSource({ type: 'image', mediaKey: 'image:ref.png' }))
+ .toEqual({ filename: 'ref.png', previewUrl: '/data/images/ref.png' });
+ expect(moodBoardItemAnalysisSource({ type: 'image', imageUrl: '/data/images/my%20render.png' }))
+ .toEqual({ filename: 'my render.png', previewUrl: '/data/images/my%20render.png' });
+ });
+ it('returns null for text items, external pins, and legacy video: pins on image items', () => {
+ expect(moodBoardItemAnalysisSource({ type: 'text', text: 'n' })).toBeNull();
+ expect(moodBoardItemAnalysisSource({ type: 'image', imageUrl: 'https://x/y.png' })).toBeNull();
+ expect(moodBoardItemAnalysisSource({ type: 'image', mediaKey: 'video:abc', imageUrl: 'https://x/t.jpg' })).toBeNull();
+ expect(moodBoardItemAnalysisSource({ type: 'video', mediaKey: null })).toBeNull();
+ expect(moodBoardItemAnalysisSource(null)).toBeNull();
+ });
+});
diff --git a/client/src/pages/MoodBoardDetail.jsx b/client/src/pages/MoodBoardDetail.jsx
index e8a10e489f..002d2c35ad 100644
--- a/client/src/pages/MoodBoardDetail.jsx
+++ b/client/src/pages/MoodBoardDetail.jsx
@@ -11,12 +11,14 @@
import { useEffect, useState, useCallback, useRef } from 'react';
import { useParams, useNavigate, Link } from 'react-router';
-import { ArrowLeft, ImageIcon, FileText, Trash2, Plus, Save, Link2, Unlink, RefreshCw, Images, Film, Play } from 'lucide-react';
+import { ArrowLeft, ImageIcon, FileText, Trash2, Plus, Save, Link2, Unlink, RefreshCw, Images, Film, Play, ScanEye, Copy } from 'lucide-react';
import PageSkeleton from '../components/ui/PageSkeleton';
import toast from '../components/ui/Toast';
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 { copyToClipboard } from '../lib/clipboard';
import {
getMoodBoard,
updateMoodBoard,
@@ -27,7 +29,7 @@ import {
unlinkMoodBoardPinterest,
syncMoodBoardPinterest,
} from '../services/api';
-import { moodBoardItemSrc, moodBoardItemVideoSrc } from '../lib/moodBoardItemSrc';
+import { moodBoardItemSrc, moodBoardItemVideoSrc, moodBoardItemAnalysisSource } from '../lib/moodBoardItemSrc';
import { timeAgo } from '../utils/formatters';
import useMounted from '../hooks/useMounted';
@@ -54,6 +56,11 @@ export default function MoodBoardDetail() {
const [videoPickerOpen, setVideoPickerOpen] = useState(false);
const [playingItemId, setPlayingItemId] = useState(null);
+ // Per-item prompt-from-media analysis (#4188 Phase 3). Track the item by id
+ // (not a snapshot) so the modal's stored-analysis view stays fresh after the
+ // persist PATCH updates the board state.
+ const [analyzeItemId, setAnalyzeItemId] = useState(null);
+
// Pinterest link/sync.
const [pinUrl, setPinUrl] = useState('');
const [linking, setLinking] = useState(false);
@@ -159,6 +166,42 @@ export default function MoodBoardDetail() {
: prev));
};
+ // Persist a prompt-from-media run onto the item (#4188 Phase 3). The
+ // analyzer can return an image and/or a video prompt; store the one that
+ // matches the item's own type, falling back to whichever was generated.
+ const persistAnalysis = async (item, result) => {
+ 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 updated = await updateMoodBoardItem(id, item.id, { analysis }, { silent: true }).catch(() => null);
+ if (!updated) { toast.error('Analysis ran but could not be saved to the item'); return; }
+ setBoard((prev) => (prev
+ ? { ...prev, items: (prev.items || []).map((it) => (it.id === item.id ? updated : it)) }
+ : prev));
+ toast.success('Analysis saved to item');
+ };
+
+ const handleClearAnalysis = async (itemId) => {
+ const updated = await updateMoodBoardItem(id, itemId, { analysis: null }, { silent: true }).catch(() => null);
+ if (!updated) { toast.error('Failed to remove analysis'); return; }
+ setBoard((prev) => (prev
+ ? { ...prev, items: (prev.items || []).map((it) => (it.id === itemId ? updated : it)) }
+ : prev));
+ };
+
const handleRemoveItem = async (itemId) => {
setConfirmingItemId(null);
const updated = await removeMoodBoardItem(id, itemId, { silent: true }).catch(() => null);
@@ -219,6 +262,7 @@ export default function MoodBoardDetail() {
}
const items = Array.isArray(board.items) ? board.items : [];
+ const analyzeItem = analyzeItemId ? (items.find((it) => it.id === analyzeItemId) || null) : null;
const linkedFeedUrl = board.pinterest?.feedUrl || '';
const linkedBoardUrl = board.pinterest?.boardUrl || '';
const lastSyncedAt = board.pinterest?.lastSyncedAt || null;
@@ -485,6 +529,7 @@ export default function MoodBoardDetail() {
{items.map((item) => {
const src = moodBoardItemSrc(item);
const videoSrc = moodBoardItemVideoSrc(item);
+ const analysisSource = moodBoardItemAnalysisSource(item);
return (
<div key={item.id} className="bg-port-card border border-port-border rounded-md overflow-hidden flex flex-col">
{item.type === 'video' && videoSrc ? (
@@ -563,15 +608,28 @@ export default function MoodBoardDetail() {
{item.source ? (
<span className="text-[10px] text-gray-500 truncate" title={item.source}>{item.source}</span>
) : <span />}
- <button
- type="button"
- onClick={() => setConfirmingItemId(item.id)}
- title="Remove item"
- aria-label="Remove item"
- className="p-1 text-gray-500 hover:text-port-error transition-colors"
- >
- <Trash2 className="w-3.5 h-3.5" aria-hidden="true" />
- </button>
+ <div className="flex items-center gap-1">
+ {analysisSource ? (
+ <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'}
+ className={`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" />
+ </button>
+ ) : null}
+ <button
+ type="button"
+ onClick={() => setConfirmingItemId(item.id)}
+ title="Remove item"
+ aria-label="Remove item"
+ className="p-1 text-gray-500 hover:text-port-error transition-colors"
+ >
+ <Trash2 className="w-3.5 h-3.5" aria-hidden="true" />
+ </button>
+ </div>
</div>
{confirmingItemId === item.id ? (
<InlineConfirmRow
@@ -601,6 +659,70 @@ export default function MoodBoardDetail() {
allowUpload
uploadToGallery
/>
+
+ {/* Per-item prompt-from-media analysis (#4188 Phase 3). A successful run
+ auto-persists onto the item; the stored analysis renders above the
+ analyzer with copy/remove. */}
+ {analyzeItem ? (
+ <PromptFromMediaModal
+ item={moodBoardItemAnalysisSource(analyzeItem)}
+ open
+ onClose={() => setAnalyzeItemId(null)}
+ kindDefault={analyzeItem.type === 'video' ? 'video' : 'image'}
+ onResult={(result) => persistAnalysis(analyzeItem, result)}
+ >
+ {analyzeItem.analysis ? (
+ <div className="mb-4 p-3 bg-port-bg border border-port-border rounded-lg space-y-2">
+ <div className="flex items-center justify-between gap-2">
+ <span className="text-[11px] uppercase tracking-wide text-gray-500">
+ Saved analysis{analyzeItem.analysis.analyzedAt ? ` · ${timeAgo(analyzeItem.analysis.analyzedAt)}` : ''}
+ </span>
+ <div className="flex items-center gap-1">
+ <button
+ type="button"
+ onClick={() => copyToClipboard(analyzeItem.analysis.prompt, 'Analysis prompt copied')}
+ className="p-1 rounded text-gray-400 hover:text-white hover:bg-port-border/50"
+ aria-label="Copy saved analysis prompt"
+ >
+ <Copy className="w-3.5 h-3.5" aria-hidden="true" />
+ </button>
+ <button
+ type="button"
+ onClick={() => handleClearAnalysis(analyzeItem.id)}
+ className="px-2 py-1 rounded text-[11px] text-gray-400 hover:text-port-error transition-colors"
+ >
+ Remove
+ </button>
+ </div>
+ </div>
+ {analyzeItem.analysis.rationale ? (
+ <p className="text-xs text-gray-300">{analyzeItem.analysis.rationale}</p>
+ ) : null}
+ <textarea
+ readOnly
+ value={analyzeItem.analysis.prompt}
+ rows={4}
+ aria-label="Saved analysis prompt"
+ className="w-full bg-port-card border border-port-border rounded-lg p-2 text-xs text-white resize-y"
+ />
+ {analyzeItem.analysis.negativePrompt ? (
+ <textarea
+ readOnly
+ value={analyzeItem.analysis.negativePrompt}
+ rows={2}
+ aria-label="Saved analysis negative prompt"
+ className="w-full bg-port-card border border-port-border rounded-lg p-2 text-xs text-gray-300 resize-y"
+ />
+ ) : null}
+ {(analyzeItem.analysis.providerId || analyzeItem.analysis.model) ? (
+ <p className="text-[10px] text-gray-500 truncate">
+ {[analyzeItem.analysis.providerId, analyzeItem.analysis.model].filter(Boolean).join(' · ')}
+ </p>
+ ) : null}
+ </div>
+ ) : null}
+ </PromptFromMediaModal>
+ ) : null}
</div>
);
}
diff --git a/client/src/pages/MoodBoardDetail.test.jsx b/client/src/pages/MoodBoardDetail.test.jsx
index 168d8945ef..a552c703bf 100644
--- a/client/src/pages/MoodBoardDetail.test.jsx
+++ b/client/src/pages/MoodBoardDetail.test.jsx
@@ -6,12 +6,13 @@ import { MemoryRouter } from 'react-router';
// ── Mocks must be declared before any imports that use them ──────────────────
const mockGetMoodBoard = vi.fn();
+const mockUpdateMoodBoardItem = vi.fn();
vi.mock('../services/api', () => ({
getMoodBoard: (...args) => mockGetMoodBoard(...args),
updateMoodBoard: vi.fn(),
addMoodBoardItem: vi.fn(),
- updateMoodBoardItem: vi.fn(),
+ updateMoodBoardItem: (...args) => mockUpdateMoodBoardItem(...args),
removeMoodBoardItem: vi.fn(),
linkMoodBoardPinterest: vi.fn(),
unlinkMoodBoardPinterest: vi.fn(),
@@ -27,6 +28,29 @@ vi.mock('../components/ui/Toast', () => ({
}),
}));
+// Stub the prompt-from-media modal (#4188 Phase 3) — the analysis flow under
+// test is the page's own wiring (open, persist via onResult, stored-analysis
+// children), not the analyzer internals, which have their own suite.
+vi.mock('../components/media/PromptFromMedia', () => ({
+ PromptFromMediaModal: ({ open, item, onResult, children }) => (open && item ? (
+ <div data-testid="pfm-modal">
+ {children}
+ <button
+ type="button"
+ onClick={() => onResult?.({
+ imagePrompt: 'a moody castle at dusk',
+ imageNegativePrompt: 'blurry',
+ rationale: 'gothic look',
+ providerId: 'openai',
+ model: 'gpt-4o',
+ })}
+ >
+ mock-generate
+ </button>
+ </div>
+ ) : null),
+}));
+
// Control the board id `useParams` returns so we can simulate the user
// navigating from one board to another mid-fetch.
let currentId = 'a';
@@ -172,3 +196,87 @@ describe('MoodBoardDetail video items (#4188)', () => {
expect(poster.getAttribute('src')).toBe('/data/video-thumbnails/downloaded-abc123.jpg');
});
});
+
+describe('MoodBoardDetail item analysis (#4188 Phase 3)', () => {
+ const galleryImageItem = {
+ id: 'i1', type: 'image', mediaKey: 'image:ref.png', imageUrl: null, caption: null, source: null,
+ };
+
+ it('offers the analyze action only on gallery-backed media items', async () => {
+ mockGetMoodBoard.mockResolvedValueOnce({
+ id: 'a',
+ name: 'Board A',
+ items: [
+ galleryImageItem,
+ { id: 'i2', type: 'text', text: 'note', caption: null, source: null },
+ { id: 'i3', type: 'image', mediaKey: null, imageUrl: 'https://x/y.png', caption: null, source: null },
+ ],
+ });
+ renderPage();
+ await waitFor(() => expect(boardNameValue()).toBe('Board A'));
+
+ // 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);
+ });
+
+ it('persists a run onto the item and flips the card to its analyzed state', async () => {
+ mockGetMoodBoard.mockResolvedValueOnce({ id: 'a', name: 'Board A', items: [galleryImageItem] });
+ const analyzedItem = {
+ ...galleryImageItem,
+ analysis: {
+ prompt: 'a moody castle at dusk',
+ negativePrompt: 'blurry',
+ rationale: 'gothic look',
+ providerId: 'openai',
+ model: 'gpt-4o',
+ analyzedAt: '2026-08-14T00:00:00.000Z',
+ },
+ };
+ mockUpdateMoodBoardItem.mockResolvedValueOnce(analyzedItem);
+ renderPage();
+ await waitFor(() => expect(boardNameValue()).toBe('Board A'));
+
+ fireEvent.click(screen.getByRole('button', { name: 'Analyze with AI' }));
+ expect(screen.getByTestId('pfm-modal')).toBeInTheDocument();
+
+ fireEvent.click(screen.getByRole('button', { name: 'mock-generate' }));
+ await waitFor(() => {
+ expect(mockUpdateMoodBoardItem).toHaveBeenCalledWith('a', 'i1', {
+ analysis: {
+ prompt: 'a moody castle at dusk',
+ negativePrompt: 'blurry',
+ rationale: 'gothic look',
+ providerId: 'openai',
+ model: 'gpt-4o',
+ },
+ }, { silent: true });
+ });
+
+ // 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' });
+ expect(screen.getByLabelText('Saved analysis prompt')).toHaveValue('a moody castle at dusk');
+ });
+
+ it('removes a stored analysis via the modal', async () => {
+ const analyzed = {
+ ...galleryImageItem,
+ analysis: {
+ prompt: 'a moody castle at dusk', negativePrompt: null, rationale: null,
+ providerId: null, model: null, analyzedAt: '2026-08-14T00:00:00.000Z',
+ },
+ };
+ mockGetMoodBoard.mockResolvedValueOnce({ id: 'a', name: 'Board A', items: [analyzed] });
+ mockUpdateMoodBoardItem.mockResolvedValueOnce({ ...galleryImageItem, analysis: null });
+ renderPage();
+ await waitFor(() => expect(boardNameValue()).toBe('Board A'));
+
+ fireEvent.click(screen.getByRole('button', { name: 'View AI analysis' }));
+ 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' });
+ });
+});
diff --git a/server/lib/moodBoardValidation.js b/server/lib/moodBoardValidation.js
index 7f0191db5d..f25200f938 100644
--- a/server/lib/moodBoardValidation.js
+++ b/server/lib/moodBoardValidation.js
@@ -113,13 +113,31 @@ export const moodBoardPinterestLinkSchema = z.object({
),
}).strict();
+// Per-item prompt-from-media analysis (#4188 Phase 3) — written by the item
+// PATCH after a user-triggered vision run on the item's media. Additive on the
+// wire: the board federates whole-record LWW (sanitizeBoardForSync's `...raw`
+// spread) and an older peer preserves the unknown key, so no `moodBoards`
+// schema-gate bump — same precedent as the `pinterest` sub-object. Bounds
+// mirror the analyzer's own caps (MAX_PROMPT_LEN / MAX_REASON_LEN in
+// mediaPromptFromMedia.js). `null` on the PATCH clears a stored analysis.
+export const moodBoardItemAnalysisSchema = z.object({
+ prompt: z.string().trim().min(1).max(8000),
+ negativePrompt: z.string().max(8000).nullable().optional(),
+ rationale: z.string().max(1200).nullable().optional(),
+ providerId: z.string().max(128).nullable().optional(),
+ model: z.string().max(256).nullable().optional(),
+ analyzedAt: z.string().datetime({ offset: true }).nullable().optional(),
+}).strict();
+
// Item PATCH — caption/source on any item, plus the type-appropriate body
// field. No `type` switch (an item's kind is fixed at creation); every field
-// optional so a partial edit validates.
+// optional so a partial edit validates. `analysis` applies to media items
+// only (enforced in logic.js where the item's type is known).
export const moodBoardItemUpdateSchema = z.object({
caption: captionSchema,
source: sourceSchema,
text: z.string().trim().max(10000).nullable().optional(),
imageUrl: imageUrlSchema.nullable().optional(),
mediaKey: mediaKeySchema.nullable().optional(),
+ analysis: moodBoardItemAnalysisSchema.nullable().optional(),
}).strict();
diff --git a/server/lib/moodBoardValidation.test.js b/server/lib/moodBoardValidation.test.js
index 2feb859982..081f8eb785 100644
--- a/server/lib/moodBoardValidation.test.js
+++ b/server/lib/moodBoardValidation.test.js
@@ -102,4 +102,27 @@ describe('moodBoardItemUpdateSchema', () => {
it('accepts a null caption (clear)', () => {
expect(moodBoardItemUpdateSchema.parse({ caption: null }).caption).toBeNull();
});
+ it('accepts a full and a minimal analysis patch (#4188 Phase 3)', () => {
+ const full = moodBoardItemUpdateSchema.parse({
+ analysis: {
+ prompt: 'a moody castle at dusk',
+ negativePrompt: 'blurry',
+ rationale: 'gothic look',
+ providerId: 'openai',
+ model: 'gpt-4o',
+ analyzedAt: '2026-08-14T00:00:00.000Z',
+ },
+ });
+ expect(full.analysis.prompt).toBe('a moody castle at dusk');
+ expect(moodBoardItemUpdateSchema.parse({ analysis: { prompt: 'p' } }).analysis.prompt).toBe('p');
+ });
+ it('accepts a null analysis (clear)', () => {
+ expect(moodBoardItemUpdateSchema.parse({ analysis: null }).analysis).toBeNull();
+ });
+ it('rejects an analysis without a prompt, with unknown keys, or with a non-ISO analyzedAt', () => {
+ expect(() => moodBoardItemUpdateSchema.parse({ analysis: {} })).toThrow();
+ expect(() => moodBoardItemUpdateSchema.parse({ analysis: { prompt: ' ' } })).toThrow();
+ expect(() => moodBoardItemUpdateSchema.parse({ analysis: { prompt: 'p', extra: true } })).toThrow();
+ expect(() => moodBoardItemUpdateSchema.parse({ analysis: { prompt: 'p', analyzedAt: 'yesterday' } })).toThrow();
+ });
});
diff --git a/server/routes/mediaJobs.js b/server/routes/mediaJobs.js
index 51c12be049..657fc02e18 100644
--- a/server/routes/mediaJobs.js
+++ b/server/routes/mediaJobs.js
@@ -85,8 +85,10 @@ const promptFromMediaSchema = z.object({
return v.length > 0 ? v : undefined;
}),
}).superRefine((data, ctx) => {
- if (data.sourceKind === 'video' && !data.videoId) {
- ctx.addIssue({ code: z.ZodIssueCode.custom, message: 'videoId is required for a gallery video', path: ['videoId'] });
+ // A gallery video resolves by history id (the gallery flow) OR by on-disk
+ // filename (a mood-board video item's `video:<filename>` ref — #4188).
+ if (data.sourceKind === 'video' && !data.videoId && !data.filename) {
+ ctx.addIssue({ code: z.ZodIssueCode.custom, message: 'videoId or filename is required for a gallery video', path: ['videoId'] });
}
if ((data.sourceKind === 'image' || data.sourceKind === 'upload') && !data.filename) {
ctx.addIssue({ code: z.ZodIssueCode.custom, message: 'filename is required', path: ['filename'] });
diff --git a/server/routes/mediaJobs.test.js b/server/routes/mediaJobs.test.js
index 843b7e6145..e2da1c646c 100644
--- a/server/routes/mediaJobs.test.js
+++ b/server/routes/mediaJobs.test.js
@@ -82,6 +82,15 @@ describe('mediaJobs routes', () => {
expect(r.status).toBe(400);
});
+ it('POST /prompt-from-media 400s when a video source has neither videoId nor filename (#4188)', async () => {
+ const r = await request(makeApp()).post('/api/media-jobs/prompt-from-media').send({
+ sourceKind: 'video',
+ targets: ['video'],
+ providerId: 'openai',
+ });
+ expect(r.status).toBe(400);
+ });
+
it('POST /:id/retry 404s for unknown id', async () => {
const r = await request(makeApp()).post('/api/media-jobs/nope/retry').send({});
expect(r.status).toBe(404);
diff --git a/server/services/mediaPromptFromMedia.js b/server/services/mediaPromptFromMedia.js
index f66a2da2fc..d9bdd6a1d2 100644
--- a/server/services/mediaPromptFromMedia.js
+++ b/server/services/mediaPromptFromMedia.js
@@ -204,6 +204,25 @@ async function resolveVideoSource(videoId) {
return sampleVideoFrames(videoPath, `pfm-${videoId}`);
}
+// A mood-board video item (#4188) references its clip by on-disk FILENAME
+// (`video:<file>.mp4` — see isVideoItemMediaKey), not by history id, so the
+// board's analyze flow resolves a gallery video directly by filename instead
+// of a history lookup. safeUnder guards traversal; the extension gate keeps
+// this to actual clip files.
+async function resolveVideoFilename(filename) {
+ if (!VIDEO_EXT_RE.test(filename || '')) {
+ throw new ServerError(`Not a gallery video filename: ${filename}`, {
+ status: 400,
+ code: 'VALIDATION_ERROR',
+ });
+ }
+ const videoPath = safeUnder(PATHS.videos, filename);
+ if (!videoPath || !existsSync(videoPath)) {
+ throw new ServerError('Video file not found on disk', { status: 404, code: 'NOT_FOUND' });
+ }
+ return sampleVideoFrames(videoPath, `pfm-vf-${randomUUID()}`);
+}
+
async function resolveUploadSource(filename) {
const uploadPath = safeUnder(PATHS.uploads, filename);
if (!uploadPath || !existsSync(uploadPath)) {
@@ -226,7 +245,7 @@ async function resolveUploadSource(filename) {
async function resolvePromptFromMediaSource({ sourceKind, filename, videoId }) {
if (sourceKind === 'image') return resolveImagePath(filename);
- if (sourceKind === 'video') return resolveVideoSource(videoId);
+ if (sourceKind === 'video') return videoId ? resolveVideoSource(videoId) : resolveVideoFilename(filename);
if (sourceKind === 'upload') return resolveUploadSource(filename);
throw new ServerError(`Unsupported sourceKind "${sourceKind}"`, {
status: 400,
diff --git a/server/services/mediaPromptFromMedia.test.js b/server/services/mediaPromptFromMedia.test.js
index bcc95e020d..9b36f8f886 100644
--- a/server/services/mediaPromptFromMedia.test.js
+++ b/server/services/mediaPromptFromMedia.test.js
@@ -193,6 +193,38 @@ describe('promptFromMedia', () => {
expect(result.frameCount).toBe(2);
});
+ it('resolves a gallery video by FILENAME when no videoId is given (mood-board item — #4188)', async () => {
+ providers.getProviderById.mockResolvedValue(CLI_PROVIDER);
+ visionCli.describeImagesFromPaths.mockResolvedValue({ text: JSON_BOTH });
+
+ const result = await promptFromMedia({
+ sourceKind: 'video',
+ filename: 'clip.webm',
+ targets: ['video'],
+ providerId: 'codex',
+ });
+
+ expect(history.loadHistory).not.toHaveBeenCalled();
+ expect(ffmpeg.extractEvaluationFrames).toHaveBeenCalledWith(
+ '/mock/videos/clip.webm',
+ expect.stringMatching(/^pfm-vf-/),
+ expect.any(Number),
+ );
+ expect(result.mediaKind).toBe('video');
+ expect(result.videoPrompt).toContain('dollies');
+ });
+
+ it('rejects an extension-less video filename (a bare id is not an on-disk clip name)', async () => {
+ providers.getProviderById.mockResolvedValue(CLI_PROVIDER);
+ await expect(promptFromMedia({
+ sourceKind: 'video',
+ filename: 'job-123',
+ targets: ['video'],
+ providerId: 'codex',
+ })).rejects.toMatchObject({ code: 'VALIDATION_ERROR', status: 400 });
+ expect(ffmpeg.extractEvaluationFrames).not.toHaveBeenCalled();
+ });
+
it('rejects a text-only CLI that cannot see images', async () => {
providers.getProviderById.mockResolvedValue({
id: 'opencode',
diff --git a/server/services/moodBoard/logic.js b/server/services/moodBoard/logic.js
index 2cc17a6c43..5116880810 100644
--- a/server/services/moodBoard/logic.js
+++ b/server/services/moodBoard/logic.js
@@ -179,6 +179,23 @@ export function addItem(board, itemInput) {
return { board: next, item };
}
+// Normalize a validated prompt-from-media analysis patch (#4188 Phase 3) into
+// the stored shape: absent optional fields become explicit nulls and
+// `analyzedAt` is stamped server-side when the client didn't send one, so
+// every stored analysis carries a wall clock for the "analyzed N ago"
+// affordance. `null` clears a stored analysis.
+function normalizeItemAnalysis(analysis, now = nowIso()) {
+ if (!analysis) return null;
+ return {
+ prompt: analysis.prompt,
+ negativePrompt: analysis.negativePrompt ?? null,
+ rationale: analysis.rationale ?? null,
+ providerId: analysis.providerId ?? null,
+ model: analysis.model ?? null,
+ analyzedAt: analysis.analyzedAt ?? now,
+ };
+}
+
// PATCH a single item's editable fields. caption/source apply to any item;
// the body fields are gated to the item's FIXED type (an item's kind can't
// change after creation) so a patch can't make a text item carry an imageUrl
@@ -193,12 +210,20 @@ export function updateItem(board, itemId, patch) {
}
const current = items[idx];
const updated = { ...current };
- const editableKeys = current.type === 'image' || current.type === 'video'
+ const isMediaItem = current.type === 'image' || current.type === 'video';
+ const editableKeys = isMediaItem
? ['caption', 'source', 'imageUrl', 'mediaKey']
: ['caption', 'source', 'text'];
for (const key of editableKeys) {
if (patch[key] !== undefined) updated[key] = patch[key];
}
+ // Analysis (#4188 Phase 3) comes from the item's media, so it only applies
+ // to media items — a patch carrying it for a text item is silently ignored,
+ // matching how the other type-gated keys behave. Stored normalized (explicit
+ // nulls + stamped analyzedAt); `null` clears.
+ if (isMediaItem && patch.analysis !== undefined) {
+ updated.analysis = normalizeItemAnalysis(patch.analysis);
+ }
// Reject a patch that would strip the item's required content (the schema
// permits nulls so a partial edit can clear one of two image sources, but the
// MERGED result must stay valid): an image keeps at least one of
diff --git a/server/services/moodBoard/logic.test.js b/server/services/moodBoard/logic.test.js
index ee57db1be2..cfd5c66bb7 100644
--- a/server/services/moodBoard/logic.test.js
+++ b/server/services/moodBoard/logic.test.js
@@ -144,6 +144,35 @@ describe('updateItem', () => {
expect(() => updateItem(board, vidId, { mediaKey: 'image:foo.png' })).toThrow(/mediaKey/i);
expect(() => updateItem(board, vidId, { mediaKey: 'video:job-123' })).toThrow(/mediaKey/i);
});
+ it('persists a normalized analysis on a media item and clears it with null (#4188 Phase 3)', () => {
+ const { board } = addItem(buildBoardRecord({ name: 'A' }, { id: 'mb-5', now: 't0' }), { type: 'image', imageUrl: 'https://x/y.png' });
+ const imgId = board.items[0].id;
+ const { board: analyzed, item } = updateItem(board, imgId, { analysis: { prompt: 'a moody castle' } });
+ expect(item.analysis).toMatchObject({
+ prompt: 'a moody castle',
+ negativePrompt: null,
+ rationale: null,
+ providerId: null,
+ model: null,
+ });
+ // analyzedAt is stamped server-side when the client didn't send one.
+ expect(typeof item.analysis.analyzedAt).toBe('string');
+ expect(item.analysis.analyzedAt.length).toBeGreaterThan(0);
+ // Other patches leave the stored analysis untouched.
+ const { board: captioned, item: kept } = updateItem(analyzed, imgId, { caption: 'c' });
+ expect(kept.analysis.prompt).toBe('a moody castle');
+ const { item: cleared } = updateItem(captioned, imgId, { analysis: null });
+ expect(cleared.analysis).toBeNull();
+ });
+ it('keeps a client-provided analyzedAt on a video item and ignores analysis on a text item', () => {
+ const { board } = addItem(buildBoardRecord({ name: 'A' }, { id: 'mb-6', now: 't0' }), { type: 'video', mediaKey: 'video:a.mp4' });
+ const vidId = board.items[0].id;
+ const { item } = updateItem(board, vidId, { analysis: { prompt: 'motion', analyzedAt: '2026-08-14T00:00:00.000Z' } });
+ expect(item.analysis.analyzedAt).toBe('2026-08-14T00:00:00.000Z');
+ // Analysis comes from the item's media, so a text item never gains one.
+ const { item: textItem } = updateItem(withItem, itemId, { analysis: { prompt: 'nope' } });
+ expect(textItem.analysis).toBeUndefined();
+ });
});
describe('removeItem', () => {