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): coerce wrong-type registry fields + validate frame cache size

Adam Eivyd86efa16440f
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 5551fecae1..880f92dd1a 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -26,7 +26,8 @@
- **"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.
-- **Media model registry tolerates partial user edits.** `loadMediaModels()` now merges parsed `data/media-models.json` over the built-in defaults so a registry missing top-level keys (e.g. `{}` or no `video`) doesn't crash server boot at module import. The loader also catches read errors (permissions, broken symlink) — not just JSON parse — falling back to defaults so a registry I/O problem can't take down startup. `getDefaultVideoModelId()` validates the configured default against the platform's available list — typos or `broken`-flagged ids fall back to the first available model with a warning instead of surfacing as "Unknown video model" in the UI. `getTextEncoderRepo()` validates that the resolved entry has a non-empty repo string before passing it to mlx_video. macOS video gen now also validates `model.repo` exists before spawning, surfacing a 500 with a clear error rather than passing `undefined` into spawn args.
+- **Media model registry tolerates partial user edits.** `loadMediaModels()` now merges parsed `data/media-models.json` over the built-in defaults so a registry missing top-level keys (e.g. `{}` or no `video`) doesn't crash server boot at module import. The loader also catches read errors (permissions, broken symlink) — not just JSON parse — falling back to defaults so a registry I/O problem can't take down startup. Wrong-type fields are coerced back to defaults too (e.g. `image: {}` or `video.macos: "ltx"` → built-in array), so consumers like `getImageModels()` / `buildAppModels()` can't throw at import-time on parseable-but-wrong-shape JSON. `getDefaultVideoModelId()` validates the configured default against the platform's available list — typos or `broken`-flagged ids fall back to the first available model with a warning instead of surfacing as "Unknown video model" in the UI. `getTextEncoderRepo()` validates that the resolved entry has a non-empty repo string before passing it to mlx_video. macOS video gen now also validates `model.repo` exists before spawning, surfacing a 500 with a clear error rather than passing `undefined` into spawn args.
+- **Last-frame cache validates non-zero size.** A prior ffmpeg crash could leave a 0-byte placeholder at `data/images/lastframe-<videoId>.png`, and the cache hit (`existsSync(framePath)`) would serve it forever as a broken image. `extractLastFrame` now `statSync`s the cached file and falls through to re-extract when it's missing or zero bytes; failed re-extractions also unlink the partial file so the next call retries instead of inheriting the broken cache.
- **Faststart remux works on Windows without risking the rendered video.** `optimizeForStreaming()` did an in-place `fs.rename(tmpPath, videoPath)` which fails on Windows when the destination already exists. The Windows replace strategy now moves the original aside to a `.bak.<uuid>` first, installs the optimized file, and restores the backup on any failure — so a transient rename failure (file lock, AV scan, permissions) skips faststart instead of destroying the rendered video. POSIX still uses the single-syscall atomic replace.
- **`caffeinate` sleep-prevention is now strictly macOS-only.** Previous gate (`!IS_WIN`) would also fire on Linux and emit a pointless ENOENT every render. Tightened to `process.platform === 'darwin'`.
- **`scripts/setup-image-video.sh` removes the wrong package before install.** The PyPI package `mlx_video` (unrelated video-loading utility) shadows the LTX backend's `import mlx_video` if previously installed. The script now `pip uninstall --yes mlx_video` before installing `mlx-video-with-audio>=0.1.35`, so upgraders aren't left in an ambiguous state.
diff --git a/server/lib/mediaModels.js b/server/lib/mediaModels.js
index 54b8ae6f7b..66bf165d67 100644
--- a/server/lib/mediaModels.js
+++ b/server/lib/mediaModels.js
@@ -81,14 +81,29 @@ const seedIfMissing = () => {
// Merge user-edited registry over DEFAULT_REGISTRY so missing top-level keys
// (e.g. someone deletes `video` or saves `{}`) don't blow up consumers that
-// assume `reg.video.macos`. We don't deep-merge arrays — if the user defines
-// `video.macos`, that's their list, full stop.
+// assume `reg.video.macos`. We also coerce array-shaped fields back to the
+// defaults when the user's JSON is parseable but wrong-shape (e.g.
+// `image: {}` or `video.macos: "ltx"`) — otherwise getImageModels /
+// getVideoModels / buildAppModels would throw at module import-time and
+// take down server startup. If a user supplies a real array, that's their
+// list, full stop — we don't deep-merge entries.
+const isPlainObject = (v) => !!v && typeof v === 'object' && !Array.isArray(v);
+const arrayOrDefault = (v, fallback) => (Array.isArray(v) ? v : fallback);
+
const normalizeRegistry = (parsed) => {
- const safe = parsed && typeof parsed === 'object' ? parsed : {};
+ const safe = isPlainObject(parsed) ? parsed : {};
+ const safeVideo = isPlainObject(safe.video) ? safe.video : {};
return {
...DEFAULT_REGISTRY,
...safe,
- video: { ...DEFAULT_REGISTRY.video, ...(safe.video || {}) },
+ image: arrayOrDefault(safe.image, DEFAULT_REGISTRY.image),
+ textEncoders: arrayOrDefault(safe.textEncoders, DEFAULT_REGISTRY.textEncoders),
+ video: {
+ ...DEFAULT_REGISTRY.video,
+ ...safeVideo,
+ macos: arrayOrDefault(safeVideo.macos, DEFAULT_REGISTRY.video.macos),
+ windows: arrayOrDefault(safeVideo.windows, DEFAULT_REGISTRY.video.windows),
+ },
};
};
diff --git a/server/lib/mediaModels.test.js b/server/lib/mediaModels.test.js
index 657af5bc0e..e615e6a085 100644
--- a/server/lib/mediaModels.test.js
+++ b/server/lib/mediaModels.test.js
@@ -149,6 +149,26 @@ describe('mediaModels registry', () => {
expect(typeof getDefaultVideoModelId()).toBe('string');
});
+ it('coerces wrong-type fields back to defaults', async () => {
+ // Parseable JSON but with non-array values where the consumers expect
+ // arrays — without coercion, getImageModels()/getVideoModels() throw at
+ // module import-time.
+ writeFileSync(registryFile, JSON.stringify({
+ video: { macos: 'ltx', windows: { id: 'oops' } },
+ image: {},
+ textEncoders: 'gemma',
+ selectedTextEncoder: 'gemma-bf16',
+ }));
+ const { loadMediaModels, getVideoModels, getImageModels } = await import('./mediaModels.js');
+ const reg = loadMediaModels();
+ expect(Array.isArray(reg.video.macos)).toBe(true);
+ expect(Array.isArray(reg.video.windows)).toBe(true);
+ expect(Array.isArray(reg.image)).toBe(true);
+ expect(Array.isArray(reg.textEncoders)).toBe(true);
+ expect(() => getVideoModels()).not.toThrow();
+ expect(() => getImageModels()).not.toThrow();
+ });
+
it('normalizes an empty object registry by merging defaults', async () => {
writeFileSync(registryFile, JSON.stringify({}));
const { loadMediaModels } = await import('./mediaModels.js');
diff --git a/server/services/videoGen/local.js b/server/services/videoGen/local.js
index 011e7ece0b..3835ebd6aa 100644
--- a/server/services/videoGen/local.js
+++ b/server/services/videoGen/local.js
@@ -11,7 +11,7 @@
*/
import { execFile, spawn } from 'child_process';
-import { existsSync } from 'fs';
+import { existsSync, statSync } from 'fs';
import { unlink, rename, writeFile } from 'fs/promises';
import { join, basename, resolve as resolvePath, sep as PATH_SEP } from 'path';
import { tmpdir } from 'os';
@@ -442,8 +442,15 @@ export async function extractLastFrame(historyId) {
// 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.
+ // Validate non-zero size — a prior ffmpeg crash could leave a 0-byte
+ // placeholder, which would otherwise be served as a broken image
+ // forever. statSync errors fall through to re-extraction.
if (existsSync(framePath)) {
- return { filename: frameFilename, path: `/data/images/${frameFilename}` };
+ const cached = statSync(framePath, { throwIfNoEntry: false });
+ if (cached && cached.size > 0) {
+ return { filename: frameFilename, path: `/data/images/${frameFilename}` };
+ }
+ await unlink(framePath).catch(() => {});
}
return new Promise((resolve, reject) => {
@@ -454,8 +461,13 @@ export async function extractLastFrame(historyId) {
// 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 || !existsSync(framePath)) {
+ proc.on('close', async (code) => {
+ const written = existsSync(framePath) ? statSync(framePath, { throwIfNoEntry: false }) : null;
+ if (code !== 0 || !written || written.size === 0) {
+ // A 0-byte file is a partial extraction, not a cache-worthy result —
+ // delete it so the next call retries instead of returning a broken
+ // image from the cache hit above.
+ if (written && written.size === 0) await unlink(framePath).catch(() => {});
return reject(new ServerError('Failed to extract last frame', { status: 500, code: 'FFMPEG_FAILED' }));
}
console.log(`🎞️ Extracted last frame: ${frameFilename}`);