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

fix: keep mood board analysis running on the server and show progress when returning to the page

Adam Eivyae8b2dd3f783
diff --git a/client/src/components/moodBoard/MoodBoardStylePanel.jsx b/client/src/components/moodBoard/MoodBoardStylePanel.jsx
index bf1816d561..dc071f9b19 100644
--- a/client/src/components/moodBoard/MoodBoardStylePanel.jsx
+++ b/client/src/components/moodBoard/MoodBoardStylePanel.jsx
@@ -8,7 +8,8 @@
* 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 { useCallback, useEffect, useRef, useState } from 'react';
+import socket from '../../services/socket';
import { ScanEye, Sparkles, ImageIcon } from 'lucide-react';
import ProviderModelSelector from '../ProviderModelSelector';
import MediaJobThumb from '../pipeline/MediaJobThumb';
@@ -18,14 +19,13 @@ 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, backfillMoodBoardPrompts } from '../../services/api';
+import { getMoodBoard, getMoodBoardAnalyze, startMoodBoardAnalyze, updateMoodBoard, composeMoodBoardPrompt } from '../../services/api';
import { isVisionCapableCliProvider, visionLocalModelFilter } from '../../utils/providers';
import { formatCount } from '../../utils/formatters';
-import { moodBoardItemAnalysisSource, moodBoardPosterSrc } from '../../lib/moodBoardItemSrc';
+import { moodBoardPosterSrc } from '../../lib/moodBoardItemSrc';
import {
boardAnalyzePlan,
boardPosterRenderCfg,
- moodBoardAnalysisFromResult,
posterStyleKey,
} from '../../lib/moodBoardAnalysis';
import { modeLabel } from '../../lib/imageGenBackends';
@@ -50,8 +50,13 @@ export default function MoodBoardStylePanel({ board, onBoardChange }) {
setNegative(savedNegative);
}
- const [busy, setBusy] = useState(false);
- const [progress, setProgress] = useState('');
+ const [composing, setComposing] = useState(false);
+ const [job, setJob] = useState(null);
+ const jobRunning = job?.status === 'running';
+ const busy = composing || jobRunning;
+ const boardId = board?.id;
+ const jobRunningRef = useRef(false);
+ jobRunningRef.current = jobRunning;
const [savingStyle, setSavingStyle] = useState(false);
const [rendererMode, setRendererMode] = useState('');
const capturedKeyRef = useRef(null);
@@ -115,12 +120,6 @@ export default function MoodBoardStylePanel({ board, onBoardChange }) {
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,
@@ -139,65 +138,74 @@ export default function MoodBoardStylePanel({ board, onBoardChange }) {
return updated;
};
+ // The analyze run lives on the server, so leaving the page never cancels it.
+ // Restore its state on mount and follow the push events while it runs.
+ const applyJob = useCallback(async (next) => {
+ if (!mountedRef.current) return;
+ setJob(next);
+ // Pull in the analyses saved so far, and the composed style once it ends.
+ const fresh = await getMoodBoard(boardId, { silent: true }).catch(() => null);
+ if (mountedRef.current && fresh) onBoardChange(fresh);
+ }, [boardId, mountedRef, onBoardChange]);
+
+ useEffect(() => {
+ if (!boardId) return undefined;
+ let cancelled = false;
+ getMoodBoardAnalyze(boardId, { silent: true })
+ .then((current) => {
+ if (cancelled || !current) return;
+ // A finished run from earlier is only news if it just ended.
+ if (current.status === 'running') applyJob(current);
+ })
+ .catch(() => {});
+ const onEvent = (evt) => {
+ if (evt?.boardId !== boardId) return;
+ const wasRunning = jobRunningRef.current;
+ if (evt.status === 'running') applyJob(evt);
+ else {
+ applyJob(evt);
+ if (wasRunning) {
+ if (evt.status === 'done') toast.success('Board style composed from item analyses');
+ else toast.error(evt.error || 'Board analysis failed');
+ }
+ }
+ };
+ socket.on('mood-board:analyze', onEvent);
+ return () => {
+ cancelled = true;
+ socket.off('mood-board:analyze', onEvent);
+ };
+ }, [boardId, applyJob]);
+
+ const jobProgress = jobRunning
+ ? (job.phase === 'composing'
+ ? 'Composing board style…'
+ : job.total > 0
+ ? `Analyzing ${formatCount(Math.min(job.done + 1, job.total))} of ${formatCount(job.total)}`
+ : 'Preparing…')
+ : '';
+
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;
- // Adopt gallery prompts for older pins first so they aren't re-analyzed.
- const filled = await backfillMoodBoardPrompts(board.id, { silent: true }).catch(() => null);
- if (!mountedRef.current) return;
- const activePlan = filled ? boardAnalyzePlan(filled.items) : plan;
- if (filled) onBoardChange(filled);
- const pending = activePlan.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 = activePlan.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 started = await startMoodBoardAnalyze(board.id, {
+ providerId: selectedProviderId,
+ model: selectedModel || undefined,
+ }, { silent: true }).catch((err) => {
+ toast.error(err?.message || 'Could not start the board analysis');
+ return null;
+ });
+ if (mountedRef.current && started) setJob(started);
};
const composeOnly = async () => {
if (!board?.id || busy) return;
- setBusy(true);
+ setComposing(true);
await compose();
- if (mountedRef.current) setBusy(false);
+ if (mountedRef.current) setComposing(false);
};
const saveStyle = async () => {
@@ -291,7 +299,7 @@ export default function MoodBoardStylePanel({ board, onBoardChange }) {
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'}
+ {jobRunning ? jobProgress : 'Analyze board'}
</button>
) : null}
{showCompose ? (
diff --git a/client/src/components/moodBoard/MoodBoardStylePanel.test.jsx b/client/src/components/moodBoard/MoodBoardStylePanel.test.jsx
index 2ce8b01fc5..5ca0355126 100644
--- a/client/src/components/moodBoard/MoodBoardStylePanel.test.jsx
+++ b/client/src/components/moodBoard/MoodBoardStylePanel.test.jsx
@@ -1,27 +1,36 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
-import { render, screen, waitFor } from '@testing-library/react';
+import { render, screen, waitFor, act } 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,
+ mockRender, mockCompose, mockStart, mockGetJob, mockGetBoard, mockUpdateBoard, socketHandlers,
} = vi.hoisted(() => ({
+ mockStart: vi.fn(),
+ mockGetJob: vi.fn(),
+ mockGetBoard: vi.fn(),
+ socketHandlers: new Map(),
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),
- backfillMoodBoardPrompts: async () => null,
- updateMoodBoardItem: (...args) => mockUpdateItem(...args),
+ startMoodBoardAnalyze: (...args) => mockStart(...args),
+ getMoodBoardAnalyze: (...args) => mockGetJob(...args),
+ getMoodBoard: (...args) => mockGetBoard(...args),
updateMoodBoard: (...args) => mockUpdateBoard(...args),
}));
+vi.mock('../../services/socket', () => ({
+ default: {
+ on: (evt, fn) => socketHandlers.set(evt, fn),
+ off: (evt) => socketHandlers.delete(evt),
+ },
+}));
+
vi.mock('../ui/Toast', () => ({
default: { success: vi.fn(), error: vi.fn(), warning: vi.fn() },
}));
@@ -77,10 +86,10 @@ beforeEach(() => {
...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,
- }));
+ mockGetJob.mockResolvedValue(null);
+ mockGetBoard.mockResolvedValue(analyzedBoard);
+ mockStart.mockResolvedValue({ boardId: 'mb-1', status: 'running', phase: 'preparing', total: 0, done: 0 });
+ socketHandlers.clear();
mockUpdateBoard.mockImplementation(async (_id, patch) => ({ ...analyzedBoard, ...patch }));
});
@@ -91,30 +100,30 @@ describe('MoodBoardStylePanel', () => {
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(mockStart).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' }],
- };
+ it('starts the server-side analyze job and shows its progress', 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 });
+ expect(mockStart).toHaveBeenCalledWith('mb-1', { providerId: 'vision-1', model: 'vlm' }, { silent: true });
+ await act(async () => {
+ socketHandlers.get('mood-board:analyze')({ boardId: 'mb-1', status: 'running', phase: 'analyzing', total: 4, done: 1 });
+ });
+ expect(screen.getByRole('button', { name: /Analyzing 2 of 4/ })).toBeDisabled();
+ });
+
+ it('picks the run back up after navigating away and returning', async () => {
+ mockGetJob.mockResolvedValue({ boardId: 'mb-1', status: 'running', phase: 'analyzing', total: 5, done: 2 });
+ const board = { id: 'mb-1', items: [{ id: 'b', type: 'image', mediaKey: 'image:b.png' }] };
+ render(<MoodBoardStylePanel board={board} onBoardChange={vi.fn()} />);
+ expect(await screen.findByRole('button', { name: /Analyzing 3 of 5/ })).toBeDisabled();
+ expect(mockStart).not.toHaveBeenCalled();
});
it('renders the poster on the selected image service and pins the filename', async () => {
diff --git a/client/src/services/apiMoodBoard.js b/client/src/services/apiMoodBoard.js
index 46990b1f76..5eb65791fa 100644
--- a/client/src/services/apiMoodBoard.js
+++ b/client/src/services/apiMoodBoard.js
@@ -54,6 +54,18 @@ export const removeMoodBoardItem = (id, itemId, options) =>
export const backfillMoodBoardPrompts = (id, options = {}) =>
request(`/mood-boards/${encodeURIComponent(id)}/backfill-prompts`, { method: 'POST', ...options });
+// Board analyze runs server-side so it survives navigation: start (or join) the
+// job, and read its live state on return. `null` = no run since server start.
+export const startMoodBoardAnalyze = (id, { providerId, model } = {}, options = {}) =>
+ request(`/mood-boards/${encodeURIComponent(id)}/analyze`, {
+ method: 'POST',
+ body: JSON.stringify({ providerId, model }),
+ ...options,
+ });
+
+export const getMoodBoardAnalyze = (id, options = {}) =>
+ request(`/mood-boards/${encodeURIComponent(id)}/analyze`, 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 = {}) =>
diff --git a/server/lib/socketEventContracts.js b/server/lib/socketEventContracts.js
index ae0e861d86..673a050c7b 100644
--- a/server/lib/socketEventContracts.js
+++ b/server/lib/socketEventContracts.js
@@ -328,6 +328,26 @@ export const SOCKET_EVENT_CONTRACTS = Object.freeze({
payloadSchema: { type: 'object', properties: { id: { type: 'string' } }, required: ['id'], additionalProperties: false },
},
+ 'mood-board:analyze': {
+ direction: 'server-to-client',
+ summary: 'Progress of a mood board analyze run (prompt-from-media over pins, then style compose) so a reopened board page can resume showing it.',
+ payloadSchema: {
+ type: 'object',
+ properties: {
+ boardId: { type: 'string' },
+ status: { type: 'string', enum: ['running', 'done', 'failed'] },
+ phase: { type: ['string', 'null'] },
+ total: { type: 'integer' },
+ done: { type: 'integer' },
+ failures: { type: 'integer' },
+ error: { type: ['string', 'null'] },
+ startedAt: { type: 'string' },
+ finishedAt: { type: ['string', 'null'] },
+ },
+ required: ['boardId', 'status'],
+ additionalProperties: false,
+ },
+ },
'brain:changed': {
direction: 'server-to-client',
summary: 'Invalidate Brain summary/settings after a persisted change.',
diff --git a/server/routes/moodBoard.js b/server/routes/moodBoard.js
index fcd8a5be07..88127e5cb2 100644
--- a/server/routes/moodBoard.js
+++ b/server/routes/moodBoard.js
@@ -26,6 +26,7 @@ import {
import { influencesSchema, lockedSchema } from './universeBuilder/shared.js';
import { synthesizeBoardStyle } from '../services/moodBoardStyleSynthesis.js';
import { composeBoardPrompt } from '../services/moodBoardCompositeStyle.js';
+import { startAnalyzeJob, getAnalyzeJob } from '../services/moodBoard/analyzeJob.js';
import { STYLE_NOTES_MAX } from '../services/universeBuilder.js';
import {
listBoards,
@@ -141,6 +142,23 @@ router.post('/:id/backfill-prompts', asyncHandler(async (req, res) => {
res.json(board);
}));
+// Background analyze job: prompt-from-media over un-analyzed pins, then compose
+// the board style. Survives the page unmounting; progress follows the
+// `mood-board:analyze` socket event and GET restores it on return.
+const analyzeSchema = composePromptSchema.extend({
+ providerId: z.string().trim().min(1).max(128),
+}).strict();
+router.post('/:id/analyze', asyncHandler(async (req, res) => {
+ const body = validateRequest(analyzeSchema, req.body ?? {});
+ const board = await getBoard(req.params.id);
+ if (!board) throw new ServerError('Mood board not found', { status: 404, code: 'NOT_FOUND' });
+ res.status(202).json(startAnalyzeJob(req.params.id, body));
+}));
+
+router.get('/:id/analyze', asyncHandler(async (req, res) => {
+ res.json(getAnalyzeJob(req.params.id));
+}));
+
router.post('/:id/compose-prompt', asyncHandler(async (req, res) => {
const body = validateRequest(composePromptSchema, req.body ?? {});
const board = await getBoard(req.params.id);
diff --git a/server/services/moodBoard/analyzeJob.js b/server/services/moodBoard/analyzeJob.js
new file mode 100644
index 0000000000..092a3b9771
--- /dev/null
+++ b/server/services/moodBoard/analyzeJob.js
@@ -0,0 +1,143 @@
+/**
+ * Board-level "analyze pins" job.
+ *
+ * Runs prompt-from-media over every pin that has no prompt yet, then composes
+ * the board style — on the SERVER, so navigating away from the board page (or
+ * closing the tab) doesn't abandon a long vision run. The page reads the live
+ * state from `getAnalyzeJob` on mount and follows `mood-board:analyze` events.
+ *
+ * One job per board, kept in memory only: a run is a user-triggered, minutes
+ * long operation, and the finished per-item analyses are persisted on the board
+ * itself. The last terminal state is retained until the next run so a page that
+ * reopens right after completion can still report the outcome.
+ */
+
+import { isNonBlankStr as hasText } from '../../lib/textUtils.js';
+import { promptFromMedia } from '../mediaPromptFromMedia.js';
+import { composeBoardPrompt } from '../moodBoardCompositeStyle.js';
+import { boardItemLocalImage } from './logic.js';
+import { getBoard, updateBoard, updateBoardItem, backfillGalleryPrompts } from './index.js';
+
+const jobs = new Map();
+
+function itemHasPrompt(item) {
+ if (hasText(item?.analysis?.prompt) || hasText(item?.prompt)) return true;
+ const galleryKey = typeof item?.mediaKey === 'string' && /^(image|video):/.test(item.mediaKey);
+ return galleryKey && hasText(item?.caption);
+}
+
+// `{ kind, filename }` for an item prompt-from-media can read, else null.
+function analysisSource(item) {
+ if (item?.type === 'video') {
+ const key = item.mediaKey;
+ const filename = typeof key === 'string' && key.startsWith('video:') ? key.slice('video:'.length) : '';
+ return filename ? { kind: 'video', filename } : null;
+ }
+ const local = boardItemLocalImage(item);
+ return local ? { kind: 'image', filename: local.filename } : null;
+}
+
+export function analysisFromResult(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 = hasText(primary);
+ const prompt = usedPrimary ? primary : fallback;
+ if (!hasText(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,
+ };
+}
+
+function pendingItems(board) {
+ return (Array.isArray(board?.items) ? board.items : [])
+ .filter((it) => (it?.type === 'image' || it?.type === 'video') && !itemHasPrompt(it) && analysisSource(it));
+}
+
+function publish(job) {
+ import('../socket.js')
+ .then(({ getIo }) => getIo()?.emit('mood-board:analyze', { ...job }))
+ .catch((err) => console.error(`❌ mood-board analyze emit failed: ${err.message}`));
+}
+
+function update(job, patch) {
+ Object.assign(job, patch);
+ publish(job);
+}
+
+async function run(job, { providerId, model }) {
+ const { boardId } = job;
+ const filled = await backfillGalleryPrompts(boardId);
+ if (!filled) throw new Error('Mood board not found');
+ const pending = pendingItems(filled);
+ update(job, { phase: 'analyzing', total: pending.length, done: 0 });
+
+ let failures = 0;
+ for (const item of pending) {
+ const source = analysisSource(item);
+ const data = await promptFromMedia({
+ sourceKind: source.kind,
+ filename: source.filename,
+ targets: source.kind === 'video' ? ['image', 'video'] : ['image'],
+ providerId,
+ model,
+ }).catch((err) => {
+ console.warn(`⚠️ mood-board ${boardId} item ${item.id} analysis failed: ${err.message}`);
+ return null;
+ });
+ const analysis = analysisFromResult(item, data);
+ const saved = analysis
+ ? await updateBoardItem(boardId, item.id, { analysis }).catch(() => null)
+ : null;
+ if (!saved) failures += 1;
+ update(job, { done: job.done + 1, failures });
+ }
+
+ const board = await getBoard(boardId);
+ const analyzedCount = (board?.items || []).filter(itemHasPrompt).length;
+ if (analyzedCount < 1) {
+ update(job, { status: 'failed', phase: null, error: 'No item could be analyzed, so the board style was not composed', finishedAt: new Date().toISOString() });
+ return;
+ }
+ update(job, { phase: 'composing' });
+ const style = await composeBoardPrompt({ board, providerId, model });
+ await updateBoard(boardId, { style });
+ update(job, { status: 'done', phase: null, finishedAt: new Date().toISOString() });
+}
+
+export function getAnalyzeJob(boardId) {
+ const job = jobs.get(boardId);
+ return job ? { ...job } : null;
+}
+
+/** Start (or join, when one is already running) the analyze job for a board. */
+export function startAnalyzeJob(boardId, { providerId, model } = {}) {
+ const existing = jobs.get(boardId);
+ if (existing?.status === 'running') return { ...existing };
+ const job = {
+ boardId,
+ status: 'running',
+ phase: 'preparing',
+ total: 0,
+ done: 0,
+ failures: 0,
+ error: null,
+ startedAt: new Date().toISOString(),
+ finishedAt: null,
+ };
+ jobs.set(boardId, job);
+ publish(job);
+ run(job, { providerId, model }).catch((err) => {
+ console.error(`❌ mood-board ${boardId} analyze failed: ${err.message}`);
+ update(job, { status: 'failed', phase: null, error: err.message, finishedAt: new Date().toISOString() });
+ });
+ return { ...job };
+}
diff --git a/server/services/moodBoard/analyzeJob.test.js b/server/services/moodBoard/analyzeJob.test.js
new file mode 100644
index 0000000000..ae7c625b93
--- /dev/null
+++ b/server/services/moodBoard/analyzeJob.test.js
@@ -0,0 +1,68 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+const { getBoard, updateBoard, updateBoardItem, backfill, promptFromMedia, composeBoardPrompt, emit } = vi.hoisted(() => ({
+ getBoard: vi.fn(),
+ updateBoard: vi.fn(async () => ({})),
+ updateBoardItem: vi.fn(async (_b, id, patch) => ({ id, ...patch })),
+ backfill: vi.fn(),
+ promptFromMedia: vi.fn(),
+ composeBoardPrompt: vi.fn(async () => ({ prompt: 'composed' })),
+ emit: vi.fn(),
+}));
+
+vi.mock('./index.js', () => ({ getBoard, updateBoard, updateBoardItem, backfillGalleryPrompts: backfill }));
+vi.mock('../mediaPromptFromMedia.js', () => ({ promptFromMedia }));
+vi.mock('../moodBoardCompositeStyle.js', () => ({ composeBoardPrompt }));
+vi.mock('../socket.js', () => ({ getIo: () => ({ emit }) }));
+
+import { startAnalyzeJob, getAnalyzeJob } from './analyzeJob.js';
+
+const waitTerminal = async (id) => {
+ for (let i = 0; i < 100; i += 1) {
+ const job = getAnalyzeJob(id);
+ if (job && job.status !== 'running') return job;
+ await new Promise((r) => setTimeout(r, 5));
+ }
+ throw new Error('job never finished');
+};
+
+beforeEach(() => vi.clearAllMocks());
+
+describe('board analyze job', () => {
+ it('analyzes only unprompted pins server-side, then composes the style', async () => {
+ const items = [
+ { id: 'a', type: 'image', mediaKey: 'image:a.png' },
+ { id: 'b', type: 'image', mediaKey: 'image:b.png', analysis: { prompt: 'done already' } },
+ { id: 'c', type: 'image', imageUrl: 'https://example.com/x.png' },
+ ];
+ backfill.mockResolvedValue({ id: 'mb-run', items });
+ getBoard.mockResolvedValue({ id: 'mb-run', items });
+ promptFromMedia.mockResolvedValue({ imagePrompt: 'ink' });
+
+ const started = startAnalyzeJob('mb-run', { providerId: 'p1', model: 'm' });
+ expect(started.status).toBe('running');
+ // A second start while running joins the live job instead of double-running.
+ expect(startAnalyzeJob('mb-run', { providerId: 'p1' }).startedAt).toBe(started.startedAt);
+
+ const job = await waitTerminal('mb-run');
+ expect(job).toMatchObject({ status: 'done', total: 1, done: 1, failures: 0 });
+ expect(promptFromMedia).toHaveBeenCalledTimes(1);
+ expect(promptFromMedia).toHaveBeenCalledWith(expect.objectContaining({ filename: 'a.png', providerId: 'p1' }));
+ expect(updateBoardItem).toHaveBeenCalledWith('mb-run', 'a', { analysis: expect.objectContaining({ prompt: 'ink' }) });
+ expect(updateBoard).toHaveBeenCalledWith('mb-run', { style: { prompt: 'composed' } });
+ expect(emit).toHaveBeenCalledWith('mood-board:analyze', expect.objectContaining({ boardId: 'mb-run' }));
+ });
+
+ it('fails without composing when no pin could be analyzed', async () => {
+ const items = [{ id: 'a', type: 'image', mediaKey: 'image:a.png' }];
+ backfill.mockResolvedValue({ id: 'mb-fail', items });
+ getBoard.mockResolvedValue({ id: 'mb-fail', items });
+ promptFromMedia.mockRejectedValue(new Error('vision down'));
+
+ startAnalyzeJob('mb-fail', { providerId: 'p1' });
+ const job = await waitTerminal('mb-fail');
+ expect(job.status).toBe('failed');
+ expect(job.failures).toBe(1);
+ expect(composeBoardPrompt).not.toHaveBeenCalled();
+ });
+});