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([strip-malloc-env-ffmpeg-children]): sanitize ffmpeg child env
[._.]/ Adam Eivye9a24b686e2f
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex dfe0bcbe1a..09d78d26e7 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -23,6 +23,7 @@## Fixed+- **[strip-malloc-env-ffmpeg-children] Video workflows now suppress macOS malloc-debug noise from ffmpeg too.** Pinokio-launched installs can export `Malloc*` debug variables that make child processes print `MallocStackLogging` warnings and bury real render progress. PortOS now builds child-process environments through one shared sanitizer and applies it to ffmpeg/ffprobe children used by thumbnails, streaming optimization, upscaling, timeline renders, device capture, last-frame extraction, and video stitching, so video logs stay focused on actual work and errors.- **[catalog-ref-deletion-tombstones] Catalog ingredient unlinks now propagate to federation peers.** Unlinking an ingredient from a universe / series / issue used to hard-DELETE the `catalog_ingredient_refs` row with no `sync_sequence` bump and no tombstone — peers that already pulled the link kept it forever, leaving the "Appears in" panel stale across the federation. The ref table now soft-deletes (new `deleted` / `deleted_at` columns + an UPDATE trigger that bumps `sync_sequence` on delete/revive), `linkIngredientToRef` revives a tombstoned row on re-link, and `upsertRefFromPeer` mirrors remote deletes via `ON CONFLICT DO UPDATE`. `PORTOS_SCHEMA_VERSIONS.catalog` bumps from 1 to 2 so older peers can't push a v1-shaped payload that would silently miss tombstones.- **[civitai-hidream-qwen-baseModels] Civitai LoRA suggestions now include HiDream and Qwen.** Both runner families existed in `RUNNER_FAMILIES` but were missing from the Civitai `baseModels` search map and the LoRA Manager UI — so every page load logged `Unknown runner family for Civitai search: hidream` / `qwen`, neither family got a "Top for …" section, and any HiDream/Qwen LoRA installed via URL ended up with `runnerFamily=null` (broken compat filter). The two families now map to Civitai's `HiDream` / `Qwen` baseModel strings and render alongside Flux 1, Flux 2, Z-Image, and ERNIE in the suggestions panel.- **Creative Director long sessions stay fast.** Per-scene render orchestration no longer slows down as a project accumulates more scenes — previously a project could degrade from ~3.5 minutes per scene to 10–30 minutes after a long run, because every render reread and rewrote the full per-project run history as that history grew unbounded. The Runs tab now shows up to 200 of the most recent run entries per project; older completed/failed runs are dropped automatically while every in-flight task is always preserved.diff --git a/PLAN.md b/PLAN.mdindex 79ae11f1b3..9b0fd9eae6 100644--- a/PLAN.md+++ b/PLAN.md@@ -38,7 +38,6 @@ _Batch-cleared 2026-05-25: 23 Next Up items shipped together via parallel sub-ag- [ ] [mediacard-use-mediaimage-for-syncing-assets] **`MediaCard.jsx` grid thumbnails still use a raw `<img src={previewUrl}>`.** Same peer-sync placeholder/live-swap gap that `[peer-sync-medialightbox-use-mediaimage-for-syncing-assets]` fixed for the lightbox — `client/src/components/media/MediaCard.jsx` (~line 42) doesn't get the "Syncing" placeholder or the `peerSync:asset-arrived` atomic swap. Swap the raw `<img>` for `MediaImage`. Surfaced by that item's cross-check during the batch-clear (2026-05-25); was outside its stated scope.- [ ] [chrome-canary-followups] **Hardening for the custom-Chrome-binary feature (xhigh code-review 2026-05-25).** _DONE in the v2.10.0 release review: (b) both `spawn()` calls now have `.on('error', …)` listeners; (d) `browser/server.js#loadConfig` now try/catches the `JSON.parse`; (e) `setup-browser.js#loadConfig` now warns + returns `null` and `applyCanaryToConfig` skips the save when the existing config is unreadable; (f) top-level `runCanarySetup()` is now `.catch()`-wrapped. (c) is tracked separately in `[setup-browser-canary-headless]`. Remaining: (a), (g)–(o)._ **High-severity:** (a) On macOS headed mode (the default), `browser/server.js:208` uses `macAppBundle` only and silently ignores `chromePath` — a UI user who fills in `chromePath` for Canary/Chromium/Brave but leaves `macAppBundle` empty gets stock Chrome and the log misreports the binary; couple the two fields in the UI (or auto-derive `macAppBundle` from `chromePath` when the latter is inside a `.app`). (b) Neither `spawn(chromePath, …)` (line 216) nor `spawn('/usr/bin/open', …)` (line 208) has an `.on('error', …)` listener — a typo in `chromePath` emits 'error' with no listener → `uncaughtException` → portos-browser PM2 child crashes and restart-loops. (c) `scripts/setup-browser.js#applyCanaryToConfig` writes `chromePath` + `macAppBundle` but doesn't flip `headless: false`; combined with the seed default of `headless: true` (`data.reference/browser-config.json`), a fresh install accepting Canary runs Canary invisibly. (d) `browser/server.js#loadConfig` does bare `JSON.parse(raw)` with no try/catch — combined with setup-browser's non-atomic `writeFileSync` and the `cachedConfig` race, a partial-file write crashes the supervisor on next start (PM2 restart-loop forever). **Medium-severity:** (e) `setup-browser.js#loadConfig` silently catches all JSON parse errors and returns `{}`, then `applyCanaryToConfig` saves `{chromePath, macAppBundle}` only — wiping every other user-customized key. (f) Top-level `await runCanarySetup()` has no try/catch — any EACCES on data/browser-config.json aborts `npm run setup` / `update.sh` at what was previously a no-op step. (g) Idempotency guard only checks `chromePath`: users who decline get re-prompted on every update, and users who set only `macAppBundle` keep getting re-prompted. (h) `PORTOS_USE_CANARY` only matches literal `'0'`/`'false'` (opt-out) or `'1'`/`'true'` (opt-in) — `'no'`/`'off'`/`'yes'`/`'on'`/`'True'` fall through both branches. (i) `spawnSync(install.cmd, …, { stdio: 'inherit' })` for brew/winget can hang on a sudo password prompt under non-TTY + `PORTOS_USE_CANARY=1` (update.sh stalls). (j) `cachedConfig` in `browserService.js` is stale relative to setup-browser's direct write — GET /api/browser/config returns pre-update values until process restart. (k) `saveConfig` uses bare `writeFileSync` — switch to the canonical `atomicWrite` pattern (`server/lib/fileUtils.js`). **Low-severity:** (l) `spawnSync` failure-status check `result.status !== 0` treats `status: null` (spawn-failure / signal kill) identically to a non-zero exit and never logs `result.error` — masks ENOENT/EPERM/SIGKILL. (m) `optionalPath` Zod schema accepts any string up to 1024 chars; no `.app`/`.exe` sanity check — user pastes the bundle into `chromePath` → spawn() EISDIR. (n) `launchBrowser`'s reuse-existing-Chrome early-return (line 167) fires BEFORE `headlessMode = config.headless === true` (line 170), leaving the module-level default `false` after a PM2 restart that reuses Chrome — /health reports wrong mode (pre-existing, but in a function touched by this change). (o) `detectCanary` on macOS only checks `/Applications/...`; misses per-user `~/Applications/Google Chrome Canary.app` installs (corporate Macs, `HOMEBREW_CASK_OPTS=--appdir=$HOME/Applications`).-- [ ] [strip-malloc-env-ffmpeg-children] **Extend `stripDebugMallocEnv` coverage to ffmpeg child spawns if Pinokio users still see the warning.** The Malloc-strip PR (`[ref-watch-phosphene-strip-malloc-subprocess-env]`) routed every direct Node→Python spawn through `stripDebugMallocEnv`, but ffmpeg children (`server/lib/ffmpeg.js:81`, the ffmpeg/ffprobe calls in `server/services/mediaService.js`, `server/services/videoTimeline/local.js`, and the post-render thumbnail/optimize/upscale paths in `server/services/videoGen/local.js`) still inherit `process.env`. ffmpeg on macOS links libSystem (which includes libmalloc) so it can in principle emit the same `MallocStackLogging: can't turn off…` line — unverified whether it actually does. Trigger: if Pinokio-launched installs still report stderr noise after the Python-spawn fix lands, wrap each ffmpeg spawn `env` the same way. Surfaced by reuse-review subagent during the original PR (2026-05-29).- [ ] [mediajobqueue-shared-provider-kind-predicate] **Share a `getJobProviderKind(job)` predicate between `getGenModuleForJob` and `resolveLiveParams` in `server/services/mediaJobQueue/index.js`.** Both now encode the same `video | image+codex | image+local` partition by hand (`getGenModuleForJob` at ~line 109, `resolveLiveParams.usesLocalPython` at ~line 122). A shared `getJobProviderKind(job) → 'video-local' | 'image-local' | 'image-codex' | null` would let both branches derive from one predicate and extend cleanly to future providers. Surfaced by reuse-review during the resolveLiveParams extract (2026-05-29); deferred because today's duplication is two lines and the seam is still small.- [ ] [ref-watch-phosphene-teacache-extend-a2v-denoise] **TeaCache through Extend + A2V Stage-1 denoise loops.** From `reference-watch` review of phosphene (commits `ea98aad8` + `17be2a79`, 2026-05-28). PortOS's `scripts/generate_ltx2.py` invokes `ExtendPipeline.extend_from_video(...)` (~line 378) and `AudioToVideoPipeline.generate_and_save(...)` (~line 417) directly without passing a TeaCache controller, so the slowest two modes in the panel run full denoise. Phosphene reuses the existing Stage-1 calibration (`ti2vid_two_stages._build_teacache_controller(n_steps, thresh=0.5)`) by monkey-patching `guided_denoise_loop` on the `ltx_pipelines_mlx.retake` and `ltx_pipelines_mlx.a2vid_two_stage` modules, gating activation on a per-call module-level config dict, set before the pipeline call and cleared in `finally`. Predicted ~1.2× on extend at default threshold (up to ~3× at 1.5); similar for A2V Stage 1. Fix: install both monkey-patches at the top of `generate_ltx2.py`, wire `_EXTEND_TC_CONFIG` / `_A2V_TC_CONFIG` from the helper's `run_extend`/`run_a2v` paths, and add a `--no-teacache` CLI flag (default-on). **Decision needed:** ride along with the `[ref-watch-phosphene-bump-ltx2-pin-v0148]` pin bump (the calibration constants are part of the same upstream surface that gets renamed) or land independently against today's pin? Scope: small/medium.## Deferred Architecture (human-led planning)diff --git a/server/lib/ffmpeg.js b/server/lib/ffmpeg.jsindex 9bc0a7617c..46eb24a82c 100644--- a/server/lib/ffmpeg.js+++ b/server/lib/ffmpeg.js@@ -13,6 +13,7 @@ import { join, resolve as resolvePath, sep as PATH_SEP, dirname } from 'path';import { randomUUID } from 'crypto';import { promisify } from 'util';import { ensureDir, PATHS } from './fileUtils.js';+import { safeChildProcessEnv } from './processEnv.js';const execFileAsync = promisify(execFile);const IS_WIN = process.platform === 'win32';@@ -40,7 +41,7 @@ export const findFfmpeg = async () => {if (existsSync(p)) { cachedFfmpegPath = p; return p; }}const cmd = IS_WIN ? 'where' : 'which';- const { stdout } = await execFileAsync(cmd, ['ffmpeg'], { timeout: 5000 }).catch(() => ({ stdout: '' }));+ const { stdout } = await execFileAsync(cmd, ['ffmpeg'], { env: safeChildProcessEnv(), timeout: 5000 }).catch(() => ({ stdout: '' }));cachedFfmpegPath = stdout.trim().split(/\r?\n/)[0] || null;return cachedFfmpegPath;};@@ -78,7 +79,7 @@ export function runFfmpegProcess({ bin, args, signal, stderrTailBytes = 2000 } =}return new Promise((resolve) => {const stdio = stderrTailBytes > 0 ? ['ignore', 'ignore', 'pipe'] : 'ignore';- const proc = spawn(bin, args, { stdio });+ const proc = spawn(bin, args, { env: safeChildProcessEnv(), stdio });let stderrTail = '';if (stderrTailBytes > 0 && proc.stderr) {proc.stderr.on('data', (chunk) => {@@ -135,7 +136,7 @@ export const findFfprobe = async () => {const probe = join(dirname(ffmpeg), IS_WIN ? 'ffprobe.exe' : 'ffprobe');if (existsSync(probe)) { cachedFfprobePath = probe; return probe; }const cmd = IS_WIN ? 'where' : 'which';- const { stdout } = await execFileAsync(cmd, ['ffprobe'], { timeout: 5000 }).catch(() => ({ stdout: '' }));+ const { stdout } = await execFileAsync(cmd, ['ffprobe'], { env: safeChildProcessEnv(), timeout: 5000 }).catch(() => ({ stdout: '' }));cachedFfprobePath = stdout.trim().split(/\r?\n/)[0] || null;return cachedFfprobePath;};@@ -164,7 +165,7 @@ const probeDurationSeconds = async (videoPath) => {'-of', 'default=nokey=1:noprint_wrappers=1',videoPath,];- const { stdout } = await execFileAsync(ffprobe, args, { timeout: 5000 }).catch(() => ({ stdout: '' }));+ const { stdout } = await execFileAsync(ffprobe, args, { env: safeChildProcessEnv(), timeout: 5000 }).catch(() => ({ stdout: '' }));const n = parseFloat((stdout || '').trim());return Number.isFinite(n) && n > 0 ? n : null;};@@ -209,7 +210,7 @@ const probeFrameCount = async (videoPath) => {'-of', 'default=nokey=1:noprint_wrappers=1',videoPath,];- const { stdout } = await execFileAsync(ffprobe, args, { timeout: 15000 }).catch(() => ({ stdout: '' }));+ const { stdout } = await execFileAsync(ffprobe, args, { env: safeChildProcessEnv(), timeout: 15000 }).catch(() => ({ stdout: '' }));const n = parseInt((stdout || '').trim(), 10);return Number.isFinite(n) && n > 0 ? n : null;};diff --git a/server/lib/ffmpeg.test.js b/server/lib/ffmpeg.test.jsindex 0cec356d93..fadc192f4a 100644--- a/server/lib/ffmpeg.test.js+++ b/server/lib/ffmpeg.test.js@@ -100,6 +100,21 @@ describe('runFfmpegProcess', () => {expect(res.reason).toMatch(/spawn failed/);});+ it('strips Malloc debug variables from spawned ffmpeg children', async () => {+ const oldMalloc = process.env.MallocStackLogging;+ process.env.MallocStackLogging = '0';+ try {+ const res = await runFfmpegProcess({+ bin: process.execPath,+ args: ['-e', "process.exit(process.env.MallocStackLogging === undefined ? 0 : 2)"],+ });+ expect(res).toEqual({ ok: true });+ } finally {+ if (oldMalloc === undefined) delete process.env.MallocStackLogging;+ else process.env.MallocStackLogging = oldMalloc;+ }+ });+it('removes the abort listener on normal completion (no listener leak)', async () => {if (process.platform === 'win32') return;const controller = new AbortController();diff --git a/server/lib/hfDownload.js b/server/lib/hfDownload.jsindex b32b6fd6a1..bf30c8ff13 100644--- a/server/lib/hfDownload.js+++ b/server/lib/hfDownload.js@@ -23,7 +23,7 @@ import { join } from 'node:path';import { resolveFlux2Python, isFlux2VenvHealthy } from './pythonSetup.js';import { PATHS } from './fileUtils.js';import { getHfTokenInfo } from './hfToken.js';-import { stripDebugMallocEnv } from './processEnv.js';+import { safeChildProcessEnv } from './processEnv.js';import { getSettings } from '../services/settings.js';const HELPER_SCRIPT = join(PATHS.root, 'scripts', 'hf_download_repo.py');@@ -71,7 +71,7 @@ export function downloadHfRepo({ repo, revision = null, onEvent }) {}const { token } = await getHfTokenInfo();if (killed) return { ok: false, errorKind: 'cancelled', errorMessage: 'Cancelled' };- const env = stripDebugMallocEnv(process.env);+ const env = safeChildProcessEnv();// The Python helper looks up the token by env-var name so we don't have// to pass secrets on argv. Strip any stale value when the user has// explicitly cleared their stored token.diff --git a/server/lib/processEnv.js b/server/lib/processEnv.jsindex 1a07534011..dce2c396f8 100644--- a/server/lib/processEnv.js+++ b/server/lib/processEnv.js@@ -15,3 +15,7 @@ export function stripDebugMallocEnv(env) {Object.entries(env).filter(([k]) => !k.startsWith('Malloc')));}++export function safeChildProcessEnv(extra = {}) {+ return stripDebugMallocEnv({ ...process.env, ...extra });+}diff --git a/server/lib/processEnv.test.js b/server/lib/processEnv.test.jsindex 089b3e3cf9..64aa59cc53 100644--- a/server/lib/processEnv.test.js+++ b/server/lib/processEnv.test.js@@ -1,5 +1,5 @@import { describe, it, expect } from 'vitest';-import { stripDebugMallocEnv } from './processEnv.js';+import { safeChildProcessEnv, stripDebugMallocEnv } from './processEnv.js';describe('stripDebugMallocEnv', () => {it('drops every key that starts with "Malloc"', () => {@@ -29,3 +29,36 @@ describe('stripDebugMallocEnv', () => {expect(input).toEqual({ PATH: '/x', MallocStackLogging: '1' });});});++describe('safeChildProcessEnv', () => {+ it('strips process-level Malloc keys and applies overrides', () => {+ const oldPath = process.env.PATH;+ const oldMalloc = process.env.MallocStackLogging;+ const oldPortosTest = process.env.PORTOS_PROCESS_ENV_TEST;+ process.env.PATH = '/usr/bin';+ process.env.MallocStackLogging = '0';+ process.env.PORTOS_PROCESS_ENV_TEST = 'parent';++ try {+ const out = safeChildProcessEnv({+ PORTOS_PROCESS_ENV_TEST: 'child',+ EXTRA: '1',+ MallocOverride: 'drop',+ });++ expect(out.PATH).toBe('/usr/bin');+ expect(out.MallocStackLogging).toBeUndefined();+ expect(out.MallocOverride).toBeUndefined();+ expect(out.PORTOS_PROCESS_ENV_TEST).toBe('child');+ expect(out.EXTRA).toBe('1');+ expect(process.env.MallocStackLogging).toBe('0');+ } finally {+ if (oldPath === undefined) delete process.env.PATH;+ else process.env.PATH = oldPath;+ if (oldMalloc === undefined) delete process.env.MallocStackLogging;+ else process.env.MallocStackLogging = oldMalloc;+ if (oldPortosTest === undefined) delete process.env.PORTOS_PROCESS_ENV_TEST;+ else process.env.PORTOS_PROCESS_ENV_TEST = oldPortosTest;+ }+ });+});diff --git a/server/lib/pythonSetup.js b/server/lib/pythonSetup.jsindex 5e5e43f566..c7cefbc7cf 100644--- a/server/lib/pythonSetup.js+++ b/server/lib/pythonSetup.js@@ -4,7 +4,7 @@ import { arch, homedir, platform } from 'node:os';import { join } from 'node:path';import { promisify } from 'node:util';import { PATHS } from './fileUtils.js';-import { stripDebugMallocEnv } from './processEnv.js';+import { safeChildProcessEnv } from './processEnv.js';const execFileAsync = promisify(execFile);const IS_WIN = platform() === 'win32';@@ -89,7 +89,7 @@ const PYTHON_CANDIDATES = IS_WINexport async function probePythonArch(pythonPath) {const { stdout } = await execFileAsync(pythonPath, ['-c', 'import platform; print(platform.machine())'- ], { env: stripDebugMallocEnv(process.env), timeout: 10_000 }).catch(() => ({ stdout: '' }));+ ], { env: safeChildProcessEnv(), timeout: 10_000 }).catch(() => ({ stdout: '' }));return stdout.trim() || null;}@@ -163,7 +163,7 @@ export async function isFlux2VenvHealthy() {if (cachedFlux2Healthy !== null) return cachedFlux2Healthy;const py = resolveFlux2Python();if (!py) { cachedFlux2Healthy = false; return false; }- const ok = await execFileAsync(py, ['-c', 'from diffusers import Flux2KleinPipeline'], { env: stripDebugMallocEnv(process.env), timeout: 30_000 })+ const ok = await execFileAsync(py, ['-c', 'from diffusers import Flux2KleinPipeline'], { env: safeChildProcessEnv(), timeout: 30_000 }).then(() => true).catch(() => false);cachedFlux2Healthy = ok;@@ -203,7 +203,7 @@ export async function createVenv(basePython, targetDir) {? join(targetDir, 'Scripts', 'python.exe'): join(targetDir, 'bin', 'python3');if (existsSync(venvPython)) return venvPython;- await execFileAsync(basePython, ['-m', 'venv', targetDir], { env: stripDebugMallocEnv(process.env), timeout: 120_000 });+ await execFileAsync(basePython, ['-m', 'venv', targetDir], { env: safeChildProcessEnv(), timeout: 120_000 });if (!existsSync(venvPython)) {throw new Error(`Venv created but interpreter missing at ${venvPython}`);}@@ -226,7 +226,7 @@ export async function probePythonHealth(pythonPath) {' "imports": imports,','}))',].join('\n');- const { stdout } = await execFileAsync(pythonPath, ['-c', probe], { env: stripDebugMallocEnv(process.env), timeout: 30_000 });+ const { stdout } = await execFileAsync(pythonPath, ['-c', probe], { env: safeChildProcessEnv(), timeout: 30_000 });const data = JSON.parse(stdout.trim().split(/\r?\n/).pop());const installed = [];const missing = [];@@ -260,7 +260,7 @@ export async function checkPackages(pythonPath) {// live child handle so the caller's outer closure can track it for SIGTERM.function streamSpawn(bin, args, onLog, onProc) {return new Promise((resolve) => {- const proc = spawn(bin, args, { env: stripDebugMallocEnv(process.env), stdio: ['ignore', 'pipe', 'pipe'] });+ const proc = spawn(bin, args, { env: safeChildProcessEnv(), stdio: ['ignore', 'pipe', 'pipe'] });onProc(proc);const onChunk = (chunk) => {for (const line of chunk.toString().split(/[\r\n]+/)) {diff --git a/server/routes/videoGen.js b/server/routes/videoGen.jsindex 4fc70c8ee3..60165ba495 100644--- a/server/routes/videoGen.js+++ b/server/routes/videoGen.js@@ -20,7 +20,7 @@ import { PATHS, ensureDir, resolveGalleryImage } from '../lib/fileUtils.js';import { safeUnder } from '../lib/ffmpeg.js';import { getSettings } from '../services/settings.js';import { checkPackages, isAllowedPython } from '../lib/pythonSetup.js';-import { stripDebugMallocEnv } from '../lib/processEnv.js';+import { safeChildProcessEnv } from '../lib/processEnv.js';import {listVideoModels,defaultVideoModelId,@@ -276,7 +276,7 @@ router.get('/setup/runtime-install', asyncHandler(async (req, res) => {// orphaned to init — the user sees the modal close but the bandwidth keeps// burning until the network drops or the snapshot completes.const child = spawn('bash', [scriptPath], {- env: { ...stripDebugMallocEnv(process.env), [info.installEnvVar]: '1' },+ env: safeChildProcessEnv({ [info.installEnvVar]: '1' }),stdio: ['ignore', 'pipe', 'pipe'],detached: true,});diff --git a/server/services/imageGen/local.js b/server/services/imageGen/local.jsindex fbe7fcab40..200d778e2b 100644--- a/server/services/imageGen/local.js+++ b/server/services/imageGen/local.js@@ -25,7 +25,7 @@ import { imageGenEvents } from '../imageGenEvents.js';import { broadcastSse, attachSseClient as attachSse, closeJobAfterDelay, PYTHON_NOISE_RE } from '../../lib/sseUtils.js';import { resolveFlux2Python, FLUX2_VENV_DEFAULT } from '../../lib/pythonSetup.js';import { hfTokenEnv } from '../../lib/hfToken.js';-import { stripDebugMallocEnv } from '../../lib/processEnv.js';+import { safeChildProcessEnv } from '../../lib/processEnv.js';import { IMAGE_GEN_MODE } from './modes.js';const IS_WIN = process.platform === 'win32';@@ -358,7 +358,7 @@ export async function generateImage({ pythonPath, prompt, negativePrompt = '', mimageGenEvents.emit('started', { generationId: jobId, totalSteps: actualSteps });activeJob = { ...meta, generationId: jobId, totalSteps: actualSteps, step: 0, progress: 0, currentImage: null, mode: IMAGE_GEN_MODE.LOCAL };- const proc = spawn(bin, args, { env: { ...stripDebugMallocEnv(process.env), ...(await hfTokenEnv()) }, stdio: ['ignore', 'pipe', 'pipe'] });+ const proc = spawn(bin, args, { env: safeChildProcessEnv(await hfTokenEnv()), stdio: ['ignore', 'pipe', 'pipe'] });activeProcess = proc;// Spawn ENOENT (missing/non-executable pythonPath) fires BOTH 'error' and// 'close' on Node — without this guard, a typo'd pythonPath emits twodiff --git a/server/services/mediaService.js b/server/services/mediaService.jsindex 5abd6bd000..8e657faaa4 100644--- a/server/services/mediaService.js+++ b/server/services/mediaService.js@@ -1,5 +1,6 @@import { spawn } from 'child_process';import { PassThrough } from 'stream';+import { safeChildProcessEnv } from '../lib/processEnv.js';let videoProcess = null;let audioProcess = null;@@ -13,7 +14,7 @@ async function listDevices() {'-f', 'avfoundation','-list_devices', 'true','-i', ''- ]);+ ], { env: safeChildProcessEnv() });let output = '';@@ -77,7 +78,7 @@ function startVideoStream(deviceId = '0') {'-f', 'mjpeg','-q:v', '5','-'- ]);+ ], { env: safeChildProcessEnv() });videoProcess.stdout.pipe(videoStream);@@ -118,7 +119,7 @@ function startAudioStream(deviceId = '0') {'-ar', '48000','-b:a', '128k','-'- ]);+ ], { env: safeChildProcessEnv() });audioProcess.stdout.pipe(audioStream);diff --git a/server/services/videoGen/local.js b/server/services/videoGen/local.jsindex 406cc7d7eb..378258495c 100644--- a/server/services/videoGen/local.js+++ b/server/services/videoGen/local.js@@ -24,7 +24,7 @@ import { broadcastSse, attachSseClient as attachSse, closeJobAfterDelay, PYTHON_import { getVideoModels, getDefaultVideoModelId, getTextEncoderRepo } from '../../lib/mediaModels.js';import { findFfmpeg, safeUnder, generateThumbnail, optimizeForStreaming, upscaleVideo2x, extractEvaluationFrames } from '../../lib/ffmpeg.js';import { hfTokenEnv } from '../../lib/hfToken.js';-import { stripDebugMallocEnv } from '../../lib/processEnv.js';+import { safeChildProcessEnv } from '../../lib/processEnv.js';// Path to the dgrauet/ltx-2-mlx venv populated by `INSTALL_LTX2=1// scripts/setup-image-video.sh`. Used when a model entry has@@ -137,7 +137,7 @@ export async function isByovRuntimeReady(runtimeId) {if (readyCache.get(runtimeId) === true) return true;const probeOk = await new Promise((resolve) => {const child = spawn(info.venvPython, ['-c', info.importProbe], {- env: stripDebugMallocEnv(process.env),+ env: safeChildProcessEnv(),stdio: ['ignore', 'ignore', 'ignore'],});const timer = setTimeout(() => { if (!child.killed) child.kill('SIGKILL'); resolve(false); }, 30000);@@ -592,7 +592,7 @@ export async function generateVideo({ pythonPath, prompt, negativePrompt = '', m'-vf', `scale=${w}:${h}:force_original_aspect_ratio=increase,crop=${w}:${h}`,'-update', '1', '-frames:v', '1','-y', resizedPath,- ], { timeout: 10000 }).catch((err) => ({ error: err }));+ ], { env: safeChildProcessEnv(), timeout: 10000 }).catch((err) => ({ error: err }));if (resizeResult.error) {console.log(`⚠️ Failed to resize ${tag} image, using original: ${resizeResult.error.message}`);return { resolved: srcPath, tempPath: null };@@ -707,7 +707,7 @@ export async function generateVideo({ pythonPath, prompt, negativePrompt = '', m// python helpers can authenticate snapshot_download() against gated repos// (mirrors the imageGen child-spawn pattern). LTX-2 doesn't currently use// a gated repo, but the merge is harmless when no token is configured.- const childEnv = { ...stripDebugMallocEnv(process.env), ...(await hfTokenEnv()) };+ const childEnv = safeChildProcessEnv(await hfTokenEnv());delete childEnv.PYTHONPATH;// Force unbuffered Python I/O so tqdm + loguru + our own STAGE: prints flush// immediately. Without this, child stdio is line-buffered against a pipe and@@ -1225,7 +1225,7 @@ export async function extractLastFrame(historyId) {// 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' });+ const proc = spawn(ffmpeg, ['-sseof', '-1.0', '-i', videoPath, '-update', '1', '-vframes', '1', '-q:v', '2', '-y', framePath], { env: safeChildProcessEnv(), stdio: 'ignore' });proc.on('close', async (code) => {// safeStatSize swallows throws so the async handler can't leak an// unhandled rejection on transient stat errors — null is treated as@@ -1313,7 +1313,7 @@ export async function stitchVideos(videoIds, opts = {}) {// ffmpeg rejects — otherwise it leaks one file per failed stitch.try {await new Promise((resolve, reject) => {- const proc = spawn(ffmpeg, ['-f', 'concat', '-safe', '0', '-i', listFile, '-c', 'copy', '-y', outPath], { stdio: 'ignore' });+ const proc = spawn(ffmpeg, ['-f', 'concat', '-safe', '0', '-i', listFile, '-c', 'copy', '-y', outPath], { env: safeChildProcessEnv(), stdio: 'ignore' });proc.on('close', (code) => code === 0 ? resolve() : reject(new ServerError('Stitch failed', { status: 500, code: 'FFMPEG_FAILED' })));proc.on('error', (err) => reject(new ServerError(`ffmpeg failed to spawn: ${err.message}`, { status: 500, code: 'FFMPEG_FAILED' })));});diff --git a/server/services/videoTimeline/local.js b/server/services/videoTimeline/local.jsindex e6ed312623..73a48c823d 100644--- a/server/services/videoTimeline/local.js+++ b/server/services/videoTimeline/local.js@@ -22,6 +22,7 @@ import { ensureDir, PATHS, readJSONFile, atomicWrite } from '../../lib/fileUtilsimport { ServerError } from '../../lib/errorHandler.js';import { broadcastSse, attachSseClient as attachSse, closeJobAfterDelay } from '../../lib/sseUtils.js';import { findFfmpeg, findFfprobe, safeUnder, generateThumbnail } from '../../lib/ffmpeg.js';+import { safeChildProcessEnv } from '../../lib/processEnv.js';import { loadHistory, saveHistory } from '../videoGen/local.js';const PROJECTS_FILE = join(PATHS.data, 'video-projects.json');@@ -174,7 +175,7 @@ const probeAudio = async (videoPath) => {'-show_entries', 'stream=codec_type','-of', 'default=nw=1:nk=1',videoPath,- ], { stdio: ['ignore', 'pipe', 'ignore'] });+ ], { env: safeChildProcessEnv(), stdio: ['ignore', 'pipe', 'ignore'] });let out = '';proc.stdout.on('data', (c) => { out += c.toString(); });proc.on('close', () => resolve(out.trim() === 'audio'));@@ -374,7 +375,7 @@ export async function renderProject(projectId) {console.log(`🎞️ Rendering timeline [${jobId.slice(0, 8)}]: project=${projectId.slice(0, 8)} clips=${clips.length} duration=${totalDuration.toFixed(2)}s`);- const proc = spawn(ffmpeg, args, { stdio: ['ignore', 'ignore', 'pipe'] });+ const proc = spawn(ffmpeg, args, { env: safeChildProcessEnv(), stdio: ['ignore', 'ignore', 'pipe'] });job.process = proc;// ffmpeg's -progress pipe:2 emits key=value lines, one per line, every