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

fix(video-gen): I2V source preservation + FFLF + extract-last-frame + media model registry

Adam Eivyaac066bf6a9b
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index f255254a43..0f0de05a97 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -2,6 +2,14 @@
## Added
+- **Media model registry at `data/media-models.json`** — single source of truth for video and image model definitions, the LTX text encoder, and per-platform defaults. Replaces hardcoded model catalogs in `videoGen/local.js`, `imageGen/local.js`, and `imageVideoModels.js`. Seeded automatically on first run; edit + restart the server to swap models. New `gemma-bf16` (now default, best output quality), `gemma-qat-4bit` (auto-detected if LM Studio installed it), and `gemma-4bit` text-encoder options. Loader resolves `~/...` and prefers a local `localPath` when it exists.
+- **`+faststart` mp4 post-processing** — every video render is remuxed (no re-encoding, ~hundreds of ms) to move the moov atom to the front of the file. Gallery tiles with `preload="metadata"` now render their poster frame on page load instead of flashing black until clicked.
+- **`caffeinate -i -w <pid>`** spawned alongside the LTX Python child on macOS so a 90s+ render isn't aborted by display/system sleep on a laptop. `-w` makes it self-exit when our pid does — no manual lifecycle management.
+- **Raw stderr/stdout logging from the LTX Python child** with `🐍`/`🐍-out` prefixes per job. Previously the python child's diagnostic output was filtered for `STATUS:`/`STAGE:` markers and the rest silently dropped, hiding upstream errors like "VAE encoder failed to load" until you ran the CLI manually.
+- **`imageStrength` parameter** on the video gen API + service. Plumbed through validation, route, service, and CLI args. mlx_video's actual semantics are inverted from its help text — `1.0` preserves the source latent (PortOS default if unspecified), `0.0` fully denoises. Documented inline.
+- **1:1 square resolutions** (512×512, 768×768) added to the Video Gen resolution dropdown.
+- **Image upload preview + larger reference-image previews** in Video Gen — uploads create object URLs so users see what they uploaded before submit; source / FFLF last-frame / extend-mode previews now render at `max-h-48 object-contain` instead of 48×48 thumbnails.
+
- **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-finished action that drops both successful and errored items. 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).
@@ -13,5 +21,12 @@
## Fixed
+- **Image-to-video on macOS now actually preserves the source image as the first frame.** Root cause: PortOS was on `mlx-video-with-audio` 0.1.33, which had a known bug where the VAE encoder failed to load for split-format unified models (LTX-2.3 distilled-Q4) and silently produced gray-fog conditioned frames. Pinned `>=0.1.35` in `scripts/setup-image-video.sh`. The setup script also installed the wrong PyPI package: `mlx_video` (a different unrelated "video loading utilities" package) instead of `mlx-video-with-audio` (the LTX generation backend). Both provide an `import mlx_video` module so the wrong install was silent. Verified end-to-end through the API: pixel-perfect first-frame preservation with coherent motion across all frames.
+- **FFLF last-frame conditioning silently produced no output.** PortOS was passing `numFrames - 1` (= 24 for 25 frames) as `--image-frame-idx`, but mlx_video expects a *latent* frame index — for LTX that's `floor((videoFrames - 1) / 8)`, max 3 for 25 frames. ffmpeg-conditioning shape check failed and the python child exited 0 with no output mp4. Now computes `lastLatentIdx` correctly.
+- **"Continue" / extract-last-frame produced phantom-success logs but no file**, leaving a broken image preview in Video Gen. Two compounded bugs: (1) `-sseof -0.1` was too narrow a seek window — for videos with audio (B-frames + AV mux), the last keyframe sits earlier than 100ms before EOF, so ffmpeg returned zero frames while sometimes still exiting 0. Widened to `-sseof -1.0` and added `-update 1`. (2) The success path resolved on exit-code without verifying the output file existed. Now requires `existsSync(framePath)` too.
+- **Last-frame extraction now caches** to `data/images/lastframe-<videoId>.png` — repeated "Continue" clicks reuse the cached PNG instead of re-spawning ffmpeg. Cuts ~1–2s per click.
+- **Delete operations now log** for both image (`🗑️ Deleted image: <filename>`) and video (`🗑️ Deleted video: <filename>`) gallery actions. Previously delete was silent, making it impossible to confirm from the server logs that the click hit the backend.
+- **Form fields stay editable during a video render.** Previously every input was `disabled={generating}`, blocking the user from queueing a different config while a render was in flight. The queue worker captures payloads at enqueue time, so live editing is safe.
+
- **Morse Send drill** no longer reveals the answer or competes with itself for spacebar input: the morse pattern under each prompt is gone (the reference tabs on the right are still available for hints), the global spacebar keying listener only attaches in Send mode (so it doesn't fire on the trainer landing page or during Copy drills), the side widget's "Practice Key" panel is hidden outside Send mode and no longer duplicates the live decoded letter, and the "Your sending" box starts blank with a "waiting for your first key…" hint instead of a misleading "—" placeholder.
- **CoS agents now reliably open PRs and request Copilot reviews when configured.** Previously, when both `openPR` and `reviewLoop` were enabled on a task, the worktree-cleanup logic's gate (`taskOpenPR && !taskReviewLoop`) skipped PR creation — falling through to auto-merge the agent's branch into main with no PR, no review, and contradictory wording in the agent prompt about whether it should open the PR itself. The cleanup now always opens the PR when `openPR` is set; when `reviewLoop` is also set, it requests a Copilot review on the new PR via the new `git.requestCopilotReview()` helper. The agent prompt is updated to consistently tell the agent the system handles PR creation and review requests.
diff --git a/client/src/pages/VideoGen.jsx b/client/src/pages/VideoGen.jsx
index 6f123015d5..eecc9cf166 100644
--- a/client/src/pages/VideoGen.jsx
+++ b/client/src/pages/VideoGen.jsx
@@ -50,6 +50,8 @@ const RESOLUTIONS = [
{ label: '768×512 (3:2 default)', w: 768, h: 512 },
{ label: '1024×576 (16:9)', w: 1024, h: 576 },
{ label: '512×768 (portrait)', w: 512, h: 768 },
+ { label: '512×512 (1:1)', w: 512, h: 512 },
+ { label: '768×768 (1:1)', w: 768, h: 768 },
];
const FRAME_OPTIONS = [25, 49, 73, 97, 121, 145, 169, 193, 217, 241];
@@ -73,6 +75,13 @@ const newQueueId = () =>
? crypto.randomUUID()
: `q-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
+const ImagePreview = ({ src, alt, label }) => (
+ <div className="space-y-1">
+ <img src={src} alt={alt} className="w-full max-h-48 object-contain rounded border border-port-border bg-port-bg" />
+ <div className="text-[11px] text-gray-500 truncate">{label}</div>
+ </div>
+);
+
export default function VideoGen() {
const [searchParams, setSearchParams] = useSearchParams();
const incomingSourceImage = searchParams.get('sourceImageFile');
@@ -129,6 +138,17 @@ 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.
+ const [sourceUploadUrl, setSourceUploadUrl] = useState(null);
+ useEffect(() => {
+ if (!(sourceImageUpload instanceof File)) { setSourceUploadUrl(null); return; }
+ const url = URL.createObjectURL(sourceImageUpload);
+ setSourceUploadUrl(url);
+ return () => URL.revokeObjectURL(url);
+ }, [sourceImageUpload]);
+
const refreshHistory = useCallback(() => {
listVideoHistory().then((items) => setHistory(Array.isArray(items) ? items : [])).catch(() => {});
}, []);
@@ -567,7 +587,6 @@ export default function VideoGen() {
type="button"
aria-pressed={active}
onClick={() => handleModeChange(id)}
- disabled={generating}
className={`flex-1 min-w-[120px] flex items-center justify-center gap-1.5 px-2.5 py-1.5 rounded-lg text-xs font-medium transition-colors disabled:opacity-50 ${
active
? 'bg-port-accent text-white shadow'
@@ -591,7 +610,6 @@ export default function VideoGen() {
value={prompt}
onChange={(e) => setPrompt(e.target.value)}
rows={3}
- disabled={generating}
className="w-full bg-port-bg border border-port-border rounded-lg px-3 py-2 text-sm text-white focus:outline-none focus:border-port-accent disabled:opacity-50 resize-y"
placeholder="Describe the video you want to generate..."
/>
@@ -602,7 +620,6 @@ export default function VideoGen() {
value={negativePrompt}
onChange={(e) => setNegativePrompt(e.target.value)}
rows={3}
- disabled={generating}
className="w-full bg-port-bg border border-port-border rounded-lg px-3 py-2 text-sm text-white focus:outline-none focus:border-port-accent disabled:opacity-50 resize-y"
placeholder="What to avoid..."
/>
@@ -620,20 +637,19 @@ export default function VideoGen() {
<button type="button" onClick={clearSourceImage} className="text-[11px] 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-12 h-12 object-cover rounded border border-port-border shrink-0" />
- <span className="text-[11px] text-gray-500 truncate">{sourceImageFile}</span>
- </div>
- )}
- {!sourceImageFile && (
+ {(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">{sourceImageUpload ? sourceImageUpload.name : 'Upload an image'}</span>
+ <span className="truncate">Upload an image</span>
<input
type="file"
accept="image/*"
- disabled={generating}
onChange={(e) => setSourceImageUpload(e.target.files?.[0] || null)}
className="hidden"
/>
@@ -649,14 +665,10 @@ export default function VideoGen() {
)}
</div>
{lastImageFile ? (
- <div className="flex items-center gap-2">
- <img src={`/data/images/${lastImageFile}`} alt="End frame" className="w-12 h-12 object-cover rounded border border-port-border shrink-0" />
- <span className="text-[11px] text-gray-500 truncate">{lastImageFile}</span>
- </div>
+ <ImagePreview src={`/data/images/${lastImageFile}`} alt="End frame" label={lastImageFile} />
) : (
<select
value=""
- disabled={generating}
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"
>
@@ -684,7 +696,7 @@ export default function VideoGen() {
</div>
<select
value={extendFromVideoId}
- disabled={generating || extendingFrame}
+ disabled={extendingFrame}
onChange={(e) => handleExtendPick(e.target.value)}
className="w-full bg-port-bg border border-port-border rounded px-2 py-1.5 text-xs text-white focus:outline-none focus:border-port-accent disabled:opacity-50"
>
@@ -699,10 +711,11 @@ export default function VideoGen() {
<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-12 h-12 object-cover rounded border border-port-border shrink-0" />
- <span className="text-[11px] text-gray-500 truncate">Starts from: {sourceImageFile}</span>
- </div>
+ <ImagePreview
+ src={`/data/images/${sourceImageFile}`}
+ alt="Last frame"
+ label={`Starts from: ${sourceImageFile}`}
+ />
)}
</div>
)}
@@ -714,7 +727,6 @@ export default function VideoGen() {
<select
value={modelId}
onChange={(e) => { setModelId(e.target.value); setSteps(''); setGuidanceScale(''); }}
- disabled={generating}
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"
>
{models.map((m) => <option key={m.id} value={m.id}>{m.name}</option>)}
@@ -727,7 +739,6 @@ export default function VideoGen() {
<select
value={resolutionLabel}
onChange={handleResolutionChange}
- disabled={generating}
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"
>
{RESOLUTIONS.map((r) => <option key={r.label} value={r.label}>{r.label}</option>)}
@@ -739,7 +750,6 @@ export default function VideoGen() {
<select
value={numFrames}
onChange={(e) => setNumFrames(Number(e.target.value))}
- disabled={generating}
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"
>
{FRAME_OPTIONS.map((f) => <option key={f} value={f}>{f} ({(f / fps).toFixed(1)}s @ {fps}fps)</option>)}
@@ -751,7 +761,6 @@ export default function VideoGen() {
<select
value={fps}
onChange={(e) => setFps(Number(e.target.value))}
- disabled={generating}
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"
>
{FPS_OPTIONS.map((f) => <option key={f} value={f}>{f}</option>)}
@@ -765,14 +774,12 @@ export default function VideoGen() {
type="number"
value={seed}
onChange={(e) => setSeed(e.target.value)}
- disabled={generating}
placeholder="Random"
className="flex-1 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"
/>
<button
type="button"
onClick={handleRandomSeed}
- disabled={generating}
className="p-2 text-gray-400 hover:text-white border border-port-border rounded-lg hover:bg-port-border/50 disabled:opacity-50 min-h-[40px] min-w-[40px] flex items-center justify-center"
title="Randomize seed"
>
@@ -790,7 +797,6 @@ export default function VideoGen() {
value={steps}
onChange={(e) => setSteps(e.target.value)}
placeholder={String(currentModel?.steps || 25)}
- disabled={generating}
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"
/>
</div>
@@ -804,7 +810,6 @@ export default function VideoGen() {
value={guidanceScale}
onChange={(e) => setGuidanceScale(e.target.value)}
placeholder={String(currentModel?.guidance ?? 3.0)}
- disabled={generating}
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"
/>
</div>
@@ -814,7 +819,6 @@ export default function VideoGen() {
<select
value={tiling}
onChange={(e) => setTiling(e.target.value)}
- disabled={generating}
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"
>
{TILING_OPTIONS.map((t) => <option key={t.value} value={t.value}>{t.label}</option>)}
@@ -826,7 +830,6 @@ export default function VideoGen() {
type="checkbox"
checked={disableAudio}
onChange={(e) => setDisableAudio(e.target.checked)}
- disabled={generating}
className="rounded"
/>
Disable audio (LTX-2 only — speeds up generation)
diff --git a/scripts/setup-image-video.sh b/scripts/setup-image-video.sh
index bcd740525f..81042abbb6 100755
--- a/scripts/setup-image-video.sh
+++ b/scripts/setup-image-video.sh
@@ -46,11 +46,17 @@ echo "📦 Installing image generation packages (mflux + deps)..."
if [[ "$INSTALL_VIDEO" == "1" ]]; then
if is_macos; then
- echo "📦 Installing video generation packages (mlx_video + mlx_vlm)..."
+ echo "📦 Installing video generation packages (mlx-video-with-audio + mlx_vlm)..."
+ # NOTE: the package on PyPI named just 'mlx_video' is unrelated (video
+ # loading utilities). The LTX-2 generation backend lives at
+ # mlx-video-with-audio (provides the `mlx_video.generate_av` module).
+ # Pin >=0.1.35 — earlier versions silently broke I2V on split-format /
+ # quantized models like LTX-2.3 distilled-Q4 by failing to load the VAE
+ # encoder, causing the conditioned frame to render as gray fog.
"$PYTHON_BIN" -m pip install --upgrade --user \
mlx \
mlx_vlm \
- mlx_video
+ "mlx-video-with-audio>=0.1.35"
else
echo "📦 Installing video generation packages (diffusers + torch)..."
"$PYTHON_BIN" -m pip install --upgrade --user \
diff --git a/server/lib/mediaModels.js b/server/lib/mediaModels.js
new file mode 100644
index 0000000000..6da419696e
--- /dev/null
+++ b/server/lib/mediaModels.js
@@ -0,0 +1,129 @@
+/**
+ * Media model registry — single source of truth for image/video model
+ * definitions and the text encoder used by the LTX video pipeline.
+ *
+ * On first load, seeds `data/media-models.json` with the project's default
+ * catalog. Edit that JSON to add models, tune steps/guidance, switch the
+ * text encoder, etc. Server restart picks up changes (the registry is
+ * cached at boot — there's no hot-reload).
+ *
+ * Schema (see seed defaults below for the full picture):
+ * - video.macos[], video.windows[]: { id, name, repo?, steps, guidance, broken? }
+ * - video.defaultMacos / video.defaultWindows: id of the default model
+ * - image[]: { id, name, steps, guidance, broken? }
+ * - textEncoders[]: { id, label, repo, localPath? }
+ * - selectedTextEncoder: id of the active text encoder
+ */
+
+import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'fs';
+import { homedir } from 'os';
+import { join, dirname } from 'path';
+import { PATHS } from './fileUtils.js';
+// fileUtils.ensureDir is async/Promise-returning; this module needs a
+// synchronous version because `loadMediaModels()` is called at import-time
+// from videoGen/imageGen modules, which can't await before exporting.
+
+const REGISTRY_FILE = join(PATHS.data, 'media-models.json');
+const IS_WIN = process.platform === 'win32';
+
+const DEFAULT_REGISTRY = {
+ _doc: 'PortOS media model registry. Edit to add models, tune defaults, or switch the text encoder. Restart the server to apply changes.',
+ video: {
+ macos: [
+ { id: 'ltx2_unified', name: 'LTX-2 Unified (~42 GB)', repo: 'notapalindrome/ltx2-mlx-av', steps: 30, guidance: 3.0 },
+ { id: 'ltx23_unified', name: 'LTX-2.3 Unified Beta (~48 GB)', repo: 'notapalindrome/ltx23-mlx-av', steps: 25, guidance: 3.0 },
+ { id: 'ltx23_distilled_q4', name: 'LTX-2.3 Distilled Q4 (~22 GB)', repo: 'notapalindrome/ltx23-mlx-av-q4', steps: 25, guidance: 3.0 },
+ ],
+ windows: [
+ { id: 'ltx_video', name: 'LTX-Video 0.9.5 — T2V + I2V (~9.5 GB, auto-downloads)', steps: 25, guidance: 3.0 },
+ ],
+ defaultMacos: 'ltx23_distilled_q4',
+ defaultWindows: 'ltx_video',
+ },
+ image: [
+ { id: 'dev', name: 'Flux 1 Dev', steps: 20, guidance: 3.5 },
+ { id: 'schnell', name: 'Flux 1 Schnell', steps: 4, guidance: 0 },
+ { id: 'flux2-klein-4b', name: 'Flux 2 Klein 4B', steps: 8, guidance: 3.5, broken: 'macos' },
+ { id: 'flux2-klein-9b', name: 'Flux 2 Klein 9B', steps: 8, guidance: 3.5, broken: 'macos' },
+ ],
+ textEncoders: [
+ { id: 'gemma-4bit', label: 'Gemma 3 12B 4-bit (default, ~7 GB)', repo: 'mlx-community/gemma-3-12b-it-4bit' },
+ { id: 'gemma-qat-4bit', label: 'Gemma 3 12B QAT 4-bit (better, ~8 GB, LM Studio)', repo: 'mlx-community/gemma-3-12b-it-qat-4bit', localPath: '~/.lmstudio/models/mlx-community/gemma-3-12b-it-qat-4bit' },
+ { id: 'gemma-bf16', label: 'Gemma 3 12B bf16 (best, ~24 GB, large download)', repo: 'mlx-community/gemma-3-12b-it-bf16' },
+ ],
+ selectedTextEncoder: 'gemma-4bit',
+};
+
+const expandHome = (p) => (p && p.startsWith('~') ? join(homedir(), p.slice(1)) : p);
+
+let cached = null;
+
+const ensureDir = (file) => {
+ const dir = dirname(file);
+ if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
+};
+
+const seedIfMissing = () => {
+ if (existsSync(REGISTRY_FILE)) return;
+ ensureDir(REGISTRY_FILE);
+ writeFileSync(REGISTRY_FILE, JSON.stringify(DEFAULT_REGISTRY, null, 2) + '\n');
+ console.log(`📝 Seeded media model registry: ${REGISTRY_FILE}`);
+};
+
+export const loadMediaModels = () => {
+ if (cached) return cached;
+ seedIfMissing();
+ const raw = readFileSync(REGISTRY_FILE, 'utf-8');
+ cached = JSON.parse(raw);
+ return cached;
+};
+
+const platformBroken = (broken) =>
+ broken === true || (typeof broken === 'string' && broken === (IS_WIN ? 'windows' : 'macos'));
+
+export const getVideoModels = () => {
+ const reg = loadMediaModels();
+ const list = IS_WIN ? (reg.video.windows || []) : (reg.video.macos || []);
+ return list.filter((m) => !platformBroken(m.broken));
+};
+
+export const getDefaultVideoModelId = () => {
+ const reg = loadMediaModels();
+ return IS_WIN ? reg.video.defaultWindows : reg.video.defaultMacos;
+};
+
+export const getImageModels = () => {
+ const reg = loadMediaModels();
+ return (reg.image || []).filter((m) => !platformBroken(m.broken));
+};
+
+// Resolve the active text encoder to a path mlx_video can pass via
+// --text-encoder-repo. Prefers `localPath` (e.g. an existing LM Studio
+// install) when it exists; otherwise returns the HF repo id which mlx_video
+// will resolve via the HF cache (downloading on first run).
+export const getTextEncoderRepo = () => {
+ const reg = loadMediaModels();
+ const id = reg.selectedTextEncoder;
+ const entry = (reg.textEncoders || []).find((t) => t.id === id);
+ if (!entry) {
+ console.log(`⚠️ Unknown selectedTextEncoder "${id}"; falling back to first entry`);
+ return reg.textEncoders?.[0]?.repo || 'mlx-community/gemma-3-12b-it-4bit';
+ }
+ if (entry.localPath) {
+ const expanded = expandHome(entry.localPath);
+ if (existsSync(expanded)) return expanded;
+ }
+ return entry.repo;
+};
+
+export const getTextEncoderEntries = () => {
+ const reg = loadMediaModels();
+ return (reg.textEncoders || []).map((t) => ({
+ id: t.id,
+ label: t.label,
+ repo: t.repo,
+ localPath: t.localPath ? expandHome(t.localPath) : null,
+ localAvailable: t.localPath ? existsSync(expandHome(t.localPath)) : false,
+ selected: t.id === reg.selectedTextEncoder,
+ }));
+};
diff --git a/server/routes/imageVideoModels.js b/server/routes/imageVideoModels.js
index 2084e8ff39..d9797835e9 100644
--- a/server/routes/imageVideoModels.js
+++ b/server/routes/imageVideoModels.js
@@ -15,6 +15,7 @@ import { homedir } from 'os';
import { join } from 'path';
import { asyncHandler, ServerError } from '../lib/errorHandler.js';
import { PATHS, formatBytes, dirSize } from '../lib/fileUtils.js';
+import { loadMediaModels } from '../lib/mediaModels.js';
const router = Router();
const HF_DEFAULT_HUB = join(homedir(), '.cache', 'huggingface', 'hub');
@@ -25,15 +26,25 @@ const HF_DEFAULT_HUB = join(homedir(), '.cache', 'huggingface', 'hub');
const HF_HUB_DIR = () =>
process.env.HF_HOME ? join(process.env.HF_HOME, 'hub') : HF_DEFAULT_HUB;
-// Friendly labels for our default model picks. Anything else is shown by repo id.
-const APP_MODELS = {
- 'black-forest-labs--FLUX.1-schnell': 'Flux 1 Schnell (Image)',
- 'black-forest-labs--FLUX.1-dev': 'Flux 1 Dev (Image)',
- 'notapalindrome--ltx2-mlx-av': 'LTX-2 Unified (Video)',
- 'notapalindrome--ltx23-mlx-av': 'LTX-2.3 Unified (Video)',
- 'notapalindrome--ltx23-mlx-av-q4': 'LTX-2.3 Distilled Q4 (Video)',
- 'mlx-community--gemma-3-12b-it-4bit': 'Gemma 3 12B 4-bit (Text Encoder)',
+// Friendly labels for known models, derived from the media-models registry.
+// HF stores cache dirs as `models--<org>--<name>` (slashes replaced with --).
+// Image gen still has a few well-known repos (Flux) that the registry tracks
+// only by short id, so we add those here as a small static fallback.
+const buildAppModels = () => {
+ const reg = loadMediaModels();
+ const out = {
+ 'black-forest-labs--FLUX.1-schnell': 'Flux 1 Schnell (Image)',
+ 'black-forest-labs--FLUX.1-dev': 'Flux 1 Dev (Image)',
+ };
+ const addEntry = (m, suffix) => {
+ if (!m.repo) return;
+ out[m.repo.replace(/\//g, '--')] = `${m.name} ${suffix}`;
+ };
+ for (const m of [...(reg.video.macos || []), ...(reg.video.windows || [])]) addEntry(m, '(Video)');
+ for (const t of (reg.textEncoders || [])) addEntry({ name: t.label, repo: t.repo }, '(Text Encoder)');
+ return out;
};
+const APP_MODELS = buildAppModels();
// Bound concurrent dirSize calls — each one spawns a `du` (or PowerShell)
// child, and a hub with 50+ models would otherwise create a process storm
diff --git a/server/routes/videoGen.js b/server/routes/videoGen.js
index 8ddf2143b2..f57fe0491d 100644
--- a/server/routes/videoGen.js
+++ b/server/routes/videoGen.js
@@ -59,6 +59,7 @@ const generateBodySchema = z.object({
steps: optionalNum(1, 200, 'steps'),
guidanceScale: optionalNum(0, 30, 'guidanceScale'),
seed: optionalNum(0, Number.MAX_SAFE_INTEGER, 'seed'),
+ imageStrength: optionalNum(0, 1, 'imageStrength'),
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(),
@@ -156,6 +157,7 @@ router.post('/', sourceImageUpload, asyncHandler(async (req, res) => {
uploadedTempPath,
lastImagePath,
mode: body.mode,
+ imageStrength: body.imageStrength,
});
res.json(result);
} catch (err) {
diff --git a/server/services/imageGen/local.js b/server/services/imageGen/local.js
index 1ee5e2a9a3..f2f24ebba4 100644
--- a/server/services/imageGen/local.js
+++ b/server/services/imageGen/local.js
@@ -23,20 +23,16 @@ import { ServerError } from '../../lib/errorHandler.js';
import { imageGenEvents } from '../imageGenEvents.js';
import { broadcastSse, attachSseClient as attachSse, closeJobAfterDelay, PYTHON_NOISE_RE } from '../../lib/sseUtils.js';
-const IS_MAC = process.platform === 'darwin';
const IS_WIN = process.platform === 'win32';
-// Model catalog. `broken: true` hides a model on a platform where it doesn't
-// run (e.g. Flux 2 Klein needs CUDA, so we mark it broken on macOS).
-export const IMAGE_MODELS = {
- dev: { id: 'dev', name: 'Flux 1 Dev', steps: 20, guidance: 3.5 },
- schnell: { id: 'schnell', name: 'Flux 1 Schnell', steps: 4, guidance: 0 },
- 'flux2-klein-4b': { id: 'flux2-klein-4b', name: 'Flux 2 Klein 4B', steps: 8, guidance: 3.5, broken: IS_MAC },
- 'flux2-klein-9b': { id: 'flux2-klein-9b', name: 'Flux 2 Klein 9B', steps: 8, guidance: 3.5, broken: IS_MAC },
-};
+// Catalog comes from data/media-models.json (see server/lib/mediaModels.js).
+// `broken: 'macos' | 'windows'` in the registry hides a model per-platform
+// (e.g. Flux 2 Klein needs CUDA, so it's broken on macOS).
+import { getImageModels } from '../../lib/mediaModels.js';
+
+export const IMAGE_MODELS = Object.fromEntries(getImageModels().map((m) => [m.id, m]));
-export const listImageModels = () =>
- Object.values(IMAGE_MODELS).filter((m) => !m.broken);
+export const listImageModels = () => getImageModels();
// Per-job clients: jobId -> { clients, status, meta, broadcast }
const jobs = new Map();
@@ -329,6 +325,7 @@ export async function deleteImage(filename) {
await unlink(join(PATHS.images, filename)).catch(() => {});
await unlink(join(PATHS.images, filename.replace('.png', '.metadata.json'))).catch(() => {});
await unlink(join(PATHS.images, `${filename}.metadata.json`)).catch(() => {});
+ console.log(`🗑️ Deleted image: ${filename}`);
return { ok: true };
}
diff --git a/server/services/videoGen/local.js b/server/services/videoGen/local.js
index c7e34ce538..fb3a470826 100644
--- a/server/services/videoGen/local.js
+++ b/server/services/videoGen/local.js
@@ -12,7 +12,7 @@
import { execFile, spawn } from 'child_process';
import { existsSync } from 'fs';
-import { unlink, writeFile } from 'fs/promises';
+import { unlink, rename, writeFile } from 'fs/promises';
import { join, basename, resolve as resolvePath, sep as PATH_SEP } from 'path';
import { tmpdir } from 'os';
import { randomUUID } from 'crypto';
@@ -21,26 +21,19 @@ import { ensureDir, PATHS, readJSONFile, atomicWrite } from '../../lib/fileUtils
import { ServerError } from '../../lib/errorHandler.js';
import { videoGenEvents } from './events.js';
import { broadcastSse, attachSseClient as attachSse, closeJobAfterDelay, PYTHON_NOISE_RE } from '../../lib/sseUtils.js';
+import { getVideoModels, getDefaultVideoModelId, getTextEncoderRepo } from '../../lib/mediaModels.js';
const execFileAsync = promisify(execFile);
const IS_WIN = process.platform === 'win32';
-// Platform-specific catalog. macOS = MLX/mlx_video, Windows = diffusers.
-const MODELS_MACOS = {
- ltx2_unified: { name: 'LTX-2 Unified (~42 GB)', repo: 'notapalindrome/ltx2-mlx-av', steps: 30, guidance: 3.0 },
- ltx23_unified: { name: 'LTX-2.3 Unified Beta (~48 GB)', repo: 'notapalindrome/ltx23-mlx-av', steps: 25, guidance: 3.0 },
- ltx23_distilled_q4: { name: 'LTX-2.3 Distilled Q4 (~22 GB)', repo: 'notapalindrome/ltx23-mlx-av-q4', steps: 25, guidance: 3.0 },
-};
-const MODELS_WINDOWS = {
- ltx_video: { name: 'LTX-Video 0.9.5 — T2V + I2V (~9.5 GB, auto-downloads)', steps: 25, guidance: 3.0 },
-};
-export const VIDEO_MODELS = IS_WIN ? MODELS_WINDOWS : MODELS_MACOS;
+// Catalog comes from data/media-models.json (see server/lib/mediaModels.js).
+// Cached as a Map at boot for O(1) lookup by id, matching the prior shape.
+export const VIDEO_MODELS = Object.fromEntries(getVideoModels().map((m) => [m.id, m]));
-export const listVideoModels = () =>
- Object.entries(VIDEO_MODELS).map(([id, m]) => ({ id, ...m }));
+export const listVideoModels = () => getVideoModels();
-export const defaultVideoModelId = () => IS_WIN ? 'ltx_video' : 'ltx23_distilled_q4';
+export const defaultVideoModelId = () => getDefaultVideoModelId();
const HISTORY_FILE = join(PATHS.data, 'video-history.json');
@@ -116,10 +109,31 @@ const generateThumbnail = async (videoPath, jobId) => {
});
};
+// mlx-video-with-audio writes mp4s with the moov atom at the END (cv2's
+// VideoWriter default). Browsers loading the gallery with preload="metadata"
+// then have to download the entire file before they can render the
+// first-frame poster, so video tiles flash black until clicked. Remuxing
+// with `-movflags +faststart` rewrites the moov atom to the front of the
+// file. Pure stream copy — no re-encoding, takes a few hundred ms even on
+// long clips. Idea borrowed from mrbizarro/phosphene's codec patch.
+const optimizeForStreaming = async (videoPath) => {
+ const ffmpeg = await findFfmpeg();
+ if (!ffmpeg) return;
+ const tmpPath = `${videoPath}.fs.mp4`;
+ const ok = await new Promise((resolve) => {
+ const proc = spawn(ffmpeg, ['-i', videoPath, '-c', 'copy', '-movflags', '+faststart', '-y', tmpPath], { stdio: 'ignore' });
+ proc.on('close', (code) => resolve(code === 0));
+ proc.on('error', () => resolve(false));
+ });
+ if (!ok) { await unlink(tmpPath).catch(() => {}); return; }
+ // Atomic single-syscall replace — no window where the file is missing.
+ await rename(tmpPath, videoPath).catch(() => {});
+};
+
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, lastImagePath, mode, outputPath }) => {
+const buildArgs = ({ pythonPath, modelId, model, prompt, negativePrompt, width, height, numFrames, fps, steps, guidance, seed, tiling, disableAudio, sourceImagePath, lastImagePath, mode, imageStrength, textEncoderRepo, 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];
@@ -140,30 +154,39 @@ const buildArgs = ({ pythonPath, modelId, model, prompt, negativePrompt, width,
'--cfg-scale', String(guidance),
'--output-path', outputPath,
'--model-repo', model.repo,
- '--text-encoder-repo', 'mlx-community/gemma-3-12b-it-4bit',
+ '--text-encoder-repo', textEncoderRepo,
'--tiling', tiling,
];
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. We only opt into the
- // last-frame-as-end-frame fallback when the caller explicitly asked for
- // FFLF and supplied ONLY a last image (no source) — gating on `mode`
- // matches the comment and avoids accidentally triggering the fallback for
- // an i2v request that happened to send a `lastImagePath`.
+
+ // Pick a single conditioning image and frame index. mlx_video.generate_av
+ // accepts only one --image so true FFLF (both keyframes) isn't supported;
+ // when only a last image was supplied for FFLF, we condition the LAST
+ // latent frame instead. --image-frame-idx is a LATENT index — LTX
+ // compression is `1 + (videoFrames - 1) / 8`, so passing a raw video
+ // frame count silently fails the conditioning shape check.
+ let condImage = sourceImagePath;
+ let condFrameIdx = null;
if (mode === 'fflf' && lastImagePath && !sourceImagePath) {
- args.push('--image', lastImagePath, '--image-frame-idx', String(Math.max(0, numFrames - 1)));
+ condImage = lastImagePath;
+ condFrameIdx = Math.max(0, Math.floor((Number(numFrames) - 1) / 8));
} else if (mode === 'fflf' && 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`);
}
+ if (condImage) {
+ args.push('--image', condImage);
+ if (condFrameIdx != null) args.push('--image-frame-idx', String(condFrameIdx));
+ // --image-strength uses mask = 1.0 - strength: 1.0 preserves the source
+ // latent, 0.0 fully denoises (= T2V). mlx_video's help text describes
+ // this inverted. Omit when no caller value so mlx_video's default (1.0)
+ // applies.
+ if (imageStrength != null) args.push('--image-strength', String(imageStrength));
+ }
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, mode = 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, imageStrength = 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
@@ -184,6 +207,9 @@ export async function generateVideo({ pythonPath, prompt, negativePrompt = '', m
const actualSeed = seed != null && seed !== '' ? Number(seed) : Math.floor(Math.random() * 2147483647);
const actualSteps = steps ? Number(steps) : model.steps;
const actualGuidance = guidanceScale != null && guidanceScale !== '' ? Number(guidanceScale) : model.guidance;
+ // Caller may pass null/'' to use mlx_video's default (1.0 = preserve source).
+ const actualImageStrength = imageStrength != null && imageStrength !== '' ? Number(imageStrength) : null;
+ const actualTextEncoderRepo = getTextEncoderRepo();
const parsedNumFrames = Number(numFrames);
const parsedFps = Number(fps);
@@ -226,7 +252,7 @@ export async function generateVideo({ pythonPath, prompt, negativePrompt = '', m
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, lastImagePath: resolvedLastImage, mode, 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, mode, imageStrength: actualImageStrength, textEncoderRepo: actualTextEncoderRepo, 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 });
@@ -239,6 +265,14 @@ export async function generateVideo({ pythonPath, prompt, negativePrompt = '', m
delete childEnv.PYTHONPATH;
const proc = spawn(bin, args, { env: childEnv, stdio: ['ignore', 'pipe', 'pipe'] });
activeProcess = proc;
+ // Hold a sleep-prevention lock for the lifetime of the python child, so a
+ // 90s+ render doesn't get aborted by display/system sleep on a laptop. -w
+ // makes caffeinate self-exit when our pid does, so no manual cleanup is
+ // needed and a server crash mid-render still releases the assertion.
+ // macOS-only — `caffeinate` doesn't exist on Windows/Linux.
+ if (!IS_WIN && proc.pid) {
+ spawn('caffeinate', ['-i', '-w', String(proc.pid)], { stdio: 'ignore', detached: false }).on('error', () => {});
+ }
// Without an 'error' handler, a missing/non-executable pythonPath would
// crash the server with an unhandled error event.
proc.on('error', (err) => {
@@ -259,46 +293,61 @@ export async function generateVideo({ pythonPath, prompt, negativePrompt = '', m
let outputBuf = '';
+ // Returns true when the line was a known progress/status message (already
+ // broadcast over SSE) or python-noise — caller should suppress logging.
+ // Returns false for unhandled lines that are worth raw-logging.
const handleLine = (raw) => {
const line = raw.trim();
- if (!line || PYTHON_NOISE_RE.test(line)) return;
+ if (!line) return true;
+ if (PYTHON_NOISE_RE.test(line)) return true;
if (line.startsWith('STATUS:')) {
broadcastSse(job, { type: 'status', message: line.slice(7) });
- } else if (line.startsWith('STAGE:')) {
+ return true;
+ }
+ if (line.startsWith('STAGE:')) {
const parts = line.split(':');
const step = parseInt(parts[3], 10) || 0;
const total = parseInt(parts[4], 10) || 1;
broadcastSse(job, { type: 'progress', progress: step / total, message: parts.slice(5).join(':') });
videoGenEvents.emit('progress', { generationId: jobId, progress: step / total, step, totalSteps: total });
- } else if (line.startsWith('DOWNLOAD:')) {
+ return true;
+ }
+ if (line.startsWith('DOWNLOAD:')) {
broadcastSse(job, { type: 'status', message: `Downloading model... ${line.slice(9)}` });
- } else {
- const m = line.match(/(\d+)%\|/);
- if (m) {
- const pct = parseInt(m[1], 10) / 100;
- broadcastSse(job, { type: 'progress', progress: pct, message: line });
- videoGenEvents.emit('progress', { generationId: jobId, progress: pct });
- }
+ return true;
}
+ const m = line.match(/(\d+)%\|/);
+ if (m) {
+ const pct = parseInt(m[1], 10) / 100;
+ broadcastSse(job, { type: 'progress', progress: pct, message: line });
+ videoGenEvents.emit('progress', { generationId: jobId, progress: pct });
+ return true;
+ }
+ return false;
};
proc.stdout.on('data', (chunk) => {
outputBuf += chunk.toString();
const lines = outputBuf.split('\n');
outputBuf = lines.pop();
- for (const line of lines) {
- if (!line.trim()) continue;
- // mlx_video emits a single JSON line on stdout when finished —
- // capture it for the metadata sidecar.
+ for (const raw of lines) {
+ const line = raw.trim();
+ if (!line) continue;
+ // mlx_video emits one JSON line on stdout when finished — capture it
+ // for the result metadata; otherwise raw-log so we can debug failures.
try {
- const parsed = JSON.parse(line.trim());
+ const parsed = JSON.parse(line);
if (parsed.video_path) job.resultJson = parsed;
+ continue;
} catch { /* not JSON */ }
+ console.log(`🐍-out [${jobId.slice(0, 8)}] ${line}`);
}
});
proc.stderr.on('data', (chunk) => {
- for (const line of chunk.toString().split(/[\n\r]+/)) handleLine(line);
+ for (const raw of chunk.toString().split(/[\n\r]+/)) {
+ if (!handleLine(raw)) console.log(`🐍 [${jobId.slice(0, 8)}] ${raw.trim()}`);
+ }
});
proc.on('close', async (code, signal) => {
@@ -322,6 +371,7 @@ export async function generateVideo({ pythonPath, prompt, negativePrompt = '', m
videoGenEvents.emit('failed', { generationId: jobId, error: reason });
} else {
job.status = 'complete';
+ await optimizeForStreaming(outputPath);
const thumbnail = await generateThumbnail(outputPath, jobId);
const history = await loadHistory();
history.unshift({ ...meta, thumbnail });
@@ -353,11 +403,26 @@ export async function extractLastFrame(historyId) {
await ensureDir(PATHS.images);
const frameFilename = `lastframe-${item.id}.png`;
const framePath = join(PATHS.images, frameFilename);
+ // Cache hit: ffmpeg-extracted frames are deterministic for a given video,
+ // so a file already on disk is reusable. UI clicks "Continue" repeatedly
+ // (palette → continue, gallery → continue, etc.) and re-extracting on
+ // every click was wasting 1–2s per click + spawning ffmpeg children.
+ if (existsSync(framePath)) {
+ return { filename: frameFilename, path: `/data/images/${frameFilename}` };
+ }
return new Promise((resolve, reject) => {
- const proc = spawn(ffmpeg, ['-sseof', '-0.1', '-i', videoPath, '-vframes', '1', '-q:v', '2', '-y', framePath], { stdio: 'ignore' });
+ // -sseof -1.0 seeks 1s before end. The previous -0.1 was too tight on
+ // videos with audio (B-frames + AV mux push the last keyframe earlier
+ // than 100 ms from EOF), and ffmpeg silently returned 0 frames while
+ // sometimes still exiting 0 — leaving a phantom-success log + missing
+ // file. The output file gets a -update 1 flag so ffmpeg overwrites
+ // any partial file from a prior failed run instead of erroring.
+ const proc = spawn(ffmpeg, ['-sseof', '-1.0', '-i', videoPath, '-update', '1', '-vframes', '1', '-q:v', '2', '-y', framePath], { stdio: 'ignore' });
proc.on('close', (code) => {
- if (code !== 0) return reject(new ServerError('Failed to extract last frame', { status: 500, code: 'FFMPEG_FAILED' }));
+ if (code !== 0 || !existsSync(framePath)) {
+ return reject(new ServerError('Failed to extract last frame', { status: 500, code: 'FFMPEG_FAILED' }));
+ }
console.log(`🎞️ Extracted last frame: ${frameFilename}`);
resolve({ filename: frameFilename, path: `/data/images/${frameFilename}` });
});
@@ -462,5 +527,6 @@ export async function deleteHistoryItem(id) {
if (thumbFile) await unlink(thumbFile).catch(() => {});
}
await saveHistory(history.filter((h) => h.id !== id));
+ console.log(`🗑️ Deleted video: ${item.filename}`);
return { ok: true };
}