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

merge: resolve conflicts with main (FFLF symmetry + uploadFields refactor)

Adam Eivy4c3ca31b1d11
diff --cc client/src/pages/VideoGen.jsx
index 859c1ac933,fe68724853..dcf9335c0d
--- a/client/src/pages/VideoGen.jsx
+++ b/client/src/pages/VideoGen.jsx
@@@ -127,15 -124,12 +127,16 @@@ 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);
+ // a2v mode — direct audio upload only (no gallery for audio yet). The File
+ // is sent as multipart field name 'audioFile'; the server stages it under
+ // data/uploads, then the python helper passes it to AudioToVideoPipeline.
+ const [audioFile, setAudioFile] = useState(null);
- // 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=...
@@@ -304,15 -308,12 +315,15 @@@
// carry over because they apply to all modes.)
const handleModeChange = (next) => {
setMode(next);
+ // Audio is only meaningful in a2v mode — drop it on every other switch
+ // so a stale upload from a prior pick doesn't sneak into a non-a2v post.
+ if (next !== 'a2v') setAudioFile(null);
if (next === 'text') {
clearSourceImage();
- setLastImageFile(null);
+ clearLastImage();
setExtendFromVideoId('');
} else if (next === 'image') {
- setLastImageFile(null);
+ clearLastImage();
setExtendFromVideoId('');
} else if (next === 'fflf') {
setExtendFromVideoId('');
@@@ -324,18 -325,6 +335,17 @@@
// extend leaves a stale source that gets silently submitted alongside
// an empty extendFromVideoId.
clearSourceImage();
+ } else if (next === 'a2v') {
+ // a2v takes audio only — buildGeneratePayload omits sourceImageFile +
+ // sourceImage in this mode, so dropping them here keeps state honest
+ // (no stale image survives in the form to imply it's being used).
+ // The python helper supports an optional first-frame image, but the
- // UI doesn't expose it yet (see PR description "Out of scope") because
- // the multipart parser only accepts one file per request. Once we add
- // a gallery-pick path for the first frame, restore the source-image
- // state pass-through here.
++ // UI doesn't expose it yet (see PR description "Out of scope"). Once
++ // we add a gallery-pick path for the first frame, restore the source-
++ // image state pass-through here.
+ clearSourceImage();
- setLastImageFile(null);
++ clearLastImage();
+ setExtendFromVideoId('');
}
};
@@@ -422,11 -411,9 +432,12 @@@
? (sourceImageFile || '') : '',
sourceImage: (mode === 'image' || mode === 'fflf') ? (sourceImageUpload || '') : '',
lastImageFile: mode === 'fflf' ? (lastImageFile || '') : '',
+ lastImage: mode === 'fflf' ? (lastImageUpload || '') : '',
extendFromVideoId: (mode === 'extend' && currentModel?.runtime === 'ltx2')
? (extendFromVideoId || '') : '',
+ // Audio File goes through under the multipart field 'audioFile'. Server
+ // routes it to the durable uploads dir and into the a2v helper.
+ audioFile: mode === 'a2v' ? (audioFile || '') : '',
chunks: chunks > 1 ? chunks : '',
};
};
@@@ -552,18 -535,20 +563,21 @@@
};
const handleEnqueue = () => {
- if (!prompt.trim() || (status && status.connected === false) || extendModeBlocked) return;
+ if (!prompt.trim() || (status && status.connected === false) || extendModeBlocked || a2vModeBlocked) return;
const payload = buildGeneratePayload();
- // Strip the 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 `_blob`/`_audioBlob`.
- const { sourceImage, audioFile: audioBlob, ...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;
++ const { sourceImage, lastImage, audioFile: audioBlob, ...summary } = payload;
setQueue((q) => [...q, {
id: newQueueId(),
status: 'pending',
params: summary,
- _blob: sourceImage instanceof File ? sourceImage : null,
- _audioBlob: audioBlob instanceof File ? audioBlob : null,
+ _blobs: {
+ sourceImage: sourceImage instanceof File ? sourceImage : null,
+ lastImage: lastImage instanceof File ? lastImage : null,
++ audioFile: audioBlob instanceof File ? audioBlob : null,
+ },
enqueuedAt: Date.now(),
}]);
toast.success('Added to queue');
@@@ -594,8 -579,8 +608,9 @@@
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._audioBlob) payload.audioFile = next._audioBlob;
+ if (next._blobs?.sourceImage) payload.sourceImage = next._blobs.sourceImage;
+ if (next._blobs?.lastImage) payload.lastImage = next._blobs.lastImage;
++ if (next._blobs?.audioFile) payload.audioFile = next._blobs.audioFile;
let busyRetry = false;
let busyRetryTimer = null;
runGeneration(payload).then((res) => {
@@@ -649,8 -634,80 +664,80 @@@
};
const notConnected = status && status.connected === false;
- const canEnqueue = prompt.trim() && !notConnected && !extendModeBlocked;
+ const canEnqueue = prompt.trim() && !notConnected && !extendModeBlocked && !a2vModeBlocked;
+ // 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,
+ }) => {
+ // Clear button shows as soon as the user picks anything (state-only).
+ // Preview gates on `uploadUrl` instead of the raw `upload` File because
+ // the object URL is generated in a useEffect — without this, the render
+ // between "user picked a file" and "useEffect ran" would mount an
+ // <img src={null}> for one frame.
+ const hasSelection = !!(file || upload);
+ const canPreview = !!(file || uploadUrl);
+ 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>
+ {canPreview ? (
+ <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)}
+ aria-label={`${label} — pick from gallery`}
+ 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">
diff --cc server/routes/videoGen.js
index 24a15e0307,25f6132320..b427d221dc
--- a/server/routes/videoGen.js
+++ b/server/routes/videoGen.js
@@@ -31,19 -31,12 +31,20 @@@ import { enqueueJob, attachSseClient, c
const router = Router();
- // Single uploader handles both sourceImage (image/fflf modes) and audioFile
- // (a2v mode). The UI never sends both in one request; if a malformed client
- // did, the parser now rejects with TOO_MANY_FILES (400) and unlinks the
- // already-staged first part — see uploadSingle() in lib/multipart.js. The
- // route's fileFilter ensures whichever single file survives matches the
- // correct content-type for its claimed fieldname.
- const mediaUpload = uploadSingle(['sourceImage', 'audioFile'], {
-// 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/')),
++// FFLF accepts up to two image uploads (start and end frame); a2v takes
++// one audio upload (audioFile). 100MB covers audio cases too (LTX-2's a2v
++// expects only seconds of audio in practice). Per-fieldname mime filter
++// rejects mismatched parts up-front so a stray .mp4 drag-drop can't get
++// staged under any of these fields.
++const frameImageUpload = uploadFields(['sourceImage', 'lastImage', 'audioFile'], {
+ limits: { fileSize: 100 * 1024 * 1024 },
+ fileFilter: (_req, file, cb) => {
- const okImage = file.fieldname === 'sourceImage' && file.mimetype.startsWith('image/');
- const okAudio = file.fieldname === 'audioFile' && file.mimetype.startsWith('audio/');
++ const isImageField = file.fieldname === 'sourceImage' || file.fieldname === 'lastImage';
++ const isAudioField = file.fieldname === 'audioFile';
++ const okImage = isImageField && file.mimetype.startsWith('image/');
++ const okAudio = isAudioField && file.mimetype.startsWith('audio/');
+ cb(null, okImage || okAudio);
+ },
});
// Multipart bodies arrive as strings; coerce numerics in the schema. The
@@@ -208,48 -199,53 +207,83 @@@ router.post('/', frameImageUpload, asyn
{ status: 500, code: 'VIDEO_GEN_UPLOAD_STAGE_FAILED' },
);
}
- await unlink(req.file.path).catch(() => {});
- if (isAudio) {
- audioFilePath = durablePath;
- } else {
- sourceImagePath = durablePath;
+ await unlink(file.path).catch(() => {});
+ stagedDurablePaths.push(durablePath);
+ 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.
+ //
+ // Cleanup plumbing: `uploadedTempPath` (single, legacy) is RESERVED for the
+ // start-frame upload — that field shape is what already-persisted jobs from
+ // before this route change carry, so keeping its semantics stable means
+ // those replays still clean up correctly. Every additional upload (today:
+ // just `lastImage`) flows through `uploadedTempPaths` as an array. The
+ // worker walks both fields when unlinking on terminal events.
+ let sourceImagePath = null;
+ let lastImagePath = null;
++ let audioFilePath = null;
+ let uploadedTempPath = null;
+ const extraUploadedTempPaths = [];
- if (uploads.sourceImage || uploads.lastImage) {
++ if (uploads.sourceImage || uploads.lastImage || uploads.audioFile) {
+ // Ensure the durable uploads dir exists before staging. Wrapped in
+ // try/catch so a permission/disk failure here still cleans up the
+ // multipart temp uploads instead of leaking them in the OS temp dir.
+ try {
+ await ensureDir(PATHS.uploads);
+ } catch (err) {
+ await cleanupAllStaged();
+ throw new ServerError(
+ `Failed to prepare uploads directory: ${err.message}`,
+ { status: 500, code: 'VIDEO_GEN_UPLOADS_DIR_FAILED' },
+ );
}
- uploadedTempPath = durablePath;
- // Mirror into the closure so cleanupTempUpload() unlinks this if a
- // post-staging validation guard rejects the request before enqueue.
- stagedUploadPath = durablePath;
+ }
+ if (uploads.sourceImage) {
+ sourceImagePath = await stageUploadDurable(uploads.sourceImage, 'source');
+ uploadedTempPath = sourceImagePath;
} else if (body.sourceImageFile) {
sourceImagePath = resolveGalleryImage(body.sourceImageFile);
}
+ if (uploads.lastImage) {
+ lastImagePath = await stageUploadDurable(uploads.lastImage, 'last');
+ extraUploadedTempPaths.push(lastImagePath);
+ } else if (body.lastImageFile) {
+ // Same path-traversal guard as the start frame.
+ lastImagePath = resolveGalleryImage(body.lastImageFile);
+ }
++ if (uploads.audioFile) {
++ // a2v: audio file rides through the same durable-staging path as the
++ // image uploads. Cleanup tracking via extraUploadedTempPaths so the
++ // worker drops it on terminal events the same way it drops lastImage.
++ audioFilePath = await stageUploadDurable(uploads.audioFile, 'audio');
++ extraUploadedTempPaths.push(audioFilePath);
++ }
+
+ // a2v mode requires an audio upload — fail fast at the route boundary so
+ // the UI gets a clear 400 instead of a queued job that fails late on the
+ // python helper's "audio_path is required" check.
+ if (body.mode === 'a2v' && !audioFilePath) {
- await cleanupTempUpload();
++ await cleanupAllStaged();
+ throw new ServerError(
+ 'a2v mode requires an audioFile upload (multipart field name: audioFile).',
+ { status: 400, code: 'VIDEO_GEN_AUDIO_REQUIRED' },
+ );
+ }
- // Inverse guard: if an audio file was uploaded but `mode` is missing or
- // is anything other than 'a2v', the job would be queued with audioFilePath
- // set and mode=undefined, and generateVideo() would treat it as plain
- // text-to-video — silently dropping the audio. Reject so the caller can't
- // accidentally pay for the wrong generation. (We deliberately do NOT
- // auto-infer mode='a2v' from the audio upload — explicit-is-better than
- // magic, and the UI always sets mode when sending audio.)
++ // Inverse guard: an audio upload paired with anything other than a2v would
++ // otherwise be silently dropped (the service ignores audioFilePath unless
++ // mode === 'a2v'), which means the user pays for a t2v render they didn't
++ // ask for. Reject so the caller can fix their request.
+ if (audioFilePath && body.mode !== 'a2v') {
- await cleanupTempUpload();
++ await cleanupAllStaged();
+ throw new ServerError(
- `audioFile upload requires mode: 'a2v' (received mode: ${body.mode || '<none>'}).`,
++ `audioFile upload is only valid with mode='a2v' (got mode='${body.mode || 'unset'}').`,
+ { status: 400, code: 'VIDEO_GEN_AUDIO_MODE_MISMATCH' },
+ );
+ }
- // FFLF end-frame: gallery-pick only. Same path-traversal guard.
- const lastImagePath = body.lastImageFile ? resolveGalleryImage(body.lastImageFile) : null;
-
// Native extend (ltx2 runtime): resolve the history id to a video file
// path under data/videos/ and forward it as extendFromVideoPath. Reject
// a missing/tampered id rather than silently falling back to t2v —
@@@ -295,8 -295,8 +333,9 @@@
tiling: body.tiling || 'auto',
disableAudio: body.disableAudio === true || body.disableAudio === 'true',
sourceImagePath,
+ audioFilePath,
uploadedTempPath,
+ uploadedTempPaths: extraUploadedTempPaths,
lastImagePath,
extendFromVideoPath,
mode: body.mode,
diff --cc server/routes/videoGen.test.js
index 6efd4ed7cc,5c8ab840c8..9e6db7ddc6
--- a/server/routes/videoGen.test.js
+++ b/server/routes/videoGen.test.js
@@@ -28,24 -28,10 +28,25 @@@ vi.mock('../services/mediaJobQueue/inde
listJobs: vi.fn(() => []),
}));
+// Pending file metadata for tests that need to simulate `req.file`. Tests set
+// this via `setPendingUpload({ ... })` before issuing the request; the mocked
+// uploadSingle middleware reads it off the holder, attaches it as req.file,
+// and clears it. Mutable wrapper avoids reaching into vi mock internals.
+const pendingUpload = { current: null };
+const setPendingUpload = (file) => { pendingUpload.current = file; };
+
vi.mock('../lib/multipart.js', () => ({
- // 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(),
+ // Bypass the streaming parser. If a test set a pending upload via
- // setPendingUpload(), inject it as req.file so the route exercises the
- // upload-staging path; otherwise pass through (no-upload path).
- uploadSingle: () => (req, _res, next) => {
++ // setPendingUpload(), inject it under req.files keyed by fieldname so the
++ // route exercises the upload-staging path; otherwise pass through.
++ uploadFields: () => (req, _res, next) => {
+ if (pendingUpload.current) {
- req.file = pendingUpload.current;
++ const f = pendingUpload.current;
++ req.files = { [f.fieldname]: f };
+ pendingUpload.current = null;
+ }
+ next();
+ },
}));
vi.mock('../lib/fileUtils.js', () => ({
@@@ -262,67 -240,6 +263,71 @@@ describe('videoGen routes', () =>
expect(r.body.error).toMatch(/mode/i);
});
+ // a2v mode requires an audio upload. Without one the route fails fast
+ // with VIDEO_GEN_AUDIO_REQUIRED (400) instead of queueing a job that
+ // would fail late on the python helper's audio_path check.
+ it('rejects a2v without an audio upload (VIDEO_GEN_AUDIO_REQUIRED)', async () => {
+ const r = await request(app).post('/api/video-gen/').send({
+ prompt: 'beat-synced dancer',
+ mode: 'a2v',
+ });
+ expect(r.status).toBe(400);
+ expect(r.body.error).toMatch(/audioFile/i);
+ expect(mediaJobQueue.enqueueJob).not.toHaveBeenCalled();
+ });
+
+ // Audio upload present + mode='a2v': route stages the audio under
+ // data/uploads/ and forwards the staged audioFilePath into enqueue
+ // params. The python helper picks it up via --audio.
+ it('stages audioFile upload and forwards audioFilePath for a2v mode', async () => {
+ setPendingUpload({
+ fieldname: 'audioFile',
+ path: '/tmp/upload-fake.wav',
+ originalname: 'beats.wav',
+ mimetype: 'audio/wav',
+ size: 1234,
+ });
+ const r = await request(app).post('/api/video-gen/').send({
+ prompt: 'beat-synced dancer',
+ mode: 'a2v',
+ });
+ expect(r.status).toBe(200);
+ expect(mediaJobQueue.enqueueJob).toHaveBeenCalledWith(expect.objectContaining({
+ kind: 'video',
+ params: expect.objectContaining({
+ mode: 'a2v',
+ // audio is staged into PATHS.uploads with the video-audio prefix
+ audioFilePath: expect.stringMatching(/\/mock\/uploads\/video-audio-.*\.wav$/),
- // and threaded into uploadedTempPath for worker cleanup
- uploadedTempPath: expect.stringMatching(/\/mock\/uploads\/video-audio-.*\.wav$/),
++ // and threaded into uploadedTempPaths (array) for worker cleanup —
++ // uploadedTempPath (singular) stays reserved for the start-frame
++ // upload so legacy persisted jobs replay correctly.
++ uploadedTempPaths: expect.arrayContaining([
++ expect.stringMatching(/\/mock\/uploads\/video-audio-.*\.wav$/),
++ ]),
+ }),
+ }));
+ });
+
+ // Defense-in-depth: an audio upload paired with the wrong mode would
+ // otherwise be silently dropped (queued as text-to-video). Reject so
+ // the caller can't accidentally pay for the wrong generation path.
+ it('rejects audioFile upload paired with a non-a2v mode (VIDEO_GEN_AUDIO_MODE_MISMATCH)', async () => {
+ setPendingUpload({
+ fieldname: 'audioFile',
+ path: '/tmp/upload-fake.wav',
+ originalname: 'beats.wav',
+ mimetype: 'audio/wav',
+ size: 1234,
+ });
+ const r = await request(app).post('/api/video-gen/').send({
+ prompt: 'a cat',
+ mode: 'text',
+ });
+ expect(r.status).toBe(400);
+ expect(r.body.error).toMatch(/a2v/i);
+ expect(mediaJobQueue.enqueueJob).not.toHaveBeenCalled();
+ });
+
// Pre-enqueue config validation: without pythonPath the queue would
// accept the job, return 200/queued, then fail asynchronously over SSE
// and pollute the persisted queue with a doomed entry.
diff --cc server/services/videoGen/local.js
index 3fb3eb15a5,74e8232037..b8424478f6
--- a/server/services/videoGen/local.js
+++ b/server/services/videoGen/local.js
@@@ -259,7 -237,7 +259,7 @@@ const buildArgs = ({ pythonPath, modelI
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, audioFilePath = 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 }) {
++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, audioFilePath = 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