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(media): video timeline editor + media collections (#189)

[._.]/ Adam Eivya1834f5d1803
diff --git a/client/src/App.jsx b/client/src/App.jsx
index 0d68f28daa..d75ae2be19 100644
--- a/client/src/App.jsx
+++ b/client/src/App.jsx
@@ -49,7 +49,11 @@ const MediaGen = lazyWithReload(() => import('./pages/MediaGen'));
const ImageGen = lazyWithReload(() => import('./pages/ImageGen'));
const VideoGen = lazyWithReload(() => import('./pages/VideoGen'));
const MediaHistory = lazyWithReload(() => import('./pages/MediaHistory'));
+const MediaCollections = lazyWithReload(() => import('./pages/MediaCollections'));
+const MediaCollectionDetail = lazyWithReload(() => import('./pages/MediaCollectionDetail'));
const MediaModels = lazyWithReload(() => import('./pages/MediaModels'));
+const VideoTimeline = lazyWithReload(() => import('./pages/VideoTimeline'));
+const VideoTimelineEditor = lazyWithReload(() => import('./pages/VideoTimelineEditor'));
const CreateApp = lazyWithReload(() => import('./pages/CreateApp'));
const Templates = lazyWithReload(() => import('./pages/Templates'));
const PromptManager = lazyWithReload(() => import('./pages/PromptManager'));
@@ -185,6 +189,10 @@ export default function App() {
<Route path="image" element={<ImageGen />} />
<Route path="video" element={<VideoGen />} />
<Route path="history" element={<MediaHistory />} />
+ <Route path="collections" element={<MediaCollections />} />
+ <Route path="collections/:id" element={<MediaCollectionDetail />} />
+ <Route path="timeline" element={<VideoTimeline />} />
+ <Route path="timeline/:projectId" element={<VideoTimelineEditor />} />
<Route path="models" element={<MediaModels />} />
</Route>
<Route path="image-gen" element={<RedirectWithSearch to="/media/image" />} />
diff --git a/client/src/components/media/AddToCollectionMenu.jsx b/client/src/components/media/AddToCollectionMenu.jsx
new file mode 100644
index 0000000000..73470c6878
--- /dev/null
+++ b/client/src/components/media/AddToCollectionMenu.jsx
@@ -0,0 +1,162 @@
+import { useEffect, useRef, useState } from 'react';
+import { FolderPlus, Check, Plus } from 'lucide-react';
+import toast from '../ui/Toast';
+import {
+ listMediaCollections, createMediaCollection,
+ addMediaCollectionItem, removeMediaCollectionItem,
+} from '../../services/api';
+
+// Self-contained popover button used by MediaCard. Fetches collections
+// lazily on first open so an empty-state grid doesn't slam the API once
+// per card. Toggling membership both adds and removes the item, so the
+// menu doubles as a "what collections is this in" indicator.
+//
+// `itemKey` is "<kind>:<ref>" — the same format the server uses for
+// coverKey and for the DELETE /items/:key route.
+export default function AddToCollectionMenu({ item }) {
+ const [open, setOpen] = useState(false);
+ const [collections, setCollections] = useState(null); // null = not loaded
+ const [creating, setCreating] = useState(false);
+ const [newName, setNewName] = useState('');
+ const [busyId, setBusyId] = useState(null);
+ const wrapperRef = useRef(null);
+
+ const itemKey = `${item.kind}:${item.kind === 'video' ? item.id : item.filename}`;
+ const itemRef = item.kind === 'video' ? item.id : item.filename;
+
+ useEffect(() => {
+ if (!open) return undefined;
+ const onClickAway = (e) => {
+ if (!wrapperRef.current?.contains(e.target)) setOpen(false);
+ };
+ const onEsc = (e) => { if (e.key === 'Escape') setOpen(false); };
+ document.addEventListener('mousedown', onClickAway);
+ document.addEventListener('keydown', onEsc);
+ return () => {
+ document.removeEventListener('mousedown', onClickAway);
+ document.removeEventListener('keydown', onEsc);
+ };
+ }, [open]);
+
+ const ensureLoaded = async () => {
+ if (collections != null) return;
+ const data = await listMediaCollections().catch((err) => {
+ toast.error(err.message || 'Failed to load collections');
+ return [];
+ });
+ setCollections(Array.isArray(data) ? data : []);
+ };
+
+ const handleToggleOpen = async (e) => {
+ e.stopPropagation();
+ const next = !open;
+ setOpen(next);
+ if (next) await ensureLoaded();
+ };
+
+ const handleToggleMembership = async (collection) => {
+ const inIt = collection.items.some((it) => `${it.kind}:${it.ref}` === itemKey);
+ setBusyId(collection.id);
+ const updated = inIt
+ ? await removeMediaCollectionItem(collection.id, itemKey).catch((err) => {
+ toast.error(err.message || 'Remove failed');
+ return null;
+ })
+ : await addMediaCollectionItem(collection.id, { kind: item.kind, ref: itemRef }).catch((err) => {
+ toast.error(err.message || 'Add failed');
+ return null;
+ });
+ setBusyId(null);
+ if (!updated) return;
+ setCollections((prev) => (prev || []).map((c) => (c.id === collection.id ? updated : c)));
+ toast.success(inIt ? `Removed from ${collection.name}` : `Added to ${collection.name}`);
+ };
+
+ const handleCreate = async (e) => {
+ e.preventDefault();
+ const name = newName.trim();
+ if (!name) return;
+ setCreating(true);
+ const created = await createMediaCollection({ name }).catch((err) => {
+ toast.error(err.message || 'Create failed');
+ return null;
+ });
+ if (!created) { setCreating(false); return; }
+ // Auto-add the current item so the user doesn't have to click twice
+ // after creating a brand-new collection for it. Track the add result
+ // separately so a failure here doesn't masquerade as success.
+ let addError = null;
+ const withItem = await addMediaCollectionItem(created.id, { kind: item.kind, ref: itemRef }).catch((err) => {
+ addError = err;
+ return created;
+ });
+ setCollections((prev) => ([...(prev || []), withItem]));
+ setNewName('');
+ setCreating(false);
+ if (addError) {
+ toast.error(`Created "${created.name}" but failed to add: ${addError.message}`);
+ } else {
+ toast.success(`Added to ${created.name}`);
+ }
+ };
+
+ return (
+ <div ref={wrapperRef} className="relative">
+ <button
+ type="button"
+ onClick={handleToggleOpen}
+ className="px-1.5 py-1 bg-port-border hover:bg-port-border/70 text-white text-[10px] rounded flex items-center justify-center"
+ title="Add to collection"
+ >
+ <FolderPlus className="w-3 h-3" />
+ </button>
+ {open && (
+ <div
+ className="absolute right-0 bottom-full mb-1 w-56 max-h-72 overflow-y-auto bg-port-card border border-port-border rounded-lg shadow-lg z-20 p-1.5"
+ onClick={(e) => e.stopPropagation()}
+ >
+ <div className="text-[10px] text-gray-500 uppercase tracking-wide px-1 pt-1 pb-1.5">Collections</div>
+ {collections == null && (
+ <div className="text-[11px] text-gray-500 px-2 py-2">Loading…</div>
+ )}
+ {collections != null && collections.length === 0 && (
+ <div className="text-[11px] text-gray-500 px-2 py-2">No collections yet — create one below.</div>
+ )}
+ {collections != null && collections.map((c) => {
+ const inIt = c.items.some((it) => `${it.kind}:${it.ref}` === itemKey);
+ return (
+ <button
+ key={c.id}
+ type="button"
+ disabled={busyId === c.id}
+ onClick={() => handleToggleMembership(c)}
+ className="w-full flex items-center justify-between gap-2 px-2 py-1.5 text-left text-[12px] text-gray-200 hover:bg-port-border rounded disabled:opacity-50"
+ >
+ <span className="truncate">{c.name}</span>
+ {inIt && <Check className="w-3.5 h-3.5 text-port-success shrink-0" />}
+ </button>
+ );
+ })}
+ <form onSubmit={handleCreate} className="mt-1.5 pt-1.5 border-t border-port-border flex gap-1">
+ <input
+ type="text"
+ value={newName}
+ onChange={(e) => setNewName(e.target.value)}
+ placeholder="New collection name"
+ maxLength={80}
+ className="flex-1 bg-port-bg border border-port-border rounded px-2 py-1 text-[11px] text-white focus:outline-none focus:border-port-accent"
+ />
+ <button
+ type="submit"
+ disabled={creating || !newName.trim()}
+ className="px-2 py-1 bg-port-accent/20 hover:bg-port-accent/40 text-port-accent text-[11px] rounded disabled:opacity-40 flex items-center gap-1"
+ title="Create and add"
+ >
+ <Plus className="w-3 h-3" />
+ </button>
+ </form>
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/client/src/components/media/MediaCard.jsx b/client/src/components/media/MediaCard.jsx
index 7a8f5049a5..eee1e99064 100644
--- a/client/src/components/media/MediaCard.jsx
+++ b/client/src/components/media/MediaCard.jsx
@@ -1,4 +1,5 @@
import { Trash2, Download, Film, Image as ImageIcon, Sparkles, Eye, EyeOff } from 'lucide-react';
+import AddToCollectionMenu from './AddToCollectionMenu';
// Single card used everywhere a generated image/video appears in a grid:
// the Image Gen page's recent gallery, the Video Gen page's recent renders,
@@ -18,6 +19,7 @@ export default function MediaCard({
selected = false,
disabled = false,
hideActions = false,
+ showCollectionMenu = true,
}) {
const { kind, prompt, modelId, previewUrl, downloadUrl } = item;
const isVideo = kind === 'video';
@@ -92,6 +94,7 @@ export default function MediaCard({
<ImageIcon className="w-3 h-3" /> Continue
</button>
)}
+ {showCollectionMenu && <AddToCollectionMenu item={item} />}
<a
href={downloadUrl}
download
diff --git a/client/src/pages/MediaCollectionDetail.jsx b/client/src/pages/MediaCollectionDetail.jsx
new file mode 100644
index 0000000000..f67c5d8578
--- /dev/null
+++ b/client/src/pages/MediaCollectionDetail.jsx
@@ -0,0 +1,215 @@
+import { useEffect, useMemo, useState } from 'react';
+import { useParams, Link, useNavigate } from 'react-router-dom';
+import { ArrowLeft, Pencil, Star } from 'lucide-react';
+import toast from '../components/ui/Toast';
+import MediaCard from '../components/media/MediaCard';
+import MediaLightbox from '../components/media/MediaLightbox';
+import { normalizeImage, normalizeVideo } from '../components/media/normalize';
+import {
+ getMediaCollection, updateMediaCollection,
+ removeMediaCollectionItem, listImageGallery, listVideoHistory,
+ extractLastFrame,
+} from '../services/api';
+
+// Hydrate a collection's "<kind>:<ref>" pointer list into the same
+// normalized records MediaCard expects. We do this on the client so the
+// service stays a pure pointer store — that way an image that's been
+// re-edited keeps its current metadata when you open the collection.
+const hydrate = (collection, imagesByName, videosById) => {
+ const out = [];
+ for (const it of collection.items || []) {
+ if (it.kind === 'image') {
+ const img = imagesByName.get(it.ref);
+ if (img) out.push({ ...normalizeImage(img), addedAt: it.addedAt });
+ } else if (it.kind === 'video') {
+ const vid = videosById.get(it.ref);
+ if (vid) out.push({ ...normalizeVideo(vid), addedAt: it.addedAt });
+ }
+ }
+ // Newest-added first — matches the cover-resolution order so the user's
+ // mental model of "what's at the top" stays consistent.
+ out.sort((a, b) => new Date(b.addedAt || 0) - new Date(a.addedAt || 0));
+ return out;
+};
+
+export default function MediaCollectionDetail() {
+ const { id } = useParams();
+ const navigate = useNavigate();
+ const [collection, setCollection] = useState(null);
+ const [imagesByName, setImagesByName] = useState(new Map());
+ const [videosById, setVideosById] = useState(new Map());
+ const [loading, setLoading] = useState(true);
+ const [editingName, setEditingName] = useState(false);
+ const [nameDraft, setNameDraft] = useState('');
+ const [preview, setPreview] = useState(null);
+
+ const refresh = async () => {
+ setLoading(true);
+ const [c, images, videos] = await Promise.all([
+ getMediaCollection(id).catch((err) => {
+ toast.error(err.message || 'Collection not found');
+ return null;
+ }),
+ listImageGallery().catch(() => []),
+ listVideoHistory().catch(() => []),
+ ]);
+ setCollection(c);
+ setNameDraft(c?.name || '');
+ setImagesByName(new Map((images || []).map((i) => [i.filename, i])));
+ setVideosById(new Map((videos || []).map((v) => [v.id, v])));
+ setLoading(false);
+ };
+ useEffect(() => { refresh(); /* eslint-disable-next-line react-hooks/exhaustive-deps */ }, [id]);
+
+ const items = useMemo(
+ () => collection ? hydrate(collection, imagesByName, videosById) : [],
+ [collection, imagesByName, videosById]
+ );
+
+ const handleRename = async () => {
+ const trimmed = nameDraft.trim();
+ if (!trimmed || trimmed === collection.name) { setEditingName(false); return; }
+ const updated = await updateMediaCollection(collection.id, { name: trimmed }).catch((err) => {
+ toast.error(err.message || 'Rename failed');
+ return null;
+ });
+ if (updated) {
+ setCollection(updated);
+ setEditingName(false);
+ }
+ };
+
+ const handleSetCover = async (item) => {
+ const key = `${item.kind}:${item.kind === 'video' ? item.id : item.filename}`;
+ const next = collection.coverKey === key ? null : key;
+ const updated = await updateMediaCollection(collection.id, { coverKey: next }).catch((err) => {
+ toast.error(err.message || 'Failed to set cover');
+ return null;
+ });
+ if (updated) {
+ setCollection(updated);
+ toast.success(next ? 'Cover updated' : 'Cover reset to newest');
+ }
+ };
+
+ const handleRemove = async (item) => {
+ const key = `${item.kind}:${item.kind === 'video' ? item.id : item.filename}`;
+ const updated = await removeMediaCollectionItem(collection.id, key).catch((err) => {
+ toast.error(err.message || 'Remove failed');
+ return null;
+ });
+ if (updated) setCollection(updated);
+ };
+
+ // Image-Gen "Remix" and "Send to Video" piping — same patterns as
+ // MediaHistory, kept here so the collection grid is a fully usable
+ // surface for action workflows, not just a viewer.
+ const handleRemix = (item) => {
+ const params = new URLSearchParams({ remix: item.filename });
+ if (item.prompt) params.set('prompt', item.prompt);
+ navigate(`/media/image?${params.toString()}`);
+ };
+ const handleSendToVideo = (item) => {
+ const params = new URLSearchParams({ sourceImageFile: item.filename });
+ if (item.width) params.set('w', String(item.width));
+ if (item.height) params.set('h', String(item.height));
+ navigate(`/media/video?${params.toString()}`);
+ };
+ const handleContinue = async (item) => {
+ const { filename } = await extractLastFrame(item.id).catch((err) => {
+ toast.error(err.message || 'Failed to extract last frame');
+ return {};
+ });
+ if (!filename) return;
+ const params = new URLSearchParams({ sourceImageFile: filename });
+ if (item.width) params.set('w', String(item.width));
+ if (item.height) params.set('h', String(item.height));
+ navigate(`/media/video?${params.toString()}`);
+ };
+
+ if (loading) return <div className="text-gray-500 text-sm">Loading…</div>;
+ if (!collection) return (
+ <div className="text-gray-500 text-sm">
+ <Link to="/media/collections" className="text-port-accent hover:underline">← Back to collections</Link>
+ </div>
+ );
+
+ return (
+ <div className="space-y-4">
+ <div className="flex items-center gap-3">
+ <Link to="/media/collections" className="text-gray-400 hover:text-white" title="Back">
+ <ArrowLeft className="w-5 h-5" />
+ </Link>
+ {editingName ? (
+ <input
+ autoFocus
+ type="text"
+ value={nameDraft}
+ onChange={(e) => setNameDraft(e.target.value)}
+ onBlur={handleRename}
+ onKeyDown={(e) => {
+ if (e.key === 'Enter') handleRename();
+ if (e.key === 'Escape') { setNameDraft(collection.name); setEditingName(false); }
+ }}
+ maxLength={80}
+ className="text-xl font-semibold bg-port-card border border-port-border rounded px-2 py-1 text-white focus:outline-none focus:border-port-accent"
+ />
+ ) : (
+ <button type="button" onClick={() => setEditingName(true)} className="text-xl font-semibold text-white hover:text-port-accent flex items-center gap-2">
+ {collection.name}
+ <Pencil className="w-4 h-4 text-gray-500" />
+ </button>
+ )}
+ <span className="text-xs text-gray-500">{items.length} item{items.length === 1 ? '' : 's'}</span>
+ </div>
+
+ {items.length === 0 ? (
+ <div className="text-gray-500 text-sm bg-port-card border border-port-border rounded-lg p-6 text-center">
+ This collection is empty. Use the folder icon on any image/video card to add items here.
+ </div>
+ ) : (
+ <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-3">
+ {items.map((item) => {
+ const key = `${item.kind}:${item.kind === 'video' ? item.id : item.filename}`;
+ const isCover = collection.coverKey === key;
+ return (
+ <div key={key} className="relative">
+ <MediaCard
+ item={item}
+ onPreview={setPreview}
+ onRemix={item.kind === 'image' ? handleRemix : undefined}
+ onSendToVideo={item.kind === 'image' ? handleSendToVideo : undefined}
+ onContinue={item.kind === 'video' ? handleContinue : undefined}
+ onDelete={handleRemove}
+ showCollectionMenu={false}
+ />
+ <button
+ type="button"
+ onClick={() => handleSetCover(item)}
+ className={`absolute top-1.5 right-1.5 w-7 h-7 rounded-full flex items-center justify-center border transition-colors ${
+ isCover
+ ? 'bg-port-accent text-white border-port-accent'
+ : 'bg-black/60 text-gray-300 border-port-border hover:text-white'
+ }`}
+ title={isCover ? 'Cover (click to reset to newest)' : 'Set as cover'}
+ >
+ <Star className="w-3.5 h-3.5" fill={isCover ? 'currentColor' : 'none'} />
+ </button>
+ </div>
+ );
+ })}
+ </div>
+ )}
+
+ {preview && (
+ <MediaLightbox
+ item={preview}
+ onClose={() => setPreview(null)}
+ onRemix={preview.kind === 'image' ? (i) => handleRemix(i) : undefined}
+ onSendToVideo={preview.kind === 'image' ? (i) => handleSendToVideo(i) : undefined}
+ onContinue={preview.kind === 'video' ? (i) => handleContinue(i.raw || i) : undefined}
+ />
+ )}
+ </div>
+ );
+}
diff --git a/client/src/pages/MediaCollections.jsx b/client/src/pages/MediaCollections.jsx
new file mode 100644
index 0000000000..768a5a95b3
--- /dev/null
+++ b/client/src/pages/MediaCollections.jsx
@@ -0,0 +1,170 @@
+import { useEffect, useMemo, useState } from 'react';
+import { Link } from 'react-router-dom';
+import { Plus, FolderOpen, Trash2, Image as ImageIcon, Film } from 'lucide-react';
+import toast from '../components/ui/Toast';
+import {
+ listMediaCollections, createMediaCollection, deleteMediaCollection,
+ listVideoHistory, listImageGallery,
+} from '../services/api';
+
+// Resolve a collection's cover-thumbnail URL. Default = newest item by
+// addedAt; user-pinned coverKey wins when set. We need full image/video
+// records to build the thumbnail src, so the page fetches both lists once
+// and shares them across cards via a Map lookup.
+const resolveCover = (collection, imagesByName, videosById) => {
+ const items = collection.items || [];
+ if (items.length === 0) return null;
+
+ const lookup = (it) => {
+ if (it.kind === 'image') {
+ const img = imagesByName.get(it.ref);
+ return img ? (img.path || `/data/images/${img.filename}`) : null;
+ }
+ const vid = videosById.get(it.ref);
+ return vid?.thumbnail ? `/data/video-thumbnails/${vid.thumbnail}` : null;
+ };
+
+ if (collection.coverKey) {
+ const pinned = items.find((it) => `${it.kind}:${it.ref}` === collection.coverKey);
+ if (pinned) {
+ const url = lookup(pinned);
+ if (url) return url;
+ }
+ }
+ // Fallback: single O(n) pass for the most-recently-added item that has a
+ // renderable thumbnail. Sorting all items is O(n log n) and gets expensive
+ // on collections approaching ITEMS_MAX (5000).
+ let bestUrl = null;
+ let bestTs = -Infinity;
+ for (const it of items) {
+ const url = lookup(it);
+ if (!url) continue;
+ const ts = new Date(it.addedAt || 0).getTime();
+ if (ts > bestTs) { bestTs = ts; bestUrl = url; }
+ }
+ return bestUrl;
+};
+
+export default function MediaCollections() {
+ const [collections, setCollections] = useState([]);
+ const [loading, setLoading] = useState(true);
+ const [creating, setCreating] = useState(false);
+ const [name, setName] = useState('');
+ const [imagesByName, setImagesByName] = useState(new Map());
+ const [videosById, setVideosById] = useState(new Map());
+
+ const refresh = async () => {
+ setLoading(true);
+ const [cols, images, videos] = await Promise.all([
+ listMediaCollections().catch(() => []),
+ listImageGallery().catch(() => []),
+ listVideoHistory().catch(() => []),
+ ]);
+ setCollections(Array.isArray(cols) ? cols : []);
+ setImagesByName(new Map((images || []).map((i) => [i.filename, i])));
+ setVideosById(new Map((videos || []).map((v) => [v.id, v])));
+ setLoading(false);
+ };
+ useEffect(() => { refresh(); }, []);
+
+ const handleCreate = async (e) => {
+ e.preventDefault();
+ const trimmed = name.trim();
+ if (!trimmed) return;
+ setCreating(true);
+ const created = await createMediaCollection({ name: trimmed }).catch((err) => {
+ toast.error(err.message || 'Failed to create');
+ return null;
+ });
+ setCreating(false);
+ if (created) {
+ setCollections((prev) => [...prev, created]);
+ setName('');
+ toast.success(`Created "${created.name}"`);
+ }
+ };
+
+ const handleDelete = async (collection) => {
+ setCollections((prev) => prev.filter((c) => c.id !== collection.id));
+ await deleteMediaCollection(collection.id).catch((err) => {
+ toast.error(err.message || 'Delete failed');
+ refresh();
+ });
+ };
+
+ const enriched = useMemo(() => collections.map((c) => {
+ const counts = (c.items || []).reduce((acc, it) => {
+ acc[it.kind] = (acc[it.kind] || 0) + 1;
+ return acc;
+ }, { image: 0, video: 0 });
+ return { ...c, cover: resolveCover(c, imagesByName, videosById), counts };
+ }), [collections, imagesByName, videosById]);
+
+ return (
+ <div className="space-y-4">
+ <form onSubmit={handleCreate} className="flex gap-2 items-center">
+ <input
+ type="text"
+ value={name}
+ onChange={(e) => setName(e.target.value)}
+ maxLength={80}
+ placeholder="New collection name"
+ className="flex-1 bg-port-card border border-port-border rounded-lg px-3 py-2 text-sm text-white focus:outline-none focus:border-port-accent"
+ />
+ <button
+ type="submit"
+ disabled={creating || !name.trim()}
+ className="px-3 py-2 bg-port-accent/20 hover:bg-port-accent/40 text-port-accent rounded-lg text-sm flex items-center gap-1.5 disabled:opacity-40"
+ >
+ <Plus className="w-4 h-4" /> Create
+ </button>
+ </form>
+
+ {loading ? (
+ <div className="text-gray-500 text-sm">Loading…</div>
+ ) : enriched.length === 0 ? (
+ <div className="text-gray-500 text-sm bg-port-card border border-port-border rounded-lg p-6 text-center">
+ No collections yet. Create one above, or use the folder icon on any image/video card to start a new collection.
+ </div>
+ ) : (
+ <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 gap-3">
+ {enriched.map((c) => (
+ <div key={c.id} className="bg-port-card border border-port-border rounded-xl overflow-hidden flex flex-col">
+ <Link
+ to={`/media/collections/${encodeURIComponent(c.id)}`}
+ className="block aspect-square bg-port-bg relative"
+ >
+ {c.cover ? (
+ <img src={c.cover} alt={c.name} className="w-full h-full object-cover" loading="lazy" />
+ ) : (
+ <div className="w-full h-full flex items-center justify-center text-gray-600">
+ <FolderOpen className="w-12 h-12" />
+ </div>
+ )}
+ </Link>
+ <div className="p-2 space-y-1.5 flex-1 flex flex-col">
+ <Link to={`/media/collections/${encodeURIComponent(c.id)}`} className="text-sm text-white hover:text-port-accent line-clamp-1" title={c.name}>
+ {c.name}
+ </Link>
+ <div className="flex items-center gap-2 text-[10px] text-gray-500">
+ {c.counts.image > 0 && <span className="flex items-center gap-1"><ImageIcon className="w-3 h-3" />{c.counts.image}</span>}
+ {c.counts.video > 0 && <span className="flex items-center gap-1"><Film className="w-3 h-3" />{c.counts.video}</span>}
+ {c.counts.image === 0 && c.counts.video === 0 && <span>Empty</span>}
+ </div>
+ <div className="flex-1" />
+ <button
+ type="button"
+ onClick={() => handleDelete(c)}
+ className="self-end px-1.5 py-1 bg-port-error/20 hover:bg-port-error/40 text-port-error text-[10px] rounded flex items-center gap-1"
+ title="Delete collection"
+ >
+ <Trash2 className="w-3 h-3" />
+ </button>
+ </div>
+ </div>
+ ))}
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/client/src/pages/MediaGen.jsx b/client/src/pages/MediaGen.jsx
index 1ff1591e10..e6192b4596 100644
--- a/client/src/pages/MediaGen.jsx
+++ b/client/src/pages/MediaGen.jsx
@@ -1,10 +1,12 @@
import { useNavigate, useLocation, Outlet } from 'react-router-dom';
-import { Layers, Image as ImageIcon, Film, History, HardDrive } from 'lucide-react';
+import { Layers, Image as ImageIcon, Film, History, HardDrive, Scissors, FolderOpen } from 'lucide-react';
const TABS = [
{ id: 'image', label: 'Image', icon: ImageIcon },
{ id: 'video', label: 'Video', icon: Film },
+ { id: 'timeline', label: 'Timeline', icon: Scissors },
{ id: 'history', label: 'History', icon: History },
+ { id: 'collections', label: 'Collections', icon: FolderOpen },
{ id: 'models', label: 'Models', icon: HardDrive }
];
diff --git a/client/src/pages/MediaHistory.jsx b/client/src/pages/MediaHistory.jsx
index d7e6e1862c..8d67848d24 100644
--- a/client/src/pages/MediaHistory.jsx
+++ b/client/src/pages/MediaHistory.jsx
@@ -92,7 +92,10 @@ export default function MediaHistory() {
const handleContinue = async (item) => {
try {
const { filename } = await extractLastFrame(item.id);
- navigate(`/media/video?sourceImageFile=${encodeURIComponent(filename)}`);
+ const params = new URLSearchParams({ sourceImageFile: filename });
+ if (item?.width) params.set('w', String(item.width));
+ if (item?.height) params.set('h', String(item.height));
+ navigate(`/media/video?${params.toString()}`);
} catch (err) {
toast.error(err.message || 'Failed to extract last frame');
}
diff --git a/client/src/pages/VideoGen.jsx b/client/src/pages/VideoGen.jsx
index 468d80aafb..cb9252fa01 100644
--- a/client/src/pages/VideoGen.jsx
+++ b/client/src/pages/VideoGen.jsx
@@ -87,6 +87,8 @@ export default function VideoGen() {
const incomingSourceImage = searchParams.get('sourceImageFile');
const incomingPrompt = searchParams.get('prompt');
const incomingNegativePrompt = searchParams.get('negativePrompt');
+ const incomingWidth = searchParams.get('w');
+ const incomingHeight = searchParams.get('h');
const settingsOpen = searchParams.get('settings') === '1';
const openSettings = () => setSearchParams(prev => { const n = new URLSearchParams(prev); n.set('settings', '1'); return n; });
const closeSettings = () => setSearchParams(prev => { const n = new URLSearchParams(prev); n.delete('settings'); return n; });
@@ -132,6 +134,15 @@ export default function VideoGen() {
useEffect(() => {
if (incomingNegativePrompt) setNegativePrompt(incomingNegativePrompt);
}, [incomingNegativePrompt]);
+ // When "Continue" pipes a video's last frame here, also sync the resolution
+ // so the new render matches the source. Width/height get rounded to the
+ // model's 64-pixel grid server-side, so off-grid sources still work.
+ useEffect(() => {
+ const w = Number(incomingWidth);
+ const h = Number(incomingHeight);
+ if (Number.isFinite(w) && w > 0) setWidth(w);
+ if (Number.isFinite(h) && h > 0) setHeight(h);
+ }, [incomingWidth, incomingHeight]);
const [history, setHistory] = useState([]);
const [preview, setPreview] = useState(null);
@@ -179,7 +190,11 @@ export default function VideoGen() {
toast.error(err.message || 'Failed to extract last frame');
return {};
});
- if (filename) navigate(`/media/video?sourceImageFile=${encodeURIComponent(filename)}`);
+ if (!filename) return;
+ const params = new URLSearchParams({ sourceImageFile: filename });
+ if (item?.width) params.set('w', String(item.width));
+ if (item?.height) params.set('h', String(item.height));
+ navigate(`/media/video?${params.toString()}`);
};
const [generating, setGenerating] = useState(false);
@@ -750,6 +765,9 @@ export default function VideoGen() {
onChange={handleResolutionChange}
className="w-full bg-port-bg border border-port-border rounded-lg px-2 py-2 text-sm text-white focus:outline-none focus:border-port-accent disabled:opacity-50"
>
+ {!matchedResolution && (
+ <option value={resolutionLabel}>{`${width}×${height} (custom)`}</option>
+ )}
{RESOLUTIONS.map((r) => <option key={r.label} value={r.label}>{r.label}</option>)}
</select>
</div>
diff --git a/client/src/pages/VideoTimeline.jsx b/client/src/pages/VideoTimeline.jsx
new file mode 100644
index 0000000000..a6545c2751
--- /dev/null
+++ b/client/src/pages/VideoTimeline.jsx
@@ -0,0 +1,155 @@
+import { useEffect, useMemo, useState } from 'react';
+import { useNavigate } from 'react-router-dom';
+import { Plus, Film, Trash2, Clock } from 'lucide-react';
+import toast from '../components/ui/Toast';
+import * as api from '../services/api';
+
+const formatDuration = (sec) => {
+ if (!sec || !Number.isFinite(sec)) return '—';
+ const m = Math.floor(sec / 60);
+ const s = Math.floor(sec % 60);
+ return `${m}:${String(s).padStart(2, '0')}`;
+};
+
+export default function VideoTimeline() {
+ const navigate = useNavigate();
+ const [projects, setProjects] = useState([]);
+ const [history, setHistory] = useState([]);
+ const [loading, setLoading] = useState(true);
+ const [creating, setCreating] = useState(false);
+ const [name, setName] = useState('');
+
+ const refresh = async () => {
+ const [list, hist] = await Promise.all([
+ api.listTimelineProjects().catch(() => []),
+ api.listVideoHistory().catch(() => []),
+ ]);
+ setProjects(list);
+ setHistory(hist);
+ setLoading(false);
+ };
+
+ useEffect(() => { refresh(); }, []);
+
+ const handleCreate = async (e) => {
+ e.preventDefault();
+ const trimmed = name.trim();
+ if (!trimmed) return;
+ setCreating(true);
+ const created = await api.createTimelineProject(trimmed).catch((err) => {
+ toast.error(`Failed to create: ${err.message}`);
+ return null;
+ });
+ setCreating(false);
+ if (created) {
+ setName('');
+ navigate(`/media/timeline/${created.id}`);
+ }
+ };
+
+ const handleDelete = async (project) => {
+ setProjects((prev) => prev.filter((p) => p.id !== project.id));
+ await api.deleteTimelineProject(project.id).catch((err) => {
+ toast.error(`Failed to delete: ${err.message}`);
+ refresh();
+ });
+ };
+
+ const projectStats = useMemo(() => {
+ const historyMap = new Map(history.map((h) => [h.id, h]));
+ const stats = new Map();
+ for (const project of projects) {
+ let totalSec = 0;
+ let firstThumb = null;
+ for (const ref of project.clips || []) {
+ const clip = historyMap.get(ref.clipId);
+ if (!clip) continue;
+ totalSec += Math.max(0, ref.outSec - ref.inSec);
+ if (!firstThumb && clip.thumbnail) firstThumb = `/data/video-thumbnails/${clip.thumbnail}`;
+ }
+ stats.set(project.id, { totalSec, firstThumb });
+ }
+ return stats;
+ }, [projects, history]);
+
+ return (
+ <div className="space-y-4">
+ <form onSubmit={handleCreate} className="flex gap-2 items-center">
+ <input
+ type="text"
+ value={name}
+ onChange={(e) => setName(e.target.value)}
+ placeholder="New project name…"
+ className="flex-1 max-w-sm px-3 py-2 bg-port-card border border-port-border rounded-md text-white text-sm placeholder-gray-500 focus:outline-none focus:border-port-accent"
+ disabled={creating}
+ />
+ <button
+ type="submit"
+ disabled={!name.trim() || creating}
+ className="flex items-center gap-2 px-3 py-2 bg-port-accent hover:bg-port-accent/80 disabled:opacity-40 disabled:cursor-not-allowed text-white text-sm rounded-md transition-colors"
+ >
+ <Plus size={16} /> New project
+ </button>
+ </form>
+
+ {loading && (
+ <div className="text-gray-500 text-sm">Loading…</div>
+ )}
+
+ {!loading && projects.length === 0 && (
+ <div className="text-center py-12 text-gray-500">
+ <Film className="w-10 h-10 mx-auto mb-3 opacity-40" />
+ <p className="text-sm">No timeline projects yet. Create one above to start compositing clips.</p>
+ </div>
+ )}
+
+ {!loading && projects.length > 0 && (
+ <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-3">
+ {projects.map((project) => {
+ const { totalSec, firstThumb } = projectStats.get(project.id) || { totalSec: 0, firstThumb: null };
+ return (
+ <div key={project.id} className="bg-port-card border border-port-border rounded-xl overflow-hidden hover:border-port-accent/50 transition-colors">
+ <button
+ type="button"
+ onClick={() => navigate(`/media/timeline/${project.id}`)}
+ className="block w-full aspect-video bg-port-bg relative"
+ >
+ {firstThumb ? (
+ <img src={firstThumb} alt={project.name} className="w-full h-full object-cover" />
+ ) : (
+ <div className="w-full h-full flex items-center justify-center text-gray-600">
+ <Film className="w-10 h-10" />
+ </div>
+ )}
+ </button>
+ <div className="p-3 space-y-1.5">
+ <div className="flex items-start justify-between gap-2">
+ <button
+ type="button"
+ onClick={() => navigate(`/media/timeline/${project.id}`)}
+ className="flex-1 text-left text-sm font-medium text-white hover:text-port-accent transition-colors truncate"
+ >
+ {project.name}
+ </button>
+ <button
+ type="button"
+ onClick={() => handleDelete(project)}
+ className="p-1 text-gray-500 hover:text-port-error transition-colors"
+ title="Delete project"
+ >
+ <Trash2 className="w-4 h-4" />
+ </button>
+ </div>
+ <div className="flex items-center gap-3 text-xs text-gray-400">
+ <span className="flex items-center gap-1"><Film className="w-3 h-3" />{(project.clips || []).length} clips</span>
+ <span className="flex items-center gap-1"><Clock className="w-3 h-3" />{formatDuration(totalSec)}</span>
+ </div>
+ </div>
+ </div>
+ );
+ })}
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/client/src/pages/VideoTimelineEditor.jsx b/client/src/pages/VideoTimelineEditor.jsx
new file mode 100644
index 0000000000..ecf597aede
--- /dev/null
+++ b/client/src/pages/VideoTimelineEditor.jsx
@@ -0,0 +1,717 @@
+import { useEffect, useRef, useState, useCallback, useMemo } from 'react';
+import { useParams, useNavigate } from 'react-router-dom';
+import {
+ DndContext,
+ PointerSensor,
+ useSensor,
+ useSensors,
+ closestCenter,
+} from '@dnd-kit/core';
+import {
+ SortableContext,
+ arrayMove,
+ horizontalListSortingStrategy,
+ useSortable,
+} from '@dnd-kit/sortable';
+import { CSS } from '@dnd-kit/utilities';
+import {
+ Play, Pause, Plus, Trash2, X, Save, Film, Loader2, ArrowLeft, Volume2, VolumeX,
+} from 'lucide-react';
+import toast from '../components/ui/Toast';
+import * as api from '../services/api';
+
+// Map project-time t (every clip contributes its trimmed duration) to the
+// (clipIndex, withinClipSec) pair the preview <video> element needs. The
+// strict t < acc+dur comparison falls through on exact boundaries so a
+// playhead landing on a seam plays the next clip, not the end of the prior.
+const findClipAt = (clips, t) => {
+ let acc = 0;
+ for (let i = 0; i < clips.length; i++) {
+ const dur = Math.max(0, clips[i].outSec - clips[i].inSec);
+ if (t < acc + dur || i === clips.length - 1) {
+ return { index: i, within: Math.max(0, t - acc), startAtProj: acc };
+ }
+ acc += dur;
+ }
+ return { index: -1, within: 0, startAtProj: 0 };
+};
+
+const totalDuration = (clips) => clips.reduce((s, c) => s + Math.max(0, c.outSec - c.inSec), 0);
+
+const formatTime = (sec) => {
+ if (!Number.isFinite(sec) || sec < 0) return '0:00.00';
+ const m = Math.floor(sec / 60);
+ const s = sec - m * 60;
+ return `${m}:${s.toFixed(2).padStart(5, '0')}`;
+};
+
+// Draggable+sortable timeline block. Snaps the trimmed duration to a width
+// derived from `pxPerSec` so longer clips visibly take more horizontal space.
+function TimelineBlock({ clip, clipMeta, isSelected, isMissing, pxPerSec, onSelect, onRemove }) {
+ const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({ id: clip._key });
+ const dur = Math.max(0.05, clip.outSec - clip.inSec);
+ const width = Math.max(60, dur * pxPerSec);
+ const style = {
+ transform: CSS.Transform.toString(transform),
+ transition,
+ width: `${width}px`,
+ opacity: isDragging ? 0.4 : 1,
+ };
+ return (
+ <div
+ ref={setNodeRef}
+ style={style}
+ className={`relative shrink-0 h-20 rounded-md border-2 cursor-pointer transition-colors group ${
+ isMissing
+ ? 'bg-port-error/20 border-port-error'
+ : isSelected
+ ? 'border-port-accent bg-port-accent/10'
+ : 'bg-port-card border-port-border hover:border-port-accent/50'
+ }`}
+ onClick={() => onSelect(clip._key)}
+ {...attributes}
+ {...listeners}
+ >
+ {clipMeta?.thumbnail && (
+ <img
+ src={`/data/video-thumbnails/${clipMeta.thumbnail}`}
+ alt=""
+ draggable={false}
+ className="w-full h-full object-cover rounded-md opacity-80"
+ />
+ )}
+ <div className="absolute inset-0 rounded-md bg-gradient-to-t from-black/70 via-transparent to-transparent pointer-events-none" />
+ <div className="absolute bottom-1 left-1.5 right-1.5 text-[10px] text-white truncate font-medium">
+ {isMissing ? '(missing)' : clipMeta?.prompt?.slice(0, 40) || 'clip'}
+ </div>
+ <div className="absolute top-1 left-1.5 text-[9px] text-white bg-black/60 px-1 rounded">
+ {dur.toFixed(2)}s
+ </div>
+ <button
+ type="button"
+ onClick={(e) => { e.stopPropagation(); onRemove(clip._key); }}
+ onPointerDown={(e) => e.stopPropagation()}
+ className="absolute top-1 right-1 p-0.5 bg-black/60 hover:bg-port-error rounded opacity-0 group-hover:opacity-100 transition-opacity text-white"
+ title="Remove from timeline"
+ >
+ <X className="w-3 h-3" />
+ </button>
+ </div>
+ );
+}
+
+// Library tile — renders a clip from history with an "Add to timeline" button.
+// Does not use DnD here; click-to-add at end is simpler and equally functional
+// for v1. Reordering on the timeline itself uses sortable.
+function LibraryTile({ clip, onAdd }) {
+ const dur = clip.numFrames && clip.fps ? clip.numFrames / clip.fps : 0;
+ return (
+ <div className="bg-port-card border border-port-border rounded-md overflow-hidden hover:border-port-accent/50 transition-colors">
+ <div className="aspect-video bg-port-bg relative">
+ {clip.thumbnail ? (
+ <img src={`/data/video-thumbnails/${clip.thumbnail}`} alt={clip.prompt} className="w-full h-full object-cover" loading="lazy" />
+ ) : (
+ <div className="w-full h-full flex items-center justify-center text-gray-600">
+ <Film className="w-6 h-6" />
+ </div>
+ )}
+ <span className="absolute bottom-1 right-1 text-[9px] px-1 py-0.5 bg-black/70 text-white rounded">
+ {dur.toFixed(1)}s
+ </span>
+ </div>
+ <div className="p-1.5 space-y-1">
+ <p className="text-[10px] text-gray-300 line-clamp-2" title={clip.prompt}>{clip.prompt}</p>
+ <button
+ type="button"
+ onClick={() => onAdd(clip)}
+ className="w-full flex items-center justify-center gap-1 px-1.5 py-1 bg-port-accent/20 hover:bg-port-accent/40 text-port-accent text-[10px] rounded"
+ >
+ <Plus className="w-3 h-3" /> Add to timeline
+ </button>
+ </div>
+ </div>
+ );
+}
+
+export default function VideoTimelineEditor() {
+ const { projectId } = useParams();
+ const navigate = useNavigate();
+ const [project, setProject] = useState(null);
+ const [history, setHistory] = useState([]);
+ const [loading, setLoading] = useState(true);
+ const [error, setError] = useState(null);
+ // Local timeline (each clip gets a stable _key for dnd-kit identity)
+ const [clips, setClips] = useState([]);
+ const [selectedKey, setSelectedKey] = useState(null);
+ const [pxPerSec, setPxPerSec] = useState(60);
+ const [t, setT] = useState(0); // project-time in seconds
+ const [playing, setPlaying] = useState(false);
+ const [muted, setMuted] = useState(false);
+ const [renderJobId, setRenderJobId] = useState(null);
+ const [renderProgress, setRenderProgress] = useState(0);
+ const [showLibrary, setShowLibrary] = useState(true);
+ // Local input drafts. Editing the canonical state on every keystroke makes
+ // the rename onBlur-vs-canonical comparison always-equal, and forces the
+ // trim inputs through toFixed() per stroke (which prevents typing "0.").
+ const [nameDraft, setNameDraft] = useState('');
+ const [trimDraft, setTrimDraft] = useState({ inSec: '', outSec: '' });
+
+ const videoRef = useRef(null);
+ const lastSrcRef = useRef('');
+ // The video.onloadedmetadata callback fires async after a src swap. Reading
+ // `playing` directly inside it captures the value at swap time — if the
+ // user pauses while metadata loads, the handler would still autoplay. A
+ // ref we update synchronously gives the handler the live value.
+ const playingRef = useRef(false);
+ useEffect(() => { playingRef.current = playing; }, [playing]);
+ const playClipIndexRef = useRef(-1);
+
+ const sensors = useSensors(useSensor(PointerSensor, { activationConstraint: { distance: 6 } }));
+
+ const refresh = useCallback(async () => {
+ setLoading(true);
+ setError(null);
+ const [proj, hist] = await Promise.all([
+ api.getTimelineProject(projectId).catch((err) => { setError(err.message); return null; }),
+ api.listVideoHistory().catch(() => []),
+ ]);
+ if (proj) {
+ setProject(proj);
+ setClips((proj.clips || []).map((c, idx) => ({ ...c, _key: `${c.clipId}-${idx}-${Math.random().toString(36).slice(2, 8)}` })));
+ }
+ setHistory(hist);
+ setLoading(false);
+ }, [projectId]);
+
+ useEffect(() => { refresh(); }, [refresh]);
+
+ // Sync the rename draft to the canonical name when the project (re)loads
+ // or is renamed elsewhere. Local edits (onChange) take over until the
+ // user blurs.
+ useEffect(() => {
+ if (project?.name) setNameDraft(project.name);
+ }, [project?.id, project?.name]);
+
+ // Sync trim drafts when the user picks a different clip. While editing the
+ // selected clip, the draft is the source of truth — committing on blur
+ // drives the canonical update.
+ useEffect(() => {
+ setTrimDraft((prev) => {
+ const sel = clips.find((c) => c._key === selectedKey);
+ if (!sel) return { inSec: '', outSec: '' };
+ const next = { inSec: sel.inSec.toFixed(2), outSec: sel.outSec.toFixed(2) };
+ if (prev.inSec === next.inSec && prev.outSec === next.outSec) return prev;
+ return next;
+ });
+ }, [selectedKey, clips]);
+
+ // O(1) clip metadata lookup. The video-sync effect runs on every rAF tick
+ // during playback; a linear find() per frame multiplied by clip count is
+ // measurable on long timelines.
+ const historyMap = useMemo(() => {
+ const m = new Map();
+ for (const h of history) m.set(h.id, h);
+ return m;
+ }, [history]);
+ const metaFor = useCallback((clipId) => historyMap.get(clipId), [historyMap]);
+
+ const total = useMemo(() => totalDuration(clips), [clips]);
+
+ // Clamp the playhead into [0, total] when the timeline duration shrinks
+ // (clip removal, tighter trim, etc.). Without this, t can exceed total
+ // and findClipAt returns a `within` past the last clip's outSec — the
+ // preview seeks to black frames.
+ useEffect(() => {
+ if (t > total) { setT(total); setPlaying(false); }
+ }, [total, t]);
+
+ // Save current timeline (debounced via the caller). Server validates and
+ // returns the canonical project; we only update updatedAt and preserve
+ // local _keys to avoid blowing away the dnd identity.
+ const saveTimeline = useCallback(async (next) => {
+ if (!project) return false;
+ const cleanClips = next.map((c) => ({ clipId: c.clipId, inSec: c.inSec, outSec: c.outSec }));
+ const updated = await api.updateTimelineProject(projectId, {
+ clips: cleanClips,
+ expectedUpdatedAt: project.updatedAt,
+ }).catch((err) => {
+ if (err.code === 'CONFLICT') {
+ toast.error('Project was modified elsewhere — reloading');
+ refresh();
+ return null;
+ }
+ toast.error(`Save failed: ${err.message}`);
+ return null;
+ });
+ if (!updated) return false;
+ setProject((p) => ({ ...p, updatedAt: updated.updatedAt }));
+ return true;
+ }, [project, projectId, refresh]);
+
+ // Debounced save: trim-input edits fire many PATCHes per drag if we don't
+ // batch them. 400ms gives the user time to stop fiddling before we hit the
+ // server.
+ const saveTimerRef = useRef(null);
+ const queueSave = useCallback((next) => {
+ clearTimeout(saveTimerRef.current);
+ saveTimerRef.current = setTimeout(() => saveTimeline(next), 400);
+ }, [saveTimeline]);
+
+ // Drop any pending debounced save when the editor unmounts so a stale
+ // timeout doesn't fire after navigation.
+ useEffect(() => () => clearTimeout(saveTimerRef.current), []);
+
+ const updateClips = useCallback((updater) => {
+ setClips((prev) => {
+ const next = typeof updater === 'function' ? updater(prev) : updater;
+ queueSave(next);
+ return next;
+ });
+ }, [queueSave]);
+
+ // Add a clip to the end of the timeline at its full natural duration
+ const addClip = (clip) => {
+ const fullDur = clip.numFrames && clip.fps ? clip.numFrames / clip.fps : 4;
+ const next = {
+ _key: `${clip.id}-${Date.now()}-${Math.random().toString(36).slice(2, 6)}`,
+ clipId: clip.id,
+ inSec: 0,
+ outSec: fullDur,
+ };
+ updateClips((prev) => [...prev, next]);
+ setSelectedKey(next._key);
+ };
+
+ const removeClip = (key) => {
+ updateClips((prev) => prev.filter((c) => c._key !== key));
+ if (selectedKey === key) setSelectedKey(null);
+ };
+
+ // Update the inSec/outSec of the selected clip; clamp to 0..sourceDuration.
+ const editSelected = (patch) => {
+ updateClips((prev) => prev.map((c) => {
+ if (c._key !== selectedKey) return c;
+ const meta = metaFor(c.clipId);
+ const sourceDur = meta?.numFrames && meta?.fps ? meta.numFrames / meta.fps : Infinity;
+ // Match the server's CLIP_TOO_SHORT guard (1/fps). Hardcoded 0.04 was
+ // too lenient at 24fps and would let the UI build a project that the
+ // render rejected with 400 CLIP_TOO_SHORT.
+ const minDur = meta?.fps && meta.fps > 0 ? 1 / meta.fps : 0.04;
+ let inSec = patch.inSec != null ? patch.inSec : c.inSec;
+ let outSec = patch.outSec != null ? patch.outSec : c.outSec;
+ inSec = Math.max(0, Math.min(inSec, sourceDur - minDur));
+ outSec = Math.max(inSec + minDur, Math.min(outSec, sourceDur));
+ return { ...c, inSec, outSec };
+ }));
+ };
+
+ const onDragEnd = ({ active, over }) => {
+ if (!over || active.id === over.id) return;
+ updateClips((prev) => {
+ const oldIdx = prev.findIndex((c) => c._key === active.id);
+ const newIdx = prev.findIndex((c) => c._key === over.id);
+ if (oldIdx === -1 || newIdx === -1) return prev;
+ return arrayMove(prev, oldIdx, newIdx);
+ });
+ };
+
+ // Preview playback: keep a single <video> element that follows project-time.
+ // On every rAF tick, advance `t` by elapsed wall-time, find which clip we're
+ // in, and swap the <video>.src + currentTime when crossing a boundary.
+ const rafRef = useRef(null);
+ const lastTickRef = useRef(0);
+ useEffect(() => {
+ if (!playing) return;
+ lastTickRef.current = performance.now();
+ const tick = (now) => {
+ const dt = (now - lastTickRef.current) / 1000;
+ lastTickRef.current = now;
+ setT((prev) => {
+ const next = prev + dt;
+ if (next >= total) {
+ setPlaying(false);
+ return total;
+ }
+ return next;
+ });
+ rafRef.current = requestAnimationFrame(tick);
+ };
+ rafRef.current = requestAnimationFrame(tick);
+ return () => cancelAnimationFrame(rafRef.current);
+ }, [playing, total]);
+
+ // Sync the <video> element to project-time `t` whenever it changes.
+ useEffect(() => {
+ if (clips.length === 0) return;
+ const { index, within } = findClipAt(clips, t);
+ if (index < 0) return;
+ const clip = clips[index];
+ const meta = metaFor(clip.clipId);
+ if (!meta) return;
+ const src = `/data/videos/${meta.filename}`;
+ const video = videoRef.current;
+ if (!video) return;
+ const wantTime = clip.inSec + within;
+ if (lastSrcRef.current !== src) {
+ lastSrcRef.current = src;
+ video.src = src;
+ // Wait for metadata before seeking — seek-before-load silently no-ops
+ // and the user sees frame 0 of the clip instead of `inSec + within`.
+ video.onloadedmetadata = () => {
+ video.currentTime = wantTime;
+ if (playingRef.current) video.play().catch(() => {});
+ };
+ } else if (index !== playClipIndexRef.current) {
+ video.currentTime = wantTime;
+ } else if (!playing && Math.abs(video.currentTime - wantTime) > 0.05) {
+ // Scrubbing while paused or moving the playhead within the same clip:
+ // the rAF loop only fires while playing, so we need to drive the
+ // element manually. During playback the video element advances on its
+ // own — re-seeking on every rAF tick would cause buffering stutter.
+ video.currentTime = wantTime;
+ }
+ playClipIndexRef.current = index;
+ }, [clips, t, metaFor, playing]);
+
+ // Pause/play the underlying element in lockstep with `playing`.
+ useEffect(() => {
+ const video = videoRef.current;
+ if (!video) return;
+ if (playing) video.play().catch(() => {});
+ else video.pause();
+ }, [playing]);
+
+ useEffect(() => {
+ const video = videoRef.current;
+ if (video) video.muted = muted;
+ }, [muted]);
+
+ const handleRender = async () => {
+ if (clips.length === 0) {
+ toast.error('Add at least one clip before rendering');
+ return;
+ }
+ // Flush any pending PATCH so the server-side render reads the latest
+ // layout. If the save fails (conflict, network), abort — otherwise we'd
+ // render a stale server-side timeline while the UI shows fresh edits.
+ clearTimeout(saveTimerRef.current);
+ const saved = await saveTimeline(clips);
+ if (!saved) return;
+ const result = await api.renderTimelineProject(projectId).catch((err) => {
+ if (err.code === 'RENDER_IN_PROGRESS') {
+ const jobId = err.context?.jobId;
+ if (jobId) { setRenderJobId(jobId); toast('Re-attaching to in-flight render'); return null; }
+ }
+ toast.error(`Render failed: ${err.message}`);
+ return null;
+ });
+ if (result?.jobId) {
+ setRenderJobId(result.jobId);
+ setRenderProgress(0);
+ }
+ };
+
+ // SSE progress wiring — opens an EventSource on the render jobId, updates
+ // the progress bar, and on 'complete' navigates to Media History focused
+ // on the new clip.
+ useEffect(() => {
+ if (!renderJobId) return;
+ const es = new EventSource(`/api/video-timeline/${renderJobId}/events`);
+ es.onmessage = (ev) => {
+ const data = JSON.parse(ev.data);
+ if (data.type === 'progress') setRenderProgress(data.progress);
+ else if (data.type === 'complete') {
+ toast.success('Timeline rendered');
+ es.close();
+ setRenderJobId(null);
+ navigate(`/media/history?focus=${data.result.id}`);
+ } else if (data.type === 'error') {
+ toast.error(data.error || 'Render failed');
+ es.close();
+ setRenderJobId(null);
+ } else if (data.type === 'cancelled') {
+ toast('Render cancelled');
+ es.close();
+ setRenderJobId(null);
+ setRenderProgress(0);
+ }
+ };
+ es.onerror = () => {
+ es.close();
+ toast.error('Lost connection to render — check Media History');
+ setRenderJobId(null);
+ setRenderProgress(0);
+ };
+ return () => es.close();
+ }, [renderJobId, navigate]);
+
+ if (loading) return <div className="text-gray-500 text-sm">Loading project…</div>;
+ if (error || !project) {
+ return (
+ <div className="text-center py-12">
+ <p className="text-port-error mb-3">{error || 'Project not found'}</p>
+ <button
+ type="button"
+ onClick={() => navigate('/media/timeline')}
+ className="px-3 py-2 bg-port-accent hover:bg-port-accent/80 text-white text-sm rounded-md"
+ >
+ Back to projects
+ </button>
+ </div>
+ );
+ }
+
+ const selectedClip = clips.find((c) => c._key === selectedKey);
+ const selectedMeta = selectedClip ? metaFor(selectedClip.clipId) : null;
+ const selectedSourceDur = selectedMeta?.numFrames && selectedMeta?.fps ? selectedMeta.numFrames / selectedMeta.fps : null;
+
+ // Filter the library: hide outputs of any timeline render so the rail
+ // doesn't grow unbounded with the user's own renders.
+ const libraryClips = history.filter((h) => !h.timelineProjectId && !h.hidden);
+
+ const usedClipIds = new Set(clips.map((c) => c.clipId));
+ const missingKeys = new Set(clips.filter((c) => !metaFor(c.clipId)).map((c) => c._key));
+
+ return (
+ <div className="space-y-3">
+ <div className="flex items-center justify-between gap-3">
+ <div className="flex items-center gap-3 min-w-0">
+ <button
+ type="button"
+ onClick={() => navigate('/media/timeline')}
+ className="p-1.5 text-gray-400 hover:text-white"
+ title="Back to projects"
+ >
+ <ArrowLeft className="w-4 h-4" />
+ </button>
+ <input
+ type="text"
+ value={nameDraft}
+ onChange={(e) => setNameDraft(e.target.value)}
+ onBlur={async (e) => {
+ const trimmed = e.target.value.trim();
+ if (!trimmed) { setNameDraft(project.name); return; }
+ if (trimmed === project.name) return;
+ const updated = await api.updateTimelineProject(projectId, {
+ name: trimmed, expectedUpdatedAt: project.updatedAt,
+ }).catch((err) => {
+ toast.error(`Rename failed: ${err.message}`);
+ setNameDraft(project.name);
+ return null;
+ });
+ if (updated) {
+ setProject((p) => ({ ...p, name: updated.name, updatedAt: updated.updatedAt }));
+ setNameDraft(updated.name);
+ }
+ }}
+ className="bg-transparent text-white font-medium text-lg focus:outline-none focus:bg-port-card focus:px-2 rounded transition-all"
+ />
+ <span className="text-xs text-gray-500">{clips.length} clips · {formatTime(total)}</span>
+ </div>
+ <div className="flex items-center gap-2">
+ <button
+ type="button"
+ onClick={() => setShowLibrary((v) => !v)}
+ className="px-2 py-1.5 text-xs text-gray-400 hover:text-white border border-port-border rounded-md"
+ >
+ {showLibrary ? 'Hide library' : 'Show library'}
+ </button>
+ <button
+ type="button"
+ onClick={handleRender}
+ disabled={clips.length === 0 || !!renderJobId}
+ className="flex items-center gap-2 px-3 py-1.5 bg-port-success hover:bg-port-success/80 disabled:opacity-40 disabled:cursor-not-allowed text-white text-sm rounded-md"
+ >
+ {renderJobId ? <Loader2 className="w-4 h-4 animate-spin" /> : <Save className="w-4 h-4" />}
+ {renderJobId ? `Rendering ${(renderProgress * 100).toFixed(0)}%` : 'Render'}
+ </button>
+ </div>
+ </div>
+
+ <div className="grid grid-cols-1 lg:grid-cols-[260px_1fr_240px] gap-3 min-h-[400px]">
+ {/* Left rail — library */}
+ {showLibrary && (
+ <div className="bg-port-card/50 border border-port-border rounded-lg p-2 max-h-[600px] overflow-y-auto">
+ <div className="text-xs uppercase text-gray-500 tracking-wide mb-2 px-1">Clip library</div>
+ {libraryClips.length === 0 ? (
+ <div className="text-xs text-gray-500 px-1 py-4">No clips. Generate some on the Video page.</div>
+ ) : (
+ <div className="grid grid-cols-1 gap-2">
+ {libraryClips.map((clip) => (
+ <div key={clip.id} className={usedClipIds.has(clip.id) ? 'ring-1 ring-port-accent/40 rounded-md' : ''}>
+ <LibraryTile clip={clip} onAdd={addClip} />
+ </div>
+ ))}
+ </div>
+ )}
+ </div>
+ )}
+
+ {/* Center — preview + track */}
+ <div className="space-y-3 min-w-0">
+ <div className="bg-black rounded-lg overflow-hidden aspect-video relative">
+ <video
+ ref={videoRef}
+ className="w-full h-full"
+ playsInline
+ preload="auto"
+ />
+ {clips.length === 0 && (
+ <div className="absolute inset-0 flex items-center justify-center text-gray-500 text-sm">
+ Add clips to start
+ </div>
+ )}
+ </div>
+
+ <div className="flex items-center gap-2 text-xs text-gray-400">
+ <button
+ type="button"
+ onClick={() => setPlaying((p) => !p)}
+ disabled={clips.length === 0}
+ className="p-2 bg-port-card border border-port-border rounded-md hover:border-port-accent disabled:opacity-40"
+ title={playing ? 'Pause' : 'Play'}
+ >
+ {playing ? <Pause className="w-4 h-4" /> : <Play className="w-4 h-4" />}
+ </button>
+ <button
+ type="button"
+ onClick={() => setMuted((m) => !m)}
+ className="p-2 bg-port-card border border-port-border rounded-md hover:border-port-accent"
+ title={muted ? 'Unmute' : 'Mute'}
+ >
+ {muted ? <VolumeX className="w-4 h-4" /> : <Volume2 className="w-4 h-4" />}
+ </button>
+ <input
+ type="range"
+ min={0}
+ max={Math.max(0.01, total)}
+ step={0.01}
+ value={Math.min(t, total)}
+ onChange={(e) => { setPlaying(false); setT(Number(e.target.value)); }}
+ className="flex-1"
+ disabled={clips.length === 0}
+ />
+ <span className="font-mono text-[11px] tabular-nums">
+ {formatTime(t)} / {formatTime(total)}
+ </span>
+ <label className="flex items-center gap-1 ml-2">
+ <span>zoom</span>
+ <input
+ type="range"
+ min={20}
+ max={200}
+ value={pxPerSec}
+ onChange={(e) => setPxPerSec(Number(e.target.value))}
+ className="w-20"
+ />
+ </label>
+ </div>
+
+ <div className="bg-port-card/30 border border-port-border rounded-lg p-2 overflow-x-auto">
+ {clips.length === 0 ? (
+ <div className="text-xs text-gray-500 py-6 text-center">
+ Drag-drop reorder once you've added clips. Add from the library on the left.
+ </div>
+ ) : (
+ <DndContext sensors={sensors} collisionDetection={closestCenter} onDragEnd={onDragEnd}>
+ <SortableContext items={clips.map((c) => c._key)} strategy={horizontalListSortingStrategy}>
+ <div className="flex gap-1 items-stretch min-w-min py-1">
+ {clips.map((clip) => (
+ <TimelineBlock
+ key={clip._key}
+ clip={clip}
+ clipMeta={metaFor(clip.clipId)}
+ isSelected={clip._key === selectedKey}
+ isMissing={missingKeys.has(clip._key)}
+ pxPerSec={pxPerSec}
+ onSelect={setSelectedKey}
+ onRemove={removeClip}
+ />
+ ))}
+ </div>
+ </SortableContext>
+ </DndContext>
+ )}
+ </div>
+ </div>
+
+ {/* Right rail — inspector */}
+ <div className="bg-port-card/50 border border-port-border rounded-lg p-3 space-y-3">
+ <div className="text-xs uppercase text-gray-500 tracking-wide">Inspector</div>
+ {!selectedClip ? (
+ <div className="text-xs text-gray-500">Select a clip on the timeline to trim it.</div>
+ ) : missingKeys.has(selectedClip._key) ? (
+ <div className="text-xs text-port-error space-y-2">
+ <p>Source clip missing — it may have been deleted from the gallery. Remove this block from the timeline.</p>
+ <button
+ type="button"
+ onClick={() => removeClip(selectedClip._key)}
+ className="w-full px-2 py-1.5 bg-port-error/20 hover:bg-port-error/40 text-port-error text-xs rounded flex items-center justify-center gap-1"
+ >
+ <Trash2 className="w-3 h-3" /> Remove
+ </button>
+ </div>
+ ) : (
+ <>
+ {selectedMeta?.thumbnail && (
+ <img
+ src={`/data/video-thumbnails/${selectedMeta.thumbnail}`}
+ alt=""
+ className="w-full aspect-video object-cover rounded"
+ />
+ )}
+ <div className="text-[11px] text-gray-300 line-clamp-3" title={selectedMeta?.prompt}>
+ {selectedMeta?.prompt}
+ </div>
+ <div className="text-[10px] text-gray-500">
+ source: {selectedSourceDur?.toFixed(2) ?? '?'}s · {selectedMeta?.width}×{selectedMeta?.height} · {selectedMeta?.fps}fps
+ </div>
+ <label className="block text-xs text-gray-400">
+ In (s)
+ <input
+ type="number"
+ step="0.05"
+ min={0}
+ max={selectedSourceDur || undefined}
+ value={trimDraft.inSec}
+ onChange={(e) => setTrimDraft((d) => ({ ...d, inSec: e.target.value }))}
+ onBlur={(e) => {
+ const n = Number(e.target.value);
+ if (Number.isFinite(n)) editSelected({ inSec: n });
+ }}
+ className="w-full mt-1 px-2 py-1.5 bg-port-bg border border-port-border rounded text-white text-sm focus:outline-none focus:border-port-accent"
+ />
+ </label>
+ <label className="block text-xs text-gray-400">
+ Out (s)
+ <input
+ type="number"
+ step="0.05"
+ min={selectedClip.inSec + 0.05}
+ max={selectedSourceDur || undefined}
+ value={trimDraft.outSec}
+ onChange={(e) => setTrimDraft((d) => ({ ...d, outSec: e.target.value }))}
+ onBlur={(e) => {
+ const n = Number(e.target.value);
+ if (Number.isFinite(n)) editSelected({ outSec: n });
+ }}
+ className="w-full mt-1 px-2 py-1.5 bg-port-bg border border-port-border rounded text-white text-sm focus:outline-none focus:border-port-accent"
+ />
+ </label>
+ <div className="text-[10px] text-gray-500">
+ trimmed: {(selectedClip.outSec - selectedClip.inSec).toFixed(2)}s
+ </div>
+ <button
+ type="button"
+ onClick={() => removeClip(selectedClip._key)}
+ className="w-full px-2 py-1.5 bg-port-error/20 hover:bg-port-error/40 text-port-error text-xs rounded flex items-center justify-center gap-1"
+ >
+ <Trash2 className="w-3 h-3" /> Remove from timeline
+ </button>
+ </>
+ )}
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/client/src/services/apiImageVideo.js b/client/src/services/apiImageVideo.js
index 4ce06c0e87..2167398b33 100644
--- a/client/src/services/apiImageVideo.js
+++ b/client/src/services/apiImageVideo.js
@@ -60,6 +60,51 @@ export async function generateVideo(fields) {
return res.json();
}
+// Video timeline projects (non-linear editor)
+export const listTimelineProjects = () => request('/video-timeline/projects');
+export const getTimelineProject = (id) => request(`/video-timeline/projects/${encodeURIComponent(id)}`);
+export const createTimelineProject = (name) => request('/video-timeline/projects', {
+ method: 'POST',
+ body: JSON.stringify({ name }),
+});
+export const updateTimelineProject = (id, patch) => request(`/video-timeline/projects/${encodeURIComponent(id)}`, {
+ method: 'PATCH',
+ body: JSON.stringify(patch),
+});
+export const deleteTimelineProject = (id) => request(`/video-timeline/projects/${encodeURIComponent(id)}`, {
+ method: 'DELETE',
+});
+export const renderTimelineProject = (id) => request(`/video-timeline/projects/${encodeURIComponent(id)}/render`, {
+ method: 'POST',
+});
+export const cancelTimelineRender = (jobId) => request(`/video-timeline/${encodeURIComponent(jobId)}/cancel`, {
+ method: 'POST',
+});
+
+// Media collections — user-named buckets that can hold any mix of images
+// and videos. An item key is "<kind>:<ref>" (e.g. "image:foo.png" or
+// "video:<uuid>"); cover keys use the same format.
+export const listMediaCollections = () => request('/media/collections');
+export const getMediaCollection = (id) => request(`/media/collections/${encodeURIComponent(id)}`);
+export const createMediaCollection = ({ name, description = '' }) => request('/media/collections', {
+ method: 'POST',
+ body: JSON.stringify({ name, description }),
+});
+export const updateMediaCollection = (id, patch) => request(`/media/collections/${encodeURIComponent(id)}`, {
+ method: 'PATCH',
+ body: JSON.stringify(patch),
+});
+export const deleteMediaCollection = (id) => request(`/media/collections/${encodeURIComponent(id)}`, {
+ method: 'DELETE',
+});
+export const addMediaCollectionItem = (id, { kind, ref }) => request(`/media/collections/${encodeURIComponent(id)}/items`, {
+ method: 'POST',
+ body: JSON.stringify({ kind, ref }),
+});
+export const removeMediaCollectionItem = (id, key) => request(`/media/collections/${encodeURIComponent(id)}/items/${encodeURIComponent(key)}`, {
+ method: 'DELETE',
+});
+
// Models management (HF cache + LoRAs)
export const listCachedModels = () => request('/image-video/models');
export const deleteCachedModel = (dirName) => request(`/image-video/models/hf/${encodeURIComponent(dirName)}`, { method: 'DELETE' });
diff --git a/server/index.js b/server/index.js
index 9404ae287f..a2ba9eb42a 100644
--- a/server/index.js
+++ b/server/index.js
@@ -64,6 +64,7 @@ import databaseRoutes from './routes/database.js';
import searchRoutes from './routes/search.js';
import paletteRoutes from './routes/palette.js';
import dashboardLayoutsRoutes from './routes/dashboardLayouts.js';
+import mediaCollectionsRoutes from './routes/mediaCollections.js';
import dataSyncRoutes from './routes/dataSync.js';
import identityRoutes from './routes/identity.js';
import instancesRoutes from './routes/instances.js';
@@ -79,6 +80,7 @@ import characterRoutes from './routes/character.js';
import toolsRoutes from './routes/tools.js';
import imageGenRoutes from './routes/imageGen.js';
import videoGenRoutes from './routes/videoGen.js';
+import videoTimelineRoutes from './routes/videoTimeline.js';
import imageVideoModelsRoutes from './routes/imageVideoModels.js';
import sdapiRoutes from './routes/sdapi.js';
import openclawRoutes from './routes/openclaw.js';
@@ -256,6 +258,7 @@ app.use('/api/screenshots', screenshotsRoutes);
app.use('/api/search', searchRoutes);
app.use('/api/palette', paletteRoutes);
app.use('/api/dashboard/layouts', dashboardLayoutsRoutes);
+app.use('/api/media/collections', mediaCollectionsRoutes);
app.use('/api/attachments', attachmentsRoutes);
app.use('/api/backup', backupRoutes);
app.use('/api/database', databaseRoutes);
@@ -310,6 +313,7 @@ app.use('/api/character', characterRoutes);
app.use('/api/tools', toolsRoutes);
app.use('/api/image-gen', imageGenRoutes);
app.use('/api/video-gen', videoGenRoutes);
+app.use('/api/video-timeline', videoTimelineRoutes);
app.use('/api/image-video/models', imageVideoModelsRoutes);
// AUTOMATIC1111-compatible surface for tailnet clients — gated by
// settings.imageGen.expose.a1111 so it returns 403 unless the user opted in.
diff --git a/server/lib/ffmpeg.js b/server/lib/ffmpeg.js
new file mode 100644
index 0000000000..ce5650d01c
--- /dev/null
+++ b/server/lib/ffmpeg.js
@@ -0,0 +1,124 @@
+/**
+ * Shared ffmpeg helpers used by both videoGen and videoTimeline services.
+ *
+ * Keeps a single ffmpeg-binary discovery path and the streaming/thumbnail
+ * primitives in one place so the two services can't drift on quoting,
+ * caching, or rename-safety semantics.
+ */
+
+import { execFile, spawn } from 'child_process';
+import { existsSync } from 'fs';
+import { unlink, rename } from 'fs/promises';
+import { join, resolve as resolvePath, sep as PATH_SEP, dirname } from 'path';
+import { randomUUID } from 'crypto';
+import { promisify } from 'util';
+import { ensureDir, PATHS } from './fileUtils.js';
+
+const execFileAsync = promisify(execFile);
+const IS_WIN = process.platform === 'win32';
+
+// Validate that a sidecar/history-supplied filename is a safe basename under
+// the expected directory — guards against tampered history entries with
+// path-traversal segments (`../etc/passwd`) leaking into ffmpeg or unlink.
+export const safeUnder = (root, name) => {
+ if (typeof name !== 'string' || !name || name.includes('/') || name.includes('\\') || name.includes('..')) return null;
+ const rootResolved = resolvePath(root) + PATH_SEP;
+ const fullPath = resolvePath(join(root, name));
+ return fullPath.startsWith(rootResolved) ? fullPath : null;
+};
+
+// ffmpeg discovery is async (which/where takes ~10ms+) and the result is
+// stable for the process lifetime — cache the first hit so subsequent calls
+// don't re-shell-out and don't block the event loop.
+let cachedFfmpegPath;
+export const findFfmpeg = async () => {
+ if (cachedFfmpegPath !== undefined) return cachedFfmpegPath;
+ const candidates = IS_WIN
+ ? ['C:\\ffmpeg\\bin\\ffmpeg.exe', 'C:\\Program Files\\ffmpeg\\bin\\ffmpeg.exe']
+ : ['/opt/homebrew/bin/ffmpeg', '/usr/local/bin/ffmpeg', '/usr/bin/ffmpeg'];
+ for (const p of candidates) {
+ if (existsSync(p)) { cachedFfmpegPath = p; return p; }
+ }
+ const cmd = IS_WIN ? 'where' : 'which';
+ const { stdout } = await execFileAsync(cmd, ['ffmpeg'], { timeout: 5000 }).catch(() => ({ stdout: '' }));
+ cachedFfmpegPath = stdout.trim().split(/\r?\n/)[0] || null;
+ return cachedFfmpegPath;
+};
+
+// ffprobe sits next to ffmpeg in standard distributions — derive the path
+// from the cached ffmpeg discovery so we don't shell out twice.
+let cachedFfprobePath;
+export const findFfprobe = async () => {
+ if (cachedFfprobePath !== undefined) return cachedFfprobePath;
+ const ffmpeg = await findFfmpeg();
+ if (!ffmpeg) { cachedFfprobePath = null; return null; }
+ // Derive ffprobe from ffmpeg's directory rather than regex-replacing the
+ // basename. A case-sensitive replace would silently miss `FFMPEG.EXE` on
+ // Windows and let callers spawn ffmpeg as if it were ffprobe (audio
+ // probing then always reports "no audio"). dirname-based join sidesteps
+ // the casing question entirely.
+ const probe = join(dirname(ffmpeg), IS_WIN ? 'ffprobe.exe' : 'ffprobe');
+ if (existsSync(probe)) { cachedFfprobePath = probe; return probe; }
+ const cmd = IS_WIN ? 'where' : 'which';
+ const { stdout } = await execFileAsync(cmd, ['ffprobe'], { timeout: 5000 }).catch(() => ({ stdout: '' }));
+ cachedFfprobePath = stdout.trim().split(/\r?\n/)[0] || null;
+ return cachedFfprobePath;
+};
+
+// Single-video thumbnail extraction at frame 1. Returns the basename on
+// success, null when ffmpeg is missing or fails — callers should treat null
+// as "no thumbnail" rather than aborting the parent operation.
+export const generateThumbnail = async (videoPath, jobId) => {
+ await ensureDir(PATHS.videoThumbnails);
+ const thumbFilename = `${jobId}.jpg`;
+ const thumbPath = join(PATHS.videoThumbnails, thumbFilename);
+ const ffmpeg = await findFfmpeg();
+ if (!ffmpeg) return null;
+ return new Promise((resolve) => {
+ const proc = spawn(ffmpeg, ['-i', videoPath, '-vframes', '1', '-q:v', '5', '-y', thumbPath], { stdio: 'ignore' });
+ proc.on('close', (code) => resolve(code === 0 ? thumbFilename : null));
+ proc.on('error', (err) => {
+ console.log(`⚠️ ffmpeg thumbnail failed to spawn: ${err.message}`);
+ resolve(null);
+ });
+ });
+};
+
+// MP4s with the moov atom at the END require browsers to download the entire
+// file before they can render the first-frame poster on preload="metadata".
+// Remux with -movflags +faststart to move moov to the front. Stream copy —
+// no re-encoding.
+export const optimizeForStreaming = async (videoPath) => {
+ const ffmpeg = await findFfmpeg();
+ if (!ffmpeg) return;
+ const tmpPath = `${videoPath}.fs.mp4`;
+ const ok = await new Promise((resolve) => {
+ const proc = spawn(ffmpeg, ['-i', videoPath, '-c', 'copy', '-movflags', '+faststart', '-y', tmpPath], { stdio: 'ignore' });
+ proc.on('close', (code) => resolve(code === 0));
+ proc.on('error', () => resolve(false));
+ });
+ if (!ok) { await unlink(tmpPath).catch(() => {}); return; }
+ // POSIX rename atomically replaces an existing dest in one syscall. On
+ // Windows, fs.rename fails when the destination already exists — but a
+ // simple unlink-first would destroy the rendered video if the subsequent
+ // rename failed (locked file, AV scan, transient permissions). Move the
+ // original aside to a .bak first, then install the optimized file, and
+ // restore the backup on any failure so the worst case is "faststart
+ // skipped", not "rendered video lost".
+ let backupPath = null;
+ try {
+ if (IS_WIN) {
+ backupPath = `${videoPath}.bak.${randomUUID()}`;
+ await rename(videoPath, backupPath).catch((err) => {
+ if (err?.code === 'ENOENT') { backupPath = null; return; }
+ throw err;
+ });
+ }
+ await rename(tmpPath, videoPath);
+ if (backupPath) await unlink(backupPath).catch(() => {});
+ } catch (err) {
+ if (backupPath) await rename(backupPath, videoPath).catch(() => {});
+ await unlink(tmpPath).catch(() => {});
+ console.log(`⚠️ Failed to install streaming-optimized video at ${videoPath}: ${err.message}`);
+ }
+};
diff --git a/server/lib/navManifest.js b/server/lib/navManifest.js
index cdfeabc8d7..02305e11e6 100644
--- a/server/lib/navManifest.js
+++ b/server/lib/navManifest.js
@@ -13,6 +13,8 @@ export const NAV_COMMANDS = [
{ id: 'nav.media.image', path: '/media/image', label: 'Image', section: 'AI', aliases: ['image-gen', 'imagegen', 'generate-image', 'sd', 'stable-diffusion'], keywords: ['stable diffusion', 'render', 'art', 'picture', 'photo', 'draw', 'flux', 'mflux'] },
{ id: 'nav.media.video', path: '/media/video', label: 'Video', section: 'AI', aliases: ['video-gen', 'videogen', 'generate-video', 'ltx'], keywords: ['video', 'animate', 'movie', 'clip', 'ltx'] },
{ id: 'nav.media.history', path: '/media/history', label: 'Media History', section: 'AI', aliases: ['media-history', 'video-history'], keywords: ['videos', 'gallery', 'stitch'] },
+ { id: 'nav.media.collections', path: '/media/collections', label: 'Collections', section: 'AI', aliases: ['collections', 'media-collections', 'stacks', 'projects'], keywords: ['bucket', 'group', 'project', 'album', 'organize'] },
+ { id: 'nav.media.timeline', path: '/media/timeline', label: 'Timeline', section: 'AI', aliases: ['timeline', 'video-timeline', 'editor'], keywords: ['edit', 'trim', 'composite', 'stitch', 'cut', 'compose'] },
{ id: 'nav.media.models', path: '/media/models', label: 'Media Models', section: 'AI', aliases: ['media-models', 'image-models', 'video-models', 'huggingface', 'loras'], keywords: ['hf cache', 'lora', 'model storage', 'disk'] },
{ id: 'nav.media.settings', path: '/media/image?settings=1', label: 'Media Gen Settings', section: 'AI', aliases: ['media-settings', 'image-gen-settings', 'sd-settings', 'video-gen-settings'] },
{ id: 'nav.prompts', path: '/prompts', label: 'Prompts', section: 'AI', aliases: ['prompts'] },
diff --git a/server/routes/mediaCollections.js b/server/routes/mediaCollections.js
new file mode 100644
index 0000000000..61e5a57bbb
--- /dev/null
+++ b/server/routes/mediaCollections.js
@@ -0,0 +1,100 @@
+/**
+ * GET /api/media/collections → Collection[]
+ * POST /api/media/collections → Collection (body: { name, description? })
+ * GET /api/media/collections/:id → Collection
+ * PATCH /api/media/collections/:id → Collection (body: { name?, description?, coverKey? })
+ * DELETE /api/media/collections/:id → { id }
+ * POST /api/media/collections/:id/items → Collection (body: { kind, ref })
+ * DELETE /api/media/collections/:id/items/:key → Collection (key = "<kind>:<ref>")
+ */
+
+import { Router } from 'express';
+import { z } from 'zod';
+import { asyncHandler, ServerError } from '../lib/errorHandler.js';
+import { validateRequest } from '../lib/validation.js';
+import * as svc from '../services/mediaCollections.js';
+
+const router = Router();
+
+const SERVICE_ERROR_STATUS = {
+ [svc.ERR_NOT_FOUND]: 404,
+ [svc.ERR_DUPLICATE]: 409,
+ [svc.ERR_VALIDATION]: 400,
+};
+
+const mapServiceError = (err) => {
+ const status = SERVICE_ERROR_STATUS[err?.code];
+ if (status) return new ServerError(err.message, { status, code: err.code });
+ return err;
+};
+
+const nameSchema = z.string().trim().min(1).max(svc.NAME_MAX_LENGTH);
+const descriptionSchema = z.string().trim().max(svc.DESCRIPTION_MAX_LENGTH);
+// `:` is the API key separator (`<kind>:<ref>` is split on first `:`), so a
+// ref containing one would be unaddressable for DELETE/coverKey lookups.
+const refSchema = z.string().trim().min(1).max(svc.REF_MAX_LENGTH).refine((s) => !s.includes(':'), { message: 'ref may not contain ":"' });
+const kindSchema = z.enum(['image', 'video']);
+
+const createSchema = z.object({
+ name: nameSchema,
+ description: descriptionSchema.optional().default(''),
+});
+
+const patchSchema = z.object({
+ name: nameSchema.optional(),
+ description: descriptionSchema.optional(),
+ // coverKey: null clears it (auto = newest); a string pins a specific item.
+ coverKey: z.union([z.string().trim().min(1).max(svc.REF_MAX_LENGTH + 8), z.null()]).optional(),
+}).refine((p) => Object.keys(p).length > 0, { message: 'patch must include at least one field' });
+
+const itemSchema = z.object({
+ kind: kindSchema,
+ ref: refSchema,
+});
+
+router.get('/', asyncHandler(async (_req, res) => {
+ res.json(await svc.listCollections());
+}));
+
+router.post('/', asyncHandler(async (req, res) => {
+ const body = validateRequest(createSchema, req.body ?? {});
+ res.status(201).json(await svc.createCollection(body));
+}));
+
+router.get('/:id', asyncHandler(async (req, res) => {
+ const c = await svc.getCollection(req.params.id).catch((err) => { throw mapServiceError(err); });
+ res.json(c);
+}));
+
+router.patch('/:id', asyncHandler(async (req, res) => {
+ const body = validateRequest(patchSchema, req.body ?? {});
+ const c = await svc.updateCollection(req.params.id, body).catch((err) => { throw mapServiceError(err); });
+ res.json(c);
+}));
+
+router.delete('/:id', asyncHandler(async (req, res) => {
+ const r = await svc.deleteCollection(req.params.id).catch((err) => { throw mapServiceError(err); });
+ res.json(r);
+}));
+
+router.post('/:id/items', asyncHandler(async (req, res) => {
+ const body = validateRequest(itemSchema, req.body ?? {});
+ const c = await svc.addItem(req.params.id, body).catch((err) => { throw mapServiceError(err); });
+ res.json(c);
+}));
+
+router.delete('/:id/items/:key', asyncHandler(async (req, res) => {
+ // The :key route param is "<kind>:<ref>" — Express decodes it for us, but
+ // we still validate the shape so a hand-rolled curl can't sneak past the
+ // service-layer check.
+ const key = req.params.key || '';
+ const idx = key.indexOf(':');
+ if (idx <= 0) throw new ServerError('Invalid item key', { status: 400, code: 'VALIDATION_ERROR' });
+ const kind = key.slice(0, idx);
+ const ref = key.slice(idx + 1);
+ validateRequest(itemSchema, { kind, ref });
+ const c = await svc.removeItem(req.params.id, key).catch((err) => { throw mapServiceError(err); });
+ res.json(c);
+}));
+
+export default router;
diff --git a/server/routes/videoTimeline.js b/server/routes/videoTimeline.js
new file mode 100644
index 0000000000..fb52683aed
--- /dev/null
+++ b/server/routes/videoTimeline.js
@@ -0,0 +1,82 @@
+/**
+ * Video Timeline Routes — non-linear editor backend.
+ *
+ * Project CRUD + render pipeline. Render emits SSE progress on the same
+ * pattern as videoGen so the client can reuse EventSource wiring. Output
+ * lands in the existing video-history.json with a `timelineProjectId` flag.
+ */
+
+import { Router } from 'express';
+import { z } from 'zod';
+import { asyncHandler, ServerError } from '../lib/errorHandler.js';
+import { validateRequest } from '../lib/validation.js';
+import {
+ listProjects,
+ getProject,
+ createProject,
+ updateProject,
+ deleteProject,
+ renderProject,
+ attachSseClient,
+ cancelRender,
+} from '../services/videoTimeline/local.js';
+
+const router = Router();
+
+const clipSchema = z.object({
+ clipId: z.string().uuid(),
+ inSec: z.number().min(0),
+ outSec: z.number().min(0),
+}).refine((c) => c.outSec > c.inSec, { message: 'outSec must be > inSec', path: ['outSec'] });
+
+const createBodySchema = z.object({
+ name: z.string().min(1).max(200),
+});
+
+const updateBodySchema = z.object({
+ name: z.string().min(1).max(200).optional(),
+ clips: z.array(clipSchema).max(200).optional(),
+ expectedUpdatedAt: z.string().optional(),
+}).refine((b) => b.name !== undefined || b.clips !== undefined, {
+ message: 'PATCH body must include at least name or clips',
+});
+
+router.get('/projects', asyncHandler(async (_req, res) => {
+ res.json(await listProjects());
+}));
+
+router.post('/projects', asyncHandler(async (req, res) => {
+ const data = validateRequest(createBodySchema, req.body);
+ res.status(201).json(await createProject(data.name));
+}));
+
+router.get('/projects/:id', asyncHandler(async (req, res) => {
+ const project = await getProject(req.params.id);
+ if (!project) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });
+ res.json(project);
+}));
+
+router.patch('/projects/:id', asyncHandler(async (req, res) => {
+ const { expectedUpdatedAt, ...patch } = validateRequest(updateBodySchema, req.body);
+ res.json(await updateProject(req.params.id, patch, expectedUpdatedAt));
+}));
+
+router.delete('/projects/:id', asyncHandler(async (req, res) => {
+ res.json(await deleteProject(req.params.id));
+}));
+
+router.post('/projects/:id/render', asyncHandler(async (req, res) => {
+ res.json(await renderProject(req.params.id));
+}));
+
+router.get('/:jobId/events', (req, res) => {
+ const ok = attachSseClient(req.params.jobId, res);
+ if (!ok) res.status(404).json({ error: 'Job not found or expired' });
+});
+
+router.post('/:jobId/cancel', (req, res) => {
+ const cancelled = cancelRender(req.params.jobId);
+ res.json({ ok: cancelled });
+});
+
+export default router;
diff --git a/server/routes/videoTimeline.test.js b/server/routes/videoTimeline.test.js
new file mode 100644
index 0000000000..2255d019a0
--- /dev/null
+++ b/server/routes/videoTimeline.test.js
@@ -0,0 +1,150 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import express from 'express';
+import { request } from '../lib/testHelper.js';
+
+vi.mock('../services/videoTimeline/local.js', () => ({
+ listProjects: vi.fn(),
+ getProject: vi.fn(),
+ createProject: vi.fn(),
+ updateProject: vi.fn(),
+ deleteProject: vi.fn(),
+ renderProject: vi.fn(),
+ attachSseClient: vi.fn(() => false),
+ cancelRender: vi.fn(() => true),
+}));
+
+import * as svc from '../services/videoTimeline/local.js';
+import videoTimelineRoutes from './videoTimeline.js';
+
+describe('videoTimeline routes', () => {
+ let app;
+ beforeEach(() => {
+ app = express();
+ app.use(express.json());
+ app.use('/api/video-timeline', videoTimelineRoutes);
+ vi.clearAllMocks();
+ });
+
+ describe('GET /projects', () => {
+ it('returns the project list', async () => {
+ svc.listProjects.mockResolvedValue([{ id: 'a', name: 'A' }]);
+ const r = await request(app).get('/api/video-timeline/projects');
+ expect(r.status).toBe(200);
+ expect(r.body).toHaveLength(1);
+ });
+ });
+
+ describe('POST /projects', () => {
+ it('rejects empty name', async () => {
+ const r = await request(app).post('/api/video-timeline/projects').send({ name: '' });
+ expect(r.status).toBe(400);
+ });
+
+ it('creates a project and returns it', async () => {
+ svc.createProject.mockResolvedValue({ id: 'p1', name: 'My Edit', clips: [] });
+ const r = await request(app).post('/api/video-timeline/projects').send({ name: 'My Edit' });
+ expect(r.status).toBe(201);
+ expect(r.body.id).toBe('p1');
+ expect(svc.createProject).toHaveBeenCalledWith('My Edit');
+ });
+ });
+
+ describe('GET /projects/:id', () => {
+ it('returns 404 when project missing', async () => {
+ svc.getProject.mockResolvedValue(null);
+ const r = await request(app).get('/api/video-timeline/projects/nope');
+ expect(r.status).toBe(404);
+ });
+
+ it('returns the project when found', async () => {
+ svc.getProject.mockResolvedValue({ id: 'p1', name: 'A', clips: [] });
+ const r = await request(app).get('/api/video-timeline/projects/p1');
+ expect(r.status).toBe(200);
+ expect(r.body.name).toBe('A');
+ });
+ });
+
+ describe('PATCH /projects/:id', () => {
+ it('rejects clip with negative inSec', async () => {
+ const r = await request(app).patch('/api/video-timeline/projects/p1').send({
+ clips: [{ clipId: '11111111-1111-4111-8111-111111111111', inSec: -1, outSec: 2 }],
+ });
+ expect(r.status).toBe(400);
+ });
+
+ it('rejects empty patch body', async () => {
+ const r = await request(app).patch('/api/video-timeline/projects/p1').send({});
+ expect(r.status).toBe(400);
+ });
+
+ it('forwards expectedUpdatedAt to the service', async () => {
+ svc.updateProject.mockResolvedValue({ id: 'p1', name: 'X', clips: [] });
+ const r = await request(app).patch('/api/video-timeline/projects/p1').send({
+ name: 'X',
+ expectedUpdatedAt: '2026-01-01T00:00:00Z',
+ });
+ expect(r.status).toBe(200);
+ expect(svc.updateProject).toHaveBeenCalledWith('p1', { name: 'X' }, '2026-01-01T00:00:00Z');
+ });
+
+ it('forwards a multi-clip update', async () => {
+ svc.updateProject.mockResolvedValue({ id: 'p1', clips: [] });
+ const clips = [
+ { clipId: '11111111-1111-4111-8111-111111111111', inSec: 0, outSec: 4 },
+ { clipId: '22222222-2222-4222-8222-222222222222', inSec: 1.5, outSec: 3.5 },
+ ];
+ const r = await request(app).patch('/api/video-timeline/projects/p1').send({ clips });
+ expect(r.status).toBe(200);
+ expect(svc.updateProject).toHaveBeenCalledWith('p1', { clips }, undefined);
+ });
+
+ it('rejects non-uuid clipId', async () => {
+ const r = await request(app).patch('/api/video-timeline/projects/p1').send({
+ clips: [{ clipId: 'not-a-uuid', inSec: 0, outSec: 1 }],
+ });
+ expect(r.status).toBe(400);
+ });
+
+ it('rejects outSec <= inSec', async () => {
+ const r = await request(app).patch('/api/video-timeline/projects/p1').send({
+ clips: [{ clipId: '11111111-1111-4111-8111-111111111111', inSec: 2, outSec: 2 }],
+ });
+ expect(r.status).toBe(400);
+ });
+ });
+
+ describe('DELETE /projects/:id', () => {
+ it('proxies to the service', async () => {
+ svc.deleteProject.mockResolvedValue({ ok: true });
+ const r = await request(app).delete('/api/video-timeline/projects/p1');
+ expect(r.status).toBe(200);
+ expect(svc.deleteProject).toHaveBeenCalledWith('p1');
+ });
+ });
+
+ describe('POST /projects/:id/render', () => {
+ it('proxies to the service and returns the jobId', async () => {
+ svc.renderProject.mockResolvedValue({ jobId: 'job-123' });
+ const r = await request(app).post('/api/video-timeline/projects/p1/render').send({});
+ expect(r.status).toBe(200);
+ expect(r.body.jobId).toBe('job-123');
+ });
+ });
+
+ describe('GET /:jobId/events', () => {
+ it('returns 404 when job is unknown', async () => {
+ svc.attachSseClient.mockReturnValue(false);
+ const r = await request(app).get('/api/video-timeline/unknown/events');
+ expect(r.status).toBe(404);
+ });
+ });
+
+ describe('POST /:jobId/cancel', () => {
+ it('returns the cancel result', async () => {
+ svc.cancelRender.mockReturnValue(true);
+ const r = await request(app).post('/api/video-timeline/job-1/cancel').send({});
+ expect(r.status).toBe(200);
+ expect(r.body.ok).toBe(true);
+ });
+ });
+});
diff --git a/server/services/mediaCollections.js b/server/services/mediaCollections.js
new file mode 100644
index 0000000000..0911f84e8a
--- /dev/null
+++ b/server/services/mediaCollections.js
@@ -0,0 +1,223 @@
+/**
+ * Media Collections
+ *
+ * User-named buckets for image filenames + video ids. Many-to-many: the same
+ * media item can live in any number of collections at once. Persisted to
+ * data/media-collections.json as a single { collections: [...] } document.
+ *
+ * An item is identified by `{ kind: 'image'|'video', ref: <filename|videoId> }`.
+ * A collection's `coverKey` is `null` (auto: newest item) or `"<kind>:<ref>"`
+ * to pin a specific item as the cover thumbnail.
+ */
+
+import { join } from 'path';
+import { randomUUID } from 'crypto';
+import { PATHS, atomicWrite, readJSONFile, ensureDir } from '../lib/fileUtils.js';
+
+const STATE_PATH = join(PATHS.data, 'media-collections.json');
+
+export const ERR_NOT_FOUND = 'NOT_FOUND';
+export const ERR_DUPLICATE = 'DUPLICATE';
+export const ERR_VALIDATION = 'VALIDATION_ERROR';
+const makeErr = (message, code) => Object.assign(new Error(message), { code });
+
+export const NAME_MAX_LENGTH = 80;
+export const DESCRIPTION_MAX_LENGTH = 500;
+export const REF_MAX_LENGTH = 256;
+export const ITEMS_MAX = 5000;
+
+const ITEM_KIND = new Set(['image', 'video']);
+
+export const itemKey = (it) => `${it.kind}:${it.ref}`;
+
+const DEFAULT_STATE = { collections: [] };
+
+const sanitizeItem = (raw) => {
+ if (!raw || typeof raw !== 'object') return null;
+ if (!ITEM_KIND.has(raw.kind)) return null;
+ if (typeof raw.ref !== 'string') return null;
+ const ref = raw.ref.trim();
+ if (!ref || ref.length > REF_MAX_LENGTH) return null;
+ // The DELETE-item route key is `<kind>:<ref>` split on the first `:`. A
+ // ref that contains `:` would be unambiguously persisted but ambiguously
+ // addressable via the REST surface — reject it here so persisted data
+ // always round-trips.
+ if (ref.includes(':')) return null;
+ // A hand-edited or corrupted `addedAt` would feed NaN into the cover
+ // resolver's Date sort — replace anything unparseable with now().
+ const parsed = typeof raw.addedAt === 'string' ? Date.parse(raw.addedAt) : NaN;
+ const addedAt = Number.isFinite(parsed) ? raw.addedAt : new Date().toISOString();
+ return { kind: raw.kind, ref, addedAt };
+};
+
+const sanitizeCollection = (raw) => {
+ if (!raw || typeof raw !== 'object') return null;
+ if (typeof raw.id !== 'string' || !raw.id) return null;
+ if (typeof raw.name !== 'string') return null;
+ const name = raw.name.trim().slice(0, NAME_MAX_LENGTH);
+ if (!name) return null;
+ const description = typeof raw.description === 'string'
+ ? raw.description.trim().slice(0, DESCRIPTION_MAX_LENGTH)
+ : '';
+ const seen = new Set();
+ const items = [];
+ if (Array.isArray(raw.items)) {
+ for (const it of raw.items) {
+ const s = sanitizeItem(it);
+ if (!s) continue;
+ const key = itemKey(s);
+ if (seen.has(key)) continue;
+ seen.add(key);
+ items.push(s);
+ if (items.length >= ITEMS_MAX) break;
+ }
+ }
+ // Cover key is only meaningful when it points at an item that's in the
+ // collection; otherwise drop it back to auto so the UI doesn't render a
+ // dangling thumbnail reference.
+ const coverKey = typeof raw.coverKey === 'string' && seen.has(raw.coverKey)
+ ? raw.coverKey
+ : null;
+ const createdAt = typeof raw.createdAt === 'string' ? raw.createdAt : new Date().toISOString();
+ const updatedAt = typeof raw.updatedAt === 'string' ? raw.updatedAt : createdAt;
+ return { id: raw.id, name, description, coverKey, items, createdAt, updatedAt };
+};
+
+export async function listCollections() {
+ await ensureDir(PATHS.data);
+ const raw = await readJSONFile(STATE_PATH, DEFAULT_STATE, { logError: false });
+ if (!Array.isArray(raw.collections)) return [];
+ const seen = new Set();
+ const out = [];
+ for (const c of raw.collections) {
+ const s = sanitizeCollection(c);
+ if (!s || seen.has(s.id)) continue;
+ seen.add(s.id);
+ out.push(s);
+ }
+ return out;
+}
+
+export async function getCollection(id) {
+ const all = await listCollections();
+ const c = all.find((x) => x.id === id);
+ if (!c) throw makeErr(`Collection not found: ${id}`, ERR_NOT_FOUND);
+ return c;
+}
+
+const writeAll = async (collections) => {
+ await atomicWrite(STATE_PATH, { collections });
+ return collections;
+};
+
+export async function createCollection({ name, description = '' }) {
+ // Service-layer guards mirror sanitizeCollection so a direct caller
+ // (tests, future internal usage) can't persist a record that the next
+ // listCollections() read would silently drop.
+ const trimmedName = typeof name === 'string' ? name.trim() : '';
+ if (!trimmedName || trimmedName.length > NAME_MAX_LENGTH) {
+ throw makeErr('Collection name is required (1..' + NAME_MAX_LENGTH + ' chars)', ERR_VALIDATION);
+ }
+ const trimmedDescription = typeof description === 'string'
+ ? description.trim().slice(0, DESCRIPTION_MAX_LENGTH)
+ : '';
+ const all = await listCollections();
+ const now = new Date().toISOString();
+ const next = {
+ id: randomUUID(),
+ name: trimmedName,
+ description: trimmedDescription,
+ coverKey: null,
+ items: [],
+ createdAt: now,
+ updatedAt: now,
+ };
+ await writeAll([...all, next]);
+ return next;
+}
+
+export async function updateCollection(id, patch) {
+ const all = await listCollections();
+ const idx = all.findIndex((c) => c.id === id);
+ if (idx < 0) throw makeErr(`Collection not found: ${id}`, ERR_NOT_FOUND);
+ const cur = all[idx];
+ // Cover key validation is deferred to sanitizeCollection on read, but we
+ // also reject up-front so the API gives a clear error rather than silently
+ // dropping the cover.
+ if (patch.coverKey != null && !cur.items.find((it) => itemKey(it) === patch.coverKey)) {
+ throw makeErr('coverKey must reference an item in this collection', ERR_VALIDATION);
+ }
+ const merged = {
+ ...cur,
+ ...('name' in patch ? { name: patch.name } : {}),
+ ...('description' in patch ? { description: patch.description } : {}),
+ ...('coverKey' in patch ? { coverKey: patch.coverKey } : {}),
+ updatedAt: new Date().toISOString(),
+ };
+ const next = [...all];
+ next[idx] = merged;
+ await writeAll(next);
+ return merged;
+}
+
+export async function deleteCollection(id) {
+ const all = await listCollections();
+ if (!all.find((c) => c.id === id)) throw makeErr(`Collection not found: ${id}`, ERR_NOT_FOUND);
+ await writeAll(all.filter((c) => c.id !== id));
+ return { id };
+}
+
+export async function addItem(id, item) {
+ // Mirror sanitizeItem so direct callers can't write a record that the
+ // next listCollections() would drop (silent add).
+ if (!item || !ITEM_KIND.has(item.kind)) {
+ throw makeErr('item.kind must be "image" or "video"', ERR_VALIDATION);
+ }
+ const ref = typeof item.ref === 'string' ? item.ref.trim() : '';
+ if (!ref || ref.length > REF_MAX_LENGTH || ref.includes(':')) {
+ throw makeErr('item.ref invalid (empty, too long, or contains ":")', ERR_VALIDATION);
+ }
+ const all = await listCollections();
+ const idx = all.findIndex((c) => c.id === id);
+ if (idx < 0) throw makeErr(`Collection not found: ${id}`, ERR_NOT_FOUND);
+ const cur = all[idx];
+ const key = `${item.kind}:${ref}`;
+ if (cur.items.find((it) => itemKey(it) === key)) {
+ throw makeErr(`Item already in collection: ${key}`, ERR_DUPLICATE);
+ }
+ if (cur.items.length >= ITEMS_MAX) {
+ throw makeErr(`Collection full (limit ${ITEMS_MAX})`, ERR_VALIDATION);
+ }
+ const merged = {
+ ...cur,
+ items: [...cur.items, { kind: item.kind, ref, addedAt: new Date().toISOString() }],
+ updatedAt: new Date().toISOString(),
+ };
+ const next = [...all];
+ next[idx] = merged;
+ await writeAll(next);
+ return merged;
+}
+
+export async function removeItem(id, key) {
+ const all = await listCollections();
+ const idx = all.findIndex((c) => c.id === id);
+ if (idx < 0) throw makeErr(`Collection not found: ${id}`, ERR_NOT_FOUND);
+ const cur = all[idx];
+ const before = cur.items.length;
+ const items = cur.items.filter((it) => itemKey(it) !== key);
+ if (items.length === before) throw makeErr(`Item not in collection: ${key}`, ERR_NOT_FOUND);
+ const merged = {
+ ...cur,
+ items,
+ // Drop the cover if it pointed at the removed item — sanitizeCollection
+ // would do this on the next read, but doing it here keeps the in-memory
+ // return consistent with what's persisted.
+ coverKey: cur.coverKey === key ? null : cur.coverKey,
+ updatedAt: new Date().toISOString(),
+ };
+ const next = [...all];
+ next[idx] = merged;
+ await writeAll(next);
+ return merged;
+}
diff --git a/server/services/mediaCollections.test.js b/server/services/mediaCollections.test.js
new file mode 100644
index 0000000000..391ee8bcd2
--- /dev/null
+++ b/server/services/mediaCollections.test.js
@@ -0,0 +1,92 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+const fileStore = new Map();
+
+vi.mock('../lib/fileUtils.js', () => ({
+ PATHS: { data: '/mock/data' },
+ ensureDir: vi.fn().mockResolvedValue(undefined),
+ atomicWrite: vi.fn(async (path, data) => { fileStore.set(path, data); }),
+ readJSONFile: vi.fn(async (path, fallback) => fileStore.has(path) ? fileStore.get(path) : fallback),
+}));
+
+let uuidCounter = 0;
+vi.mock('crypto', async () => {
+ const actual = await vi.importActual('crypto');
+ return { ...actual, randomUUID: () => `uuid-${++uuidCounter}` };
+});
+
+const svc = await import('./mediaCollections.js');
+
+describe('mediaCollections service', () => {
+ beforeEach(() => {
+ fileStore.clear();
+ uuidCounter = 0;
+ });
+
+ it('listCollections returns [] for fresh state', async () => {
+ expect(await svc.listCollections()).toEqual([]);
+ });
+
+ it('createCollection persists a new collection', async () => {
+ const c = await svc.createCollection({ name: 'Project A' });
+ expect(c.id).toBe('uuid-1');
+ expect(c.name).toBe('Project A');
+ expect(c.items).toEqual([]);
+ expect(c.coverKey).toBeNull();
+ const all = await svc.listCollections();
+ expect(all).toHaveLength(1);
+ });
+
+ it('addItem rejects duplicate (same kind+ref)', async () => {
+ const c = await svc.createCollection({ name: 'A' });
+ await svc.addItem(c.id, { kind: 'image', ref: 'foo.png' });
+ await expect(svc.addItem(c.id, { kind: 'image', ref: 'foo.png' }))
+ .rejects.toMatchObject({ code: svc.ERR_DUPLICATE });
+ });
+
+ it('many-to-many: same item can live in multiple collections', async () => {
+ const a = await svc.createCollection({ name: 'A' });
+ const b = await svc.createCollection({ name: 'B' });
+ await svc.addItem(a.id, { kind: 'video', ref: 'vid-1' });
+ await svc.addItem(b.id, { kind: 'video', ref: 'vid-1' });
+ const all = await svc.listCollections();
+ expect(all[0].items).toHaveLength(1);
+ expect(all[1].items).toHaveLength(1);
+ });
+
+ it('removeItem clears coverKey when the cover is removed', async () => {
+ const c = await svc.createCollection({ name: 'A' });
+ await svc.addItem(c.id, { kind: 'image', ref: 'cover.png' });
+ await svc.updateCollection(c.id, { coverKey: 'image:cover.png' });
+ const after = await svc.removeItem(c.id, 'image:cover.png');
+ expect(after.coverKey).toBeNull();
+ });
+
+ it('updateCollection rejects coverKey not in items', async () => {
+ const c = await svc.createCollection({ name: 'A' });
+ await expect(svc.updateCollection(c.id, { coverKey: 'image:missing.png' }))
+ .rejects.toMatchObject({ code: svc.ERR_VALIDATION });
+ });
+
+ it('deleteCollection removes the entry', async () => {
+ const c = await svc.createCollection({ name: 'A' });
+ await svc.deleteCollection(c.id);
+ expect(await svc.listCollections()).toEqual([]);
+ });
+
+ it('sanitizes hand-edited JSON with bogus items', async () => {
+ fileStore.set('/mock/data/media-collections.json', {
+ collections: [
+ { id: 'c1', name: 'OK', items: [
+ { kind: 'image', ref: 'a.png' },
+ { kind: 'image', ref: 'a.png' }, // duplicate -> dropped
+ { kind: 'bogus', ref: 'b.png' }, // invalid kind -> dropped
+ { ref: 'no-kind' }, // missing kind -> dropped
+ ], coverKey: 'image:missing' }, // dangling cover -> nulled
+ ],
+ });
+ const all = await svc.listCollections();
+ expect(all[0].items).toHaveLength(1);
+ expect(all[0].coverKey).toBeNull();
+ });
+});
diff --git a/server/services/videoGen/local.js b/server/services/videoGen/local.js
index 8d93c29b19..edcd780a74 100644
--- a/server/services/videoGen/local.js
+++ b/server/services/videoGen/local.js
@@ -12,8 +12,8 @@
import { execFile, spawn } from 'child_process';
import { existsSync, statSync } from 'fs';
-import { unlink, rename, writeFile } from 'fs/promises';
-import { join, basename, resolve as resolvePath, sep as PATH_SEP } from 'path';
+import { unlink, writeFile } from 'fs/promises';
+import { join, basename } from 'path';
import { tmpdir } from 'os';
import { randomUUID } from 'crypto';
import { promisify } from 'util';
@@ -22,6 +22,7 @@ import { ServerError } from '../../lib/errorHandler.js';
import { videoGenEvents } from './events.js';
import { broadcastSse, attachSseClient as attachSse, closeJobAfterDelay, PYTHON_NOISE_RE } from '../../lib/sseUtils.js';
import { getVideoModels, getDefaultVideoModelId, getTextEncoderRepo } from '../../lib/mediaModels.js';
+import { findFfmpeg, safeUnder, generateThumbnail, optimizeForStreaming } from '../../lib/ffmpeg.js';
const execFileAsync = promisify(execFile);
@@ -37,16 +38,6 @@ export const defaultVideoModelId = () => getDefaultVideoModelId();
const HISTORY_FILE = join(PATHS.data, 'video-history.json');
-// Validate that a sidecar/history-supplied filename is a safe basename under
-// the expected directory — guards against tampered history entries with
-// path-traversal segments (`../etc/passwd`) leaking into ffmpeg or unlink.
-const safeUnder = (root, name) => {
- if (typeof name !== 'string' || !name || name.includes('/') || name.includes('\\') || name.includes('..')) return null;
- const rootResolved = resolvePath(root) + PATH_SEP;
- const fullPath = resolvePath(join(root, name));
- return fullPath.startsWith(rootResolved) ? fullPath : null;
-};
-
const jobs = new Map();
let activeProcess = null;
@@ -72,85 +63,6 @@ export const cancel = () => {
return true;
};
-// ffmpeg discovery is async (which/where takes ~10ms+) and the result is
-// stable for the process lifetime — cache the first hit so subsequent video
-// generations don't re-shell-out and don't block the event loop.
-let cachedFfmpegPath;
-const findFfmpeg = async () => {
- if (cachedFfmpegPath !== undefined) return cachedFfmpegPath;
- const candidates = IS_WIN
- ? ['C:\\ffmpeg\\bin\\ffmpeg.exe', 'C:\\Program Files\\ffmpeg\\bin\\ffmpeg.exe']
- : ['/opt/homebrew/bin/ffmpeg', '/usr/local/bin/ffmpeg', '/usr/bin/ffmpeg'];
- for (const p of candidates) {
- if (existsSync(p)) { cachedFfmpegPath = p; return p; }
- }
- const cmd = IS_WIN ? 'where' : 'which';
- const { stdout } = await execFileAsync(cmd, ['ffmpeg'], { timeout: 5000 }).catch(() => ({ stdout: '' }));
- cachedFfmpegPath = stdout.trim().split(/\r?\n/)[0] || null;
- return cachedFfmpegPath;
-};
-
-const generateThumbnail = async (videoPath, jobId) => {
- await ensureDir(PATHS.videoThumbnails);
- const thumbFilename = `${jobId}.jpg`;
- const thumbPath = join(PATHS.videoThumbnails, thumbFilename);
- const ffmpeg = await findFfmpeg();
- if (!ffmpeg) return null;
- return new Promise((resolve) => {
- const proc = spawn(ffmpeg, ['-i', videoPath, '-vframes', '1', '-q:v', '5', '-y', thumbPath], { stdio: 'ignore' });
- proc.on('close', (code) => resolve(code === 0 ? thumbFilename : null));
- // Without this, a stale ffmpeg path or permission error emits 'error'
- // (never 'close') and the Promise never settles — the entire video gen
- // close handler that awaits this would hang forever.
- proc.on('error', (err) => {
- console.log(`⚠️ ffmpeg thumbnail failed to spawn: ${err.message}`);
- resolve(null);
- });
- });
-};
-
-// mlx-video-with-audio writes mp4s with the moov atom at the END (cv2's
-// VideoWriter default). Browsers loading the gallery with preload="metadata"
-// then have to download the entire file before they can render the
-// first-frame poster, so video tiles flash black until clicked. Remuxing
-// with `-movflags +faststart` rewrites the moov atom to the front of the
-// file. Pure stream copy — no re-encoding, takes a few hundred ms even on
-// long clips. Idea borrowed from mrbizarro/phosphene's codec patch.
-const optimizeForStreaming = async (videoPath) => {
- const ffmpeg = await findFfmpeg();
- if (!ffmpeg) return;
- const tmpPath = `${videoPath}.fs.mp4`;
- const ok = await new Promise((resolve) => {
- const proc = spawn(ffmpeg, ['-i', videoPath, '-c', 'copy', '-movflags', '+faststart', '-y', tmpPath], { stdio: 'ignore' });
- proc.on('close', (code) => resolve(code === 0));
- proc.on('error', () => resolve(false));
- });
- if (!ok) { await unlink(tmpPath).catch(() => {}); return; }
- // POSIX rename atomically replaces an existing dest in one syscall. On
- // Windows, fs.rename fails when the destination already exists — but a
- // simple unlink-first would destroy the rendered video if the subsequent
- // rename failed (locked file, AV scan, transient permissions). Move the
- // original aside to a .bak first, then install the optimized file, and
- // restore the backup on any failure so the worst case is "faststart
- // skipped", not "rendered video lost".
- let backupPath = null;
- try {
- if (IS_WIN) {
- backupPath = `${videoPath}.bak.${randomUUID()}`;
- await rename(videoPath, backupPath).catch((err) => {
- if (err?.code === 'ENOENT') { backupPath = null; return; }
- throw err;
- });
- }
- await rename(tmpPath, videoPath);
- if (backupPath) await unlink(backupPath).catch(() => {});
- } catch (err) {
- if (backupPath) await rename(backupPath, videoPath).catch(() => {});
- await unlink(tmpPath).catch(() => {});
- console.log(`⚠️ Failed to install streaming-optimized video at ${videoPath}: ${err.message}`);
- }
-};
-
export const loadHistory = () => readJSONFile(HISTORY_FILE, []);
export const saveHistory = (h) => atomicWrite(HISTORY_FILE, h);
diff --git a/server/services/videoTimeline/local.js b/server/services/videoTimeline/local.js
new file mode 100644
index 0000000000..98074b46e2
--- /dev/null
+++ b/server/services/videoTimeline/local.js
@@ -0,0 +1,451 @@
+/**
+ * Video Timeline — non-linear editor backend.
+ *
+ * Lets users compose multiple already-generated video clips into a single
+ * output video with per-clip in/out trim and drag-drop ordering. Distinct
+ * from videoGen/local.js#stitchVideos: that one is stream-copy concat (no
+ * trim, requires identical codec/dims). This one re-encodes through a
+ * filter_complex graph so trims, mixed-audio inputs, and dim mismatches
+ * across LTX-2 model versions all work safely.
+ *
+ * Projects persist to data/video-projects.json. Output entries land in the
+ * existing data/video-history.json with a `timelineProjectId` flag so
+ * Media History shows them alongside generated clips.
+ */
+
+import { spawn } from 'child_process';
+import { existsSync } from 'fs';
+import { unlink } from 'fs/promises';
+import { join } from 'path';
+import { randomUUID } from 'crypto';
+import { ensureDir, PATHS, readJSONFile, atomicWrite } from '../../lib/fileUtils.js';
+import { ServerError } from '../../lib/errorHandler.js';
+import { broadcastSse, attachSseClient as attachSse, closeJobAfterDelay } from '../../lib/sseUtils.js';
+import { findFfmpeg, findFfprobe, safeUnder, generateThumbnail } from '../../lib/ffmpeg.js';
+import { loadHistory, saveHistory } from '../videoGen/local.js';
+
+const PROJECTS_FILE = join(PATHS.data, 'video-projects.json');
+
+// Per-project render mutex map. Keyed by projectId so two different projects
+// can render in parallel; same project re-render returns 409 with the
+// existing jobId so the UI can attach SSE instead of getting a stale failure.
+const jobs = new Map();
+const projectRenders = new Map(); // projectId → jobId
+
+export const attachSseClient = (jobId, res) => attachSse(jobs, jobId, res);
+
+// =====================================================================
+// Project CRUD
+// =====================================================================
+
+export const loadProjects = async () => {
+ // Defend against a hand-edited / corrupted JSON state file. Without this,
+ // a non-array root would crash every CRUD path with "x.findIndex is not a
+ // function" instead of degrading gracefully to an empty list.
+ const raw = await readJSONFile(PROJECTS_FILE, []);
+ return Array.isArray(raw) ? raw : [];
+};
+const saveProjects = async (projects) => {
+ // First write on a fresh install lands before PATHS.data is created by any
+ // other service — without ensureDir it would ENOENT on the temp-file write
+ // inside atomicWrite.
+ await ensureDir(PATHS.data);
+ return atomicWrite(PROJECTS_FILE, projects);
+};
+
+export async function listProjects() {
+ return loadProjects();
+}
+
+export async function getProject(id) {
+ const projects = await loadProjects();
+ return projects.find((p) => p.id === id) || null;
+}
+
+export async function createProject(name) {
+ const trimmed = (name || '').trim();
+ if (!trimmed) throw new ServerError('Project name required', { status: 400, code: 'VALIDATION_ERROR' });
+ const projects = await loadProjects();
+ const now = new Date().toISOString();
+ const project = {
+ id: randomUUID(),
+ name: trimmed,
+ createdAt: now,
+ updatedAt: now,
+ clips: [],
+ };
+ projects.unshift(project);
+ await saveProjects(projects);
+ console.log(`🎬 Timeline project created: ${project.id.slice(0, 8)} "${project.name}"`);
+ return project;
+}
+
+// Validate a single clip patch entry. Returns the cleaned object or throws.
+// We don't trust client-supplied numFrames/fps — those come from the history
+// entry at render time. Only clipId + inSec/outSec are persisted.
+const validateClip = (raw, idx) => {
+ if (!raw || typeof raw !== 'object') {
+ throw new ServerError(`Clip ${idx}: must be an object`, { status: 400, code: 'VALIDATION_ERROR' });
+ }
+ const clipId = String(raw.clipId || '').trim();
+ if (!/^[a-f0-9-]{36}$/i.test(clipId)) {
+ throw new ServerError(`Clip ${idx}: invalid clipId`, { status: 400, code: 'VALIDATION_ERROR' });
+ }
+ const inSec = Number(raw.inSec);
+ const outSec = Number(raw.outSec);
+ if (!Number.isFinite(inSec) || !Number.isFinite(outSec) || inSec < 0 || outSec <= inSec) {
+ throw new ServerError(`Clip ${idx}: inSec/outSec invalid (need 0 ≤ inSec < outSec)`, { status: 400, code: 'VALIDATION_ERROR' });
+ }
+ return { clipId, inSec, outSec };
+};
+
+export async function updateProject(id, patch, expectedUpdatedAt) {
+ const projects = await loadProjects();
+ const idx = projects.findIndex((p) => p.id === id);
+ if (idx === -1) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });
+ const project = projects[idx];
+ // Treat any explicitly-provided value (including '' or wrong type) as a
+ // concurrency assertion — only `undefined` skips the check. A truthy guard
+ // would silently let an empty-string `expectedUpdatedAt` clobber a
+ // newer-than-claimed project.
+ if (expectedUpdatedAt !== undefined) {
+ if (typeof expectedUpdatedAt !== 'string' || project.updatedAt !== expectedUpdatedAt) {
+ throw new ServerError('Project was modified by another writer', {
+ status: 409, code: 'CONFLICT', context: { current: project.updatedAt },
+ });
+ }
+ }
+ if (patch.name != null) {
+ const trimmed = String(patch.name).trim();
+ if (!trimmed) throw new ServerError('Project name cannot be empty', { status: 400, code: 'VALIDATION_ERROR' });
+ project.name = trimmed;
+ }
+ if (patch.clips != null) {
+ if (!Array.isArray(patch.clips)) {
+ throw new ServerError('clips must be an array', { status: 400, code: 'VALIDATION_ERROR' });
+ }
+ project.clips = patch.clips.map(validateClip);
+ }
+ project.updatedAt = new Date().toISOString();
+ projects[idx] = project;
+ await saveProjects(projects);
+ return project;
+}
+
+export async function deleteProject(id) {
+ const projects = await loadProjects();
+ const filtered = projects.filter((p) => p.id !== id);
+ if (filtered.length === projects.length) {
+ throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });
+ }
+ await saveProjects(filtered);
+ console.log(`🗑️ Timeline project deleted: ${id.slice(0, 8)}`);
+ return { ok: true };
+}
+
+// =====================================================================
+// Render pipeline
+// =====================================================================
+
+// ffprobe a clip to find out whether it has an audio stream. Used to decide
+// whether to wire the clip's audio through trim/aresample chain or to insert
+// an anullsrc silent input. Falls back to false when ffprobe is missing so
+// the render can still proceed (silent track inserted for every clip).
+const probeAudio = async (videoPath) => {
+ const ffprobe = await findFfprobe();
+ if (!ffprobe) return false;
+ return new Promise((resolve) => {
+ const proc = spawn(ffprobe, [
+ '-v', 'error',
+ '-select_streams', 'a:0',
+ '-show_entries', 'stream=codec_type',
+ '-of', 'default=nw=1:nk=1',
+ videoPath,
+ ], { stdio: ['ignore', 'pipe', 'ignore'] });
+ let out = '';
+ proc.stdout.on('data', (c) => { out += c.toString(); });
+ proc.on('close', () => resolve(out.trim() === 'audio'));
+ proc.on('error', () => resolve(false));
+ });
+};
+
+// Resolve every clip in a project to a verified on-disk path + duration +
+// audio-presence. Throws ServerError(404) listing every missing/invalid clip
+// so the editor can highlight them. Returns the array of resolved entries
+// in project order.
+export async function resolveClips(project) {
+ if (!Array.isArray(project.clips) || project.clips.length === 0) {
+ throw new ServerError('Project has no clips', { status: 400, code: 'EMPTY_PROJECT' });
+ }
+ const history = await loadHistory();
+ // loadHistory comes from the JSON state file; defend against corruption so
+ // a non-array root degrades to "all clips missing" rather than crashing.
+ const historyList = Array.isArray(history) ? history : [];
+ const historyMap = new Map(historyList.map((h) => [h.id, h]));
+ const missing = [];
+ const prepared = [];
+ for (let i = 0; i < project.clips.length; i++) {
+ const ref = project.clips[i];
+ const entry = historyMap.get(ref.clipId);
+ if (!entry) { missing.push(ref.clipId); continue; }
+ const videoPath = safeUnder(PATHS.videos, entry.filename);
+ if (!videoPath || !existsSync(videoPath)) { missing.push(ref.clipId); continue; }
+ const sourceDuration = entry.numFrames && entry.fps ? entry.numFrames / entry.fps : null;
+ const inSec = Math.max(0, ref.inSec);
+ const outSec = sourceDuration != null ? Math.min(ref.outSec, sourceDuration) : ref.outSec;
+ if (outSec - inSec < 1 / Math.max(1, entry.fps || 24)) {
+ throw new ServerError(`Clip ${i} trim too short — must be ≥ 1 frame`, {
+ status: 400, code: 'CLIP_TOO_SHORT', context: { index: i, clipId: ref.clipId },
+ });
+ }
+ prepared.push({ i, ref, entry, videoPath, inSec, outSec });
+ }
+ if (missing.length > 0) {
+ throw new ServerError(`Missing source clips: ${missing.length}`, {
+ status: 404, code: 'MISSING_CLIPS', context: { missingClipIds: missing },
+ });
+ }
+ // ffprobe spawns one child per clip. Parallelize, but cap concurrency so a
+ // 200-clip project doesn't fork-bomb on render startup.
+ const PROBE_CONCURRENCY = 8;
+ const audioFlags = new Array(prepared.length);
+ for (let start = 0; start < prepared.length; start += PROBE_CONCURRENCY) {
+ const batch = prepared.slice(start, start + PROBE_CONCURRENCY);
+ const results = await Promise.all(batch.map((p) => probeAudio(p.videoPath)));
+ for (let j = 0; j < results.length; j++) audioFlags[start + j] = results[j];
+ }
+ return prepared.map((p, idx) => ({
+ index: p.i,
+ clipId: p.ref.clipId,
+ videoPath: p.videoPath,
+ inSec: p.inSec,
+ outSec: p.outSec,
+ duration: p.outSec - p.inSec,
+ width: p.entry.width,
+ height: p.entry.height,
+ fps: p.entry.fps,
+ hasAudio: audioFlags[idx],
+ }));
+}
+
+// scale+pad, aresample, and aformat are unconditional belt-and-suspenders.
+// Without them, mixed LTX-2 versions error with "Input link parameters do
+// not match" mid-render.
+export function buildFfmpegArgs(clips, outputPath) {
+ if (clips.length === 0) throw new Error('buildFfmpegArgs: empty clips');
+ const canonW = clips[0].width;
+ const canonH = clips[0].height;
+
+ const inputs = [];
+ const filters = [];
+ const concatStreams = [];
+
+ let inputIdx = 0;
+ const indices = clips.map((c) => {
+ const vIdx = inputIdx++;
+ inputs.push('-i', c.videoPath);
+ let aIdx;
+ if (c.hasAudio) {
+ aIdx = vIdx;
+ } else {
+ // -t bounds the otherwise-infinite anullsrc to match the trimmed clip
+ // duration so concat=v=1:a=1 gets a length-matched silent track.
+ aIdx = inputIdx++;
+ inputs.push('-f', 'lavfi', '-t', String(c.duration), '-i', `anullsrc=channel_layout=stereo:sample_rate=48000`);
+ }
+ return { vIdx, aIdx };
+ });
+
+ for (let i = 0; i < clips.length; i++) {
+ const c = clips[i];
+ const { vIdx, aIdx } = indices[i];
+ // fps=<canon> resamples each clip to the timeline's canonical frame rate;
+ // without it, concat fails with "Input link parameters do not match" when
+ // a project mixes clips of different fps (e.g. a 24fps generation and a
+ // 30fps one).
+ filters.push(
+ `[${vIdx}:v]scale=${canonW}:${canonH}:force_original_aspect_ratio=decrease,pad=${canonW}:${canonH}:(ow-iw)/2:(oh-ih)/2,setsar=1,fps=${clips[0].fps || 24},trim=start=${c.inSec}:end=${c.outSec},setpts=PTS-STARTPTS[v${i}]`
+ );
+ if (c.hasAudio) {
+ filters.push(
+ `[${aIdx}:a]aresample=48000,aformat=sample_fmts=fltp:channel_layouts=stereo,atrim=start=${c.inSec}:end=${c.outSec},asetpts=PTS-STARTPTS[a${i}]`
+ );
+ } else {
+ // The silent input must match the same sample-format/layout as the
+ // real-audio branches; concat=v=1:a=1 fails fast with "Input link
+ // parameters do not match" if they diverge.
+ filters.push(
+ `[${aIdx}:a]aresample=48000,aformat=sample_fmts=fltp:channel_layouts=stereo,asetpts=PTS-STARTPTS[a${i}]`
+ );
+ }
+ concatStreams.push(`[v${i}][a${i}]`);
+ }
+
+ filters.push(`${concatStreams.join('')}concat=n=${clips.length}:v=1:a=1[outv][outa]`);
+
+ const totalDuration = clips.reduce((s, c) => s + c.duration, 0);
+
+ const args = [
+ ...inputs,
+ '-filter_complex', filters.join(';'),
+ '-map', '[outv]',
+ '-map', '[outa]',
+ '-c:v', 'libx264',
+ '-preset', 'veryfast',
+ '-crf', '18',
+ '-pix_fmt', 'yuv420p',
+ '-c:a', 'aac',
+ '-b:a', '192k',
+ '-movflags', '+faststart',
+ '-progress', 'pipe:2',
+ '-y',
+ outputPath,
+ ];
+
+ return { args, totalDuration, canonW, canonH, fps: clips[0].fps };
+}
+
+export function cancelRender(jobId) {
+ const job = jobs.get(jobId);
+ if (!job || !job.process) return false;
+ const proc = job.process;
+ proc.kill('SIGTERM');
+ setTimeout(() => {
+ if (job.process === proc && proc.exitCode === null && proc.signalCode === null) {
+ console.log(`⚠️ ffmpeg render didn't exit on SIGTERM — escalating to SIGKILL`);
+ proc.kill('SIGKILL');
+ }
+ }, 8000);
+ return true;
+}
+
+export async function renderProject(projectId) {
+ const project = await getProject(projectId);
+ if (!project) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });
+
+ // Per-project mutex — return the existing jobId so the UI can re-attach
+ // SSE instead of getting a stale 500. A different project can render in
+ // parallel; only same-project re-entry is blocked.
+ const existingJob = projectRenders.get(projectId);
+ if (existingJob && jobs.has(existingJob)) {
+ throw new ServerError('Render already in progress for this project', {
+ status: 409, code: 'RENDER_IN_PROGRESS', context: { jobId: existingJob },
+ });
+ }
+
+ const ffmpeg = await findFfmpeg();
+ if (!ffmpeg) throw new ServerError('ffmpeg not found on PATH', { status: 500, code: 'FFMPEG_MISSING' });
+
+ // Resolve clips and build args BEFORE claiming the mutex — if either step
+ // throws (missing clips, validation), a stale projectRenders entry would
+ // permanently block future renders of this project.
+ const clips = await resolveClips(project);
+ await ensureDir(PATHS.videos);
+ await ensureDir(PATHS.videoThumbnails);
+
+ const jobId = randomUUID();
+ const filename = `timeline-${projectId.slice(0, 8)}-${Date.now()}.mp4`;
+ const outputPath = join(PATHS.videos, filename);
+ const { args, totalDuration, canonW, canonH, fps } = buildFfmpegArgs(clips, outputPath);
+
+ const job = {
+ id: jobId,
+ projectId,
+ status: 'running',
+ clients: [],
+ process: null,
+ totalDuration,
+ };
+ jobs.set(jobId, job);
+ projectRenders.set(projectId, jobId);
+
+ console.log(`🎞️ Rendering timeline [${jobId.slice(0, 8)}]: project=${projectId.slice(0, 8)} clips=${clips.length} duration=${totalDuration.toFixed(2)}s`);
+
+ const proc = spawn(ffmpeg, args, { stdio: ['ignore', 'ignore', 'pipe'] });
+ job.process = proc;
+
+ // ffmpeg's -progress pipe:2 emits key=value lines, one per line, every
+ // few hundred ms. The relevant key is `out_time_us` (microseconds of
+ // output written so far). Divide by total duration to get a 0..1 ratio.
+ let stderrBuf = '';
+ proc.stderr.on('data', (chunk) => {
+ stderrBuf += chunk.toString();
+ const lines = stderrBuf.split('\n');
+ stderrBuf = lines.pop();
+ for (const raw of lines) {
+ const line = raw.trim();
+ if (!line) continue;
+ const eq = line.indexOf('=');
+ if (eq <= 0) continue;
+ const key = line.slice(0, eq);
+ const val = line.slice(eq + 1);
+ if (key === 'out_time_us') {
+ const us = parseInt(val, 10);
+ if (Number.isFinite(us) && totalDuration > 0) {
+ const progress = Math.min(1, (us / 1_000_000) / totalDuration);
+ broadcastSse(job, { type: 'progress', progress });
+ }
+ } else if (key === 'progress' && val === 'end') {
+ broadcastSse(job, { type: 'progress', progress: 1 });
+ }
+ }
+ });
+
+ proc.on('error', (err) => {
+ job.status = 'error';
+ const reason = `Failed to spawn ffmpeg: ${err.message}`;
+ console.log(`❌ Timeline render spawn error [${jobId.slice(0, 8)}]: ${reason}`);
+ broadcastSse(job, { type: 'error', error: reason });
+ projectRenders.delete(projectId);
+ closeJobAfterDelay(jobs, jobId);
+ });
+
+ proc.on('close', async (code, signal) => {
+ job.process = null;
+ if (code !== 0) {
+ const cancelled = signal === 'SIGTERM' || signal === 'SIGKILL';
+ job.status = cancelled ? 'cancelled' : 'error';
+ const reason = cancelled
+ ? 'Render cancelled'
+ : signal ? `Killed by signal ${signal}` : `ffmpeg exit ${code}`;
+ console.log(`${cancelled ? '🛑' : '❌'} Timeline render ${cancelled ? 'cancelled' : 'failed'} [${jobId.slice(0, 8)}]: ${reason}`);
+ await unlink(outputPath).catch(() => {});
+ broadcastSse(job, { type: cancelled ? 'cancelled' : 'error', error: reason });
+ projectRenders.delete(projectId);
+ closeJobAfterDelay(jobs, jobId);
+ return;
+ }
+ job.status = 'complete';
+ // The encode args already include -movflags +faststart, so no separate
+ // remux pass is needed here.
+ const thumb = await generateThumbnail(outputPath, jobId);
+
+ // Push to existing video history with a timelineProjectId flag so the
+ // Media History page picks it up alongside generated clips.
+ const renderedNumFrames = Math.round(totalDuration * (fps || 24));
+ const meta = {
+ id: jobId,
+ prompt: `Timeline: ${project.name}`,
+ modelId: 'timeline',
+ seed: 0,
+ width: canonW,
+ height: canonH,
+ numFrames: renderedNumFrames,
+ fps: fps || 24,
+ filename,
+ thumbnail: thumb,
+ createdAt: new Date().toISOString(),
+ timelineProjectId: projectId,
+ };
+ const loadedHistory = await loadHistory();
+ const history = Array.isArray(loadedHistory) ? loadedHistory : [];
+ history.unshift(meta);
+ await saveHistory(history);
+ console.log(`✅ Timeline rendered [${jobId.slice(0, 8)}]: ${filename}`);
+ broadcastSse(job, { type: 'complete', result: { id: jobId, filename, thumbnail: thumb, path: `/data/videos/${filename}` } });
+ projectRenders.delete(projectId);
+ closeJobAfterDelay(jobs, jobId);
+ });
+
+ return { jobId };
+}
diff --git a/server/services/videoTimeline/local.test.js b/server/services/videoTimeline/local.test.js
new file mode 100644
index 0000000000..ae6d4d0d57
--- /dev/null
+++ b/server/services/videoTimeline/local.test.js
@@ -0,0 +1,115 @@
+import { describe, it, expect } from 'vitest';
+import { buildFfmpegArgs } from './local.js';
+
+const baseClip = (overrides = {}) => ({
+ index: 0,
+ clipId: 'clip-1',
+ videoPath: '/tmp/clip-1.mp4',
+ inSec: 0,
+ outSec: 4,
+ duration: 4,
+ width: 768,
+ height: 512,
+ fps: 24,
+ hasAudio: true,
+ ...overrides,
+});
+
+describe('buildFfmpegArgs', () => {
+ it('throws on empty clip list', () => {
+ expect(() => buildFfmpegArgs([], '/out.mp4')).toThrow(/empty/i);
+ });
+
+ it('produces a single-clip filter_complex with audio passthrough', () => {
+ const clips = [baseClip()];
+ const { args, totalDuration, canonW, canonH } = buildFfmpegArgs(clips, '/out.mp4');
+
+ expect(totalDuration).toBe(4);
+ expect(canonW).toBe(768);
+ expect(canonH).toBe(512);
+
+ const fcIdx = args.indexOf('-filter_complex');
+ expect(fcIdx).toBeGreaterThan(-1);
+ const filter = args[fcIdx + 1];
+
+ // Single clip → only one input, audio uses the same input idx (0:a)
+ expect(filter).toContain('[0:v]scale=768:512');
+ expect(filter).toContain('trim=start=0:end=4');
+ expect(filter).toContain('[0:a]aresample=48000');
+ expect(filter).toContain('atrim=start=0:end=4');
+ // Final concat for n=1 still wraps the streams
+ expect(filter).toContain('[v0][a0]concat=n=1:v=1:a=1[outv][outa]');
+ });
+
+ it('inserts anullsrc inputs for clips without audio', () => {
+ const clips = [
+ baseClip({ hasAudio: false, duration: 3, outSec: 3 }),
+ baseClip({ hasAudio: true, duration: 5, outSec: 5 }),
+ ];
+ const { args } = buildFfmpegArgs(clips, '/out.mp4');
+
+ // Inputs: -i clip0, -f lavfi -t 3 -i anullsrc..., -i clip1
+ // Indices: 0 = clip0 video, 1 = silent stub, 2 = clip1 (with audio at 2:a)
+ const inputs = args.slice(0, args.indexOf('-filter_complex'));
+ expect(inputs.filter((a) => a === '-i')).toHaveLength(3);
+ expect(inputs).toContain('-f');
+ expect(inputs).toContain('lavfi');
+ expect(inputs).toContain('anullsrc=channel_layout=stereo:sample_rate=48000');
+
+ const filter = args[args.indexOf('-filter_complex') + 1];
+ // Clip 0's video uses input 0; its audio uses input 1 (silent stub) and
+ // is normalized to match the real-audio sample-format/layout so concat
+ // accepts both branches.
+ expect(filter).toContain('[0:v]scale=768:512');
+ expect(filter).toContain('[1:a]aresample=48000,aformat=sample_fmts=fltp:channel_layouts=stereo,asetpts=PTS-STARTPTS[a0]');
+ // Clip 1's video uses input 2; its audio uses input 2 (real audio)
+ expect(filter).toContain('[2:v]scale=768:512');
+ expect(filter).toContain('[2:a]aresample=48000');
+ });
+
+ it('encodes a 3-clip mixed-audio timeline correctly', () => {
+ const clips = [
+ baseClip({ hasAudio: true, inSec: 0, outSec: 2, duration: 2 }),
+ baseClip({ hasAudio: false, inSec: 1, outSec: 4, duration: 3 }),
+ baseClip({ hasAudio: true, inSec: 0.5, outSec: 3, duration: 2.5 }),
+ ];
+ const { args, totalDuration } = buildFfmpegArgs(clips, '/out.mp4');
+
+ expect(totalDuration).toBeCloseTo(7.5);
+
+ const filter = args[args.indexOf('-filter_complex') + 1];
+ // Final concat must include all 3 clip pairs in order
+ expect(filter).toContain('[v0][a0][v1][a1][v2][a2]concat=n=3:v=1:a=1[outv][outa]');
+ // Trims preserve per-clip in/out
+ expect(filter).toContain('trim=start=0:end=2');
+ expect(filter).toContain('trim=start=1:end=4');
+ expect(filter).toContain('trim=start=0.5:end=3');
+ });
+
+ it('uses canonical dims from the first clip for scale+pad on every clip', () => {
+ const clips = [
+ baseClip({ width: 1024, height: 576 }),
+ baseClip({ width: 768, height: 512 }), // different — should still be padded to 1024x576
+ ];
+ const { args, canonW, canonH } = buildFfmpegArgs(clips, '/out.mp4');
+ expect(canonW).toBe(1024);
+ expect(canonH).toBe(576);
+ const filter = args[args.indexOf('-filter_complex') + 1];
+ // Both video chains scale to 1024:576
+ const scales = filter.match(/scale=1024:576/g) || [];
+ expect(scales).toHaveLength(2);
+ });
+
+ it('emits encoder + faststart + progress flags', () => {
+ const { args } = buildFfmpegArgs([baseClip()], '/out.mp4');
+ expect(args).toContain('-c:v');
+ expect(args).toContain('libx264');
+ expect(args).toContain('-c:a');
+ expect(args).toContain('aac');
+ expect(args).toContain('-movflags');
+ expect(args).toContain('+faststart');
+ expect(args).toContain('-progress');
+ expect(args).toContain('pipe:2');
+ expect(args[args.length - 1]).toBe('/out.mp4');
+ });
+});