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]): mood boards gain gallery/upload pickers and real video items

[._.]/ Adam Eivyb559646d0b6b
diff --git a/.changelog/next/added-issue-4188.md b/.changelog/next/added-issue-4188.md
index e992e20da3..b5e7a04752 100644
--- a/.changelog/next/added-issue-4188.md
+++ b/.changelog/next/added-issue-4188.md
@@ -1 +1,2 @@
- 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.
diff --git a/client/src/components/videoGen/GalleryVideoPicker.jsx b/client/src/components/videoGen/GalleryVideoPicker.jsx
index c1e578eaec..966a5e6a62 100644
--- a/client/src/components/videoGen/GalleryVideoPicker.jsx
+++ b/client/src/components/videoGen/GalleryVideoPicker.jsx
@@ -3,7 +3,12 @@
// search (same haystack as MediaHistory) and click a thumbnail. With
// `allowUpload`, a header Upload button saves the file via POST /api/uploads
// and selects it as `{ kind: 'upload', filename }` so the reverse-prompt
-// endpoint can sample frames from PATHS.uploads.
+// endpoint can sample frames from PATHS.uploads. With `uploadToGallery`
+// (#4188), the upload instead lands in the shared gallery (POST
+// /api/video-gen/upload → /data/videos/ + a history entry, peer-syncable) and
+// selects the normalized gallery item — required when the selection will be
+// REFERENCED by a synced record (e.g. a mood-board item), because
+// /api/uploads' scratch dir does not federate.
import { useEffect, useMemo, useState } from 'react';
import { Search, X, RefreshCw, Upload } from 'lucide-react';
@@ -11,7 +16,7 @@ import Modal from '../ui/Modal';
import FilePickerButton from '../ui/FilePickerButton';
import MediaCard from '../media/MediaCard';
import { normalizeVideo } from '../media/normalize';
-import { listVideoHistory } from '../../services/apiImageVideo';
+import { listVideoHistory, uploadGalleryVideo } from '../../services/apiImageVideo';
import { uploadFile } from '../../services/apiMedia';
import { readFileAsBase64, JSON_UPLOAD_MAX_FILE_SIZE } from '../../utils/fileUpload';
import { buildMediaHaystack, tokenizeQuery, matchHaystack } from '../../lib/mediaSearch';
@@ -20,7 +25,7 @@ import toast from '../ui/Toast';
const VIDEO_ACCEPT = 'video/mp4,video/webm,video/quicktime,video/x-m4v,.mp4,.webm,.mov,.m4v';
-export default function GalleryVideoPicker({ open, onClose, onSelect, allowUpload = false }) {
+export default function GalleryVideoPicker({ open, onClose, onSelect, allowUpload = false, uploadToGallery = false }) {
const [items, setItems] = useState([]);
const [loading, setLoading] = useState(false);
const [uploading, setUploading] = useState(false);
@@ -60,6 +65,17 @@ export default function GalleryVideoPicker({ open, onClose, onSelect, allowUploa
setUploading(true);
const base64 = await readFileAsBase64(file).catch(() => null);
if (!base64) { setUploading(false); toast.error(`Failed to read ${file.name}`); return; }
+ if (uploadToGallery) {
+ const entry = await uploadGalleryVideo(base64, file.name, { silent: true }).catch((err) => {
+ toast.error(err?.message || 'Upload failed');
+ return null;
+ });
+ setUploading(false);
+ if (!entry?.filename) return;
+ onSelect?.(normalizeVideo(entry));
+ onClose?.();
+ return;
+ }
const saved = await uploadFile(base64, file.name, { silent: true }).catch((err) => {
toast.error(err?.message || 'Upload failed');
return null;
diff --git a/client/src/components/videoGen/GalleryVideoPicker.test.jsx b/client/src/components/videoGen/GalleryVideoPicker.test.jsx
index f421c868fe..b103a2c832 100644
--- a/client/src/components/videoGen/GalleryVideoPicker.test.jsx
+++ b/client/src/components/videoGen/GalleryVideoPicker.test.jsx
@@ -3,8 +3,10 @@ import { render, screen, fireEvent, waitFor } from '@testing-library/react';
import GalleryVideoPicker from './GalleryVideoPicker';
const listVideoHistory = vi.fn();
+const uploadGalleryVideo = vi.fn();
vi.mock('../../services/apiImageVideo', () => ({
listVideoHistory: (...args) => listVideoHistory(...args),
+ uploadGalleryVideo: (...args) => uploadGalleryVideo(...args),
}));
vi.mock('../../services/apiMedia', () => ({
@@ -27,6 +29,7 @@ describe('GalleryVideoPicker', () => {
beforeEach(() => {
listVideoHistory.mockReset();
listVideoHistory.mockResolvedValue(HISTORY);
+ uploadGalleryVideo.mockReset();
});
it('does not fetch when closed', () => {
@@ -47,4 +50,26 @@ describe('GalleryVideoPicker', () => {
}));
expect(onClose).toHaveBeenCalled();
});
+
+ it('uploads into the gallery and selects the normalized entry with uploadToGallery (#4188)', async () => {
+ uploadGalleryVideo.mockResolvedValue({
+ id: 'upload-ab12cd34', filename: 'upload-ab12cd34.mp4', thumbnail: 'upload-ab12cd34.jpg', source: 'upload',
+ });
+ const onSelect = vi.fn();
+ const onClose = vi.fn();
+ render(
+ <GalleryVideoPicker open onClose={onClose} onSelect={onSelect} allowUpload uploadToGallery />,
+ );
+ await waitFor(() => expect(screen.getByText('a neon chase')).toBeInTheDocument());
+ // The modal renders through a portal, so query the document, not the container.
+ const fileInput = document.querySelector('input[type="file"]');
+ fireEvent.change(fileInput, { target: { files: [new File(['x'], 'clip.mp4', { type: 'video/mp4' })] } });
+ await waitFor(() => expect(uploadGalleryVideo).toHaveBeenCalledWith('ZmFrZQ==', 'clip.mp4', { silent: true }));
+ await waitFor(() => expect(onSelect).toHaveBeenCalledWith(expect.objectContaining({
+ kind: 'video',
+ filename: 'upload-ab12cd34.mp4',
+ previewUrl: '/data/video-thumbnails/upload-ab12cd34.jpg',
+ })));
+ expect(onClose).toHaveBeenCalled();
+ });
});
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index 248ef7f5c1..9c4f24d2fb 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 src (`imageUrl` → served `image:<file>` bytes → null). 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. 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 96359976c6..cd66221e5a 100644
--- a/client/src/lib/moodBoardItemSrc.js
+++ b/client/src/lib/moodBoardItemSrc.js
@@ -1,22 +1,42 @@
-// Resolve a mood-board item to a display image src (issue #911 / #1455).
+// Resolve a mood-board item to display sources (issue #911 / #1455 / #4188).
//
// A board item is renderable as an image when it carries either an explicit
// `imageUrl` (external or absolute app path) or a pinned `image:<file>`
-// media-key — the served bytes live at `/data/images/<file>`. A `video:<id>`
-// media-key has no derivable thumbnail path (the id isn't the thumbnail
-// filename), so a video pin renders only when the pin also stored an
-// `imageUrl` thumbnail (the cross-surface pin flow does this). Returns null
-// when there's nothing renderable.
+// media-key — the served bytes live at `/data/images/<file>`.
+//
+// A `type: 'video'` item (#4188) stores its media-key as `video:<filename>`
+// (the ref IS the on-disk filename, extension included), so playback resolves
+// to `/data/videos/<filename>` and the poster falls back to the derived
+// thumbnail `/data/video-thumbnails/<stem>.jpg` — the same name the sender's
+// upload/generation wrote and a receiving peer's asset pull regenerates.
+// Legacy `video:<id>` pins on IMAGE items (the cross-surface pin flow) render
+// only via their stored `imageUrl` thumbnail, as before.
//
// Shared by MoodBoardDetail (the canvas) and MoodBoardReferenceStrip (the
// creation-flow picker) so the two can't diverge on how a pin resolves.
const IMAGE_PREFIX = 'image:';
+const VIDEO_PREFIX = 'video:';
export function moodBoardItemSrc(item) {
if (item?.imageUrl) return item.imageUrl;
if (typeof item?.mediaKey === 'string' && item.mediaKey.startsWith(IMAGE_PREFIX)) {
return `/data/images/${encodeURIComponent(item.mediaKey.slice(IMAGE_PREFIX.length))}`;
}
+ if (item?.type === 'video' && typeof item?.mediaKey === 'string' && item.mediaKey.startsWith(VIDEO_PREFIX)) {
+ const stem = item.mediaKey.slice(VIDEO_PREFIX.length).replace(/\.[a-z0-9]+$/i, '');
+ if (stem) return `/data/video-thumbnails/${encodeURIComponent(stem)}.jpg`;
+ }
+ 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) {
+ if (item?.type !== 'video') return null;
+ if (typeof item?.mediaKey === 'string' && item.mediaKey.startsWith(VIDEO_PREFIX)) {
+ const filename = item.mediaKey.slice(VIDEO_PREFIX.length);
+ if (filename) return `/data/videos/${encodeURIComponent(filename)}`;
+ }
return null;
}
diff --git a/client/src/lib/moodBoardItemSrc.test.js b/client/src/lib/moodBoardItemSrc.test.js
index c16eb218c7..c2e8f5a222 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 } from './moodBoardItemSrc';
+import { moodBoardItemSrc, moodBoardItemVideoSrc } from './moodBoardItemSrc';
describe('moodBoardItemSrc', () => {
it('prefers an explicit imageUrl', () => {
@@ -26,4 +26,28 @@ describe('moodBoardItemSrc', () => {
expect(moodBoardItemSrc(null)).toBeNull();
expect(moodBoardItemSrc({})).toBeNull();
});
+
+ it('derives a video item poster from the filename stem when no imageUrl is stored (#4188)', () => {
+ expect(moodBoardItemSrc({ type: 'video', mediaKey: 'video:upload-ab12cd34.mp4' }))
+ .toBe('/data/video-thumbnails/upload-ab12cd34.jpg');
+ });
+
+ it('still prefers a stored poster imageUrl on a video item', () => {
+ expect(moodBoardItemSrc({ type: 'video', mediaKey: 'video:a.mp4', imageUrl: '/data/video-thumbnails/x.jpg' }))
+ .toBe('/data/video-thumbnails/x.jpg');
+ });
+});
+
+describe('moodBoardItemVideoSrc', () => {
+ it('resolves a video item mediaKey to the served playback URL (URL-encoded)', () => {
+ expect(moodBoardItemVideoSrc({ type: 'video', mediaKey: 'video:my clip.mp4' }))
+ .toBe('/data/videos/my%20clip.mp4');
+ });
+
+ it('returns null for image/text items and legacy video pins on image items', () => {
+ expect(moodBoardItemVideoSrc({ type: 'image', mediaKey: 'video:job-123' })).toBeNull();
+ expect(moodBoardItemVideoSrc({ type: 'text', text: 'hi' })).toBeNull();
+ expect(moodBoardItemVideoSrc({ type: 'video' })).toBeNull();
+ expect(moodBoardItemVideoSrc(null)).toBeNull();
+ });
});
diff --git a/client/src/pages/MoodBoardDetail.jsx b/client/src/pages/MoodBoardDetail.jsx
index e58f7d617a..e6e18eea22 100644
--- a/client/src/pages/MoodBoardDetail.jsx
+++ b/client/src/pages/MoodBoardDetail.jsx
@@ -11,10 +11,12 @@
import { useEffect, useState, useCallback, useRef } from 'react';
import { useParams, useNavigate, Link } from 'react-router';
-import { ArrowLeft, ImageIcon, FileText, Trash2, Plus, Save, Link2, Unlink, RefreshCw } from 'lucide-react';
+import { ArrowLeft, ImageIcon, FileText, Trash2, Plus, Save, Link2, Unlink, RefreshCw, Images, Film, Play } 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 {
getMoodBoard,
updateMoodBoard,
@@ -25,7 +27,7 @@ import {
unlinkMoodBoardPinterest,
syncMoodBoardPinterest,
} from '../services/api';
-import { moodBoardItemSrc } from '../lib/moodBoardItemSrc';
+import { moodBoardItemSrc, moodBoardItemVideoSrc } from '../lib/moodBoardItemSrc';
import { timeAgo } from '../utils/formatters';
import useMounted from '../hooks/useMounted';
@@ -47,6 +49,11 @@ export default function MoodBoardDetail() {
const [source, setSource] = useState('');
const [adding, setAdding] = useState(false);
+ // Gallery pickers (#4188) + inline video playback.
+ const [imagePickerOpen, setImagePickerOpen] = useState(false);
+ const [videoPickerOpen, setVideoPickerOpen] = useState(false);
+ const [playingItemId, setPlayingItemId] = useState(null);
+
// Pinterest link/sync.
const [pinUrl, setPinUrl] = useState('');
const [linking, setLinking] = useState(false);
@@ -115,6 +122,35 @@ export default function MoodBoardDetail() {
resetAddForm();
};
+ // Gallery-picker pins (#4188). Both pickers hand back a normalized media
+ // item; the payload mirrors PinToMoodBoardMenu's shape — mediaKey for source
+ // linkage + a directly-renderable preview. A video pin's mediaKey ref is the
+ // FILENAME (`video:<file>.mp4`) so playback and peer-sync asset transfer
+ // both resolve without an id→filename lookup.
+ const addPickedItem = async (payload) => {
+ const item = await addMoodBoardItem(id, payload, { silent: true }).catch(() => null);
+ if (!item) { toast.error('Failed to add item'); return; }
+ setBoard((prev) => (prev ? { ...prev, items: [...(prev.items || []), item] } : prev));
+ };
+
+ const handlePickGalleryImage = (picked) => {
+ if (!picked?.previewUrl && !picked?.key) return;
+ addPickedItem({
+ type: 'image',
+ mediaKey: typeof picked.key === 'string' && picked.key.startsWith('image:') ? picked.key : null,
+ imageUrl: picked.previewUrl || null,
+ });
+ };
+
+ const handlePickGalleryVideo = (picked) => {
+ if (!picked?.filename) return;
+ addPickedItem({
+ type: 'video',
+ mediaKey: `video:${picked.filename}`,
+ imageUrl: picked.previewUrl || null,
+ });
+ };
+
const handleUpdateCaption = async (itemId, nextCaption) => {
const item = await updateMoodBoardItem(id, itemId, { caption: nextCaption || null }, { silent: true }).catch(() => null);
if (!item) { toast.error('Failed to update caption'); return; }
@@ -334,25 +370,44 @@ export default function MoodBoardDetail() {
{/* Add item */}
<div className="bg-port-card border border-port-border rounded-md p-4 mb-6">
- <div className="flex items-center gap-2 mb-3" role="tablist" aria-label="Item type">
- <button
- type="button"
- role="tab"
- aria-selected={itemType === 'image'}
- onClick={() => setItemType('image')}
- className={`flex items-center gap-1.5 px-3 py-1.5 text-sm rounded transition-colors ${itemType === 'image' ? 'bg-port-accent text-white' : 'bg-port-bg text-gray-400 hover:text-white'}`}
- >
- <ImageIcon className="w-4 h-4" aria-hidden="true" /> Image
- </button>
- <button
- type="button"
- role="tab"
- aria-selected={itemType === 'text'}
- onClick={() => setItemType('text')}
- className={`flex items-center gap-1.5 px-3 py-1.5 text-sm rounded transition-colors ${itemType === 'text' ? 'bg-port-accent text-white' : 'bg-port-bg text-gray-400 hover:text-white'}`}
- >
- <FileText className="w-4 h-4" aria-hidden="true" /> Note
- </button>
+ <div className="flex flex-wrap items-center gap-2 mb-3">
+ <div className="flex items-center gap-2" role="tablist" aria-label="Item type">
+ <button
+ type="button"
+ role="tab"
+ aria-selected={itemType === 'image'}
+ onClick={() => setItemType('image')}
+ className={`flex items-center gap-1.5 px-3 py-1.5 text-sm rounded transition-colors ${itemType === 'image' ? 'bg-port-accent text-white' : 'bg-port-bg text-gray-400 hover:text-white'}`}
+ >
+ <ImageIcon className="w-4 h-4" aria-hidden="true" /> Image
+ </button>
+ <button
+ type="button"
+ role="tab"
+ aria-selected={itemType === 'text'}
+ onClick={() => setItemType('text')}
+ className={`flex items-center gap-1.5 px-3 py-1.5 text-sm rounded transition-colors ${itemType === 'text' ? 'bg-port-accent text-white' : 'bg-port-bg text-gray-400 hover:text-white'}`}
+ >
+ <FileText className="w-4 h-4" aria-hidden="true" /> Note
+ </button>
+ </div>
+ {/* Gallery pins (#4188) — pick or upload, added to the board immediately. */}
+ <div className="flex items-center gap-2 sm:ml-auto">
+ <button
+ type="button"
+ onClick={() => setImagePickerOpen(true)}
+ className="flex items-center gap-1.5 px-3 py-1.5 text-sm rounded bg-port-bg text-gray-400 hover:text-white transition-colors"
+ >
+ <Images className="w-4 h-4" aria-hidden="true" /> Pick from gallery
+ </button>
+ <button
+ type="button"
+ onClick={() => setVideoPickerOpen(true)}
+ className="flex items-center gap-1.5 px-3 py-1.5 text-sm rounded bg-port-bg text-gray-400 hover:text-white transition-colors"
+ >
+ <Film className="w-4 h-4" aria-hidden="true" /> Pick video
+ </button>
+ </div>
</div>
<div className="space-y-3">
@@ -429,9 +484,40 @@ export default function MoodBoardDetail() {
<div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-3">
{items.map((item) => {
const src = moodBoardItemSrc(item);
+ const videoSrc = moodBoardItemVideoSrc(item);
return (
<div key={item.id} className="bg-port-card border border-port-border rounded-md overflow-hidden flex flex-col">
- {item.type === 'image' ? (
+ {item.type === 'video' && videoSrc ? (
+ playingItemId === item.id ? (
+ // eslint-disable-next-line jsx-a11y/media-has-caption -- reference clips have no caption track
+ <video
+ src={videoSrc}
+ poster={src || undefined}
+ controls
+ autoPlay
+ playsInline
+ className="w-full aspect-square object-cover bg-black"
+ />
+ ) : (
+ <button
+ type="button"
+ onClick={() => setPlayingItemId(item.id)}
+ aria-label="Play video"
+ className="relative w-full aspect-square bg-port-bg text-gray-600 group"
+ >
+ {src ? (
+ <img src={src} alt={item.caption || ''} loading="lazy" className="w-full h-full object-cover" />
+ ) : (
+ <span className="w-full h-full flex items-center justify-center">
+ <Film className="w-8 h-8" aria-hidden="true" />
+ </span>
+ )}
+ <span className="absolute inset-0 flex items-center justify-center bg-black/30 opacity-80 group-hover:opacity-100 transition-opacity">
+ <Play className="w-8 h-8 text-white drop-shadow" aria-hidden="true" />
+ </span>
+ </button>
+ )
+ ) : item.type === 'image' || item.type === 'video' ? (
src ? (
<img src={src} alt={item.caption || ''} loading="lazy" className="w-full aspect-square object-cover bg-port-bg" />
) : (
@@ -484,6 +570,20 @@ export default function MoodBoardDetail() {
})}
</div>
)}
+
+ <GalleryImagePicker
+ open={imagePickerOpen}
+ onClose={() => setImagePickerOpen(false)}
+ onSelect={handlePickGalleryImage}
+ allowUpload
+ />
+ <GalleryVideoPicker
+ open={videoPickerOpen}
+ onClose={() => setVideoPickerOpen(false)}
+ onSelect={handlePickGalleryVideo}
+ allowUpload
+ uploadToGallery
+ />
</div>
);
}
diff --git a/client/src/pages/MoodBoardDetail.test.jsx b/client/src/pages/MoodBoardDetail.test.jsx
index 6d92bc8fc1..cd1890634f 100644
--- a/client/src/pages/MoodBoardDetail.test.jsx
+++ b/client/src/pages/MoodBoardDetail.test.jsx
@@ -1,6 +1,6 @@
import { StrictMode } from 'react';
import { describe, it, expect, vi, beforeEach } from 'vitest';
-import { render, screen, waitFor } from '@testing-library/react';
+import { render, screen, waitFor, fireEvent } from '@testing-library/react';
import { MemoryRouter } from 'react-router';
// ── Mocks must be declared before any imports that use them ──────────────────
@@ -120,3 +120,31 @@ describe('MoodBoardDetail stale-response guards', () => {
expect(mockToastError).not.toHaveBeenCalled();
});
});
+
+describe('MoodBoardDetail video items (#4188)', () => {
+ it('renders a video item as a poster with a play affordance, then plays inline', async () => {
+ mockGetMoodBoard.mockResolvedValueOnce({
+ id: 'a',
+ name: 'Board A',
+ items: [{
+ id: 'mbi-1',
+ type: 'video',
+ mediaKey: 'video:upload-ab12cd34.mp4',
+ imageUrl: '/data/video-thumbnails/upload-ab12cd34.jpg',
+ caption: null,
+ source: null,
+ }],
+ });
+ const { container } = renderPage();
+ await waitFor(() => expect(boardNameValue()).toBe('Board A'));
+
+ const playButton = screen.getByRole('button', { name: 'Play video' });
+ expect(playButton.querySelector('img').getAttribute('src')).toBe('/data/video-thumbnails/upload-ab12cd34.jpg');
+ fireEvent.click(playButton);
+ await waitFor(() => {
+ const video = container.querySelector('video');
+ expect(video).not.toBeNull();
+ expect(video.getAttribute('src')).toBe('/data/videos/upload-ab12cd34.mp4');
+ });
+ });
+});
diff --git a/client/src/services/apiImageVideo.js b/client/src/services/apiImageVideo.js
index d3d640356b..9648d26b41 100644
--- a/client/src/services/apiImageVideo.js
+++ b/client/src/services/apiImageVideo.js
@@ -221,6 +221,14 @@ export const getVideoGenRuntimeStatus = (runtime, { signal } = {}) =>
// poll doesn't double-toast on every navigation.
export const getActiveVideoJob = () => request('/video-gen/active', { silent: true });
export const listVideoHistory = (options = {}) => request('/video-gen/history', options);
+// Upload a video into the shared gallery (#4188) — lands under /data/videos/
+// with a video-history entry (peer-syncable), unlike the /api/uploads scratch
+// dir. Returns the history entry; feed it through normalizeVideo to display.
+export const uploadGalleryVideo = (base64Data, filename, options = {}) => request('/video-gen/upload', {
+ method: 'POST',
+ body: JSON.stringify({ data: base64Data, ...(filename ? { filename } : {}) }),
+ ...options,
+});
export const deleteVideoHistoryItem = (id, options = {}) => request(`/video-gen/history/${encodeURIComponent(id)}`, { method: 'DELETE', ...options });
export const setVideoHidden = (id, hidden, options = {}) => request(`/video-gen/history/${encodeURIComponent(id)}/visibility`, {
method: 'POST',
diff --git a/server/lib/moodBoardValidation.js b/server/lib/moodBoardValidation.js
index dd9123ff51..1c1467ea28 100644
--- a/server/lib/moodBoardValidation.js
+++ b/server/lib/moodBoardValidation.js
@@ -1,5 +1,5 @@
import { z } from 'zod';
-import { isValidKey } from './mediaItemKey.js';
+import { isValidKey, parseKey } from './mediaItemKey.js';
// =============================================================================
// MOOD BOARD SCHEMAS (issue #911)
@@ -8,7 +8,7 @@ import { isValidKey } from './mediaItemKey.js';
// Boards are db-primary, local-only records; items live inline in the board's
// JSONB. validation.js re-exports everything here so deep imports keep working.
-export const MOOD_BOARD_ITEM_TYPES = Object.freeze(['image', 'text']);
+export const MOOD_BOARD_ITEM_TYPES = Object.freeze(['image', 'text', 'video']);
// A media-key references an indexed asset as `<kind>:<ref>` (e.g.
// `image:my-render.png`, `video:job-123`). Reuse the shared key validator from
@@ -43,8 +43,12 @@ export const moodBoardUpdateSchema = z.object({
}).strict();
// Add-item. An `image` item requires at least one of mediaKey / imageUrl; a
-// `text` item requires non-empty text. The cross-field rule is enforced with a
-// superRefine so the failure is specific.
+// `text` item requires non-empty text; a `video` item (#4188) requires a
+// `video:<filename>` mediaKey — the ref is the on-disk filename (extension
+// included) so playback (`/data/videos/<ref>`) and the peer-sync asset
+// manifest both resolve without guessing, and `imageUrl` optionally carries
+// the poster thumbnail. The cross-field rule is enforced with a superRefine
+// so the failure is specific.
export const moodBoardItemCreateSchema = z.object({
type: z.enum(MOOD_BOARD_ITEM_TYPES),
mediaKey: mediaKeySchema.nullable().optional(),
@@ -69,6 +73,14 @@ export const moodBoardItemCreateSchema = z.object({
path: ['text'],
});
}
+ } else if (val.type === 'video') {
+ if (parseKey(val.mediaKey || '')?.kind !== 'video') {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ message: 'a video item requires a `video:<filename>` mediaKey',
+ path: ['mediaKey'],
+ });
+ }
}
});
diff --git a/server/lib/moodBoardValidation.test.js b/server/lib/moodBoardValidation.test.js
index 93983be8c4..6c80db61ff 100644
--- a/server/lib/moodBoardValidation.test.js
+++ b/server/lib/moodBoardValidation.test.js
@@ -59,6 +59,20 @@ describe('moodBoardItemCreateSchema', () => {
it('rejects a text item with blank text', () => {
expect(moodBoardItemCreateSchema.safeParse({ type: 'text', text: ' ' }).success).toBe(false);
});
+ it('accepts a video item with a video mediaKey (#4188)', () => {
+ expect(moodBoardItemCreateSchema.safeParse({ type: 'video', mediaKey: 'video:upload-ab12cd34.mp4' }).success).toBe(true);
+ });
+ it('accepts a video item with a poster imageUrl alongside the mediaKey', () => {
+ expect(moodBoardItemCreateSchema.safeParse({
+ type: 'video', mediaKey: 'video:a.mp4', imageUrl: '/data/video-thumbnails/a.jpg',
+ }).success).toBe(true);
+ });
+ it('rejects a video item without a mediaKey', () => {
+ expect(moodBoardItemCreateSchema.safeParse({ type: 'video', imageUrl: '/data/video-thumbnails/a.jpg' }).success).toBe(false);
+ });
+ it('rejects a video item whose mediaKey is not kind video', () => {
+ expect(moodBoardItemCreateSchema.safeParse({ type: 'video', mediaKey: 'image:a.png' }).success).toBe(false);
+ });
});
describe('moodBoardItemUpdateSchema', () => {
diff --git a/server/lib/schemaVersions.js b/server/lib/schemaVersions.js
index c1b1420854..12403ff6c5 100644
--- a/server/lib/schemaVersions.js
+++ b/server/lib/schemaVersions.js
@@ -381,10 +381,18 @@ export const PORTOS_SCHEMA_VERSIONS = Object.freeze({
// record type with its own per-category gate — a v1 sender pushing to a ≤v0
// (pre-feature) receiver is sender-ahead on `moodBoards` and gets a 412 (only
// that category pauses); a v1 receiver still accepts a ≤v0 sender (pre-feature
- // peers never push a `moodBoard`). The FIRST incompatible board-shape change
- // MUST bump this to 2 then. The board body (name/description/items) is
+ // peers never push a `moodBoard`). The board body (name/description/items) is
// LWW-overwritten whole; referenced image bytes ride the asset manifest.
- moodBoards: 1,
+ // v2 = `type: 'video'` board items (#4188). An EXECUTION-semantics break for
+ // v1 receivers, not a sanitizer strip (the whole-record LWW passes unknown
+ // item shapes through verbatim): a v1 renderer treats a non-image item as a
+ // text note (blank card), and its updateItem gates a 'video' item onto the
+ // text editable-keys — so a v1 peer that edits the board can mangle video
+ // items and LWW the damage back. Bumping makes the v1 receiver 412-reject
+ // the ahead-version push until it upgrades. Video bytes ride the existing
+ // asset manifest (`video:<filename>` ref → PATHS.videos, receiver regenerates
+ // the poster thumbnail on pull).
+ moodBoards: 2,
// v1 = Writers Room works (PostgreSQL `writers_room_works` + decomposed
// `writers_room_draft_versions`) federated via the per-record peer-sync push
// pipeline (record kind `writersRoomWork`, sync category `writersRoomWorks`,
diff --git a/server/routes/videoGen.js b/server/routes/videoGen.js
index 1baa56b1f8..aa9b32afca 100644
--- a/server/routes/videoGen.js
+++ b/server/routes/videoGen.js
@@ -61,6 +61,7 @@ import {
isSafeHfRepoRelativePath,
} from '../lib/hfCache.js';
import { startHfDownloadStream, openSseStream } from '../lib/sseDownload.js';
+import { saveUploadedGalleryVideo } from '../services/videoUpload.js';
import { createInstallLogger } from '../lib/installLogger.js';
const router = Router();
@@ -1216,6 +1217,24 @@ router.get('/history', asyncHandler(async (_req, res) => {
res.json(await loadHistory());
}));
+// Upload a video into the shared gallery (#4188) — the video counterpart of
+// POST /api/image-gen/upload. Lands the bytes under PATHS.videos with a
+// `source: 'upload'` history entry so the file federates via the peer-sync
+// asset manifest (unlike POST /api/uploads → data/uploads/, which does not).
+// Base64 max = 56MB ≈ the 41MB binary cap (MAX_GALLERY_VIDEO_UPLOAD_BYTES)
+// after base64 expansion, mirroring the image route's transport bound.
+const uploadVideoSchema = z.object({
+ data: z.string().min(1).max(56 * 1024 * 1024),
+ filename: z.string().max(255).optional(),
+});
+
+router.post('/upload', asyncHandler(async (req, res) => {
+ const parsed = uploadVideoSchema.safeParse(req.body || {});
+ if (!parsed.success) failValidation(parsed);
+ const { data, filename } = parsed.data;
+ res.json(await saveUploadedGalleryVideo(data, filename));
+}));
+
router.delete('/history/:id', asyncHandler(async (req, res) => {
res.json(await deleteHistoryItem(req.params.id));
}));
diff --git a/server/services/moodBoard/logic.js b/server/services/moodBoard/logic.js
index 36e3e9e812..f19a8066b3 100644
--- a/server/services/moodBoard/logic.js
+++ b/server/services/moodBoard/logic.js
@@ -146,15 +146,18 @@ export function applyBoardPatch(board, patch) {
// Normalize a validated item input into the stored item shape. An image item
// carries a `mediaKey` (an indexed `<kind>:<ref>` asset) OR an `imageUrl`
-// (external/pinned), never required to have both; a text item carries `text`.
-// `caption`/`source` are optional on both. The route schema guarantees the
-// type-appropriate field is present, so this only fills the shared shape.
+// (external/pinned), never required to have both; a video item (#4188)
+// carries a `video:<filename>` mediaKey plus an optional poster-thumbnail
+// `imageUrl`; a text item carries `text`. `caption`/`source` are optional on
+// all. The route schema guarantees the type-appropriate field is present, so
+// this only fills the shared shape.
function normalizeItem(input, { id, now = nowIso() } = {}) {
+ const hasMedia = input.type === 'image' || input.type === 'video';
return {
id,
type: input.type,
- mediaKey: input.type === 'image' ? (input.mediaKey ?? null) : null,
- imageUrl: input.type === 'image' ? (input.imageUrl ?? null) : null,
+ mediaKey: hasMedia ? (input.mediaKey ?? null) : null,
+ imageUrl: hasMedia ? (input.imageUrl ?? null) : null,
text: input.type === 'text' ? input.text : null,
caption: input.caption ?? null,
source: input.source ?? null,
@@ -189,7 +192,7 @@ export function updateItem(board, itemId, patch) {
}
const current = items[idx];
const updated = { ...current };
- const editableKeys = current.type === 'image'
+ const editableKeys = current.type === 'image' || current.type === 'video'
? ['caption', 'source', 'imageUrl', 'mediaKey']
: ['caption', 'source', 'text'];
for (const key of editableKeys) {
@@ -202,6 +205,9 @@ export function updateItem(board, itemId, patch) {
if (updated.type === 'image' && !updated.mediaKey && !updated.imageUrl) {
throw new ServerError('An image item must keep a mediaKey or imageUrl', { status: 400, code: 'INVALID_ITEM' });
}
+ if (updated.type === 'video' && !updated.mediaKey) {
+ throw new ServerError('A video item must keep its mediaKey', { status: 400, code: 'INVALID_ITEM' });
+ }
if (updated.type === 'text' && (typeof updated.text !== 'string' || !updated.text.trim())) {
throw new ServerError('A text item must keep non-empty text', { status: 400, code: 'INVALID_ITEM' });
}
diff --git a/server/services/moodBoard/logic.test.js b/server/services/moodBoard/logic.test.js
index e183a1bb9f..bd21753f30 100644
--- a/server/services/moodBoard/logic.test.js
+++ b/server/services/moodBoard/logic.test.js
@@ -79,6 +79,15 @@ describe('addItem', () => {
expect(item.mediaKey).toBeNull();
expect(item.imageUrl).toBeNull();
});
+ it('normalizes a video item with mediaKey + poster imageUrl (#4188)', () => {
+ const { item } = addItem(base, {
+ type: 'video', mediaKey: 'video:upload-ab12cd34.mp4', imageUrl: '/data/video-thumbnails/upload-ab12cd34.jpg',
+ });
+ expect(item.type).toBe('video');
+ expect(item.mediaKey).toBe('video:upload-ab12cd34.mp4');
+ expect(item.imageUrl).toBe('/data/video-thumbnails/upload-ab12cd34.jpg');
+ expect(item.text).toBeNull();
+ });
it('throws BOARD_FULL at the item cap', () => {
const full = { ...base, items: Array.from({ length: MAX_ITEMS_PER_BOARD }, (_, i) => ({ id: `i${i}` })) };
expect(() => addItem(full, { type: 'text', text: 'x' })).toThrow(/full/i);
@@ -121,6 +130,16 @@ describe('updateItem', () => {
it('rejects blanking a text item', () => {
expect(() => updateItem(withItem, itemId, { text: ' ' })).toThrow(/non-empty text/i);
});
+ it('edits a video item like a media item and rejects clearing its mediaKey (#4188)', () => {
+ const { board } = addItem(buildBoardRecord({ name: 'A' }, { id: 'mb-4', now: 't0' }), {
+ type: 'video', mediaKey: 'video:a.mp4', imageUrl: '/data/video-thumbnails/a.jpg',
+ });
+ const vidId = board.items[0].id;
+ const { item } = updateItem(board, vidId, { caption: 'clip', text: 'nope' });
+ expect(item.caption).toBe('clip');
+ expect(item.text).toBeNull();
+ expect(() => updateItem(board, vidId, { mediaKey: null })).toThrow(/mediaKey/i);
+ });
});
describe('removeItem', () => {
diff --git a/server/services/sharing/peerSyncAssets.js b/server/services/sharing/peerSyncAssets.js
index 66aa1741df..2647ddc5fb 100644
--- a/server/services/sharing/peerSyncAssets.js
+++ b/server/services/sharing/peerSyncAssets.js
@@ -494,7 +494,12 @@ export async function buildMusicVideoAssetManifest(project) {
export async function buildBoardAssetManifest(board) {
const dedup = new Map();
for (const it of board?.items || []) {
- if (!it || it.type !== 'image') continue;
+ // `video` items (#4188) carry a `video:<filename>` mediaKey (the ref IS
+ // the on-disk filename, so collectionVideoRefToFilename passes it through
+ // untouched) plus an optional poster-thumbnail imageUrl. Thumbnails under
+ // /data/video-thumbnails are NOT shipped — the receiver's video pull
+ // regenerates `<stem>.jpg` locally (see doPullOneAsset's video branch).
+ if (!it || (it.type !== 'image' && it.type !== 'video')) continue;
const pending = [];
if (typeof it.mediaKey === 'string') {
const parsed = parseKey(it.mediaKey);
diff --git a/server/services/sharing/peerSyncAssets.test.js b/server/services/sharing/peerSyncAssets.test.js
index ceb7fc5c5d..9d117c7662 100644
--- a/server/services/sharing/peerSyncAssets.test.js
+++ b/server/services/sharing/peerSyncAssets.test.js
@@ -24,7 +24,7 @@ vi.mock('../tracks/index.js', async () => ({
}));
const { getTrack } = await import('../tracks/index.js');
-const { buildMusicVideoAssetManifest, buildProjectAssetManifest } = await import('./peerSyncAssets.js');
+const { buildMusicVideoAssetManifest, buildProjectAssetManifest, buildBoardAssetManifest } = await import('./peerSyncAssets.js');
const sha = (buf) => createHash('sha256').update(buf).digest('hex');
@@ -40,6 +40,12 @@ function writeImage(filename, bytes) {
writeFileSync(join(dir, filename), bytes);
}
+function writeVideo(filename, bytes) {
+ const dir = join(tempRoot, 'videos');
+ mkdirSync(dir, { recursive: true });
+ writeFileSync(join(dir, filename), bytes);
+}
+
describe('buildMusicVideoAssetManifest — master audio', () => {
beforeEach(() => {
tempRoot = mkdtempSync(join(tmpdir(), 'portos-mv-assets-'));
@@ -157,3 +163,60 @@ describe('buildProjectAssetManifest — first-pass music bed (#1928)', () => {
expect(manifest).toHaveLength(2);
});
});
+
+describe('buildBoardAssetManifest — video items (#4188)', () => {
+ beforeEach(() => {
+ tempRoot = mkdtempSync(join(tmpdir(), 'portos-board-assets-'));
+ });
+ afterEach(() => {
+ if (tempRoot) rmSync(tempRoot, { recursive: true, force: true });
+ });
+
+ it('bundles a video item by its filename-as-ref mediaKey', async () => {
+ const bytes = Buffer.from('video-bytes');
+ writeVideo('upload-ab12cd34.mp4', bytes);
+ const manifest = await buildBoardAssetManifest({
+ items: [{ id: 'i1', type: 'video', mediaKey: 'video:upload-ab12cd34.mp4', imageUrl: null }],
+ });
+ expect(manifest).toContainEqual(expect.objectContaining({
+ filename: 'upload-ab12cd34.mp4', kind: 'video', sha256: sha(bytes),
+ }));
+ });
+
+ it('passes a non-mp4 extension through untouched (no `.mp4` guess)', async () => {
+ const bytes = Buffer.from('webm-bytes');
+ writeVideo('upload-ff00aa11.webm', bytes);
+ const manifest = await buildBoardAssetManifest({
+ items: [{ id: 'i1', type: 'video', mediaKey: 'video:upload-ff00aa11.webm', imageUrl: null }],
+ });
+ expect(manifest).toContainEqual(expect.objectContaining({
+ filename: 'upload-ff00aa11.webm', kind: 'video', sha256: sha(bytes),
+ }));
+ });
+
+ it('skips a video item whose bytes are missing, and never bundles the poster thumbnail', async () => {
+ const manifest = await buildBoardAssetManifest({
+ items: [
+ { id: 'i1', type: 'video', mediaKey: 'video:never-written.mp4', imageUrl: '/data/video-thumbnails/never-written.jpg' },
+ { id: 'i2', type: 'text', text: 'note' },
+ ],
+ });
+ expect(manifest).toEqual([]);
+ });
+
+ it('still bundles image items alongside video items', async () => {
+ const imageBytes = Buffer.from('img-bytes');
+ const videoBytes = Buffer.from('vid-bytes');
+ writeImage('render.png', imageBytes);
+ writeVideo('clip.mp4', videoBytes);
+ const manifest = await buildBoardAssetManifest({
+ items: [
+ { id: 'i1', type: 'image', mediaKey: 'image:render.png', imageUrl: null },
+ { id: 'i2', type: 'video', mediaKey: 'video:clip.mp4', imageUrl: null },
+ ],
+ });
+ expect(manifest).toContainEqual(expect.objectContaining({ filename: 'render.png', kind: 'image', sha256: sha(imageBytes) }));
+ expect(manifest).toContainEqual(expect.objectContaining({ filename: 'clip.mp4', kind: 'video', sha256: sha(videoBytes) }));
+ expect(manifest).toHaveLength(2);
+ });
+});
diff --git a/server/services/videoUpload.js b/server/services/videoUpload.js
new file mode 100644
index 0000000000..f9df90e6c1
--- /dev/null
+++ b/server/services/videoUpload.js
@@ -0,0 +1,109 @@
+/**
+ * Gallery video upload (#4188) — the video counterpart of
+ * `saveUploadedGalleryImage` (imageGen/local.js), built on the same "derived,
+ * not a generation" tail as videoDownload.js: land the bytes under
+ * PATHS.videos, generate a thumbnail, and write a `source: 'upload'` entry
+ * into the shared video-history store so the file shows up in the existing
+ * media library/gallery, federates through the peer-sync asset manifest, and
+ * gets picked up by the mediaAssetIndex `videoGenEvents 'completed'` hook
+ * unmodified.
+ *
+ * This exists because `POST /api/uploads` lands files in `data/uploads/`,
+ * which does NOT federate — a mood-board (or collection) item referencing an
+ * upload there 404s on every peer. Board-referenced media must live in a
+ * peer-syncable directory; for video that is PATHS.videos.
+ *
+ * The filename is `upload-<uuid8>.<ext>` — the stem doubles as the history id
+ * AND the thumbnail name (`<stem>.jpg`), matching the convention the
+ * receiver-side asset pull regenerates thumbnails under, so a poster URL built
+ * from the stem resolves identically on the sender and on every peer.
+ */
+
+import { join } from 'path';
+import { randomUUID } from 'crypto';
+import { writeFile, unlink } from 'fs/promises';
+import { ServerError } from '../lib/errorHandler.js';
+import { PATHS, ensureDir } from '../lib/fileUtils.js';
+import { generateThumbnail, probeVideoDuration } from '../lib/ffmpeg.js';
+import { mutateVideoHistory } from './videoGen/history.js';
+import { videoGenEvents } from './videoGen/events.js';
+
+// Matches the client-side JSON transport cap (JSON_UPLOAD_MAX_FILE_SIZE) so
+// the server never accepts what the picker wouldn't send.
+export const MAX_GALLERY_VIDEO_UPLOAD_BYTES = 41 * 1024 * 1024;
+
+// Container sniff — extension comes from the BYTES, not the client filename.
+// ISO-BMFF (`ftyp` box at offset 4) covers mp4/m4v/mov; the `qt` major brand
+// distinguishes QuickTime. EBML magic covers webm/mkv (served as .webm — the
+// same h264/vp9 payloads browsers already play).
+export function detectVideoContainer(buffer) {
+ if (buffer.length >= 12 && buffer.toString('latin1', 4, 8) === 'ftyp') {
+ const brand = buffer.toString('latin1', 8, 12);
+ return brand.startsWith('qt') ? 'mov' : 'mp4';
+ }
+ if (buffer.length >= 4 && buffer.readUInt32BE(0) === 0x1a45dfa3) return 'webm';
+ return null;
+}
+
+// Pure + exported so the load-bearing shape (the fields normalizeVideo,
+// mediaAssetIndex videoToRow, and deleteHistoryItem depend on) is pinned by a
+// unit test — same rationale as buildDownloadHistoryEntry (videoDownload.js).
+export function buildUploadHistoryEntry({ id, filename, thumbnail, durationSec, title }) {
+ return {
+ id,
+ filename,
+ thumbnail,
+ createdAt: new Date().toISOString(),
+ source: 'upload',
+ title: title || 'Uploaded video',
+ ...(durationSec != null ? { durationSec } : {}),
+ };
+}
+
+/**
+ * Save an uploaded video into the shared gallery. Returns the video-history
+ * entry (`{ id, filename, thumbnail, source: 'upload', … }`); the served file
+ * is `/data/videos/<filename>`.
+ */
+export async function saveUploadedGalleryVideo(base64Data, originalName = '') {
+ const buffer = Buffer.from(base64Data, 'base64');
+ if (buffer.length === 0) {
+ throw new ServerError('Empty video upload', { status: 400, code: 'VALIDATION_ERROR' });
+ }
+ if (buffer.length > MAX_GALLERY_VIDEO_UPLOAD_BYTES) {
+ throw new ServerError(`Video exceeds maximum size of ${MAX_GALLERY_VIDEO_UPLOAD_BYTES / 1024 / 1024}MB`, { status: 400, code: 'FILE_TOO_LARGE' });
+ }
+ const ext = detectVideoContainer(buffer);
+ if (!ext) {
+ throw new ServerError('Unsupported video format (expected MP4, MOV/M4V, or WebM)', { status: 400, code: 'UNSUPPORTED_VIDEO' });
+ }
+ const id = `upload-${randomUUID().slice(0, 8)}`;
+ const filename = `${id}.${ext}`;
+ await ensureDir(PATHS.videos);
+ const outPath = join(PATHS.videos, filename);
+ await writeFile(outPath, buffer);
+ try {
+ // Both best-effort: a missing ffmpeg/ffprobe degrades to a thumbnail-less
+ // entry (normalizeVideo renders a no-preview tile), never a failed upload.
+ const [thumbnail, durationSec] = await Promise.all([
+ generateThumbnail(outPath, id).catch(() => null),
+ probeVideoDuration(outPath).catch(() => null),
+ ]);
+ const title = typeof originalName === 'string' && originalName.trim()
+ ? originalName.trim().slice(0, 200)
+ : '';
+ const entry = buildUploadHistoryEntry({ id, filename, thumbnail, durationSec, title });
+ await mutateVideoHistory((history) => { history.unshift(entry); return history; });
+ // Let the live media-asset index hook index this immediately (same event
+ // the generation and download paths emit). Reconcile is the backstop.
+ videoGenEvents.emit('completed', { generationId: id, filename, path: `/data/videos/${filename}`, thumbnail });
+ console.log(`📥 Saved uploaded gallery video: ${filename} (${(buffer.length / 1024 / 1024).toFixed(1)}MB)`);
+ return entry;
+ } catch (err) {
+ // A throw between the byte write and the history write would orphan a
+ // large file in data/videos with nothing pointing at it — mirror
+ // downloadVideoIntoLibrary's cleanup-then-rethrow.
+ await unlink(outPath).catch(() => {});
+ throw err;
+ }
+}
diff --git a/server/services/videoUpload.test.js b/server/services/videoUpload.test.js
new file mode 100644
index 0000000000..be92fae047
--- /dev/null
+++ b/server/services/videoUpload.test.js
@@ -0,0 +1,73 @@
+/**
+ * Gallery video upload (#4188) — pins the container sniff, the load-bearing
+ * history-entry shape (the fields normalizeVideo / mediaAssetIndex videoToRow /
+ * deleteHistoryItem depend on), and the pre-write validation errors. The happy
+ * path's fs/ffmpeg tail mirrors downloadVideoIntoLibrary and is exercised by
+ * the route surface, not re-run here against real dirs.
+ */
+
+import { describe, it, expect } from 'vitest';
+import {
+ detectVideoContainer,
+ buildUploadHistoryEntry,
+ saveUploadedGalleryVideo,
+ MAX_GALLERY_VIDEO_UPLOAD_BYTES,
+} from './videoUpload.js';
+
+const ftyp = (brand) => Buffer.concat([
+ Buffer.from([0, 0, 0, 24]),
+ Buffer.from('ftyp', 'latin1'),
+ Buffer.from(brand, 'latin1'),
+ Buffer.alloc(8),
+]);
+
+describe('detectVideoContainer', () => {
+ it('detects ISO-BMFF (ftyp) as mp4', () => {
+ expect(detectVideoContainer(ftyp('isom'))).toBe('mp4');
+ expect(detectVideoContainer(ftyp('mp42'))).toBe('mp4');
+ });
+ it('detects the QuickTime brand as mov', () => {
+ expect(detectVideoContainer(ftyp('qt '))).toBe('mov');
+ });
+ it('detects EBML magic as webm', () => {
+ expect(detectVideoContainer(Buffer.from([0x1a, 0x45, 0xdf, 0xa3, 0, 0, 0, 0]))).toBe('webm');
+ });
+ it('rejects non-video bytes', () => {
+ expect(detectVideoContainer(Buffer.from('hello world, definitely not a video'))).toBeNull();
+ expect(detectVideoContainer(Buffer.alloc(2))).toBeNull();
+ });
+});
+
+describe('buildUploadHistoryEntry', () => {
+ it('pins the shape the gallery/index/delete paths depend on', () => {
+ const entry = buildUploadHistoryEntry({
+ id: 'upload-ab12cd34', filename: 'upload-ab12cd34.mp4', thumbnail: 'upload-ab12cd34.jpg', durationSec: 3.2, title: 'clip.mp4',
+ });
+ expect(entry.id).toBe('upload-ab12cd34');
+ expect(entry.filename).toBe('upload-ab12cd34.mp4');
+ expect(entry.thumbnail).toBe('upload-ab12cd34.jpg');
+ expect(entry.source).toBe('upload');
+ expect(entry.title).toBe('clip.mp4');
+ expect(entry.durationSec).toBe(3.2);
+ expect(typeof entry.createdAt).toBe('string');
+ });
+ it('omits durationSec when unknown and defaults the title', () => {
+ const entry = buildUploadHistoryEntry({ id: 'u', filename: 'u.mp4', thumbnail: null, durationSec: null, title: '' });
+ expect('durationSec' in entry).toBe(false);
+ expect(entry.title).toBe('Uploaded video');
+ });
+});
+
+describe('saveUploadedGalleryVideo validation', () => {
+ it('rejects an empty upload before touching disk', async () => {
+ await expect(saveUploadedGalleryVideo('')).rejects.toThrow(/empty/i);
+ });
+ it('rejects an oversize upload', async () => {
+ const oversize = Buffer.alloc(MAX_GALLERY_VIDEO_UPLOAD_BYTES + 1, 1).toString('base64');
+ await expect(saveUploadedGalleryVideo(oversize)).rejects.toThrow(/maximum size/i);
+ });
+ it('rejects a non-video payload', async () => {
+ const notVideo = Buffer.from('hello world, definitely not a video').toString('base64');
+ await expect(saveUploadedGalleryVideo(notVideo)).rejects.toThrow(/unsupported video format/i);
+ });
+});