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 gen mode switch (text/image/FFLF/extend) + batch queue

Adam Eivy82dba2f0b0f5
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 6072276714..31287fda3e 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -4,6 +4,7 @@
- **Morse code trainer** in POST (`/post/morse`) — Koch-method Copy mode (listen → type, 90% accuracy unlocks the next letter) and a Send mode that decodes spacebar/touch keying into text. Native Web Audio (no new deps), Farnsworth timing, configurable WPM/tone. Reachable from the POST launcher header, the sidebar, ⌘K, and voice (`ui_navigate "morse"`).
- **Morse trainer side widget** with a binary tree visualization that highlights the live keying path (DAH-left, DIT-right), three reference views (Tree / Length / List), a tap-anywhere practice key, and a real-time decoded log. Spacebar keying is intercepted in capture phase so it doesn't trigger the voice FAB push-to-talk hotkey while on the morse page.
+- **Video Gen mode switch + batch queue** (`/media/video`) — segmented control selects Text / Image / FFLF (first-frame + last-frame) / Extend (continue from a prior render). Mode-specific input panels (start image, end image, prior-video picker) replace the always-on source image upload. New "Add to queue" button enqueues the current configuration; a batch-queue panel runs jobs serially with per-item status (pending/running/complete/error), inline error messages, and a clear-completed action. Backend route accepts a `lastImageFile` (gallery-pick) and `mode` field; `--last-image` is plumbed to the LTX Python child (currently advisory until a multi-keyframe wrapper lands).
## Changed
diff --git a/client/src/components/media/BatchQueuePanel.jsx b/client/src/components/media/BatchQueuePanel.jsx
new file mode 100644
index 0000000000..1f2e125625
--- /dev/null
+++ b/client/src/components/media/BatchQueuePanel.jsx
@@ -0,0 +1,73 @@
+import { Trash2, CheckCircle2, AlertCircle, Loader2, Clock } from 'lucide-react';
+
+// Shared batch-queue panel used by both Video Gen and Image Gen. The owner
+// page tracks queue state and the worker effect; this component is
+// presentation-only — it renders the list, status icons, and the
+// remove/clear-completed affordances.
+//
+// Each item is { id, status: 'pending'|'running'|'complete'|'error',
+// params: { prompt, mode, ... }, error?, ... }. `summarize` lets the host
+// page format the per-item subtitle line however it wants (e.g. video
+// shows resolution+frames, image shows resolution+steps).
+
+const STATUS_ICON = {
+ pending: { Icon: Clock, color: 'text-gray-400' },
+ running: { Icon: Loader2, color: 'text-port-accent animate-spin' },
+ complete: { Icon: CheckCircle2, color: 'text-port-success' },
+ error: { Icon: AlertCircle, color: 'text-port-error' },
+};
+
+export default function BatchQueuePanel({ queue, inFlightCount, onRemove, onClear, summarize }) {
+ if (!queue.length) return null;
+ const completedCount = queue.filter((q) => q.status === 'complete' || q.status === 'error').length;
+ return (
+ <div className="bg-port-card border border-port-border rounded-xl p-5 space-y-3">
+ <div className="flex items-center justify-between">
+ <h2 className="text-sm font-medium text-gray-300">
+ Batch queue
+ <span className="ml-2 text-xs text-gray-500">
+ {inFlightCount > 0 ? `${inFlightCount} in flight` : 'idle'}
+ </span>
+ </h2>
+ {completedCount > 0 && (
+ <button
+ type="button"
+ onClick={onClear}
+ className="text-xs text-gray-400 hover:text-white"
+ >
+ Clear completed ({completedCount})
+ </button>
+ )}
+ </div>
+ <ul className="space-y-2 max-h-72 overflow-y-auto">
+ {queue.map((item) => {
+ const { Icon, color } = STATUS_ICON[item.status] || STATUS_ICON.pending;
+ return (
+ <li
+ key={item.id}
+ className="flex items-center gap-3 px-3 py-2 bg-port-bg border border-port-border rounded-lg text-xs"
+ >
+ <Icon className={`w-4 h-4 flex-shrink-0 ${color}`} />
+ <div className="flex-1 min-w-0">
+ <div className="text-gray-200 truncate">{item.params.prompt}</div>
+ <div className="text-gray-500 text-[11px] truncate">
+ {summarize(item)}
+ {item.error && <span className="text-port-error ml-2">— {item.error}</span>}
+ </div>
+ </div>
+ <button
+ type="button"
+ onClick={() => onRemove(item.id)}
+ disabled={item.status === 'running'}
+ className="p-1 text-gray-500 hover:text-port-error disabled:opacity-30 disabled:cursor-not-allowed"
+ title={item.status === 'running' ? 'Cancel via the form button' : 'Remove from queue'}
+ >
+ <Trash2 className="w-3.5 h-3.5" />
+ </button>
+ </li>
+ );
+ })}
+ </ul>
+ </div>
+ );
+}
diff --git a/client/src/pages/VideoGen.jsx b/client/src/pages/VideoGen.jsx
index 4e7db4343b..8cf1efa79c 100644
--- a/client/src/pages/VideoGen.jsx
+++ b/client/src/pages/VideoGen.jsx
@@ -5,6 +5,20 @@
* Accepts a source image either via direct upload or via the
* `?sourceImageFile=` query param so the Image Gen page can pipe a generation
* straight into video.
+ *
+ * Modes (UI state, also forwarded to the backend as `mode`):
+ * - text: pure text-to-video
+ * - image: image-to-video (one source image, current I2V behavior)
+ * - fflf: first frame + last frame (two images — backend support is
+ * experimental; mlx_video CLI consumes only the first today)
+ * - extend: pick a previous render → its last frame becomes the source
+ * image for a new image-to-video generation
+ *
+ * Batch queue: client-side serial executor. The form's "Add to queue" button
+ * appends a job to the queue (preserving the current params). When no job is
+ * actively generating, the head of the queue is dequeued and submitted via
+ * the same generate path as the inline button — so SSE progress, history
+ * refresh, and error handling are all reused.
*/
import { useState, useEffect, useRef, useCallback, useMemo } from 'react';
@@ -16,13 +30,15 @@ import MediaLightbox from '../components/media/MediaLightbox';
import { normalizeVideo } from '../components/media/normalize';
import {
Film, Sparkles, Settings as SettingsIcon, RefreshCw, AlertTriangle,
- Dice5, X, Upload
+ Dice5, X, Upload, Type, Image as ImageIcon, GitBranch, ListPlus,
} from 'lucide-react';
import toast from '../components/ui/Toast';
import BrailleSpinner from '../components/BrailleSpinner';
+import BatchQueuePanel from '../components/media/BatchQueuePanel';
import {
getVideoGenStatus, generateVideo, cancelVideoGen,
listVideoHistory, deleteVideoHistoryItem, setVideoHidden, extractLastFrame,
+ listImageGallery,
} from '../services/api';
import { randomSeed, safeParseJSON } from '../lib/genUtils';
@@ -44,6 +60,18 @@ const TILING_OPTIONS = [
{ value: 'temporal', label: 'Temporal only' },
];
+const MODES = [
+ { id: 'text', label: 'Text', icon: Type, desc: 'Text-to-video' },
+ { id: 'image', label: 'Image', icon: ImageIcon, desc: 'Image-to-video (start frame)' },
+ { id: 'fflf', label: 'FFLF', icon: GitBranch, desc: 'First frame + last frame' },
+ { id: 'extend', label: 'Extend', icon: Film, desc: 'Continue from a prior render' },
+];
+
+const newQueueId = () =>
+ (typeof crypto !== 'undefined' && crypto.randomUUID)
+ ? crypto.randomUUID()
+ : `q-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
+
export default function VideoGen() {
const [searchParams, setSearchParams] = useSearchParams();
const incomingSourceImage = searchParams.get('sourceImageFile');
@@ -57,6 +85,7 @@ export default function VideoGen() {
const [statusLoading, setStatusLoading] = useState(true);
const [models, setModels] = useState([]);
+ const [mode, setMode] = useState(incomingSourceImage ? 'image' : 'text');
const [prompt, setPrompt] = useState(incomingPrompt || '');
const [negativePrompt, setNegativePrompt] = useState(incomingNegativePrompt || '');
const [modelId, setModelId] = useState('');
@@ -71,13 +100,20 @@ export default function VideoGen() {
const [disableAudio, setDisableAudio] = useState(false);
const [sourceImageFile, setSourceImageFile] = useState(incomingSourceImage || null);
const [sourceImageUpload, setSourceImageUpload] = useState(null);
+ const [lastImageFile, setLastImageFile] = useState(null);
+ const [extendFromVideoId, setExtendFromVideoId] = useState('');
+ const [extendingFrame, setExtendingFrame] = useState(false);
+
+ // Image gallery for the FFLF end-frame picker (gallery only — no upload
+ // for the second image so the multipart parser stays single-file).
+ const [imageGallery, setImageGallery] = useState([]);
+
// Re-sync when ImageGen pipes a new image via ?sourceImageFile=...
- // React Router doesn't remount on query-string-only navigation, so the
- // initial useState capture would otherwise stick.
useEffect(() => {
if (incomingSourceImage) {
setSourceImageFile(incomingSourceImage);
setSourceImageUpload(null);
+ setMode((m) => (m === 'text' ? 'image' : m));
}
}, [incomingSourceImage]);
useEffect(() => {
@@ -86,6 +122,7 @@ export default function VideoGen() {
useEffect(() => {
if (incomingNegativePrompt) setNegativePrompt(incomingNegativePrompt);
}, [incomingNegativePrompt]);
+
const [history, setHistory] = useState([]);
const [preview, setPreview] = useState(null);
const [showHidden, setShowHidden] = useState(false);
@@ -95,6 +132,7 @@ export default function VideoGen() {
listVideoHistory().then((items) => setHistory(Array.isArray(items) ? items : [])).catch(() => {});
}, []);
useEffect(() => { refreshHistory(); }, [refreshHistory]);
+ useEffect(() => { listImageGallery().then(setImageGallery).catch(() => {}); }, []);
const { visibleHistory, hiddenHistory } = useMemo(() => ({
visibleHistory: history.filter((v) => !v.hidden),
@@ -116,12 +154,11 @@ export default function VideoGen() {
if (result) toast.success(nextHidden ? 'Video hidden' : 'Video unhidden');
};
const handleContinueHistory = async (item) => {
- try {
- const { filename } = await extractLastFrame(item.id);
- navigate(`/media/video?sourceImageFile=${encodeURIComponent(filename)}`);
- } catch (err) {
+ const { filename } = await extractLastFrame(item.id).catch((err) => {
toast.error(err.message || 'Failed to extract last frame');
- }
+ return {};
+ });
+ if (filename) navigate(`/media/video?sourceImageFile=${encodeURIComponent(filename)}`);
};
const [generating, setGenerating] = useState(false);
@@ -131,14 +168,19 @@ export default function VideoGen() {
const [error, setError] = useState(null);
const eventSourceRef = useRef(null);
+ // Batch queue. Each item snapshots the params at enqueue time so the user
+ // can keep editing the form while jobs are in flight without affecting the
+ // queued ones. The active generation is held in `generating`/`progress`;
+ // `runningQueueId` (if set) marks which queued item it represents.
+ const [queue, setQueue] = useState([]);
+ const [runningQueueId, setRunningQueueId] = useState(null);
+
const refreshStatus = useCallback(() => {
setStatusLoading(true);
getVideoGenStatus()
.then((s) => {
setStatus(s);
setModels(s.models || []);
- // Functional update so a stale `modelId` closure can't reset the
- // user's selected model on a refresh — only set when no choice yet.
if (s.defaultModel) setModelId((prev) => prev || s.defaultModel);
})
.catch(() => setStatus({ connected: false, reason: 'Status check failed' }))
@@ -160,7 +202,6 @@ export default function VideoGen() {
const r = RESOLUTIONS.find((r) => r.label === e.target.value);
if (r) { setWidth(r.w); setHeight(r.h); }
};
-
const handleRandomSeed = () => setSeed(randomSeed());
const clearSourceImage = () => {
@@ -172,33 +213,76 @@ export default function VideoGen() {
setSearchParams(next, { replace: true });
}
};
+ const clearLastImage = () => setLastImageFile(null);
+
+ // Switching mode resets the now-irrelevant fields so a stale choice from
+ // a prior mode can't sneak into the next generation. (Prompt/seed/etc.
+ // carry over because they apply to all modes.)
+ const handleModeChange = (next) => {
+ setMode(next);
+ if (next === 'text') {
+ clearSourceImage();
+ setLastImageFile(null);
+ setExtendFromVideoId('');
+ } else if (next === 'image') {
+ setLastImageFile(null);
+ setExtendFromVideoId('');
+ } else if (next === 'fflf') {
+ setExtendFromVideoId('');
+ } else if (next === 'extend') {
+ setLastImageFile(null);
+ }
+ };
- const handleGenerate = async (e) => {
- e?.preventDefault?.();
- if (!prompt.trim() || generating) return;
+ // Extend mode: the user picks a prior video; we extract its last frame
+ // (lazily — only when picked, since extraction shells out to ffmpeg) and
+ // use that as the source image for image-to-video.
+ const handleExtendPick = async (videoId) => {
+ setExtendFromVideoId(videoId);
+ if (!videoId) { clearSourceImage(); return; }
+ setExtendingFrame(true);
+ const res = await extractLastFrame(videoId).catch((err) => {
+ toast.error(err.message || 'Failed to extract last frame');
+ return null;
+ });
+ setExtendingFrame(false);
+ if (res?.filename) {
+ setSourceImageFile(res.filename);
+ setSourceImageUpload(null);
+ }
+ };
+
+ // Snapshot the current form into a generate-payload. Used both by the
+ // inline Generate button and by enqueue, so the two paths stay in lockstep.
+ const buildGeneratePayload = () => ({
+ prompt: prompt.trim(),
+ negativePrompt: negativePrompt.trim() || '',
+ modelId,
+ width, height,
+ numFrames,
+ fps,
+ steps: steps || '',
+ guidanceScale: guidanceScale || '',
+ seed: seed || '',
+ tiling,
+ disableAudio: disableAudio ? 'true' : 'false',
+ mode,
+ sourceImageFile: (mode === 'image' || mode === 'fflf' || mode === 'extend') ? (sourceImageFile || '') : '',
+ sourceImage: (mode === 'image' || mode === 'fflf') ? (sourceImageUpload || '') : '',
+ lastImageFile: mode === 'fflf' ? (lastImageFile || '') : '',
+ });
+
+ // Run a single payload through the SSE pipeline. Returns a promise that
+ // resolves when the job completes (or rejects on error). Shared by the
+ // inline submit and the queue worker.
+ const runGeneration = (payload) => new Promise((resolve, reject) => {
setGenerating(true);
setProgress({ progress: 0 });
setStatusMsg('Starting...');
setResult(null);
setError(null);
- try {
- const data = await generateVideo({
- prompt: prompt.trim(),
- negativePrompt: negativePrompt.trim() || '',
- modelId,
- width, height,
- numFrames,
- fps,
- steps: steps || '',
- guidanceScale: guidanceScale || '',
- seed: seed || '',
- tiling,
- disableAudio: disableAudio ? 'true' : 'false',
- sourceImageFile: sourceImageFile || '',
- sourceImage: sourceImageUpload || '',
- });
-
+ generateVideo(payload).then((data) => {
const jobId = data.jobId || data.generationId;
const es = new EventSource(`/api/video-gen/${jobId}/events`);
eventSourceRef.current = es;
@@ -219,34 +303,96 @@ export default function VideoGen() {
es.close();
toast.success('Video generated');
refreshHistory();
+ resolve(msg.result);
}
if (msg.type === 'error') {
setError(msg.error);
setGenerating(false);
es.close();
toast.error(msg.error);
+ reject(new Error(msg.error));
}
};
es.onerror = () => {
setError('Lost connection to server');
setGenerating(false);
es.close();
+ reject(new Error('Lost connection to server'));
};
- } catch (err) {
+ }).catch((err) => {
setError(err.message || 'Video generation failed');
setGenerating(false);
toast.error(err.message || 'Video generation failed');
- }
+ reject(err);
+ });
+ });
+
+ const handleGenerate = async (e) => {
+ e?.preventDefault?.();
+ if (!prompt.trim() || generating) return;
+ await runGeneration(buildGeneratePayload()).catch(() => {});
};
+ const handleEnqueue = () => {
+ if (!prompt.trim()) return;
+ const payload = buildGeneratePayload();
+ // Strip the File blob for snapshot — re-using a File across multiple
+ // queued submissions is fine, but we need a stable JSON-ish summary
+ // for the queue UI display. Hold the File in `_blob` separately.
+ const { sourceImage, ...summary } = payload;
+ setQueue((q) => [...q, {
+ id: newQueueId(),
+ status: 'pending',
+ params: summary,
+ _blob: sourceImage instanceof File ? sourceImage : null,
+ enqueuedAt: Date.now(),
+ }]);
+ toast.success('Added to queue');
+ };
+
+ const removeFromQueue = (id) => {
+ setQueue((q) => q.filter((item) => item.id !== id || item.status === 'running'));
+ };
+ const clearCompletedQueue = () => {
+ setQueue((q) => q.filter((item) => item.status !== 'complete' && item.status !== 'error'));
+ };
+
+ // Queue worker — pumps the head of the queue when nothing's running.
+ // Runs as an effect so it picks up any newly-enqueued item even while
+ // the user is interacting with the form.
+ useEffect(() => {
+ if (generating || runningQueueId) return;
+ const next = queue.find((item) => item.status === 'pending');
+ if (!next) return;
+ setRunningQueueId(next.id);
+ setQueue((q) => q.map((item) => item.id === next.id ? { ...item, status: 'running', startedAt: Date.now() } : item));
+ const payload = { ...next.params };
+ if (next._blob) payload.sourceImage = next._blob;
+ runGeneration(payload).then((res) => {
+ setQueue((q) => q.map((item) => item.id === next.id ? { ...item, status: 'complete', result: res } : item));
+ }).catch((err) => {
+ setQueue((q) => q.map((item) => item.id === next.id ? { ...item, status: 'error', error: err.message } : item));
+ }).finally(() => {
+ setRunningQueueId(null);
+ });
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [queue, generating, runningQueueId]);
+
const handleCancel = async () => {
eventSourceRef.current?.close();
await cancelVideoGen().catch(() => {});
setGenerating(false);
setStatusMsg('Cancelled');
+ if (runningQueueId) {
+ setQueue((q) => q.map((item) => item.id === runningQueueId ? { ...item, status: 'error', error: 'Cancelled' } : item));
+ setRunningQueueId(null);
+ }
};
const notConnected = status && status.connected === false;
+ const canEnqueue = prompt.trim() && !notConnected;
+ const pendingCount = queue.filter((q) => q.status === 'pending').length;
+ const inFlightCount = pendingCount + (runningQueueId ? 1 : 0);
return (
<div className="space-y-6">
@@ -290,6 +436,33 @@ export default function VideoGen() {
</div>
</div>
+ {/* Mode switch — segmented control above the form. Sets state that
+ both the form rendering and the submit payload react to. */}
+ <div className="bg-port-card border border-port-border rounded-xl p-1.5 flex flex-wrap gap-1" role="tablist" aria-label="Video generation mode">
+ {MODES.map(({ id, label, icon: Icon, desc }) => {
+ const active = mode === id;
+ return (
+ <button
+ key={id}
+ type="button"
+ role="tab"
+ aria-selected={active}
+ onClick={() => handleModeChange(id)}
+ disabled={generating}
+ className={`flex-1 min-w-[140px] flex items-center justify-center gap-2 px-3 py-2 rounded-lg text-sm font-medium transition-colors disabled:opacity-50 ${
+ active
+ ? 'bg-port-accent text-white shadow'
+ : 'text-gray-400 hover:text-white hover:bg-port-border/40'
+ }`}
+ title={desc}
+ >
+ <Icon className="w-4 h-4" />
+ <span>{label}</span>
+ </button>
+ );
+ })}
+ </div>
+
<form onSubmit={handleGenerate} className="grid grid-cols-1 lg:grid-cols-[1fr,1.2fr] gap-6">
<div className="bg-port-card border border-port-border rounded-xl p-5 space-y-4">
<div>
@@ -316,34 +489,105 @@ export default function VideoGen() {
/>
</div>
- {/* Source image (image-to-video) */}
- <div className="border border-port-border/50 rounded-lg p-3 space-y-2">
- <div className="flex items-center justify-between">
- <span className="text-xs font-medium text-gray-400">Source Image (optional, image-to-video)</span>
- {(sourceImageFile || sourceImageUpload) && (
- <button type="button" onClick={clearSourceImage} className="text-xs text-port-error hover:underline">Clear</button>
+ {/* Mode-specific image / video pickers */}
+ {(mode === 'image' || mode === 'fflf') && (
+ <div className="border border-port-border/50 rounded-lg p-3 space-y-2">
+ <div className="flex items-center justify-between">
+ <span className="text-xs font-medium text-gray-400">
+ {mode === 'fflf' ? 'First frame (start image)' : 'Source image (image-to-video)'}
+ </span>
+ {(sourceImageFile || sourceImageUpload) && (
+ <button type="button" onClick={clearSourceImage} className="text-xs text-port-error hover:underline">Clear</button>
+ )}
+ </div>
+ {sourceImageFile && (
+ <div className="flex items-center gap-2">
+ <img src={`/data/images/${sourceImageFile}`} alt="Source" className="w-16 h-16 object-cover rounded border border-port-border" />
+ <span className="text-xs text-gray-500 truncate">{sourceImageFile}</span>
+ </div>
+ )}
+ {!sourceImageFile && (
+ <label className="flex items-center gap-2 text-xs text-gray-400 cursor-pointer hover:text-white">
+ <Upload className="w-4 h-4" />
+ <span>{sourceImageUpload ? sourceImageUpload.name : 'Upload an image'}</span>
+ <input
+ type="file"
+ accept="image/*"
+ disabled={generating}
+ onChange={(e) => setSourceImageUpload(e.target.files?.[0] || null)}
+ className="hidden"
+ />
+ </label>
)}
</div>
- {sourceImageFile && (
- <div className="flex items-center gap-2">
- <img src={`/data/images/${sourceImageFile}`} alt="Source" className="w-16 h-16 object-cover rounded border border-port-border" />
- <span className="text-xs text-gray-500 truncate">{sourceImageFile}</span>
+ )}
+
+ {mode === 'fflf' && (
+ <div className="border border-port-border/50 rounded-lg p-3 space-y-2">
+ <div className="flex items-center justify-between">
+ <span className="text-xs font-medium text-gray-400">Last frame (end image)</span>
+ {lastImageFile && (
+ <button type="button" onClick={clearLastImage} className="text-xs text-port-error hover:underline">Clear</button>
+ )}
</div>
- )}
- {!sourceImageFile && (
- <label className="flex items-center gap-2 text-xs text-gray-400 cursor-pointer hover:text-white">
- <Upload className="w-4 h-4" />
- <span>{sourceImageUpload ? sourceImageUpload.name : 'Upload an image'}</span>
- <input
- type="file"
- accept="image/*"
+ {lastImageFile ? (
+ <div className="flex items-center gap-2">
+ <img src={`/data/images/${lastImageFile}`} alt="End frame" className="w-16 h-16 object-cover rounded border border-port-border" />
+ <span className="text-xs text-gray-500 truncate">{lastImageFile}</span>
+ </div>
+ ) : (
+ <select
+ value=""
disabled={generating}
- onChange={(e) => setSourceImageUpload(e.target.files?.[0] || null)}
- className="hidden"
- />
- </label>
- )}
- </div>
+ onChange={(e) => setLastImageFile(e.target.value || null)}
+ 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"
+ >
+ <option value="">Pick an image from gallery…</option>
+ {imageGallery.filter((img) => !img.hidden).slice(0, 50).map((img) => (
+ <option key={img.filename} value={img.filename}>{img.filename}</option>
+ ))}
+ </select>
+ )}
+ <p className="text-[11px] text-gray-500 leading-snug">
+ Note: FFLF (two-keyframe) backend support is experimental — current
+ LTX/mlx_video CLI consumes the start frame and treats the last frame
+ as advisory. Generate the end image first via Image Gen, then pick it here.
+ </p>
+ </div>
+ )}
+
+ {mode === 'extend' && (
+ <div className="border border-port-border/50 rounded-lg p-3 space-y-2">
+ <div className="flex items-center justify-between">
+ <span className="text-xs font-medium text-gray-400">Continue from a prior render</span>
+ {extendFromVideoId && (
+ <button type="button" onClick={() => handleExtendPick('')} className="text-xs text-port-error hover:underline">Clear</button>
+ )}
+ </div>
+ <select
+ value={extendFromVideoId}
+ disabled={generating || extendingFrame}
+ onChange={(e) => handleExtendPick(e.target.value)}
+ 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"
+ >
+ <option value="">Pick a previous video…</option>
+ {visibleHistory.slice(0, 50).map((v) => (
+ <option key={v.id} value={v.id}>
+ {(v.prompt || v.filename || v.id).slice(0, 80)}
+ </option>
+ ))}
+ </select>
+ {extendingFrame && (
+ <span className="text-[11px] text-gray-500">Extracting last frame…</span>
+ )}
+ {sourceImageFile && extendFromVideoId && !extendingFrame && (
+ <div className="flex items-center gap-2">
+ <img src={`/data/images/${sourceImageFile}`} alt="Last frame" className="w-16 h-16 object-cover rounded border border-port-border" />
+ <span className="text-xs text-gray-500 truncate">Starts from: {sourceImageFile}</span>
+ </div>
+ )}
+ </div>
+ )}
<div className="grid grid-cols-2 gap-3">
{models.length > 0 && (
@@ -471,7 +715,7 @@ export default function VideoGen() {
</label>
</div>
- <div className="flex items-center gap-2 pt-2">
+ <div className="flex flex-wrap items-center gap-2 pt-2">
{generating ? (
<button
type="button"
@@ -489,6 +733,15 @@ export default function VideoGen() {
<Sparkles className="w-4 h-4" /> Generate
</button>
)}
+ <button
+ type="button"
+ onClick={handleEnqueue}
+ disabled={!canEnqueue}
+ className="flex items-center gap-2 px-4 py-2 border border-port-border text-gray-200 hover:text-white hover:bg-port-border/40 disabled:opacity-50 disabled:cursor-not-allowed text-sm font-medium rounded-lg min-h-[40px]"
+ title="Add this configuration to the batch queue"
+ >
+ <ListPlus className="w-4 h-4" /> Add to queue
+ </button>
{progressPct != null && <span className="text-xs text-port-accent">{progressPct}%</span>}
</div>
@@ -536,6 +789,19 @@ export default function VideoGen() {
</div>
</form>
+ <BatchQueuePanel
+ queue={queue}
+ inFlightCount={inFlightCount}
+ onRemove={removeFromQueue}
+ onClear={clearCompletedQueue}
+ summarize={(item) => (
+ <>
+ <span className="uppercase mr-2">{item.params.mode}</span>
+ {item.params.width}×{item.params.height} · {item.params.numFrames}f
+ </>
+ )}
+ />
+
{visibleHistory.length > 0 && (
<div className="bg-port-card border border-port-border rounded-xl p-5 space-y-3">
<div className="flex items-center justify-between">
@@ -604,3 +870,4 @@ export default function VideoGen() {
</div>
);
}
+
diff --git a/scripts/generate_win.py b/scripts/generate_win.py
index 8fb722cfad..b514346e3d 100644
--- a/scripts/generate_win.py
+++ b/scripts/generate_win.py
@@ -68,7 +68,14 @@ def main():
p.add_argument('--seed', type=int, default=None)
p.add_argument('--output', required=True)
p.add_argument('--image', default=None)
+ p.add_argument('--last-image', default=None,
+ help='Optional end-frame target (FFLF). Currently advisory — '
+ 'LTX-Video 0.9.5 diffusers pipeline does not natively '
+ 'consume two keyframes; flag is accepted for forward '
+ 'compatibility with multi-keyframe pipelines.')
args = p.parse_args()
+ if args.last_image:
+ log(f'STATUS:Last-frame image supplied ({args.last_image}) — currently advisory; falling back to single-image I2V')
dtype = torch.bfloat16
generator = torch.Generator('cuda').manual_seed(args.seed) if args.seed is not None else None
diff --git a/server/routes/videoGen.js b/server/routes/videoGen.js
index 02ee855f6a..e13acb5e46 100644
--- a/server/routes/videoGen.js
+++ b/server/routes/videoGen.js
@@ -62,6 +62,14 @@ const generateBodySchema = z.object({
tiling: z.enum(['auto', 'none', 'spatial', 'temporal']).optional(),
disableAudio: z.union([z.boolean(), z.literal('true'), z.literal('false')]).optional(),
sourceImageFile: z.string().max(512).optional(),
+ // FFLF mode end-frame target. Gallery-pick only (no upload field) so the
+ // multipart parser stays single-file. Users wanting a fresh end-frame
+ // image can generate or upload it via Image Gen first, then reference
+ // its basename here.
+ lastImageFile: z.string().max(512).optional(),
+ // UI mode hint — backend only uses it for logging/branching; absence
+ // falls back to inferring (sourceImage→i2v, no source→t2v).
+ mode: z.enum(['text', 'image', 'fflf', 'extend']).optional(),
});
router.get('/status', asyncHandler(async (_req, res) => {
@@ -79,6 +87,14 @@ router.get('/models', (_req, res) => {
res.json(listVideoModels());
});
+// Path-traversal guard: basename() strips dirs, then resolve+prefix-check
+// against PATHS.images so a unicode trick can't escape data/images.
+const resolveGalleryImage = (name) => {
+ const imagesRoot = resolvePath(PATHS.images) + PATH_SEP;
+ const localPath = resolvePath(join(PATHS.images, basename(name)));
+ return localPath.startsWith(imagesRoot) && existsSync(localPath) ? localPath : null;
+};
+
router.post('/', sourceImageUpload, asyncHandler(async (req, res) => {
const parsed = generateBodySchema.safeParse(req.body);
if (!parsed.success) {
@@ -98,13 +114,12 @@ router.post('/', sourceImageUpload, asyncHandler(async (req, res) => {
// (where the python child reads it directly and we can't unlink earlier).
uploadedTempPath = req.file.path;
} else if (body.sourceImageFile) {
- // Path-traversal guard: basename() strips dirs, then resolve+prefix-check
- // against PATHS.images so a unicode trick can't escape data/images.
- const imagesRoot = resolvePath(PATHS.images) + PATH_SEP;
- const localPath = resolvePath(join(PATHS.images, basename(body.sourceImageFile)));
- if (localPath.startsWith(imagesRoot) && existsSync(localPath)) sourceImagePath = localPath;
+ sourceImagePath = resolveGalleryImage(body.sourceImageFile);
}
+ // FFLF end-frame: gallery-pick only. Same path-traversal guard.
+ const lastImagePath = body.lastImageFile ? resolveGalleryImage(body.lastImageFile) : null;
+
try {
const result = await generateVideo({
pythonPath,
@@ -122,6 +137,8 @@ router.post('/', sourceImageUpload, asyncHandler(async (req, res) => {
disableAudio: body.disableAudio === true || body.disableAudio === 'true',
sourceImagePath,
uploadedTempPath,
+ lastImagePath,
+ mode: body.mode,
});
res.json(result);
} catch (err) {
diff --git a/server/routes/videoGen.test.js b/server/routes/videoGen.test.js
index c3ae242399..aab04aec19 100644
--- a/server/routes/videoGen.test.js
+++ b/server/routes/videoGen.test.js
@@ -113,6 +113,30 @@ describe('videoGen routes', () => {
prompt: 'a cat',
}));
});
+
+ it('forwards lastImageFile + mode for FFLF', async () => {
+ videoGenService.generateVideo.mockResolvedValue({ jobId: 'j3', filename: 'j3.mp4' });
+ const r = await request(app).post('/api/video-gen/').send({
+ prompt: 'morph between two scenes',
+ sourceImageFile: 'first.png',
+ lastImageFile: 'last.png',
+ mode: 'fflf',
+ });
+ expect(r.status).toBe(200);
+ expect(videoGenService.generateVideo).toHaveBeenCalledWith(expect.objectContaining({
+ prompt: 'morph between two scenes',
+ mode: 'fflf',
+ }));
+ });
+
+ it('rejects an unknown mode value', async () => {
+ const r = await request(app).post('/api/video-gen/').send({
+ prompt: 'a cat',
+ mode: 'bogus',
+ });
+ expect(r.status).toBe(400);
+ expect(r.body.error).toMatch(/mode/i);
+ });
});
describe('GET /:jobId/events', () => {
diff --git a/server/services/videoGen/local.js b/server/services/videoGen/local.js
index a279aaae7f..4651994382 100644
--- a/server/services/videoGen/local.js
+++ b/server/services/videoGen/local.js
@@ -119,12 +119,13 @@ const generateThumbnail = async (videoPath, jobId) => {
export const loadHistory = () => readJSONFile(HISTORY_FILE, []);
export const saveHistory = (h) => atomicWrite(HISTORY_FILE, h);
-const buildArgs = ({ pythonPath, modelId, model, prompt, negativePrompt, width, height, numFrames, fps, steps, guidance, seed, tiling, disableAudio, sourceImagePath, outputPath }) => {
+const buildArgs = ({ pythonPath, modelId, model, prompt, negativePrompt, width, height, numFrames, fps, steps, guidance, seed, tiling, disableAudio, sourceImagePath, lastImagePath, outputPath }) => {
if (IS_WIN) {
const scriptPath = join(PATHS.root, 'scripts', 'generate_win.py');
const args = [scriptPath, '--model', modelId, '--prompt', prompt, '--height', String(height), '--width', String(width), '--num-frames', String(numFrames), '--fps', String(fps), '--steps', String(steps), '--guidance', String(guidance), '--seed', String(seed), '--output', outputPath];
if (negativePrompt) args.push('--negative-prompt', negativePrompt);
if (sourceImagePath) args.push('--image', sourceImagePath);
+ if (lastImagePath) args.push('--last-image', lastImagePath);
return { bin: pythonPath, args };
}
const args = [
@@ -145,10 +146,23 @@ const buildArgs = ({ pythonPath, modelId, model, prompt, negativePrompt, width,
if (negativePrompt) args.push('--negative-prompt', negativePrompt);
if (disableAudio) args.push('--no-audio');
if (sourceImagePath) args.push('--image', sourceImagePath);
+ // mlx_video.generate_av exposes only single-image conditioning at a chosen
+ // frame index (--image-frame-idx). True FFLF (two keyframes) requires the
+ // wrapper script to support multi-frame conditioning. For now we surface
+ // the limitation: if the caller requested FFLF, we condition on the LAST
+ // image at the final frame index — gives a "video ends here" feel even
+ // without the start-frame keyframe. UI labels this clearly.
+ if (lastImagePath && !sourceImagePath) {
+ args.push('--image', lastImagePath, '--image-frame-idx', String(Math.max(0, numFrames - 1)));
+ } else if (lastImagePath && sourceImagePath) {
+ // Both frames provided. mlx_video CLI can't currently consume both —
+ // log so the user knows their last image is advisory.
+ console.log(`⚠️ FFLF requested but mlx_video CLI only supports single-frame conditioning — last image ignored`);
+ }
return { bin: pythonPath, args };
};
-export async function generateVideo({ pythonPath, prompt, negativePrompt = '', modelId = defaultVideoModelId(), width = 768, height = 512, numFrames = 121, fps = 24, steps, guidanceScale, seed, tiling = 'auto', disableAudio = false, sourceImagePath = null, uploadedTempPath = null }) {
+export async function generateVideo({ pythonPath, prompt, negativePrompt = '', modelId = defaultVideoModelId(), width = 768, height = 512, numFrames = 121, fps = 24, steps, guidanceScale, seed, tiling = 'auto', disableAudio = false, sourceImagePath = null, uploadedTempPath = null, lastImagePath = null, mode = null }) {
if (!pythonPath) throw new ServerError('Python path not configured — set it in Settings > Image Gen', { status: 400, code: 'VIDEO_GEN_NOT_CONFIGURED' });
if (!prompt?.trim()) throw new ServerError('Prompt is required', { status: 400, code: 'VALIDATION_ERROR' });
// Enforce the single-activeProcess invariant — without this a double-submit
@@ -176,32 +190,30 @@ export async function generateVideo({ pythonPath, prompt, negativePrompt = '', m
// exact dimensions (it doesn't auto-pad), and pixie-forge learned the
// hard way that letting the model upscale a portrait reference makes
// garbled output.
- let resolvedSourceImage = sourceImagePath;
- let resizedTempPath = null;
- if (resolvedSourceImage) {
- const ffmpeg = await findFfmpeg();
- if (ffmpeg) {
- const resizedPath = join(tmpdir(), `resized-${jobId}.png`);
- const resizeResult = await execFileAsync(ffmpeg, [
- '-i', resolvedSourceImage,
- '-vf', `scale=${w}:${h}:force_original_aspect_ratio=increase,crop=${w}:${h}`,
- '-update', '1', '-frames:v', '1',
- '-y', resizedPath,
- ], { timeout: 10000 }).catch((err) => ({ error: err }));
- if (resizeResult.error) {
- console.log(`⚠️ Failed to resize source image, using original: ${resizeResult.error.message}`);
- } else {
- resolvedSourceImage = resizedPath;
- resizedTempPath = resizedPath;
- }
+ const ffmpeg = (sourceImagePath || lastImagePath) ? await findFfmpeg() : null;
+ const resizeImage = async (srcPath, tag) => {
+ if (!srcPath || !ffmpeg) return { resolved: srcPath, tempPath: null };
+ const resizedPath = join(tmpdir(), `resized-${tag}-${jobId}.png`);
+ const resizeResult = await execFileAsync(ffmpeg, [
+ '-i', srcPath,
+ '-vf', `scale=${w}:${h}:force_original_aspect_ratio=increase,crop=${w}:${h}`,
+ '-update', '1', '-frames:v', '1',
+ '-y', resizedPath,
+ ], { timeout: 10000 }).catch((err) => ({ error: err }));
+ if (resizeResult.error) {
+ console.log(`⚠️ Failed to resize ${tag} image, using original: ${resizeResult.error.message}`);
+ return { resolved: srcPath, tempPath: null };
}
- }
+ return { resolved: resizedPath, tempPath: resizedPath };
+ };
+ const { resolved: resolvedSourceImage, tempPath: resizedSrcTempPath } = await resizeImage(sourceImagePath, 'src');
+ const { resolved: resolvedLastImage, tempPath: resizedLastTempPath } = await resizeImage(lastImagePath, 'last');
- const meta = { id: jobId, prompt, negativePrompt, modelId, seed: actualSeed, width: w, height: h, numFrames: parsedNumFrames, fps: parsedFps, filename, createdAt: new Date().toISOString() };
+ const meta = { id: jobId, prompt, negativePrompt, modelId, seed: actualSeed, width: w, height: h, numFrames: parsedNumFrames, fps: parsedFps, filename, createdAt: new Date().toISOString(), mode: mode || (sourceImagePath ? 'image' : 'text') };
const job = { ...meta, clients: [], status: 'running' };
jobs.set(jobId, job);
- const { bin, args } = buildArgs({ pythonPath, modelId, model, prompt, negativePrompt, width: w, height: h, numFrames: parsedNumFrames, fps: parsedFps, steps: actualSteps, guidance: actualGuidance, seed: actualSeed, tiling, disableAudio, sourceImagePath: resolvedSourceImage, outputPath });
+ const { bin, args } = buildArgs({ pythonPath, modelId, model, prompt, negativePrompt, width: w, height: h, numFrames: parsedNumFrames, fps: parsedFps, steps: actualSteps, guidance: actualGuidance, seed: actualSeed, tiling, disableAudio, sourceImagePath: resolvedSourceImage, lastImagePath: resolvedLastImage, outputPath });
console.log(`🎬 Generating video [${jobId.slice(0, 8)}]: ${modelId} ${w}x${h} frames=${parsedNumFrames} steps=${actualSteps}`);
videoGenEvents.emit('started', { generationId: jobId, totalSteps: actualSteps, ...meta });
@@ -223,7 +235,8 @@ export async function generateVideo({ pythonPath, prompt, negativePrompt = '', m
broadcastSse(job, { type: 'error', error: reason });
videoGenEvents.emit('failed', { generationId: jobId, error: reason });
activeProcess = null;
- if (resizedTempPath) unlink(resizedTempPath).catch(() => {});
+ if (resizedSrcTempPath) unlink(resizedSrcTempPath).catch(() => {});
+ if (resizedLastTempPath) unlink(resizedLastTempPath).catch(() => {});
closeJobAfterDelay(jobs, jobId);
});
@@ -273,10 +286,11 @@ export async function generateVideo({ pythonPath, prompt, negativePrompt = '', m
proc.on('close', async (code, signal) => {
activeProcess = null;
- // Cleanup the resized temp image if we made one. Track via a flag rather
+ // Cleanup the resized temp images if we made them. Track via flags rather
// than a path-prefix check — tmpdir() can return a symlinked path
// (macOS /var → /private/var) so startsWith() can silently miss.
- if (resizedTempPath) await unlink(resizedTempPath).catch(() => {});
+ if (resizedSrcTempPath) await unlink(resizedSrcTempPath).catch(() => {});
+ if (resizedLastTempPath) await unlink(resizedLastTempPath).catch(() => {});
// Cleanup the original multipart upload temp file too — without this,
// every i2v request leaves a file in os.tmpdir() forever.
if (uploadedTempPath) await unlink(uploadedTempPath).catch(() => {});