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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat(mood-boards): upload images and videos directly with safe retries (#12335)
[._.]/0e04943a346a
diff --git a/client/src/components/media/MediaBatchImport.jsx b/client/src/components/media/MediaBatchImport.jsxindex 29331642b2..190d92cb9b 100644--- a/client/src/components/media/MediaBatchImport.jsx+++ b/client/src/components/media/MediaBatchImport.jsx@@ -2,12 +2,13 @@ import { useEffect, useRef, useState } from 'react';import { Upload } from 'lucide-react';import FilePickerButton from '../ui/FilePickerButton';import { importGalleryFile, assignImportedMedia } from '../../services/apiMedia';+import { pinImportedMedia } from '../../services/apiMoodBoard';import { formatCount } from '../../utils/formatters';import useMounted from '../../hooks/useMounted';const ACCEPT = 'image/png,image/jpeg,image/gif,image/webp,video/mp4,video/quicktime,video/webm,.png,.jpg,.jpeg,.gif,.webp,.mp4,.m4v,.mov,.webm,.mkv';-export default function MediaBatchImport({ collectionId, onImported }) {+export default function MediaBatchImport({ collectionId, moodBoardId, onImported }) {const [rows, setRows] = useState([]);const [busy, setBusy] = useState(false);const [stopping, setStopping] = useState(false);@@ -34,13 +35,25 @@ export default function MediaBatchImport({ collectionId, onImported }) {// Finish the current request so cancellation never misreports a durable// import as aborted. The saved reference survives assignment retries.const imported = row.saved || await importGalleryFile(row.file, { silent: true }).catch(error => {- row.error = `${error.message || 'Upload failed.'} If the connection was lost, check History before retrying.`;+ row.uncertain = !['INVALID_MEDIA_FILE', 'VALIDATION_ERROR', 'UNSUPPORTED_IMAGE', 'UNSUPPORTED_VIDEO'].includes(error.code);+ row.error = row.uncertain+ ? `${error.message || 'Upload response lost.'} The file may already be in History. Check History and pick the existing import from the gallery; Retry will not upload this file again.`+ : error.message;return null;});- if (!imported) { row.status = 'failed'; publish(); continue; }+ if (!imported) { row.status = row.uncertain ? 'uncertain' : 'failed'; publish(); continue; }row.saved = imported;let collection;- if (collectionId) {+ let boardItem;+ if (moodBoardId) {+ row.status = 'assigning';+ publish();+ boardItem = await pinImportedMedia(moodBoardId, imported, { silent: true }).catch(error => {+ row.error = `Imported to History; mood board assignment failed: ${error.message}. Retry will only pin the existing import.`;+ return null;+ });+ if (!boardItem) { row.status = 'failed'; publish(); continue; }+ } else if (collectionId) {row.status = 'assigning';publish();const assigned = await assignImportedMedia(collectionId, imported, { silent: true }).catch(error => {@@ -52,7 +65,7 @@ export default function MediaBatchImport({ collectionId, onImported }) {}row.status = 'done';publish();- if (mounted.current) importedCallback.current?.(imported, collection);+ if (mounted.current) importedCallback.current?.(imported, collection, boardItem);}publish();running.current = false;@@ -63,6 +76,7 @@ export default function MediaBatchImport({ collectionId, onImported }) {// Keep results for retry/accounting, but completed files leave the visible queue.const pending = rows.filter(row => ['queued', 'uploading', 'assigning'].includes(row.status));const retryable = rows.filter(row => ['failed', 'cancelled'].includes(row.status));+ const uncertain = rows.filter(row => row.status === 'uncertain');const warnings = rows.filter(row => row.status === 'done' && row.saved.data.importWarnings?.length);const retry = () => run(rows.map(row => ['failed', 'cancelled'].includes(row.status)? { ...row, status: 'queued', error: null } : row));@@ -75,9 +89,9 @@ export default function MediaBatchImport({ collectionId, onImported }) {if (files.length) run([...rows, ...files.map(file => ({ file, status: 'queued' }))]);}}className="inline-flex min-h-[44px] items-center gap-2 rounded border border-port-border px-3 text-sm text-port-accent hover:bg-port-border/50">- <Upload className="h-4 w-4" aria-hidden="true" /> Upload / import+ <Upload className="h-4 w-4" aria-hidden="true" /> {moodBoardId ? 'Upload' : 'Upload / import'}</FilePickerButton>- <span className="text-xs text-gray-400">Images and videos · embedded prompts checked{collectionId ? ' · added to this collection' : ''}</span>+ <span className="text-xs text-gray-400">Images and videos · embedded prompts checked{moodBoardId ? ' · pinned to this mood board' : collectionId ? ' · added to this collection' : ''}</span>{busy && <button type="button" disabled={stopping} className="min-h-[44px] px-3 text-sm text-port-accent disabled:opacity-50"onClick={() => { cancelled.current = true; setStopping(true); }}>{stopping ? 'Finishing current file…' : 'Cancel remaining'}@@ -100,6 +114,10 @@ export default function MediaBatchImport({ collectionId, onImported }) {</ul><button type="button" disabled={busy} onClick={retry} className="min-h-[44px] px-3 text-sm text-port-accent disabled:opacity-50">Retry failed / cancelled</button></section>}+ {uncertain.length > 0 && <section aria-label="Uploads to check in History" className="rounded border border-port-border p-2 text-xs">+ {uncertain.map((row, index) => <p key={index} role="alert" className="break-words text-port-error">{row.file.name}: {row.error}</p>)}+ <a href="/media/history" target="_blank" rel="noreferrer" className="inline-flex min-h-[44px] items-center text-port-accent">Check Media History</a>+ </section>}{warnings.length > 0 && <section aria-label="Import warnings" className="text-xs text-port-warning">{warnings.map((row, index) => <p key={index} role="status" className="break-words">{row.file.name}: {row.saved.data.importWarnings.join(' ')}</p>)}</section>}diff --git a/client/src/components/media/MediaBatchImport.test.jsx b/client/src/components/media/MediaBatchImport.test.jsxindex 1de0eb6692..552362137f 100644--- a/client/src/components/media/MediaBatchImport.test.jsx+++ b/client/src/components/media/MediaBatchImport.test.jsx@@ -21,7 +21,7 @@ beforeEach(() => {describe('shared gallery batch import', () => {it('posts a mixed batch through the Prompt gallery endpoints and reports unsupported and failed files independently', async () => {const imported = vi.fn();- request.mockRejectedValueOnce(new Error('Image decoder rejected the bytes'));+ request.mockRejectedValueOnce(Object.assign(new Error('Image decoder rejected the bytes'), { code: 'UNSUPPORTED_IMAGE' }));render(<MediaBatchImport onImported={imported} />);pick([image, video, new File(['x'], 'unsafe.svg'), image]);await waitFor(() => expect(imported).toHaveBeenCalledTimes(2));@@ -134,7 +134,7 @@ it.each([undefined, 'collection-a'])('clears completed rows while later files re});it('keeps failed imports retryable when another batch is selected without retrying them implicitly', async () => {- request.mockRejectedValueOnce(new Error('Image decoder rejected the bytes'));+ request.mockRejectedValueOnce(Object.assign(new Error('Image decoder rejected the bytes'), { code: 'UNSUPPORTED_IMAGE' }));render(<MediaBatchImport />);pick([image]);await screen.findByText(/Image decoder rejected the bytes/);@@ -158,3 +158,18 @@ it('keeps inspection warnings separate from the completed upload queue', async (expect(screen.getByRole('region', { name: 'Import warnings' })).toHaveTextContent('clip.mp4: Embedded metadata could not be inspected.');expect(screen.queryByRole('button', { name: /Retry/ })).not.toBeInTheDocument();});+++it('keeps uncertain upload outcomes out of retry while allowing definitive failures to recover', async () => {+ request.mockRejectedValueOnce(new Error('Response lost'));+ request.mockRejectedValueOnce(Object.assign(new Error('Unsupported video bytes'), { code: 'UNSUPPORTED_VIDEO' }));+ render(<MediaBatchImport />);+ pick([image, video]);+ await screen.findByText(/Unsupported video bytes/);+ expect(screen.getByRole('region', { name: 'Uploads to check in History' })).toHaveTextContent('Retry will not upload this file again');+ expect(screen.getByRole('link', { name: 'Check Media History' })).toHaveAttribute('href', '/media/history');+ fireEvent.click(screen.getByRole('button', { name: 'Retry failed / cancelled' }));+ await screen.findByText('1 of 2 imported');+ expect(request.mock.calls.map(([path]) => path)).toEqual(['/image-gen/upload', '/video-gen/upload', '/video-gen/upload']);+ expect(screen.getByRole('region', { name: 'Uploads to check in History' })).toHaveTextContent('portrait.png');+});diff --git a/client/src/components/media/PinToMoodBoardMenu.jsx b/client/src/components/media/PinToMoodBoardMenu.jsxindex 6f4f047ea6..e77ddc5807 100644--- a/client/src/components/media/PinToMoodBoardMenu.jsx+++ b/client/src/components/media/PinToMoodBoardMenu.jsx@@ -125,7 +125,7 @@ export default function PinToMoodBoardMenu({ item, size = 'sm' }) {// The add endpoint returns the new item, not the board — merge it into the// board's items locally so the checkmark flips without a refetch.updateBoards((prev) => (prev || []).map((b) => (- b.id === board.id ? { ...b, items: [...(Array.isArray(b.items) ? b.items : []), created] } : b+ b.id === board.id ? { ...b, items: [...(Array.isArray(b.items) ? b.items : []).filter(existing => existing.id !== created.id), created] } : b)));toast.success(`Pinned to ${board.name}`);}, [pinKey, pinPayload]);@@ -156,7 +156,7 @@ export default function PinToMoodBoardMenu({ item, size = 'sm' }) {return null;});const withItem = pinnedItem- ? { ...created, items: [...(Array.isArray(created.items) ? created.items : []), pinnedItem] }+ ? { ...created, items: [...(Array.isArray(created.items) ? created.items : []).filter(existing => existing.id !== pinnedItem.id), pinnedItem] }: created;addToCollectionsState((prev) => ([...(prev || []), withItem]));if (pinError) {diff --git a/client/src/pages/MoodBoardDetail.browser.test.js b/client/src/pages/MoodBoardDetail.browser.test.jsnew file mode 100644index 0000000000..be1431dd4f--- /dev/null+++ b/client/src/pages/MoodBoardDetail.browser.test.js@@ -0,0 +1,157 @@+// @vitest-environment node+import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';+import { join } from 'node:path';+import { fileURLToPath } from 'node:url';+import { createServer } from 'vite';+import react from '@vitejs/plugin-react';+import { chromium } from 'playwright-core';+import { BROWSER_FIXTURE_STARTUP_MS, startBrowserFixture } from '../test/browserFixture.js';+import { resolveTestChrome } from '../../../scripts/lib/testChrome.js';++vi.setConfig({ testTimeout: 30000 });+const chrome = resolveTestChrome();+const root = fileURLToPath(new URL('../..', import.meta.url));+const image = { name: 'reference.png', mimeType: 'image/png', buffer: Buffer.from('isolated image fixture') };+const video = { name: 'motion.mp4', mimeType: 'video/mp4', buffer: Buffer.from('isolated video fixture') };+const savedImage = { filename: 'upload-image.png', path: '/data/images/upload-image.png', metadata: { prompt: 'Paper boat' } };+const savedVideo = { id: 'upload-video', filename: 'upload-video.mp4', thumbnail: 'upload-video.jpg', prompt: 'Clouds' };+const pixel = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jRZkAAAAASUVORK5CYII=', 'base64');++// Every request is contained by this fixture; no live API, catalog or provider.+async function openBoard(fixture, viewport) {+ const page = await fixture.browser.newPage({ viewport });+ page.setDefaultTimeout(10000);+ const boards = { a: { id: 'a', name: 'Example A', items: [] }, b: { id: 'b', name: 'Example B', items: [] } };+ const state = { calls: [], failures: 0, hold: null, release: null, errors: [] };+ page.on('pageerror', error => state.errors.push(error.message));+ await page.route('**/*', async route => {+ const url = new URL(route.request().url());+ if (url.origin !== new URL(fixture.origin).origin) return route.abort();+ if (url.pathname.startsWith('/data/')) return route.fulfill({ contentType: 'image/png', body: pixel });+ if (!url.pathname.startsWith('/api/')) return route.continue();+ const path = url.pathname.slice(4);+ state.calls.push(path);+ if (path.endsWith('/upload')) {+ if (state.hold) await state.hold;+ return route.fulfill({ json: path === '/image-gen/upload' ? savedImage : savedVideo });+ }+ const match = path.match(/^\/mood-boards\/([ab])(?:\/(items))?$/);+ if (!match) { state.errors.push(`Unexpected API: ${path}`); return route.abort(); }+ const board = boards[match[1]];+ if (!match[2]) return route.fulfill({ json: board });+ const payload = route.request().postDataJSON();+ let item = board.items.find(row => row.mediaKey === payload.mediaKey);+ if (!item) { item = { ...payload, id: `pin-${board.items.length}` }; board.items.push(item); }+ if (state.failures-- > 0) return route.fulfill({ status: 503, json: { error: 'Synthetic lost pin response' } });+ return route.fulfill({ json: item });+ });+ await page.goto(`${fixture.origin}board-test`);+ if (viewport.width < 896) await page.getByRole('navigation', { name: 'Board tools' }).getByRole('button', { name: 'Add', exact: true }).click();+ await page.getByLabel('Upload', { exact: true }).waitFor();+ return { page, boards, state };+}++describe.skipIf(!chrome)('direct mood board upload in Chromium', () => {+ let fixture;+ beforeAll(async () => {+ fixture = await startBrowserFixture({+ name: 'mood-board-upload', createServer, chromium,+ launchOptions: { executablePath: chrome, args: ['--mute-audio'] },+ viteConfig: temp => ({+ configFile: false, root, cacheDir: join(temp, 'vite-cache'),+ optimizeDeps: { entries: ['src/pages/MoodBoardDetail.jsx'], include: ['react', 'react-dom/client', 'react-router', 'lucide-react'] },+ plugins: [react(), {+ name: 'mood-board-upload-fixture', enforce: 'pre',+ resolveId(id, importer) {+ if (id === '/board-fixture.jsx') return '\0board-fixture.jsx';+ if (!importer?.endsWith('/MoodBoardDetail.jsx')) return;+ if (id === '../services/api') return join(root, 'src/services/apiMoodBoard.js');+ if (id === '../services/socket') return '\0board-socket';+ if (/MoodBoard(Generate|Style|Collage)Panel|Gallery(Image|Video)Picker|VideoFramePicker|MediaLightbox/.test(id)) return '\0board-empty';+ if (id.endsWith('/PromptFromMedia')) return '\0board-prompt';+ },+ load(id) {+ if (id === '\0board-empty') return 'export default () => null;';+ if (id === '\0board-prompt') return 'export const PromptFromMediaModal = () => null;';+ if (id === '\0board-socket') return 'export default { on() {}, off() {} };';+ if (id !== '\0board-fixture.jsx') return;+ return `+ import React from 'react';+ import { createRoot } from 'react-dom/client';+ import { MemoryRouter, Routes, Route, Link } from 'react-router';+ import MoodBoardDetail from '/src/pages/MoodBoardDetail.jsx';+ import '/src/index.css';+ const h = React.createElement;+ createRoot(document.getElementById('root')).render(+ h(MemoryRouter, { initialEntries: ['/mood-boards/a'] },+ h('nav', null, h(Link, { to: '/mood-boards/a' }, 'Example A'), ' ', h(Link, { to: '/mood-boards/b' }, 'Example B')),+ h('main', { className: 'p-4' }, h(Routes, null,+ h(Route, { path: '/mood-boards/:id', element: h(MoodBoardDetail) }))))+ );`;+ },+ configureServer(vite) {+ vite.middlewares.use('/board-test', async (_req, res) => {+ res.setHeader('Content-Type', 'text/html');+ res.end(await vite.transformIndexHtml('/board-test', '<div id="root"></div><script type="module" src="/board-fixture.jsx"></script>'));+ });+ },+ }],+ server: { host: '127.0.0.1', port: 0 },+ }),+ });+ }, BROWSER_FIXTURE_STARTUP_MS);+ afterAll(() => fixture?.close());++ it.each([{ width: 390, height: 844 }, { width: 1440, height: 900 }])('imports a mixed batch, rejects repeated actions and retries assignment at $width px', async viewport => {+ const { page, boards, state } = await openBoard(fixture, viewport);+ try {+ state.failures = 1;+ state.hold = new Promise(resolve => { state.release = resolve; });+ const [chooser] = await Promise.all([+ page.waitForEvent('filechooser'),+ page.locator('label').filter({ hasText: /^\s*Upload\s*$/ }).click(),+ ]);+ await chooser.setFiles([image, video]);+ await page.getByRole('list', { name: 'Import queue' }).waitFor();+ await page.getByLabel('Upload', { exact: true }).dispatchEvent('change');+ expect(await page.getByLabel('Upload', { exact: true }).isDisabled()).toBe(true);+ expect(state.calls.filter(path => path.endsWith('/upload'))).toHaveLength(1);+ state.release();+ await page.getByRole('button', { name: 'Retry failed / cancelled' }).waitFor();+ await page.getByText('1 of 2 imported', { exact: true }).waitFor();+ expect(await page.getByRole('list', { name: 'Import queue' }).count()).toBe(0);+ await page.getByRole('tab', { name: 'Import', exact: true }).click();+ await page.getByRole('tab', { name: 'Add', exact: true }).click();+ await page.getByRole('button', { name: 'Retry failed / cancelled' }).evaluate(button => { button.click(); button.click(); });+ await page.getByText('2 of 2 imported', { exact: true }).waitFor();+ expect(state.calls.filter(path => path.endsWith('/upload'))).toHaveLength(2);+ expect(boards.a.items.map(item => item.mediaKey)).toEqual(['image:upload-image.png', 'video:upload-video.mp4']);+ expect(await page.getByLabel('Item prompt').evaluateAll(inputs => inputs.map(input => input.value))).toEqual(['Clouds', 'Paper boat']);+ expect(await page.getByRole('region', { name: 'Imports needing attention' }).count()).toBe(0);+ expect(await page.getByRole('button', { name: 'Pick from gallery' }).isVisible()).toBe(true);+ const labelBox = await page.locator('label').filter({ hasText: /^\s*Upload\s*$/ }).boundingBox();+ expect(labelBox.x).toBeGreaterThanOrEqual(0);+ expect(labelBox.x + labelBox.width).toBeLessThanOrEqual(viewport.width);+ expect(state.errors).toEqual([]);+ } finally { state.release?.(); await page.close(); }+ });++ it('cancels remaining files and finishes an active upload on the original board after navigation', async () => {+ const { page, boards, state } = await openBoard(fixture, { width: 1100, height: 800 });+ try {+ state.hold = new Promise(resolve => { state.release = resolve; });+ await page.getByLabel('Upload', { exact: true }).setInputFiles([image, video]);+ await page.getByRole('button', { name: 'Cancel remaining' }).click();+ await page.getByRole('link', { name: 'Example B' }).click();+ await page.getByLabel('Name', { exact: true }).waitFor();+ state.release();+ await vi.waitFor(() => expect(boards.a.items).toHaveLength(1));+ expect(state.calls.filter(path => path.endsWith('/upload'))).toEqual(['/image-gen/upload']);+ expect(boards.b.items).toEqual([]);+ expect(await page.getByLabel('Name', { exact: true }).inputValue()).toBe('Example B');+ expect(await page.getByLabel('Item prompt').count()).toBe(0);+ expect(await page.getByRole('list', { name: 'Import queue' }).count()).toBe(0);+ expect(state.errors).toEqual([]);+ } finally { state.release?.(); await page.close(); }+ });+});diff --git a/client/src/pages/MoodBoardDetail.jsx b/client/src/pages/MoodBoardDetail.jsxindex 1345687cf5..f0d955b060 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 MediaBatchImport from '../components/media/MediaBatchImport';import MediaLightbox from '../components/media/MediaLightbox';import MoodBoardGeneratePanel from '../components/moodBoard/MoodBoardGeneratePanel';import MoodBoardStylePanel from '../components/moodBoard/MoodBoardStylePanel';@@ -307,7 +308,7 @@ function MoodBoardEditor({ id }) {if (!mountedRef.current) return;setAdding(false);if (!item) { toast.error('Failed to add item'); return; }- setBoard((prev) => (prev ? { ...prev, items: [...(prev.items || []), item] } : prev));+ setBoard((prev) => (prev ? { ...prev, items: [...(prev.items || []).filter(existing => existing.id !== item.id), item] } : prev));resetAddForm();};@@ -321,7 +322,7 @@ function MoodBoardEditor({ id }) {const item = await addMoodBoardItem(id, payload, { silent: true }).catch(() => null);if (!mountedRef.current) return;if (!item) { toast.error('Failed to add item'); return; }- setBoard((prev) => (prev ? { ...prev, items: [...(prev.items || []), item] } : prev));+ setBoard((prev) => (prev ? { ...prev, items: [...(prev.items || []).filter(existing => existing.id !== item.id), item] } : prev));};const handlePickGalleryImage = (picked) => {@@ -598,6 +599,14 @@ function MoodBoardEditor({ id }) {<Plus className="w-4 h-4 text-port-accent" aria-hidden="true" /><h2 className="text-sm font-medium text-white">Add item</h2></div>+ <div className="mb-3">+ <MediaBatchImport moodBoardId={id} onImported={(_media, _collection, item) => {+ setBoard(previous => previous ? {+ ...previous,+ items: [...(previous.items || []).filter(existing => existing.id !== item.id), item],+ } : previous);+ }} />+ </div><div className="flex flex-wrap items-center gap-2 mb-3">{/* The shared TabPills owns the roving tabindex + arrow-keycontract — never roll a tab bar (client/src/AGENTS.md). */}@@ -1052,7 +1061,7 @@ function MoodBoardEditor({ id }) {defaultValue={displayText}title={displayText}placeholder={hasPrompt ? "Add a prompt…" : "Add a caption…"}- maxLength={2000}+ maxLength={isAnalyzed ? 8000 : item.prompt ? 16000 : 2000}onBlur={(e) => {const next = e.target.value.trim();if (next !== displayText) handleUpdateItemText(item, next);diff --git a/client/src/pages/MoodBoardDetail.test.jsx b/client/src/pages/MoodBoardDetail.test.jsxindex d51249a6b0..09afef461c 100644--- a/client/src/pages/MoodBoardDetail.test.jsx+++ b/client/src/pages/MoodBoardDetail.test.jsx@@ -5,6 +5,9 @@ import { MemoryRouter } from 'react-router';// ── Mocks must be declared before any imports that use them ──────────────────+const mockUploadRequest = vi.fn();+vi.mock('../services/apiCore.js', async importOriginal => ({ ...await importOriginal(), request: (...args) => mockUploadRequest(...args) }));+const mockGetMoodBoard = vi.fn();const mockUpdateMoodBoard = vi.fn();const mockAddMoodBoardItem = vi.fn();@@ -53,6 +56,7 @@ 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/imageGen/GalleryImagePicker', () => ({ default: ({ open, onSelect }) => open ? <button onClick={() => onSelect({ key: 'image:pic.png', previewUrl: '/data/images/pic.png' })}>Choose fixture</button> : null }));vi.mock('../components/moodBoard/MoodBoardGeneratePanel', () => ({ default: () => <div data-testid="generate-more-panel" /> }));vi.mock('../components/moodBoard/MoodBoardStylePanel', () => ({default: () => <div data-testid="board-style-panel" />,@@ -620,6 +624,7 @@ describe('MoodBoardDetail item analysis (#4188 Phase 3)', () => {expect(screen.getByTestId('item-indicator-prompt')).toHaveTextContent('Prompt');const input = screen.getByLabelText('Item prompt');expect(input).toHaveValue('explicit prompt text');+ expect(input).toHaveAttribute('maxlength', '16000');});it('displays only default caption with no indicator when item has not been analyzed or given a prompt', async () => {@@ -745,3 +750,83 @@ describe('MoodBoardDetail note render', () => {expect(screen.getByRole('button', { name: 'Render' })).toBeEnabled();});});+++describe('MoodBoardDetail direct upload', () => {+ const image = new File(['synthetic image'], 'reference.png', { type: 'image/png' });+ const video = new File(['synthetic video'], 'motion.mp4', { type: 'video/mp4' });+ const savedImage = { filename: 'upload-image.png', path: '/data/images/upload-image.png', metadata: { prompt: 'Paper boat' } };+ const savedVideo = { id: 'upload-video', filename: 'upload-video.mp4', thumbnail: 'upload-video-thumb.jpg', prompt: 'Clouds' };+ const pick = files => fireEvent.change(screen.getByLabelText('Upload'), { target: { files } });++ it('uploads mixed files once, preserves embedded prompts, and retries a lost pin response without reuploading or duplicating the pin', async () => {+ const upload = deferred();+ const pins = new Map();+ let loseResponse = true;+ mockGetMoodBoard.mockResolvedValueOnce({ id: 'a', name: 'Board A', items: [] });+ mockUploadRequest.mockImplementation(async (path, options) => {+ if (path === '/image-gen/upload') return upload.promise;+ if (path === '/video-gen/upload') return savedVideo;+ const payload = JSON.parse(options.body);+ if (!pins.has(payload.mediaKey)) pins.set(payload.mediaKey, { ...payload, id: `pin-${pins.size}` });+ if (loseResponse) { loseResponse = false; throw new Error('Response lost'); }+ return pins.get(payload.mediaKey);+ });+ renderPage();+ await screen.findByLabelText('Upload');+ expect(screen.getByLabelText('Upload')).toHaveAttribute('multiple');+ expect(screen.getByRole('button', { name: 'Pick from gallery' })).toBeInTheDocument();+ pick([image, video]);+ pick([image, video]);+ expect(screen.getByLabelText('Upload')).toBeDisabled();+ expect(mockUploadRequest).toHaveBeenCalledTimes(1);+ expect(screen.getByRole('list', { name: 'Import queue' })).toHaveTextContent('queued');+ await act(async () => upload.resolve(savedImage));+ await screen.findByText(/mood board assignment failed: Response lost/);+ await screen.findByText('1 of 2 imported');+ expect(screen.queryByRole('list', { name: 'Import queue' })).toBeNull();+ const retry = screen.getByRole('button', { name: 'Retry failed / cancelled' });+ await act(async () => { fireEvent.click(retry); fireEvent.click(retry); });+ await screen.findByText('2 of 2 imported');+ expect(screen.queryByRole('region', { name: 'Imports needing attention' })).toBeNull();+ expect(mockUploadRequest.mock.calls.filter(([path]) => path.endsWith('/upload'))).toHaveLength(2);+ expect([...pins.values()]).toEqual([+ expect.objectContaining({ type: 'image', mediaKey: 'image:upload-image.png', prompt: 'Paper boat' }),+ expect.objectContaining({ type: 'video', mediaKey: 'video:upload-video.mp4', imageUrl: '/data/video-thumbnails/upload-video-thumb.jpg', prompt: 'Clouds' }),+ ]);+ expect(screen.getAllByLabelText('Item prompt')).toHaveLength(2);+ });++ it('finishes the active upload on its original board and stops queued files after navigation', async () => {+ const upload = deferred();+ mockGetMoodBoard.mockImplementation(async id => ({ id, name: `Board ${id}`, items: [] }));+ mockUploadRequest.mockImplementation(async (path, options) => {+ if (path === '/image-gen/upload') return upload.promise;+ return { id: 'pin-old', ...JSON.parse(options.body) };+ });+ const view = renderPage();+ await screen.findByLabelText('Upload');+ pick([image, video]);+ currentId = 'b';+ view.rerender(<MemoryRouter><MoodBoardDetail /></MemoryRouter>);+ await waitFor(() => expect(boardNameValue()).toBe('Board b'));+ await act(async () => upload.resolve(savedImage));+ expect(mockUploadRequest.mock.calls.map(([path]) => path)).toEqual(['/image-gen/upload', '/mood-boards/a/items']);+ expect(screen.queryByLabelText('Item prompt')).toBeNull();+ expect(screen.queryByRole('list', { name: 'Import queue' })).toBeNull();+ expect(mockToastError).not.toHaveBeenCalled();+ });+});+++it('keeps one visible item when the gallery returns an already pinned asset', async () => {+ const item = { id: 'existing-pin', type: 'image', mediaKey: 'image:pic.png', imageUrl: '/data/images/pic.png', caption: 'Legacy gallery caption' };+ mockGetMoodBoard.mockResolvedValueOnce({ id: 'a', name: 'Board A', items: [item] });+ mockAddMoodBoardItem.mockResolvedValue(item);+ renderPage();+ fireEvent.click(await screen.findByRole('button', { name: 'Pick from gallery' }));+ await act(async () => { fireEvent.click(screen.getByRole('button', { name: 'Choose fixture' })); });+ await act(async () => { fireEvent.click(screen.getByRole('button', { name: 'Choose fixture' })); });+ expect(screen.getAllByRole('button', { name: 'Preview image' })).toHaveLength(1);+ expect(screen.getByLabelText('Item prompt')).toHaveAttribute('maxlength', '2000');+});diff --git a/client/src/services/apiMedia.js b/client/src/services/apiMedia.jsindex cb54670a7a..091e0cb7fa 100644--- a/client/src/services/apiMedia.js+++ b/client/src/services/apiMedia.js@@ -370,7 +370,7 @@ export const saveCleanResult = (jobId, options = {}) =>// Reuse the same upload endpoints as the Prompt page's gallery pickers.export async function importGalleryFile(file, options = {}) {const extension = file.name.split('.').pop().toLowerCase();- if (!file.size) throw new Error('The file is empty.');+ if (!file.size) throw Object.assign(new Error('The file is empty.'), { code: 'INVALID_MEDIA_FILE' });if (['png', 'jpg', 'jpeg', 'webp', 'gif'].includes(extension)) {const saved = await uploadGalleryImage(file, options);return { kind: 'image', data: { ...saved, ...saved.metadata }, ref: saved.filename };@@ -379,7 +379,7 @@ export async function importGalleryFile(file, options = {}) {const saved = await uploadGalleryVideo(file, file.name, options);return { kind: 'video', data: saved, ref: saved.id };}- throw new Error('Unsupported type. Use PNG, JPEG, GIF, WebP, MP4, MOV, M4V, WebM, or MKV.');+ throw Object.assign(new Error('Unsupported type. Use PNG, JPEG, GIF, WebP, MP4, MOV, M4V, WebM, or MKV.'), { code: 'INVALID_MEDIA_FILE' });}export const assignImportedMedia = (collectionId, item, options = {}) => request(diff --git a/client/src/services/apiMoodBoard.js b/client/src/services/apiMoodBoard.jsindex 038666ef90..8680f0501b 100644--- a/client/src/services/apiMoodBoard.js+++ b/client/src/services/apiMoodBoard.js@@ -166,3 +166,12 @@ export const generateMoodBoardImages = (id, data, options) =>});export const getMoodBoardGeneration = (id, options) =>request(`/mood-boards/${encodeURIComponent(id)}/generate`, options);++// Video pins use the filename (not the history id) for playback and sync.+export const pinImportedMedia = (boardId, { kind, data }, options) => addMoodBoardItem(boardId, {+ type: kind,+ mediaKey: `${kind}:${data.filename}`,+ imageUrl: kind === 'image' ? data.path : data.thumbnail ? `/data/video-thumbnails/${data.thumbnail}` : null,+ prompt: data.prompt || null,+ caption: data.prompt?.slice(0, 2000) || null,+}, options);diff --git a/server/lib/moodBoardValidation.js b/server/lib/moodBoardValidation.jsindex bef3650915..e3656097d1 100644--- a/server/lib/moodBoardValidation.js+++ b/server/lib/moodBoardValidation.js@@ -1,4 +1,5 @@import { z } from 'zod';+import { GENERATION_METADATA_LIMITS } from './pngMetadata.js';import { isValidKey, parseKey } from './mediaItemKey.js';import { MAX_IMAGE_EDGE, MAX_IMAGE_PIXELS } from './imageLimits.js';import { QUEUEABLE_IMAGE_MODES } from './generationModes.js';@@ -48,7 +49,7 @@ const imageUrlSchema = z.string().trim().min(1).max(2048).refine(const captionSchema = z.string().max(2000).nullable().optional();const sourceSchema = z.string().max(2048).nullable().optional();-const promptSchema = z.string().trim().max(8000).nullable().optional();+const promptSchema = z.string().trim().max(GENERATION_METADATA_LIMITS.prompt).nullable().optional();// Board create. description optional (defaults to '' in the record builder).export const moodBoardCreateSchema = z.object({diff --git a/server/lib/moodBoardValidation.test.js b/server/lib/moodBoardValidation.test.jsindex 98f7c21615..1dae74eefc 100644--- a/server/lib/moodBoardValidation.test.js+++ b/server/lib/moodBoardValidation.test.js@@ -112,6 +112,11 @@ describe('moodBoardItemCreateSchema', () => {it('rejects a video item whose ref is a bare id (no extension) — it would 404 as a filename', () => {expect(moodBoardItemCreateSchema.safeParse({ type: 'video', mediaKey: 'video:job-123' }).success).toBe(false);});+ it('accepts the full embedded-upload prompt without truncation', () => {+ const prompt = 'p'.repeat(16000);+ expect(moodBoardItemCreateSchema.parse({ type: 'image', mediaKey: 'image:upload.png', prompt }).prompt).toBe(prompt);+ expect(moodBoardItemCreateSchema.safeParse({ type: 'image', mediaKey: 'image:upload.png', prompt: prompt + 'x' }).success).toBe(false);+ });it('accepts an image item with prompt alongside imageUrl', () => {const item = moodBoardItemCreateSchema.parse({ type: 'image', imageUrl: 'https://x/y.png', prompt: 'a prompt' });expect(item.prompt).toBe('a prompt');diff --git a/server/services/moodBoard/db.js b/server/services/moodBoard/db.jsindex 6c0d185eab..ece8afba60 100644--- a/server/services/moodBoard/db.js+++ b/server/services/moodBoard/db.js@@ -238,7 +238,7 @@ export async function pruneTombstonedBoards(olderThanMs) {export async function addBoardItem(id, itemInput) {const { result } = await withLockedBoard(id, (b) => {const { board, item } = addItem(b, itemInput);- return { board, result: item };+ return { board, result: item, skipPersist: board === b };});return result;}diff --git a/server/services/moodBoard/db.test.js b/server/services/moodBoard/db.test.jsindex fa2537f768..e9fa985313 100644--- a/server/services/moodBoard/db.test.js+++ b/server/services/moodBoard/db.test.js@@ -110,6 +110,15 @@ describe.skipIf(!runDb)('mood board DB round-trip', () => {expect(afterRemove.items).toHaveLength(0);});+ it('serializes concurrent pins of the same saved upload into one board item', async () => {+ const board = await db.createBoard({ name: 'Upload retry fixture' });+ created.push(board.id);+ const input = { type: 'video', mediaKey: 'video:upload-fixture.mp4', prompt: 'Clouds' };+ const [first, repeated] = await Promise.all([db.addBoardItem(board.id, input), db.addBoardItem(board.id, input)]);+ expect(repeated.id).toBe(first.id);+ expect((await db.getBoard(board.id)).items).toEqual([first]);+ });+it('removeBoardItem is a no-op for an unknown item id', async () => {const board = await db.createBoard({ name: 'Noop' });created.push(board.id);diff --git a/server/services/moodBoard/logic.js b/server/services/moodBoard/logic.jsindex ac9eebc925..835336504a 100644--- a/server/services/moodBoard/logic.js+++ b/server/services/moodBoard/logic.js@@ -203,6 +203,10 @@ function normalizeItem(input, { id, now = nowIso() } = {}) {export function addItem(board, itemInput) {const items = Array.isArray(board.items) ? board.items : [];+ // Runs inside the store's row lock: retrying a lost assignment response+ // returns the original pin without overwriting its edited prompt/caption.+ const existing = itemInput.mediaKey && items.find(item => item.mediaKey === itemInput.mediaKey);+ if (existing) return { board, item: existing };if (items.length >= MAX_ITEMS_PER_BOARD) {throw new ServerError(`Board is full (max ${MAX_ITEMS_PER_BOARD} items)`, {status: 400,diff --git a/server/services/moodBoard/logic.test.js b/server/services/moodBoard/logic.test.jsindex b4561ba32a..52e0e5739a 100644--- a/server/services/moodBoard/logic.test.js+++ b/server/services/moodBoard/logic.test.js@@ -583,3 +583,10 @@ describe('text note render lifecycle (#10531)', () => {expect(() => claimItemRender(board(), 'missing')).toThrow(expect.objectContaining({ code: 'NOT_FOUND' }));});});+++it('returns the original media pin on retry even at capacity, preserving user edits', () => {+ const original = { id: 'pin-original', type: 'image', mediaKey: 'image:upload.png', caption: 'Edited caption' };+ const board = { items: [original, ...Array.from({ length: MAX_ITEMS_PER_BOARD - 1 }, (_, i) => ({ id: `note-${i}`, type: 'text', text: 'Note' }))] };+ expect(addItem(board, { type: 'image', mediaKey: original.mediaKey, caption: 'Upload caption' })).toEqual({ board, item: original });+});