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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat([video-resume-restore-keyframes]): multi-keyframe FFLF picker + resume restore
[._.]/ Adam Eivy4e489ae8c251
diff --git a/client/src/pages/VideoGen.jsx b/client/src/pages/VideoGen.jsxindex 94ad175675..fadb413c20 100644--- a/client/src/pages/VideoGen.jsx+++ b/client/src/pages/VideoGen.jsx@@ -151,6 +151,16 @@ export default function VideoGen() {const [sourceImageUpload, setSourceImageUpload] = useState(null);const [lastImageFile, setLastImageFile] = useState(null);const [lastImageUpload, setLastImageUpload] = useState(null);+ // Multi-keyframe FFLF (ltx2 runtime only): the user anchors 2–8 gallery+ // images at specific pixel-frame indices and the model interpolates between+ // them. This is a distinct server path from the legacy first/last pair+ // (the route rejects mixing the two) — `keyframesMode` flips fflf between+ // the two pickers. Each entry is { file, index } where file is a gallery+ // basename; the route resolves it to an absolute path. Keyframes are+ // gallery-only (no per-frame upload) because the route only accepts+ // gallery references for them.+ const [keyframesMode, setKeyframesMode] = useState(false);+ const [keyframes, setKeyframes] = useState([]);const [extendFromVideoId, setExtendFromVideoId] = useState('');const [extendingFrame, setExtendingFrame] = useState(false);// a2v mode — direct audio upload only (no gallery for audio yet). The File@@ -161,6 +171,13 @@ export default function VideoGen() {// 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([]);+ // Visible gallery options, shared by every gallery <select> (the frame+ // panels and each multi-keyframe row) so the filter+slice runs once per+ // gallery change rather than once per picker per render.+ const visibleGallery = useMemo(+ () => imageGallery.filter((img) => !img.hidden).slice(0, 50),+ [imageGallery],+ );// Re-sync when ImageGen pipes a new image via ?sourceImageFile=...useEffect(() => {@@ -530,6 +547,16 @@ export default function VideoGen() {if (typeof p.disableAudio === 'boolean') setDisableAudio(p.disableAudio);if (p.mode) setMode(p.mode);if (p.chunks && p.chunks > 1) setChunks(p.chunks);+ // Multi-keyframe FFLF: the route maps the stored { path, index } back to+ // { file, index } (gallery basename) for us, so restore the picker+ // state directly. >= 2 mirrors the server's accept floor; flipping+ // keyframesMode on re-renders the multi-keyframe picker (the model was+ // ltx2 for the job to have keyframes, so keyframesSupported holds once+ // setModelId above resolves).+ if (Array.isArray(p.keyframes) && p.keyframes.length >= 2) {+ setKeyframes(p.keyframes.map((kf) => ({ file: kf.file, index: kf.index })));+ setKeyframesMode(true);+ }setGenerating(true);// Skip a forced setProgress(0) here — attachJobEvents will replay the// server's last SSE payload synchronously after EventSource open, and@@ -620,6 +647,31 @@ export default function VideoGen() {const currentModel = models.find((m) => m.id === modelId);+ // Multi-keyframe availability + validation. Keyframes are an ltx2-runtime+ // primitive (the route 400s with KEYFRAMES_REQUIRE_LTX2 otherwise), so the+ // picker only offers itself when the selected model runs on ltx2. Mirror+ // the server's accept rules (server/routes/videoGen.js ~line 574) so the+ // form blocks before a doomed POST: 2–8 entries, each pinned to a gallery+ // file, indices strictly ascending and within [0, numFrames-1].+ const keyframesSupported = currentModel?.runtime === 'ltx2';+ const keyframesActive = mode === 'fflf' && keyframesMode && keyframesSupported;+ const keyframesError = useMemo(() => {+ if (!keyframesActive) return null;+ if (keyframes.length < 2) return 'Add at least 2 keyframes.';+ if (keyframes.length > 8) return 'Use at most 8 keyframes.';+ let prev = -1;+ for (let i = 0; i < keyframes.length; i++) {+ const kf = keyframes[i];+ if (!kf.file) return `Keyframe ${i + 1} needs a gallery image.`;+ if (!Number.isInteger(kf.index) || kf.index < 0) return `Keyframe ${i + 1} needs a frame index ≥ 0.`;+ if (kf.index > numFrames - 1) return `Keyframe ${i + 1} frame ${kf.index} must be below numFrames (${numFrames}).`;+ if (kf.index <= prev) return 'Keyframe frame indices must be strictly ascending.';+ prev = kf.index;+ }+ return null;+ }, [keyframesActive, keyframes, numFrames]);+ const keyframesBlocked = keyframesActive && !!keyframesError;+// Probe the per-runtime status BEFORE the user hits Generate — without// this they'd see the buildArgs-time "venv not found" 500 with no good way// to recover. The set of "BYOV" runtimes comes from /status server-side so@@ -694,6 +746,37 @@ export default function VideoGen() {setLastImageUpload(null);};+ // Multi-keyframe list mutators. A new row defaults its index to the prior+ // row's index + 1 (clamped to the last addressable frame) so the strictly-+ // ascending invariant holds out of the box without the user hand-typing it.+ const addKeyframe = () => setKeyframes((prev) => {+ if (prev.length >= 8) return prev;+ const lastIndex = prev.length ? prev[prev.length - 1].index : -1;+ const nextIndex = Math.min(lastIndex + 1, Math.max(0, numFrames - 1));+ return [...prev, { file: '', index: nextIndex }];+ });+ const updateKeyframe = (i, patch) => setKeyframes((prev) =>+ prev.map((kf, idx) => (idx === i ? { ...kf, ...patch } : kf)));+ const removeKeyframe = (i) => setKeyframes((prev) => prev.filter((_, idx) => idx !== i));+ // Toggling multi-keyframe mode on seeds two empty rows anchored at the first+ // and last frame (the FFLF mental model, and the minimum 2 the server+ // requires) and drops the legacy first/last pair (the route rejects mixing+ // them). Toggling off clears the keyframe list for the same reason.+ const toggleKeyframesMode = () => setKeyframesMode((on) => {+ const next = !on;+ if (next) {+ clearSourceImage();+ clearLastImage();+ setKeyframes((prev) => (prev.length >= 2 ? prev : [+ { file: '', index: 0 },+ { file: '', index: Math.max(1, numFrames - 1) },+ ]));+ } else {+ setKeyframes([]);+ }+ return next;+ });+// 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.)@@ -702,6 +785,10 @@ export default function VideoGen() {// 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);+ // Multi-keyframe is fflf-only — drop it on every other switch so a stale+ // keyframe list can't sneak into the next post (the route would 400 on a+ // non-fflf mode anyway, but keep the form honest).+ if (next !== 'fflf') { setKeyframesMode(false); setKeyframes([]); }if (next === 'text') {clearSourceImage();clearLastImage();@@ -803,6 +890,10 @@ export default function VideoGen() {const promptOut = (noMusic && !disableAudio && !/no music/i.test(composed.prompt))? `${composed.prompt}\n\nno music, no soundtrack`: composed.prompt;+ // Legacy first/last-frame fflf: the two-image picker is mutually exclusive+ // with multi-keyframe mode on the server, so its image fields only ride+ // along when keyframes aren't active.+ const legacyFflf = mode === 'fflf' && !keyframesActive;return {prompt: promptOut,negativePrompt: composed.negativePrompt,@@ -821,12 +912,17 @@ export default function VideoGen() {// video's history id directly so the server resolves it to a disk// path and routes through ExtendPipeline. Legacy extend (mlx_video)// still uses sourceImageFile populated from extractLastFrame.- sourceImageFile: (mode === 'image' || mode === 'fflf'+ // keyframes goes as a JSON string — buildFormData would otherwise+ // stringify each {file,index} object to "[object Object]" (it appends+ // arrays element-by-element); the route's zod preprocess JSON-parses it+ // and strips any unknown keys, so sending the entries verbatim is safe.+ keyframes: keyframesActive ? JSON.stringify(keyframes) : '',+ sourceImageFile: (mode === 'image' || legacyFflf|| (mode === 'extend' && currentModel?.runtime !== 'ltx2'))? (sourceImageFile || '') : '',- sourceImage: (mode === 'image' || mode === 'fflf') ? (sourceImageUpload || '') : '',- lastImageFile: mode === 'fflf' ? (lastImageFile || '') : '',- lastImage: mode === 'fflf' ? (lastImageUpload || '') : '',+ sourceImage: (mode === 'image' || legacyFflf) ? (sourceImageUpload || '') : '',+ lastImageFile: legacyFflf ? (lastImageFile || '') : '',+ lastImage: legacyFflf ? (lastImageUpload || '') : '',extendFromVideoId: (mode === 'extend' && currentModel?.runtime === 'ltx2')? (extendFromVideoId || '') : '',// Audio File goes through under the multipart field 'audioFile'. Server@@ -904,7 +1000,7 @@ export default function VideoGen() {// Without these guards the user could press Enter in the prompt// textarea and fire a request the disabled button would otherwise// have prevented.- if (!prompt.trim() || generating || notConnected || extendModeBlocked || a2vModeBlocked || byovGateBlocked) return;+ if (!prompt.trim() || generating || notConnected || extendModeBlocked || a2vModeBlocked || byovGateBlocked || keyframesBlocked) return;await runGeneration(buildGeneratePayload()).catch(() => {});};@@ -913,7 +1009,7 @@ export default function VideoGen() {// would silently queue a doomed job that fails late in the worker with// VENV_MISSING, hiding the installer banner from the user. Block at// enqueue time so the only path forward is the install banner above.- if (!prompt.trim() || notConnected || extendModeBlocked || a2vModeBlocked || byovGateBlocked) return;+ if (!prompt.trim() || notConnected || extendModeBlocked || a2vModeBlocked || byovGateBlocked || keyframesBlocked) return;const payload = buildGeneratePayload();// 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@@ -1020,7 +1116,7 @@ export default function VideoGen() {// ONLY a BYOV runtime via the modal would stay stuck behind a "not// configured" error from the unrelated legacy probe.const notConnected = !!status && status.connected === false && !needsByovProbe;- const canEnqueue = prompt.trim() && !notConnected && !extendModeBlocked && !a2vModeBlocked && !byovGateBlocked;+ const canEnqueue = prompt.trim() && !notConnected && !extendModeBlocked && !a2vModeBlocked && !byovGateBlocked && !keyframesBlocked;// Symmetric frame picker for the FFLF + image modes. Each slot accepts// EITHER a gallery filename OR a fresh upload; the preview renders@@ -1070,7 +1166,7 @@ export default function VideoGen() {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) => (+ {visibleGallery.map((img) => (<option key={img.filename} value={img.filename}>{img.filename}</option>))}</select>@@ -1240,7 +1336,86 @@ export default function VideoGen() {</div></div>- {(mode === 'image' || mode === 'fflf') && (+ {mode === 'fflf' && keyframesSupported && (+ <div className="border border-port-border/50 rounded-lg p-2 space-y-2">+ <label htmlFor="keyframes-mode" className="flex items-center justify-between gap-2 cursor-pointer">+ <span className="text-[11px] font-medium text-gray-400">+ Multi-keyframe interpolation+ <span className="block text-[10px] text-gray-500 font-normal">Anchor 2–8 gallery frames at frame indices (LTX-2)</span>+ </span>+ <input+ id="keyframes-mode"+ type="checkbox"+ checked={keyframesMode}+ onChange={toggleKeyframesMode}+ className="w-4 h-4 accent-port-accent cursor-pointer"+ />+ </label>+ {keyframesActive && (+ <div className="space-y-2">+ {keyframes.map((kf, i) => (+ <div key={i} className="flex items-start gap-2">+ <div className="flex-1 space-y-1">+ <select+ value={kf.file}+ onChange={(e) => updateKeyframe(i, { file: e.target.value })}+ aria-label={`Keyframe ${i + 1} gallery image`}+ 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"+ >+ <option value="">Pick from gallery…</option>+ {visibleGallery.map((img) => (+ <option key={img.filename} value={img.filename}>{img.filename}</option>+ ))}+ </select>+ {kf.file && (+ <ImagePreview src={`/data/images/${kf.file}`} alt={`Keyframe ${i + 1}`} label={kf.file} />+ )}+ </div>+ <div className="flex flex-col items-center gap-1">+ <label htmlFor={`kf-index-${i}`} className="text-[10px] text-gray-500">frame</label>+ <input+ id={`kf-index-${i}`}+ type="number"+ min={0}+ max={numFrames - 1}+ value={kf.index}+ onChange={(e) => updateKeyframe(i, { index: e.target.value === '' ? '' : Number(e.target.value) })}+ aria-label={`Keyframe ${i + 1} frame index`}+ className="w-16 bg-port-bg border border-port-border rounded px-2 py-1 text-xs text-white focus:outline-none focus:border-port-accent"+ />+ </div>+ <button+ type="button"+ onClick={() => removeKeyframe(i)}+ disabled={keyframes.length <= 2}+ aria-label={`Remove keyframe ${i + 1}`}+ className="mt-5 p-1 text-gray-400 hover:text-port-error disabled:opacity-30 disabled:cursor-not-allowed"+ >+ <X className="w-3.5 h-3.5" />+ </button>+ </div>+ ))}+ <div className="flex items-center justify-between">+ <button+ type="button"+ onClick={addKeyframe}+ disabled={keyframes.length >= 8}+ className="flex items-center gap-1.5 text-[11px] text-port-accent hover:text-port-accent/80 disabled:opacity-40 disabled:cursor-not-allowed"+ >+ <ListPlus className="w-3.5 h-3.5" /> Add keyframe+ </button>+ <span className="text-[10px] text-gray-500">{keyframes.length}/8</span>+ </div>+ {keyframesError && <p className="text-[10px] text-port-error leading-snug">{keyframesError}</p>}+ <p className="text-[10px] text-gray-500 leading-snug">+ Keyframes pull from your gallery only. Indices must be strictly ascending and below numFrames ({numFrames}).+ </p>+ </div>+ )}+ </div>+ )}++ {(mode === 'image' || (mode === 'fflf' && !keyframesActive)) && (<div className={`grid gap-2 ${mode === 'fflf' ? 'grid-cols-1 sm:grid-cols-2' : 'grid-cols-1'}`}>{renderFramePanel({label: mode === 'fflf' ? 'First frame' : 'Source image',@@ -1575,7 +1750,7 @@ export default function VideoGen() {) : (<buttontype="submit"- disabled={!prompt.trim() || notConnected || extendModeBlocked || a2vModeBlocked || byovGateBlocked}+ disabled={!prompt.trim() || notConnected || extendModeBlocked || a2vModeBlocked || byovGateBlocked || keyframesBlocked}className="flex items-center gap-2 px-4 py-2 bg-port-accent hover:bg-port-accent/80 disabled:opacity-50 disabled:cursor-not-allowed text-white text-sm font-medium rounded-lg min-h-[40px]"title={byovRuntimeMissing ? `${byovStatus?.label || byovRuntime} runtime is not installed — use the install banner above`@@ -1584,6 +1759,7 @@ export default function VideoGen() {: a2vModeBlocked ? (currentModel?.runtime !== 'ltx2'? 'a2v mode requires an ltx2-runtime model — pick one from the Model dropdown': 'Pick an audio file before generating')+ : keyframesBlocked ? keyframesError: undefined}>diff --git a/server/routes/videoGen.js b/server/routes/videoGen.jsindex 60165ba495..00ae895b81 100644--- a/server/routes/videoGen.js+++ b/server/routes/videoGen.js@@ -10,7 +10,7 @@ import { Router } from 'express';import { existsSync } from 'fs';import { copyFile, unlink } from 'fs/promises';import { randomUUID } from 'crypto';-import { join, extname } from 'path';+import { join, extname, basename } from 'path';import { spawn } from 'child_process';import os from 'os';import { z } from 'zod';@@ -748,6 +748,18 @@ const pickJobParams = (params) => {for (const k of ACTIVE_JOB_PARAM_FIELDS) {if (params[k] !== undefined) out[k] = params[k];}+ // keyframes ride a separate mapping rather than the raw whitelist: they're+ // stored as { path, index } where `path` is an absolute gallery path (the+ // same internal-path-leak the whitelist exists to prevent — see the+ // comment above). Re-derive the gallery basename as `file` so the resuming+ // client's multi-keyframe picker can repopulate { file, index } entries+ // (its submit shape) without ever seeing the server's filesystem layout.+ if (Array.isArray(params.keyframes)) {+ const mapped = params.keyframes+ .filter((kf) => kf && typeof kf.path === 'string' && Number.isInteger(kf.index))+ .map((kf) => ({ file: basename(kf.path), index: kf.index }));+ if (mapped.length) out.keyframes = mapped;+ }return out;};diff --git a/server/routes/videoGen.test.js b/server/routes/videoGen.test.jsindex 7652da7251..5ea4e3a14f 100644--- a/server/routes/videoGen.test.js+++ b/server/routes/videoGen.test.js@@ -776,6 +776,46 @@ describe('videoGen routes', () => {expect(p.uploadedTempPaths).toBeUndefined();expect(p.extendFromVideoPath).toBeUndefined();});++ // keyframes are stored as { path, index } (absolute gallery paths) but+ // must surface to the resuming client as { file, index } (basename only)+ // — same internal-path-leak rule as sourceImagePath, plus the client+ // picker's submit shape uses gallery filenames.+ it('maps stored keyframes { path, index } -> { file, index } without leaking the absolute path', async () => {+ mediaJobQueue.listJobs.mockImplementation(listJobsByFilter([+ { id: 'running-kf', kind: 'video', status: 'running', position: 1, params: {+ prompt: 'kf prompt', modelId: 'ltx2_unified', mode: 'fflf',+ keyframes: [+ { path: '/Users/secret/data/images/a.png', index: 0 },+ { path: '/Users/secret/data/images/b.png', index: 24 },+ ],+ } },+ ]));+ const r = await request(app).get('/api/video-gen/active');+ expect(r.status).toBe(200);+ const p = r.body.activeJob.params;+ expect(p.keyframes).toEqual([+ { file: 'a.png', index: 0 },+ { file: 'b.png', index: 24 },+ ]);+ // The absolute server path must never round-trip.+ expect(JSON.stringify(p.keyframes)).not.toMatch(/secret/);+ });++ // Defensive: malformed keyframe entries (missing path / non-integer index)+ // are dropped rather than surfaced as half-formed picker rows. When every+ // entry is malformed, keyframes is omitted entirely (no empty array).+ it('drops malformed keyframe entries and omits keyframes when none survive', async () => {+ mediaJobQueue.listJobs.mockImplementation(listJobsByFilter([+ { id: 'running-bad-kf', kind: 'video', status: 'running', position: 1, params: {+ prompt: 'p', modelId: 'ltx2_unified',+ keyframes: [{ index: 0 }, { path: '/x/y.png', index: 'nope' }, null],+ } },+ ]));+ const r = await request(app).get('/api/video-gen/active');+ expect(r.status).toBe(200);+ expect(r.body.activeJob.params.keyframes).toBeUndefined();+ });});describe('GET /:jobId/events', () => {