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: symmetric upload + gallery picker on both FFLF frames

Adam Eivyc80c5327bce2
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 1ff31dfb97..c9dec57eb3 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -14,6 +14,7 @@
## Changed
+- Video Gen FFLF mode: both the first-frame and last-frame slots now offer the same dual control — pick from your image gallery, OR upload a fresh image. Previously the first frame was upload-only and the last frame was gallery-only.
- Release workflow no longer silently skips creating the GitHub Release when something else pushed the version tag before the workflow ran.
- Release-notes style guide tightened — entries should be one sentence per change in user-facing language, not code-review prose with file paths and internal symbols.
- Chief of Staff 3D avatars (Cyber, Sigil, Esoteric, Nexus, Muse) now fill the agent panel as a full-bleed background, with the title, status, and controls overlaying the scene instead of sharing a column with it.
diff --git a/client/src/pages/VideoGen.jsx b/client/src/pages/VideoGen.jsx
index 0c8fbec8bb..716c44834a 100644
--- a/client/src/pages/VideoGen.jsx
+++ b/client/src/pages/VideoGen.jsx
@@ -124,11 +124,12 @@ export default function VideoGen() {
const [sourceImageFile, setSourceImageFile] = useState(incomingSourceImage || null);
const [sourceImageUpload, setSourceImageUpload] = useState(null);
const [lastImageFile, setLastImageFile] = useState(null);
+ const [lastImageUpload, setLastImageUpload] = 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).
+ // Image gallery — used by both the start and end frame pickers so the
+ // user can pull from any prior render in either slot.
const [imageGallery, setImageGallery] = useState([]);
// Re-sync when ImageGen pipes a new image via ?sourceImageFile=...
@@ -160,9 +161,9 @@ export default function VideoGen() {
const [showHidden, setShowHidden] = useState(false);
const navigate = useNavigate();
- // Object URL for the currently-selected upload File so we can render a
- // real preview before the file ever hits the server. Revoked on change /
- // unmount so the blob is released.
+ // Object URLs for the currently-selected upload Files so we can render
+ // real previews before the files ever hit the server. Revoked on change /
+ // unmount so the blobs are released.
const [sourceUploadUrl, setSourceUploadUrl] = useState(null);
useEffect(() => {
if (!(sourceImageUpload instanceof File)) { setSourceUploadUrl(null); return; }
@@ -170,6 +171,13 @@ export default function VideoGen() {
setSourceUploadUrl(url);
return () => URL.revokeObjectURL(url);
}, [sourceImageUpload]);
+ const [lastUploadUrl, setLastUploadUrl] = useState(null);
+ useEffect(() => {
+ if (!(lastImageUpload instanceof File)) { setLastUploadUrl(null); return; }
+ const url = URL.createObjectURL(lastImageUpload);
+ setLastUploadUrl(url);
+ return () => URL.revokeObjectURL(url);
+ }, [lastImageUpload]);
const refreshHistory = useCallback(() => {
listVideoHistory().then((items) => setHistory(Array.isArray(items) ? items : [])).catch(() => {});
@@ -290,7 +298,10 @@ export default function VideoGen() {
setSearchParams(next, { replace: true });
}
};
- const clearLastImage = () => setLastImageFile(null);
+ const clearLastImage = () => {
+ setLastImageFile(null);
+ setLastImageUpload(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.
@@ -299,15 +310,15 @@ export default function VideoGen() {
setMode(next);
if (next === 'text') {
clearSourceImage();
- setLastImageFile(null);
+ clearLastImage();
setExtendFromVideoId('');
} else if (next === 'image') {
- setLastImageFile(null);
+ clearLastImage();
setExtendFromVideoId('');
} else if (next === 'fflf') {
setExtendFromVideoId('');
} else if (next === 'extend') {
- setLastImageFile(null);
+ clearLastImage();
// Drop any source image carried over from a prior mode — extend will
// populate sourceImageFile fresh from the picked video's last frame
// via handleExtendPick. Without this, switching from image/fflf into
@@ -400,6 +411,7 @@ export default function VideoGen() {
? (sourceImageFile || '') : '',
sourceImage: (mode === 'image' || mode === 'fflf') ? (sourceImageUpload || '') : '',
lastImageFile: mode === 'fflf' ? (lastImageFile || '') : '',
+ lastImage: mode === 'fflf' ? (lastImageUpload || '') : '',
extendFromVideoId: (mode === 'extend' && currentModel?.runtime === 'ltx2')
? (extendFromVideoId || '') : '',
chunks: chunks > 1 ? chunks : '',
@@ -525,15 +537,18 @@ export default function VideoGen() {
const handleEnqueue = () => {
if (!prompt.trim() || (status && status.connected === false) || extendModeBlocked) 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;
+ // Strip File blobs 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 Files in `_blobs` separately.
+ const { sourceImage, lastImage, ...summary } = payload;
setQueue((q) => [...q, {
id: newQueueId(),
status: 'pending',
params: summary,
- _blob: sourceImage instanceof File ? sourceImage : null,
+ _blobs: {
+ sourceImage: sourceImage instanceof File ? sourceImage : null,
+ lastImage: lastImage instanceof File ? lastImage : null,
+ },
enqueuedAt: Date.now(),
}]);
toast.success('Added to queue');
@@ -564,7 +579,8 @@ export default function VideoGen() {
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;
+ if (next._blobs?.sourceImage) payload.sourceImage = next._blobs.sourceImage;
+ if (next._blobs?.lastImage) payload.lastImage = next._blobs.lastImage;
let busyRetry = false;
let busyRetryTimer = null;
runGeneration(payload).then((res) => {
@@ -620,6 +636,71 @@ export default function VideoGen() {
const notConnected = status && status.connected === false;
const canEnqueue = prompt.trim() && !notConnected && !extendModeBlocked;
+ // Symmetric frame picker for the FFLF + image modes. Each slot accepts
+ // EITHER a gallery filename OR a fresh upload; the preview renders
+ // whichever is currently set, and clearing either one snaps the slot back
+ // to the dual upload+gallery picker. Defined inline because it closes
+ // over imageGallery and the per-slot state — extracting it as a real
+ // component would mean prop-drilling 6+ values for no real reuse.
+ const renderFramePanel = ({
+ label,
+ file,
+ upload,
+ uploadUrl,
+ onPickGallery,
+ onUpload,
+ onClear,
+ alt,
+ advisoryNote,
+ }) => {
+ const hasSelection = !!(file || upload);
+ return (
+ <div className="border border-port-border/50 rounded-lg p-2 space-y-1.5">
+ <div className="flex items-center justify-between">
+ <span className="text-[11px] font-medium text-gray-400">{label}</span>
+ {hasSelection && (
+ <button type="button" onClick={onClear} className="text-[11px] text-port-error hover:underline">Clear</button>
+ )}
+ </div>
+ {hasSelection ? (
+ <ImagePreview
+ src={file ? `/data/images/${file}` : uploadUrl}
+ alt={alt}
+ label={file || upload?.name}
+ />
+ ) : (
+ <div className="space-y-1.5">
+ <select
+ value=""
+ onChange={(e) => onPickGallery(e.target.value || null)}
+ className="w-full bg-port-bg border border-port-border rounded px-2 py-1 text-xs text-white focus:outline-none focus:border-port-accent disabled:opacity-50"
+ >
+ <option value="">Pick from gallery…</option>
+ {imageGallery.filter((img) => !img.hidden).slice(0, 50).map((img) => (
+ <option key={img.filename} value={img.filename}>{img.filename}</option>
+ ))}
+ </select>
+ <label className="flex items-center gap-2 text-[11px] text-gray-400 cursor-pointer hover:text-white">
+ <Upload className="w-3.5 h-3.5" />
+ <span className="truncate">Upload an image</span>
+ <input
+ type="file"
+ accept="image/*"
+ onChange={(e) => onUpload(e.target.files?.[0] || null)}
+ className="hidden"
+ />
+ </label>
+ </div>
+ )}
+ {advisoryNote && (
+ <p className="text-[10px] text-gray-500 leading-snug" title={advisoryNote.title}>
+ {advisoryNote.text}
+ </p>
+ )}
+ </div>
+ );
+ };
+
return (
<div className="space-y-3">
<div className="flex items-center justify-between gap-2 text-xs">
@@ -722,70 +803,54 @@ export default function VideoGen() {
{(mode === 'image' || mode === 'fflf') && (
<div className={`grid gap-2 ${mode === 'fflf' ? 'grid-cols-1 sm:grid-cols-2' : 'grid-cols-1'}`}>
- <div className="border border-port-border/50 rounded-lg p-2 space-y-1.5">
- <div className="flex items-center justify-between">
- <span className="text-[11px] font-medium text-gray-400">
- {mode === 'fflf' ? 'First frame' : 'Source image'}
- </span>
- {(sourceImageFile || sourceImageUpload) && (
- <button type="button" onClick={clearSourceImage} className="text-[11px] text-port-error hover:underline">Clear</button>
- )}
- </div>
- {(sourceImageFile || sourceUploadUrl) ? (
- <ImagePreview
- src={sourceImageFile ? `/data/images/${sourceImageFile}` : sourceUploadUrl}
- alt="Source"
- label={sourceImageFile || sourceImageUpload?.name}
- />
- ) : (
- <label className="flex items-center gap-2 text-[11px] text-gray-400 cursor-pointer hover:text-white">
- <Upload className="w-3.5 h-3.5" />
- <span className="truncate">Upload an image</span>
- <input
- type="file"
- accept="image/*"
- onChange={(e) => {
- const file = e.target.files?.[0] || null;
- // Clear any gallery pick + URL param when an upload is
- // chosen — otherwise the preview keeps rendering the
- // old gallery image (src prefers sourceImageFile) while
- // the POST sends `req.file` from the upload, which
- // looks like the wrong image was used.
- if (file && (sourceImageFile || incomingSourceImage)) clearSourceImage();
- setSourceImageUpload(file);
- }}
- className="hidden"
- />
- </label>
- )}
- </div>
- {mode === 'fflf' && (
- <div className="border border-port-border/50 rounded-lg p-2 space-y-1.5">
- <div className="flex items-center justify-between">
- <span className="text-[11px] font-medium text-gray-400">Last frame</span>
- {lastImageFile && (
- <button type="button" onClick={clearLastImage} className="text-[11px] text-port-error hover:underline">Clear</button>
- )}
- </div>
- {lastImageFile ? (
- <ImagePreview src={`/data/images/${lastImageFile}`} alt="End frame" label={lastImageFile} />
- ) : (
- <select
- value=""
- onChange={(e) => setLastImageFile(e.target.value || null)}
- className="w-full bg-port-bg border border-port-border rounded px-2 py-1 text-xs text-white focus:outline-none focus:border-port-accent disabled:opacity-50"
- >
- <option value="">Pick 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-[10px] text-gray-500 leading-snug" title="FFLF backend support is experimental — LTX/mlx_video uses the start frame and treats the last frame as advisory.">
- Experimental — last frame is advisory.
- </p>
- </div>
- )}
+ {renderFramePanel({
+ label: mode === 'fflf' ? 'First frame' : 'Source image',
+ file: sourceImageFile,
+ upload: sourceImageUpload,
+ uploadUrl: sourceUploadUrl,
+ onPickGallery: (filename) => {
+ // Switching to a gallery pick must drop any pending upload
+ // and the deep-link URL param; otherwise the next render
+ // would still POST the stale upload (req.files wins) while
+ // the preview shows the gallery image.
+ setSourceImageUpload(null);
+ if (incomingSourceImage) {
+ const next = new URLSearchParams(searchParams);
+ next.delete('sourceImageFile');
+ setSearchParams(next, { replace: true });
+ }
+ setSourceImageFile(filename);
+ },
+ onUpload: (file) => {
+ // Clear any gallery pick + URL param when an upload is
+ // chosen — otherwise the preview keeps rendering the old
+ // gallery image while the POST sends the upload.
+ if (file && (sourceImageFile || incomingSourceImage)) clearSourceImage();
+ setSourceImageUpload(file);
+ },
+ onClear: clearSourceImage,
+ alt: 'Source',
+ })}
+ {mode === 'fflf' && renderFramePanel({
+ label: 'Last frame',
+ file: lastImageFile,
+ upload: lastImageUpload,
+ uploadUrl: lastUploadUrl,
+ onPickGallery: (filename) => {
+ setLastImageUpload(null);
+ setLastImageFile(filename);
+ },
+ onUpload: (file) => {
+ if (file && lastImageFile) setLastImageFile(null);
+ setLastImageUpload(file);
+ },
+ onClear: clearLastImage,
+ alt: 'End frame',
+ advisoryNote: {
+ text: 'Experimental — last frame is advisory.',
+ title: 'FFLF backend support is experimental — LTX/mlx_video uses the start frame and treats the last frame as advisory.',
+ },
+ })}
</div>
)}
diff --git a/server/lib/multipart.js b/server/lib/multipart.js
index 13e3de8f2b..8ca223afd8 100644
--- a/server/lib/multipart.js
+++ b/server/lib/multipart.js
@@ -8,9 +8,12 @@
*
* Returns an Express middleware. Populates:
* - req.body[name] — for text parts (Content-Disposition has no filename)
- * - req.file = { path, originalname, mimetype, size } — for the matching
- * file part (Content-Disposition has filename and name === fieldName).
- * Other file parts (different field names) are silently skipped.
+ * - req.file — uploadSingle: { path, originalname, mimetype, size }
+ * for the matching file part. Other file parts (different
+ * field names) are silently skipped.
+ * - req.files — uploadFields: { [fieldName]: { path, ... } } for each
+ * accepted file field. Field names not in the accepted
+ * set are silently skipped.
*/
import { createWriteStream } from 'fs';
@@ -19,26 +22,54 @@ import { tmpdir } from 'os';
import { join } from 'path';
import { randomUUID } from 'crypto';
+const parseBoundary = (req) => {
+ const ct = req.headers['content-type'] || '';
+ // Media type is case-insensitive (RFC 2045), but the boundary value is
+ // case-sensitive — match the type prefix on a lowercased copy and parse
+ // the boundary off the original.
+ if (!ct.toLowerCase().startsWith('multipart/form-data')) {
+ const err = new Error('Expected multipart/form-data');
+ err.status = 400; err.code = 'INVALID_CONTENT_TYPE';
+ return { err };
+ }
+ const bm = ct.match(/boundary=([^\s;]+)/i);
+ if (!bm) {
+ const err = new Error('Missing multipart boundary');
+ err.status = 400; err.code = 'INVALID_CONTENT_TYPE';
+ return { err };
+ }
+ return { boundary: bm[1] };
+};
+
export function uploadSingle(fieldName, { limits = {}, fileFilter } = {}) {
const maxSize = limits.fileSize ?? Infinity;
+ const accepted = new Set([fieldName]);
return (req, res, next) => {
- const ct = req.headers['content-type'] || '';
- // Media type is case-insensitive (RFC 2045), but the boundary value is
- // case-sensitive — match the type prefix on a lowercased copy and parse
- // the boundary off the original.
- if (!ct.toLowerCase().startsWith('multipart/form-data')) {
- const err = new Error('Expected multipart/form-data');
- err.status = 400; err.code = 'INVALID_CONTENT_TYPE';
- return next(err);
- }
- const bm = ct.match(/boundary=([^\s;]+)/i);
- if (!bm) {
- const err = new Error('Missing multipart boundary');
- err.status = 400; err.code = 'INVALID_CONTENT_TYPE';
- return next(err);
- }
- streamMultipart(req, bm[1], fieldName, maxSize, fileFilter, next);
+ const { err, boundary } = parseBoundary(req);
+ if (err) return next(err);
+ streamMultipart(req, boundary, accepted, maxSize, fileFilter, (innerErr) => {
+ if (innerErr) return next(innerErr);
+ // Back-compat: surface the matched file as req.file for callers that
+ // predate the multi-file `req.files` shape.
+ if (req.files?.[fieldName]) req.file = req.files[fieldName];
+ next();
+ });
+ };
+}
+
+// Multi-file variant — accepts a list of allowed file field names and
+// populates req.files = { [fieldName]: { path, originalname, mimetype, size } }
+// for each one that arrives. Same semantics as uploadSingle for everything
+// else (text fields → req.body, unknown file fields silently dropped).
+export function uploadFields(fieldNames, { limits = {}, fileFilter } = {}) {
+ const maxSize = limits.fileSize ?? Infinity;
+ const accepted = new Set(fieldNames);
+
+ return (req, res, next) => {
+ const { err, boundary } = parseBoundary(req);
+ if (err) return next(err);
+ streamMultipart(req, boundary, accepted, maxSize, fileFilter, next);
};
}
@@ -54,7 +85,7 @@ export function optionalUpload(fieldName, opts) {
};
}
-function streamMultipart(req, boundary, fileFieldName, maxSize, fileFilter, next) {
+function streamMultipart(req, boundary, acceptedNames, maxSize, fileFilter, next) {
const PART_DELIM = Buffer.from('\r\n--' + boundary);
const FIRST_DELIM = Buffer.from('--' + boundary);
const HEADER_END = Buffer.from('\r\n\r\n');
@@ -76,14 +107,17 @@ function streamMultipart(req, boundary, fileFieldName, maxSize, fileFilter, next
// Per-part state
let currentName = null;
let currentFilename = null;
- let isMatchingFile = false; // true when current part is the file we want
+ let isMatchingFile = false; // true when current part is one of acceptedNames
let writeStream = null;
let writePath = null;
let bytesWritten = 0;
let textBuf = null; // Buffer when current part is a text field
const body = {};
- let fileResult = null;
+ // Map of finalized files keyed by field name. Truncated-request cleanup
+ // walks this to unlink everything that was already flushed before the
+ // request died mid-stream.
+ const fileResults = {};
const fail = (err) => {
if (done) return;
@@ -94,6 +128,11 @@ function streamMultipart(req, boundary, fileFieldName, maxSize, fileFilter, next
// Best-effort cleanup of the partially-written file.
if (writePath) unlink(writePath).catch(() => {});
}
+ // Also drop any already-finalized files — a fail mid-request must not
+ // leak completed uploads to the OS temp dir.
+ for (const f of Object.values(fileResults)) {
+ if (f?.path) unlink(f.path).catch(() => {});
+ }
req.removeAllListeners('data');
next(err);
};
@@ -108,9 +147,10 @@ function streamMultipart(req, boundary, fileFieldName, maxSize, fileFilter, next
// Clean up any partially-written file before failing.
if (writeStream) writeStream.destroy();
if (writePath) unlink(writePath).catch(() => {});
- // Also drop the in-progress fileResult if endPart already finalized
- // a file from a part that was followed by truncated data.
- if (fileResult?.path) unlink(fileResult.path).catch(() => {});
+ // Also drop any files already finalized before the truncation.
+ for (const f of Object.values(fileResults)) {
+ if (f?.path) unlink(f.path).catch(() => {});
+ }
done = true;
const err = new Error('Truncated multipart request — never reached terminal boundary');
err.code = 'INVALID_MULTIPART';
@@ -120,7 +160,7 @@ function streamMultipart(req, boundary, fileFieldName, maxSize, fileFilter, next
}
done = true;
req.body = body;
- if (fileResult) req.file = fileResult;
+ if (Object.keys(fileResults).length) req.files = fileResults;
next();
};
@@ -142,7 +182,7 @@ function streamMultipart(req, boundary, fileFieldName, maxSize, fileFilter, next
currentFilename = filenameMatch?.[1];
if (currentFilename != null && currentFilename !== '') {
- isMatchingFile = currentName === fileFieldName;
+ isMatchingFile = acceptedNames.has(currentName);
const mimeMatch = headerStr.match(/Content-Type:\s*([^\r\n]+)/i);
currentFileMimetype = mimeMatch ? mimeMatch[1].trim() : 'application/octet-stream';
if (isMatchingFile) {
@@ -233,11 +273,12 @@ function streamMultipart(req, boundary, fileFieldName, maxSize, fileFilter, next
const size = bytesWritten;
const filename = currentFilename;
const mimetype = currentFileMimetype || 'application/octet-stream';
+ const fieldName = currentName;
writeStream = null;
writePath = null;
pendingFlush += 1;
ws.end(() => {
- fileResult = { path, originalname: filename, mimetype, size };
+ fileResults[fieldName] = { path, originalname: filename, mimetype, size };
pendingFlush -= 1;
cb();
// If 'end' arrived while we were still flushing, finalize now.
diff --git a/server/lib/multipart.test.js b/server/lib/multipart.test.js
index 8efa1f2c2c..f4f8f92970 100644
--- a/server/lib/multipart.test.js
+++ b/server/lib/multipart.test.js
@@ -1,6 +1,6 @@
import { describe, it, expect, vi } from 'vitest';
import { Readable } from 'stream';
-import { uploadSingle } from './multipart.js';
+import { uploadSingle, uploadFields } from './multipart.js';
vi.mock('fs', () => ({
createWriteStream: () => {
@@ -139,6 +139,38 @@ describe('uploadSingle multipart parser', () => {
vi.doUnmock('fs');
});
+ it('uploadFields collects two file parts into req.files keyed by field name', async () => {
+ const req = makeMultipartReq([
+ { name: 'prompt', body: 'morph between two scenes' },
+ { name: 'sourceImage', filename: 'first.png', contentType: 'image/png', body: Buffer.from([0x89, 0x50, 0x4e, 0x47]) },
+ { name: 'lastImage', filename: 'last.png', contentType: 'image/png', body: Buffer.from([0x89, 0x50, 0x4e, 0x47]) },
+ ]);
+ await new Promise((resolve, reject) => {
+ const mw = uploadFields(['sourceImage', 'lastImage'], { limits: { fileSize: 1024 * 1024 } });
+ mw(req, {}, (err) => err ? reject(err) : resolve());
+ });
+ expect(req.body.prompt).toBe('morph between two scenes');
+ expect(req.files).toBeDefined();
+ expect(req.files.sourceImage?.originalname).toBe('first.png');
+ expect(req.files.lastImage?.originalname).toBe('last.png');
+ // The single-file back-compat field should not appear when uploadFields is used.
+ expect(req.file).toBeUndefined();
+ });
+
+ it('uploadFields silently drops a file part whose name is not in the accepted set', async () => {
+ const req = makeMultipartReq([
+ { name: 'sourceImage', filename: 'good.png', contentType: 'image/png', body: Buffer.from([0xaa]) },
+ { name: 'unrelated', filename: 'bad.png', contentType: 'image/png', body: Buffer.from([0xbb]) },
+ ]);
+ await new Promise((resolve, reject) => {
+ const mw = uploadFields(['sourceImage', 'lastImage']);
+ mw(req, {}, (err) => err ? reject(err) : resolve());
+ });
+ expect(req.files?.sourceImage?.originalname).toBe('good.png');
+ expect(req.files?.unrelated).toBeUndefined();
+ expect(req.files?.lastImage).toBeUndefined();
+ });
+
it('rejects requests without the multipart Content-Type', async () => {
const stream = Readable.from(['nope']);
stream.headers = { 'content-type': 'application/json' };
diff --git a/server/routes/videoGen.js b/server/routes/videoGen.js
index 0c922894a7..925acd437c 100644
--- a/server/routes/videoGen.js
+++ b/server/routes/videoGen.js
@@ -13,7 +13,7 @@ import { randomUUID } from 'crypto';
import { join, basename, resolve as resolvePath, sep as PATH_SEP, extname } from 'path';
import { z } from 'zod';
import { asyncHandler, ServerError } from '../lib/errorHandler.js';
-import { uploadSingle } from '../lib/multipart.js';
+import { uploadFields } from '../lib/multipart.js';
import { PATHS, ensureDir } from '../lib/fileUtils.js';
import { safeUnder } from '../lib/ffmpeg.js';
import { getSettings } from '../services/settings.js';
@@ -31,7 +31,10 @@ import { enqueueJob, attachSseClient, cancelJob, listJobs } from '../services/me
const router = Router();
-const sourceImageUpload = uploadSingle('sourceImage', {
+// FFLF accepts up to two image uploads (start and end frame). The 50MB cap
+// applies per-file; image-only filter rejects non-image parts up-front so a
+// stray .mp4 drag-drop can't get staged as a "source image".
+const frameImageUpload = uploadFields(['sourceImage', 'lastImage'], {
limits: { fileSize: 50 * 1024 * 1024 },
fileFilter: (_req, file, cb) => cb(null, file.mimetype.startsWith('image/')),
});
@@ -64,10 +67,10 @@ 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.
+ // Gallery-pick filename for the FFLF end-frame. The end-frame can also
+ // arrive as a multipart `lastImage` upload (handled below) — when both
+ // are present the upload wins, mirroring the sourceImage/sourceImageFile
+ // precedence on the start-frame side.
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).
@@ -123,16 +126,19 @@ const resolveGalleryImage = (name) => {
}
};
-router.post('/', sourceImageUpload, asyncHandler(async (req, res) => {
- // Pre-enqueue cleanup hook: every throw path below MUST drop the multipart
- // temp upload (Multer wrote it before this handler ran). Without this a
- // configuration/validation error leaks the upload in the OS temp dir.
- const cleanupTempUpload = async () => {
- if (req.file?.path) await unlink(req.file.path).catch(() => {});
+router.post('/', frameImageUpload, asyncHandler(async (req, res) => {
+ // Pre-enqueue cleanup hook: every throw path below MUST drop ALL multipart
+ // temp uploads (the parser wrote them before this handler ran). Without
+ // this a configuration/validation error leaks files in the OS temp dir.
+ const uploads = req.files || {};
+ const cleanupTempUploads = async () => {
+ for (const f of Object.values(uploads)) {
+ if (f?.path) await unlink(f.path).catch(() => {});
+ }
};
const parsed = generateBodySchema.safeParse(req.body);
if (!parsed.success) {
- await cleanupTempUpload();
+ await cleanupTempUploads();
throw new ServerError(`Validation failed: ${parsed.error.issues.map((i) => `${i.path.join('.')}: ${i.message}`).join(', ')}`, { status: 400, code: 'VALIDATION_ERROR' });
}
const body = parsed.data;
@@ -143,7 +149,7 @@ router.post('/', sourceImageUpload, asyncHandler(async (req, res) => {
// surface the failure asynchronously on SSE — which then pollutes the
// persisted queue with a doomed entry.
if (!pythonPath) {
- await cleanupTempUpload();
+ await cleanupTempUploads();
throw new ServerError(
'Local video generation is not configured (settings.imageGen.local.pythonPath is missing).',
{ status: 400, code: 'VIDEO_GEN_NOT_CONFIGURED' },
@@ -155,7 +161,7 @@ router.post('/', sourceImageUpload, asyncHandler(async (req, res) => {
if (body.modelId) {
const known = listVideoModels();
if (!known.some((m) => m.id === body.modelId)) {
- await cleanupTempUpload();
+ await cleanupTempUploads();
throw new ServerError(
`Unknown modelId: ${body.modelId}`,
{ status: 400, code: 'VIDEO_GEN_UNKNOWN_MODEL' },
@@ -163,41 +169,54 @@ router.post('/', sourceImageUpload, asyncHandler(async (req, res) => {
}
}
- let sourceImagePath = null;
- let uploadedTempPath = null;
- if (req.file) {
- // Copy the multipart upload into a durable location under data/uploads
- // before enqueueing. The Multer temp file lives in the OS temp dir —
- // which gets reaped by macOS on reboot, and might be missing entirely
- // when the queue replays a persisted `queued` job after a server
- // restart. Copying here gives the worker a stable path that survives
- // restarts; the worker unlinks it on completion or cancel.
- await ensureDir(PATHS.uploads);
- const ext = extname(req.file.originalname || req.file.path) || '.bin';
- const durablePath = join(PATHS.uploads, `video-source-${randomUUID()}${ext}`);
- // copyFile can throw on disk-full / permission errors. If it does we
- // need to clean up: drop the multipart temp upload AND the half-written
- // durablePath (copyFile may have created a zero-byte sentinel before
- // bailing). Without this, a failed POST leaks files in /tmp + data/uploads.
+ // Stage a multipart upload into data/uploads so the queue worker can find
+ // it after a server restart — the OS temp dir gets reaped on reboot, and a
+ // persisted `queued` job may replay long after the original POST. Worker
+ // unlinks the durable file when the job completes or cancels. Throws
+ // ServerError on copy failure (and cleans up every staged temp upload so a
+ // mid-flight failure doesn't leak files under /tmp + data/uploads).
+ const stageUploadDurable = async (file, kind) => {
+ const ext = extname(file.originalname || file.path) || '.bin';
+ const durablePath = join(PATHS.uploads, `video-${kind}-${randomUUID()}${ext}`);
try {
- await copyFile(req.file.path, durablePath);
+ await copyFile(file.path, durablePath);
} catch (err) {
await unlink(durablePath).catch(() => {});
- await cleanupTempUpload();
+ await cleanupTempUploads();
throw new ServerError(
`Failed to stage upload to durable location: ${err.message}`,
{ status: 500, code: 'VIDEO_GEN_UPLOAD_STAGE_FAILED' },
);
}
- await unlink(req.file.path).catch(() => {});
- sourceImagePath = durablePath;
- uploadedTempPath = durablePath;
+ await unlink(file.path).catch(() => {});
+ return durablePath;
+ };
+
+ // Resolution precedence on each frame side: a fresh upload always wins over
+ // a gallery filename so users can override a stale gallery pick by dropping
+ // in a new file without first clearing the picker.
+ let sourceImagePath = null;
+ let lastImagePath = null;
+ const stagedUploads = [];
+ if (uploads.sourceImage || uploads.lastImage) await ensureDir(PATHS.uploads);
+ if (uploads.sourceImage) {
+ sourceImagePath = await stageUploadDurable(uploads.sourceImage, 'source');
+ stagedUploads.push(sourceImagePath);
} else if (body.sourceImageFile) {
sourceImagePath = resolveGalleryImage(body.sourceImageFile);
}
-
- // FFLF end-frame: gallery-pick only. Same path-traversal guard.
- const lastImagePath = body.lastImageFile ? resolveGalleryImage(body.lastImageFile) : null;
+ if (uploads.lastImage) {
+ lastImagePath = await stageUploadDurable(uploads.lastImage, 'last');
+ stagedUploads.push(lastImagePath);
+ } else if (body.lastImageFile) {
+ // Same path-traversal guard as the start frame.
+ lastImagePath = resolveGalleryImage(body.lastImageFile);
+ }
+ // Worker cleans up every staged temp file on terminal events. The legacy
+ // `uploadedTempPath` field stays single (start-frame upload, if any) so
+ // already-persisted jobs from before this route change still replay
+ // cleanly; everything else flows through the array.
+ const [uploadedTempPath = null, ...extraUploadedTempPaths] = stagedUploads;
// Native extend (ltx2 runtime): resolve the history id to a video file
// path under data/videos/ and forward it as extendFromVideoPath. Reject
@@ -245,6 +264,7 @@ router.post('/', sourceImageUpload, asyncHandler(async (req, res) => {
disableAudio: body.disableAudio === true || body.disableAudio === 'true',
sourceImagePath,
uploadedTempPath,
+ uploadedTempPaths: extraUploadedTempPaths,
lastImagePath,
extendFromVideoPath,
mode: body.mode,
diff --git a/server/routes/videoGen.test.js b/server/routes/videoGen.test.js
index 30dc7bffe3..5c8ab840c8 100644
--- a/server/routes/videoGen.test.js
+++ b/server/routes/videoGen.test.js
@@ -29,9 +29,9 @@ vi.mock('../services/mediaJobQueue/index.js', () => ({
}));
vi.mock('../lib/multipart.js', () => ({
- // Bypass the multipart parser for unit tests — handler treats req.file as
- // optional, and we exercise the no-upload path here.
- uploadSingle: () => (_req, _res, next) => next(),
+ // Bypass the multipart parser for unit tests — the handler treats req.files
+ // as optional, and we exercise the no-upload path here.
+ uploadFields: () => (_req, _res, next) => next(),
}));
vi.mock('../lib/fileUtils.js', () => ({
diff --git a/server/services/mediaJobQueue/index.js b/server/services/mediaJobQueue/index.js
index 7003e0789f..e737123096 100644
--- a/server/services/mediaJobQueue/index.js
+++ b/server/services/mediaJobQueue/index.js
@@ -80,6 +80,17 @@ async function safeUnlinkUpload(path) {
await unlink(path).catch(() => {});
}
+// Walks both `uploadedTempPath` (single, start-frame upload) and
+// `uploadedTempPaths` (array, additional staged uploads such as the FFLF
+// lastImage) so cleanup paths stay agnostic to which fields contributed.
+async function safeUnlinkAllUploads(params) {
+ if (!params) return;
+ await safeUnlinkUpload(params.uploadedTempPath);
+ if (Array.isArray(params.uploadedTempPaths)) {
+ for (const p of params.uploadedTempPaths) await safeUnlinkUpload(p);
+ }
+}
+
export const JOB_KINDS = Object.freeze(['video', 'image']);
export const JOB_STATUSES = Object.freeze(['queued', 'running', 'completed', 'failed', 'canceled']);
@@ -222,11 +233,11 @@ export async function initMediaJobQueue() {
archive.push(failed);
restartedFailedIds.push(failed.id);
// The failed job will never reach the worker's cleanup, so any
- // multipart upload it staged into data/uploads would leak forever.
- // safeUnlinkUpload constrains the delete to PATHS.uploads so we
+ // multipart uploads it staged into data/uploads would leak forever.
+ // safeUnlinkAllUploads constrains each delete to PATHS.uploads so we
// never delete a file the job merely referenced (gallery image,
// prior render, etc).
- safeUnlinkUpload(j.params?.uploadedTempPath);
+ safeUnlinkAllUploads(j.params);
} else if (j.status === 'queued') {
queue.push({ ...j });
} else {
@@ -491,16 +502,28 @@ async function runJob(job) {
},
};
- // Thread #1: sanitize uploadedTempPath before passing params to the gen
+ // Thread #1: sanitize uploadedTempPath(s) before passing params to the gen
// module. Even though safeUnlinkUpload guards the *delete* path, the gen
// module receives the raw job.params spread and could itself act on a
- // corrupted path from a hand-edited media-jobs.json. Null it out here if
- // it doesn't resolve under PATHS.uploads so the constraint holds end-to-end.
+ // corrupted path from a hand-edited media-jobs.json. Null/strip anything
+ // that doesn't resolve under PATHS.uploads so the constraint holds end-to-end.
const safeParams = { ...job.params };
if (safeParams.uploadedTempPath && (typeof safeParams.uploadedTempPath !== 'string' || !isUnderUploadsRoot(safeParams.uploadedTempPath))) {
console.log(`⚠️ media-job [${job.id.slice(0, 8)}] uploadedTempPath outside PATHS.uploads — nulled before gen invoke: ${safeParams.uploadedTempPath}`);
safeParams.uploadedTempPath = null;
}
+ if (Array.isArray(safeParams.uploadedTempPaths)) {
+ const filtered = safeParams.uploadedTempPaths.filter((p) => {
+ if (typeof p === 'string' && isUnderUploadsRoot(p)) return true;
+ console.log(`⚠️ media-job [${job.id.slice(0, 8)}] uploadedTempPaths entry outside PATHS.uploads — dropped before gen invoke: ${p}`);
+ return false;
+ });
+ safeParams.uploadedTempPaths = filtered;
+ } else if (safeParams.uploadedTempPaths != null) {
+ // Persisted as a non-array (corrupted JSON) — drop it rather than feed
+ // a non-iterable into the worker's cleanup loop.
+ safeParams.uploadedTempPaths = [];
+ }
const emitter = job.kind === 'video' ? videoGenEvents : imageGenEvents;
const dispatcher = makeGenDispatcher(emitter, job, handlers);
@@ -565,10 +588,10 @@ async function runJob(job) {
} catch (err) {
// generateVideo / generateImage threw before reaching their proc.on
// cleanup hooks (e.g. PYTHON not configured, validation fail). Clean up
- // multipart upload temp files the route handed us so they don't leak
- // under data/uploads. safeUnlinkUpload constrains the delete to
- // PATHS.uploads as defense-in-depth against corrupted persisted params.
- await safeUnlinkUpload(job.params?.uploadedTempPath);
+ // every multipart upload temp file the route handed us so they don't
+ // leak under data/uploads. safeUnlinkAllUploads constrains each delete
+ // to PATHS.uploads as defense-in-depth against corrupted persisted params.
+ await safeUnlinkAllUploads(job.params);
handlers.failed({ error: err.message });
}
@@ -615,12 +638,12 @@ export async function cancelJob(jobId) {
const queueIdx = queue.findIndex((j) => j.id === jobId);
if (queueIdx >= 0) {
const [job] = queue.splice(queueIdx, 1);
- // Multipart uploads (e.g. /api/video-gen with an image) hand us a path
- // staged under PATHS.uploads. If we drop the job before it starts,
- // runJob never gets a chance to delete it — clean up here so the
- // uploads dir doesn't accumulate. safeUnlinkUpload constrains the
- // delete to PATHS.uploads.
- await safeUnlinkUpload(job.params?.uploadedTempPath);
+ // Multipart uploads (e.g. /api/video-gen with an image — start frame,
+ // end frame, or both) are staged under PATHS.uploads. If we drop the
+ // job before it starts, runJob never gets a chance to delete them —
+ // clean up here so the uploads dir doesn't accumulate. Each delete is
+ // constrained to PATHS.uploads.
+ await safeUnlinkAllUploads(job.params);
job.status = 'canceled';
// Persist the cancel reason on the job so a late SSE reconnect (after
// the live SSE entry was cleaned up) can synthesize the same terminal
diff --git a/server/services/videoGen/local.js b/server/services/videoGen/local.js
index e0f39976b1..74e8232037 100644
--- a/server/services/videoGen/local.js
+++ b/server/services/videoGen/local.js
@@ -237,7 +237,7 @@ const buildArgs = ({ pythonPath, modelId, model, prompt, negativePrompt, width,
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, lastImagePath = null, extendFromVideoPath = null, mode = null, imageStrength = null, jobId: providedJobId = 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, uploadedTempPaths = [], lastImagePath = null, extendFromVideoPath = null, mode = null, imageStrength = null, jobId: providedJobId = 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' });
// Single-flight is now enforced by the mediaJobQueue worker upstream — only
@@ -349,6 +349,7 @@ export async function generateVideo({ pythonPath, prompt, negativePrompt = '', m
if (resizedSrcTempPath) unlink(resizedSrcTempPath).catch(() => {});
if (resizedLastTempPath) unlink(resizedLastTempPath).catch(() => {});
if (uploadedTempPath) unlink(uploadedTempPath).catch(() => {});
+ for (const p of uploadedTempPaths) unlink(p).catch(() => {});
closeJobAfterDelay(jobs, jobId);
});
@@ -421,6 +422,7 @@ export async function generateVideo({ pythonPath, prompt, negativePrompt = '', m
// 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(() => {});
+ for (const p of uploadedTempPaths) await unlink(p).catch(() => {});
if (code !== 0) {
job.status = 'error';
@@ -538,6 +540,7 @@ export async function generateChainedVideo({ chunks, jobId: outerJobId, ...rest
// copy under data/uploads). Later chunks use a frame extracted from a
// prior render, which lives under data/images.
uploadedTempPath: i === 0 ? rest.uploadedTempPath : null,
+ uploadedTempPaths: i === 0 ? (rest.uploadedTempPaths || []) : [],
mode: i === 0 ? firstMode : 'image',
// After the first chunk, drop FFLF-style last image — chained continuation
// is single-conditioned on the previous chunk's tail frame.