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
fix(video-gen): cross-platform hardening + registry I/O + spawn-arg validation
Adam Eivy2803f847451f
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 614074b515..fbe4d9f9b8 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -26,7 +26,10 @@- **"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. `getDefaultVideoModelId()` also 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.+- **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.+- **Faststart remux works on Windows.** `optimizeForStreaming()` did an in-place `fs.rename(tmpPath, videoPath)` which fails on Windows when the destination already exists, so every successful render would log a warning and skip the optimization. Now unlinks the destination first on Windows (non-atomic, but preserves faststart) and keeps the single-syscall atomic replace on POSIX.+- **`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.- **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.diff --git a/scripts/setup-image-video.sh b/scripts/setup-image-video.shindex 81042abbb6..cf864d085d 100755--- a/scripts/setup-image-video.sh+++ b/scripts/setup-image-video.sh@@ -53,6 +53,10 @@ if [[ "$INSTALL_VIDEO" == "1" ]]; then# 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.+ # Both packages provide an `import mlx_video` module, so a prior install+ # of the wrong one shadows the right one. Uninstall first to remove the+ # ambiguity for users upgrading from earlier setup-image-video.sh runs.+ "$PYTHON_BIN" -m pip uninstall --yes mlx_video >/dev/null 2>&1 || true"$PYTHON_BIN" -m pip install --upgrade --user \mlx \mlx_vlm \diff --git a/server/lib/mediaModels.js b/server/lib/mediaModels.jsindex 7d864caf31..54b8ae6f7b 100644--- a/server/lib/mediaModels.js+++ b/server/lib/mediaModels.js@@ -95,17 +95,16 @@ const normalizeRegistry = (parsed) => {export const loadMediaModels = () => {if (cached) return cached;seedIfMissing();- // Catch parse failures so a malformed user edit doesn't crash server boot- // — the loader is invoked at module import-time from videoGen/imageGen, so- // an exception here aborts startup. Fall back to the in-memory defaults- // and surface the error in logs so the operator can fix the file.- const raw = readFileSync(REGISTRY_FILE, 'utf-8');- let parsed;+ // Catch read AND parse failures — both can happen at module import-time+ // (videoGen/imageGen import this synchronously), so an unhandled throw+ // here aborts server startup. Permissions, broken symlink, transient I/O+ // all surface from readFileSync; malformed JSON from JSON.parse.+ let parsed = DEFAULT_REGISTRY;try {+ const raw = readFileSync(REGISTRY_FILE, 'utf-8');parsed = JSON.parse(raw);} catch (err) {- console.log(`⚠️ Failed to parse ${REGISTRY_FILE} (${err.message}) — using built-in defaults`);- parsed = DEFAULT_REGISTRY;+ console.log(`⚠️ Failed to load ${REGISTRY_FILE} (${err.message}) — using built-in defaults`);}cached = normalizeRegistry(parsed);return cached;@@ -146,18 +145,29 @@ export const getImageModels = () => {// --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).+const FALLBACK_TEXT_ENCODER_REPO = 'mlx-community/gemma-3-12b-it-4bit';+const isNonEmptyString = (v) => typeof v === 'string' && v.length > 0;+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';+ const firstRepo = reg.textEncoders?.[0]?.repo;+ return isNonEmptyString(firstRepo) ? firstRepo : FALLBACK_TEXT_ENCODER_REPO;}if (entry.localPath) {const expanded = expandHome(entry.localPath);if (existsSync(expanded)) return expanded;}+ // Spawn args must be non-empty strings — a malformed registry entry+ // (missing/empty `repo`) would otherwise reach mlx_video as undefined and+ // surface as a confusing TypeError or downstream CLI error.+ if (!isNonEmptyString(entry.repo)) {+ console.log(`⚠️ Text encoder "${id}" has no repo; falling back to "${FALLBACK_TEXT_ENCODER_REPO}"`);+ return FALLBACK_TEXT_ENCODER_REPO;+ }return entry.repo;};diff --git a/server/lib/mediaModels.test.js b/server/lib/mediaModels.test.jsindex 3cd5e775d7..657af5bc0e 100644--- a/server/lib/mediaModels.test.js+++ b/server/lib/mediaModels.test.js@@ -112,7 +112,7 @@ describe('mediaModels registry', () => {const reg = loadMediaModels();expect(reg.video).toBeDefined();expect(reg.selectedTextEncoder).toBe('gemma-bf16');- expect(logSpy).toHaveBeenCalledWith(expect.stringContaining('Failed to parse'));+ expect(logSpy).toHaveBeenCalledWith(expect.stringContaining('Failed to load'));logSpy.mockRestore();});@@ -183,6 +183,34 @@ describe('mediaModels registry', () => {logSpy.mockRestore();});+ it('getTextEncoderRepo falls back when entry has no repo string', async () => {+ writeFileSync(registryFile, JSON.stringify({+ video: { macos: [], windows: [], defaultMacos: 'x', defaultWindows: 'x' },+ image: [],+ textEncoders: [{ id: 't', label: 't' }], // no repo field+ selectedTextEncoder: 't',+ }));+ const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {});+ const { getTextEncoderRepo } = await import('./mediaModels.js');+ const repo = getTextEncoderRepo();+ expect(typeof repo).toBe('string');+ expect(repo.length).toBeGreaterThan(0);+ logSpy.mockRestore();+ });++ it('falls back to defaults when registry file read fails (e.g., permissions)', async () => {+ // Point at a path that exists as a directory — readFileSync will throw+ // EISDIR rather than parse-fail, exercising the read error path.+ process.env.PORTOS_MEDIA_MODELS_FILE = tmpDir;+ const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {});+ const { loadMediaModels } = await import('./mediaModels.js');+ const reg = loadMediaModels();+ expect(reg.video).toBeDefined();+ expect(reg.selectedTextEncoder).toBe('gemma-bf16');+ expect(logSpy).toHaveBeenCalledWith(expect.stringContaining('Failed to load'));+ logSpy.mockRestore();+ });+it('getDefaultVideoModelId skips broken-on-platform models when falling back', async () => {const platformKey = process.platform === 'win32' ? 'windows' : 'macos';const here = process.platform === 'win32' ? 'windows' : 'macos';diff --git a/server/services/videoGen/local.js b/server/services/videoGen/local.jsindex 58ed712e35..5d78a8eddd 100644--- a/server/services/videoGen/local.js+++ b/server/services/videoGen/local.js@@ -126,10 +126,14 @@ const optimizeForStreaming = async (videoPath) => {proc.on('error', () => resolve(false));});if (!ok) { await unlink(tmpPath).catch(() => {}); return; }- // Atomic single-syscall replace — no window where the file is missing.- // If rename fails (cross-device, permissions, file-in-use) we'd otherwise- // leak the tmp file silently and slowly fill data/videos with .fs.mp4s.+ // POSIX rename atomically replaces an existing dest in one syscall. On+ // Windows, fs.rename fails when the destination already exists, so every+ // successful render would log a warning and skip faststart. Unlink first+ // there — non-atomic (brief window with no file) but preserves the+ // optimization. If the eventual rename still fails, clean up the tmp file+ // so we don't slowly fill data/videos with .fs.mp4 leaks.try {+ if (IS_WIN) await unlink(videoPath).catch((err) => { if (err?.code !== 'ENOENT') throw err; });await rename(tmpPath, videoPath);} catch (err) {await unlink(tmpPath).catch(() => {});@@ -202,6 +206,12 @@ export async function generateVideo({ pythonPath, prompt, negativePrompt = '', mconst model = VIDEO_MODELS[modelId];if (!model) throw new ServerError(`Unknown video model: ${modelId}`, { status: 400, code: 'VALIDATION_ERROR' });+ // macOS/mlx_video requires a HuggingFace repo id — Windows doesn't (the+ // diffusers wrapper hardcodes Lightricks/LTX-Video). A user-edited registry+ // entry missing `repo` would otherwise pass `undefined` into spawn args.+ if (!IS_WIN && (typeof model.repo !== 'string' || model.repo.length === 0)) {+ throw new ServerError(`Video model "${modelId}" is missing the required \`repo\` field in data/media-models.json`, { status: 500, code: 'VIDEO_MODEL_MISCONFIGURED' });+ }await ensureDir(PATHS.videos);await ensureDir(PATHS.videoThumbnails);@@ -276,8 +286,9 @@ export async function generateVideo({ pythonPath, prompt, negativePrompt = '', m// 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) {+ // macOS-only — `caffeinate` is a darwin binary; gating on `!IS_WIN` would+ // also fire on Linux and emit a pointless ENOENT every render.+ if (process.platform === 'darwin' && 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