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: hide background subprocess windows

[._.]/ Adam Eivy32a6084df041
diff --git a/.changelog/next/fixed-codex-fix-hidden-subprocess-windows.md b/.changelog/next/fixed-codex-fix-hidden-subprocess-windows.md
new file mode 100644
index 0000000000..177d8f1a50
--- /dev/null
+++ b/.changelog/next/fixed-codex-fix-hidden-subprocess-windows.md
@@ -0,0 +1 @@
+- Prevent background Python and CLI probes from flashing console windows or repeatedly spawning Windows Terminal hosts.
diff --git a/server/lib/README.md b/server/lib/README.md
index e34467904b..812197d68e 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -205,7 +205,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `gitRemote.js` | `getOriginInfo`, `parseGitRemoteUrl`, `UPSTREAM_OWNER`/`UPSTREAM_REPO` — classifies the local `origin` remote vs the upstream atomantic/PortOS repo. Used by the update flow to detect forks. |
| `githubRepoUrl.js` | `parseGitHubUrl(url)` → `{ owner, repo }` / `isGitHubRepoUrl(url)` — authoritative "is this a clonable GitHub repo URL?" rule, re-exported by `services/githubCloner.js`. Mirrored to `client/src/lib/githubRepoUrl.js` (parity pinned by `githubRepoUrl.mirror.test.js`) so the Brain capture boxes reveal the post-clone agent options for exactly the URLs the server will clone. |
| `killWithEscalation.js` | `killWithEscalation(proc, {label, stillRunning, delayMs=8000})` — shared SIGTERM→grace→SIGKILL cancel-escalation for spawn-based media jobs. Sends SIGTERM, then escalates to SIGKILL after `delayMs` only when `stillRunning()` holds and the child hasn't exited (`exitCode===null && signalCode===null`). The timer is unref'd and the callback is try/catch-wrapped (runs outside the request lifecycle). Converges musicVideo/render, videoTimeline, imageGen local+codex, videoGen, loraTraining, and the yt-dlp track import cancel paths. |
-| `processEnv.js` | `stripDebugMallocEnv(env)` / `safeChildProcessEnv(extra)` — drop macOS `Malloc*` debug env vars before spawning a child. Pinokio-launched PortOS exports `MallocStackLogging`/`MallocScribble`/etc. that flood Python subprocess stderr with `can't turn off malloc stack logging` lines; route every Node→Python spawn through this. No-op on Linux/Windows. Also `whichFirst(name)` — first-hit `which`/`where` PATH probe (Malloc-stripped env, 5s timeout) returning the absolute binary path or `null`; the shared discovery probe behind `findYtDlp`/`findFfmpeg`/`detectPython`/voice `which`. `whichFirstSync(name)` — same contract without the await, for callers resolving a binary mid-spawn (`detectPythonSync`). |
+| `processEnv.js` | `stripDebugMallocEnv(env)` / `safeChildProcessEnv(extra)` — drop macOS `Malloc*` debug env vars before spawning a child. `safeChildProcessOptions(options)` adds that sanitized environment plus `windowsHide: true`, preventing detached PM2 subprocesses from opening transient Windows console UI; route Node→Python and other background CLI spawns through it. Also `whichFirst(name)` — first-hit `which`/`where` PATH probe (safe options, 5s timeout) returning the absolute binary path or `null`; `whichFirstSync(name)` provides the same contract without the await. |
| `branchUpstreamGuard.js` | `enforceSafeBranchUpstream(repo, branch)` / `readBranchUpstream` / `isSafeBranchUpstream` — the agent-branch upstream invariant (#4172): a branch handed to a CoS agent tracks either NOTHING or its OWN ref, never `refs/heads/main`. `git worktree add -b <b> <path> origin/main` does not leave the branch untracked — `branch.autoSetupMerge` records `merge=refs/heads/main` — and `/do:pr` derives its push destination from that config (`git push <remote> HEAD:<merge>`), so the agent's work lands straight on the default branch with no PR. Prevention is `--no-track` at the `worktreeManager.js` creation sites; this is the backstop that also REPAIRS branches created before the fix (drops the bogus upstream, logs it) and throws only if the repair doesn't take. Fails CLOSED: `readBranchUpstream` returns `null` for could-not-read (distinct from `''` = genuinely unset), and an unverifiable upstream is refused rather than waved through — `worktreeManager.js` undoes the `worktree add` on refusal so the throw can't strand a tree. Pairs with `primaryCheckoutGuard.js`, which catches the other way agent work reaches `main`. |
| `primaryCheckoutGuard.js` | `capturePrimaryCheckoutState(path)` / `detectPrimaryCheckoutDrift(baseline, {agentBranch})` + `PRIMARY_CHECKOUT_MUTATED_REASON`/`_CATEGORY` — the branch-jack detector (#3680): stamps the PRIMARY checkout's branch + HEAD onto a worktree agent's metadata at spawn (`agentLifecycle.js`) and re-reads it in the shared finalize path (`agentFinalization.js`), so a worktree-isolated agent that commits to the primary is recorded as a FAILURE naming the drifted branch, the commit count, and the `git reset --hard` recovery — instead of a silent "completed". Detect-and-report only: the reset discards commits, so it stays a human decision. Non-throwing (runs outside the request lifecycle); an unreadable checkout reports no drift rather than inventing one. |
| `pythonSetup.js` | Python venv / runner setup helpers. |
diff --git a/server/lib/aiToolkit/providers.js b/server/lib/aiToolkit/providers.js
index 9034b86445..3606ed7b4a 100644
--- a/server/lib/aiToolkit/providers.js
+++ b/server/lib/aiToolkit/providers.js
@@ -630,7 +630,7 @@ export function createProviderService(config = {}) {
// Use execFile (no shell) so user-configured `provider.command` cannot
// inject extra shell commands via metacharacters.
const lookup = isWin32 ? 'where' : 'which';
- const { stdout } = await execFileAsync(lookup, [provider.command])
+ const { stdout } = await execFileAsync(lookup, [provider.command], { windowsHide: true })
.catch(() => ({ stdout: '', stderr: 'not found' }));
// `where` lists every match (one per line); `which` prints one. Take the
diff --git a/server/lib/bashResolver.js b/server/lib/bashResolver.js
index c8230b503d..e5677af16b 100644
--- a/server/lib/bashResolver.js
+++ b/server/lib/bashResolver.js
@@ -54,7 +54,7 @@ function standardGitBashPaths() {
function gitBashFromPath() {
let gitExe = '';
try {
- gitExe = execFileSync('where', ['git'], { encoding: 'utf8' }).split(/\r?\n/)[0].trim();
+ gitExe = execFileSync('where', ['git'], { encoding: 'utf8', windowsHide: true }).split(/\r?\n/)[0].trim();
} catch {
return null;
}
diff --git a/server/lib/detachedSpawn.js b/server/lib/detachedSpawn.js
index 3b52c5a974..a99d51ef0e 100644
--- a/server/lib/detachedSpawn.js
+++ b/server/lib/detachedSpawn.js
@@ -247,7 +247,7 @@ export async function spawnDetached(bin, args = [], {
// is a POSIX-only guarantee; Windows keeps its prior spawn semantics apart
// from `kill`, which is replaced with a tree-kill below.
if (process.platform === 'win32') {
- const child = spawn(bin, args, { env: withSpawnCwdEnv(env ?? process.env, cwd), cwd, stdio: ['ignore', 'pipe', 'pipe'] });
+ const child = spawn(bin, args, { env: withSpawnCwdEnv(env ?? process.env, cwd), cwd, stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true });
// A bare `child.kill()` terminates ONLY the runner. Windows has no process
// group for the POSIX `-pid` trick `killProcessGroup` relies on, so whatever
// the runner spawned (the ffmpeg mux a CUDA video runtime shells out to, a
@@ -355,6 +355,7 @@ export async function spawnDetached(bin, args = [], {
// Pin PWD to the spawn cwd — see withSpawnCwdEnv (#3193).
env: withSpawnCwdEnv(env ?? process.env, cwd),
cwd,
+ windowsHide: true,
detached: true,
stdio: 'ignore',
});
diff --git a/server/lib/ffmpeg.js b/server/lib/ffmpeg.js
index 64bb3235eb..ee7366b9e4 100644
--- a/server/lib/ffmpeg.js
+++ b/server/lib/ffmpeg.js
@@ -13,7 +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, whichFirst } from './processEnv.js';
+import { safeChildProcessOptions, whichFirst } from './processEnv.js';
const execFileAsync = promisify(execFile);
const IS_WIN = process.platform === 'win32';
@@ -77,7 +77,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, { env: safeChildProcessEnv(), stdio });
+ const proc = spawn(bin, args, safeChildProcessOptions({ stdio }));
let stderrTail = '';
if (stderrTailBytes > 0 && proc.stderr) {
proc.stderr.on('data', (chunk) => {
@@ -145,7 +145,7 @@ export const findFfprobe = async () => {
const runFfprobe = async (args, timeout = 5000) => {
const ffprobe = await findFfprobe();
if (!ffprobe) return '';
- const { stdout } = await execFileAsync(ffprobe, args, { env: safeChildProcessEnv(), timeout }).catch(() => ({ stdout: '' }));
+ const { stdout } = await execFileAsync(ffprobe, args, safeChildProcessOptions({ timeout })).catch(() => ({ stdout: '' }));
return (stdout || '').trim();
};
@@ -387,10 +387,9 @@ export const supportsSetparamsFilter = async () => {
if (setparamsAvailable !== null) return setparamsAvailable;
const ffmpeg = await findFfmpeg();
if (!ffmpeg) return false;
- const listing = await execFileAsync(ffmpeg, ['-hide_banner', '-filters'], {
- env: safeChildProcessEnv(),
+ const listing = await execFileAsync(ffmpeg, ['-hide_banner', '-filters'], safeChildProcessOptions({
maxBuffer: 4 * 1024 * 1024,
- }).then((r) => String(r.stdout || ''), () => null);
+ })).then((r) => String(r.stdout || ''), () => null);
if (listing === null) return false;
setparamsAvailable = /(^|\s)setparams(\s|$)/m.test(listing);
if (!setparamsAvailable) {
diff --git a/server/lib/hfDownload.js b/server/lib/hfDownload.js
index 77a6a3f378..1634ab5b3a 100644
--- a/server/lib/hfDownload.js
+++ b/server/lib/hfDownload.js
@@ -31,7 +31,7 @@ import {
} from './pythonSetup.js';
import { PATHS } from './fileUtils.js';
import { getHfTokenInfo } from './hfToken.js';
-import { safeChildProcessEnv } from './processEnv.js';
+import { safeChildProcessEnv, safeChildProcessOptions } from './processEnv.js';
import { createLineReader } from './streamLines.js';
import { getSettings } from '../services/settings.js';
@@ -222,7 +222,7 @@ export function downloadHfRepo({ repo, revision = null, only = null, pythonPath:
});
return new Promise((resolve) => {
- proc = spawn(pythonPath, args, { env, stdio: ['ignore', 'pipe', 'pipe'] });
+ proc = spawn(pythonPath, args, safeChildProcessOptions({ env, stdio: ['ignore', 'pipe', 'pipe'] }));
// Window: kill() could have fired between the second `if (killed)`
// check and the spawn returning the proc handle. Re-check now that we
// own a proc — if it raced, kill it immediately.
diff --git a/server/lib/icloudFile.js b/server/lib/icloudFile.js
index 2b77214be4..edc04dc258 100644
--- a/server/lib/icloudFile.js
+++ b/server/lib/icloudFile.js
@@ -324,7 +324,7 @@ export function requestMaterialization(path, options = {}) {
// is still correctly refused either way.
let child;
try {
- child = spawn('brctl', ['download', path], { detached: true, stdio: 'ignore' });
+ child = spawn('brctl', ['download', path], { detached: true, stdio: 'ignore', windowsHide: true });
child.unref();
} catch (err) {
// Nothing was reserved yet — the slot is claimed below, after a successful
diff --git a/server/lib/processEnv.js b/server/lib/processEnv.js
index 81596b53fd..7abf9cd733 100644
--- a/server/lib/processEnv.js
+++ b/server/lib/processEnv.js
@@ -26,6 +26,14 @@ export function safeChildProcessEnv(extra = {}) {
return stripDebugMallocEnv({ ...process.env, ...extra });
}
+// Canonical options for background server subprocesses. PM2 detaches PortOS
+// from its launch terminal, so a Windows console executable spawned without
+// windowsHide asks the default terminal host to open a transient UI window.
+export function safeChildProcessOptions(options = {}) {
+ const { env = process.env, ...rest } = options;
+ return { ...rest, env: stripDebugMallocEnv(env), windowsHide: true };
+}
+
// Resolve the first PATH hit for a binary via `which` (POSIX) / `where`
// (Windows) — the "is this system tool installed, and where?" probe copied
// inline across ytdlp/ffmpeg/pythonSetup/voice discovery. Returns the absolute
@@ -38,9 +46,9 @@ export function safeChildProcessEnv(extra = {}) {
export function whichFirstSync(name) {
const cmd = IS_WIN ? 'where' : 'which';
try {
- const stdout = execFileSync(cmd, [name], {
- encoding: 'utf8', env: safeChildProcessEnv(), timeout: 5000, stdio: ['ignore', 'pipe', 'ignore'],
- });
+ const stdout = execFileSync(cmd, [name], safeChildProcessOptions({
+ encoding: 'utf8', timeout: 5000, stdio: ['ignore', 'pipe', 'ignore'],
+ }));
return stdout.trim().split(/\r?\n/)[0] || null;
} catch {
return null; // not on PATH, or the probe itself failed
@@ -49,7 +57,7 @@ export function whichFirstSync(name) {
export async function whichFirst(name) {
const cmd = IS_WIN ? 'where' : 'which';
- const { stdout } = await execFileAsync(cmd, [name], { env: safeChildProcessEnv(), timeout: 5000 })
+ const { stdout } = await execFileAsync(cmd, [name], safeChildProcessOptions({ timeout: 5000 }))
.catch(() => ({ stdout: '' }));
return stdout.trim().split(/\r?\n/)[0] || null;
}
diff --git a/server/lib/processEnv.spawnOptions.test.js b/server/lib/processEnv.spawnOptions.test.js
new file mode 100644
index 0000000000..2adc003f21
--- /dev/null
+++ b/server/lib/processEnv.spawnOptions.test.js
@@ -0,0 +1,53 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const childProcessMocks = vi.hoisted(() => ({
+ execFile: vi.fn(),
+ execFileSync: vi.fn(),
+}));
+
+vi.mock('child_process', () => childProcessMocks);
+
+import { safeChildProcessOptions, whichFirst, whichFirstSync } from './processEnv.js';
+
+const pathProbeCommand = process.platform === 'win32' ? 'where' : 'which';
+
+describe('safeChildProcessOptions', () => {
+ it('hides console windows and sanitizes an explicitly supplied environment', () => {
+ expect(safeChildProcessOptions({
+ cwd: '/example',
+ env: { PATH: '/bin', MallocStackLogging: '1' },
+ windowsHide: false,
+ })).toEqual({
+ cwd: '/example',
+ env: { PATH: '/bin' },
+ windowsHide: true,
+ });
+ });
+});
+
+describe('PATH probe spawn options', () => {
+ beforeEach(() => {
+ childProcessMocks.execFile.mockReset();
+ childProcessMocks.execFileSync.mockReset();
+ });
+
+ it('hides the async probe console', async () => {
+ childProcessMocks.execFile.mockImplementation((_cmd, _args, _opts, callback) => {
+ callback(null, { stdout: '/example/node\n', stderr: '' });
+ });
+
+ await expect(whichFirst('node')).resolves.toBe('/example/node');
+ expect(childProcessMocks.execFile).toHaveBeenCalledWith(pathProbeCommand, ['node'], expect.objectContaining({
+ windowsHide: true,
+ }), expect.any(Function));
+ });
+
+ it('hides the synchronous probe console', () => {
+ childProcessMocks.execFileSync.mockReturnValue('/example/node\n');
+
+ expect(whichFirstSync('node')).toBe('/example/node');
+ expect(childProcessMocks.execFileSync).toHaveBeenCalledWith(pathProbeCommand, ['node'], expect.objectContaining({
+ windowsHide: true,
+ }));
+ });
+});
diff --git a/server/lib/pythonSetup.js b/server/lib/pythonSetup.js
index 28156da3c7..8e1ece3b9c 100644
--- a/server/lib/pythonSetup.js
+++ b/server/lib/pythonSetup.js
@@ -4,7 +4,7 @@ import { arch, homedir, platform } from 'node:os';
import { dirname, join } from 'node:path';
import { promisify } from 'node:util';
import { PATHS } from './fileUtils.js';
-import { safeChildProcessEnv, whichFirst, whichFirstSync } from './processEnv.js';
+import { safeChildProcessOptions, whichFirst, whichFirstSync } from './processEnv.js';
import { createLineReader } from './streamLines.js';
import { getCudaCapability } from './cudaCapability.js';
@@ -124,7 +124,7 @@ const PYTHON_CANDIDATES = IS_WIN
export async function probePythonArch(pythonPath) {
const { stdout } = await execFileAsync(pythonPath, [
'-c', 'import platform; print(platform.machine())'
- ], { env: safeChildProcessEnv(), timeout: 10_000 }).catch(() => ({ stdout: '' }));
+ ], safeChildProcessOptions({ timeout: 10_000 })).catch(() => ({ stdout: '' }));
return stdout.trim() || null;
}
@@ -259,7 +259,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: safeChildProcessEnv(), timeout: 30_000 })
+ const ok = await execFileAsync(py, ['-c', 'from diffusers import Flux2KleinPipeline'], safeChildProcessOptions({ timeout: 30_000 }))
.then(() => true)
.catch(() => false);
cachedFlux2Healthy = ok;
@@ -527,7 +527,7 @@ export async function isMuscriptorRuntimeReady() {
if (cachedMuscriptorReady) return true;
const py = resolveMuscriptorPython();
if (!py) return false;
- const ok = await execFileAsync(py, ['-c', 'from muscriptor import TranscriptionModel'], { env: safeChildProcessEnv(), timeout: 30_000 })
+ const ok = await execFileAsync(py, ['-c', 'from muscriptor import TranscriptionModel'], safeChildProcessOptions({ timeout: 30_000 }))
.then(() => true)
.catch(() => false);
cachedMuscriptorReady = ok;
@@ -568,7 +568,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: safeChildProcessEnv(), timeout: 120_000 });
+ await execFileAsync(basePython, ['-m', 'venv', targetDir], safeChildProcessOptions({ timeout: 120_000 }));
if (!existsSync(venvPython)) {
throw new Error(`Venv created but interpreter missing at ${venvPython}`);
}
@@ -592,7 +592,7 @@ export async function probePythonHealth(pythonPath) {
' "imports": imports,',
'}))',
].join('\n');
- const { stdout } = await execFileAsync(pythonPath, ['-c', probe], { env: safeChildProcessEnv(), timeout: 30_000 });
+ const { stdout } = await execFileAsync(pythonPath, ['-c', probe], safeChildProcessOptions({ timeout: 30_000 }));
const data = JSON.parse(stdout.trim().split(/\r?\n/).pop());
const installed = [];
const missing = [];
@@ -627,7 +627,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: safeChildProcessEnv(), stdio: ['ignore', 'pipe', 'pipe'] });
+ const proc = spawn(bin, args, safeChildProcessOptions({ stdio: ['ignore', 'pipe', 'pipe'] }));
onProc(proc);
// `splitRe: /[\r\n]+/` so a torch/tqdm progress bar that redraws with a
// bare `\r` surfaces each redraw as its own log line; the carry buffer
diff --git a/server/lib/setupScriptRunner.js b/server/lib/setupScriptRunner.js
index cbba1f2df4..529a41e5d0 100644
--- a/server/lib/setupScriptRunner.js
+++ b/server/lib/setupScriptRunner.js
@@ -17,7 +17,7 @@ import { spawn } from 'child_process';
import { join } from 'path';
import { PATHS } from './fileUtils.js';
import { resolveBashBinary, toBashPath } from './bashResolver.js';
-import { safeChildProcessEnv } from './processEnv.js';
+import { safeChildProcessEnv, safeChildProcessOptions } from './processEnv.js';
import { detectVenvBasePythonSync } from './pythonSetup.js';
import { killProcessTree } from './bufferedSpawn.js';
@@ -44,15 +44,14 @@ export function spawnSetupScript(envVars = {}) {
const python = detectVenvBasePythonSync();
if (python) env.PYTHON_BIN = toBashPath(python);
}
- return spawn(resolveBashBinary(), [toBashPath(SETUP_IMAGE_VIDEO_SCRIPT)], {
+ return spawn(resolveBashBinary(), [toBashPath(SETUP_IMAGE_VIDEO_SCRIPT)], safeChildProcessOptions({
env: safeChildProcessEnv(env),
stdio: ['ignore', 'pipe', 'pipe'],
// POSIX only: its own process group is what lets a cancel reach uv / pip /
// git (stopSetupScript signals the group). On Windows `detached` instead
// means "own console window" and buys nothing — taskkill /T is the tree.
detached: !IS_WIN,
- windowsHide: true,
- });
+ }));
}
/**
diff --git a/server/lib/sidecarProcess.js b/server/lib/sidecarProcess.js
index 6d36b1a24f..b379f347bf 100644
--- a/server/lib/sidecarProcess.js
+++ b/server/lib/sidecarProcess.js
@@ -15,6 +15,7 @@
*/
import { spawn } from 'child_process';
+import { safeChildProcessOptions } from './processEnv.js';
// Only the trailing RESULT: line is ever consumed, and sidecar runs are
// long-lived (first-run weight downloads, multi-minute inference) — so both
@@ -60,7 +61,7 @@ export function runSidecarProcess({ bin, args, env, signal, onStage, onProcess }
resolve({ ok: false, canceled: true, reason: 'cancelled (aborted before spawn)', stdout: '' });
return;
}
- const proc = spawn(bin, args, { env, stdio: ['ignore', 'pipe', 'pipe'] });
+ const proc = spawn(bin, args, safeChildProcessOptions({ env, stdio: ['ignore', 'pipe', 'pipe'] }));
onProcess?.(proc);
let stdoutTail = '';
let stderrTail = '';
diff --git a/server/lib/testHelper.js b/server/lib/testHelper.js
index 7322e67d4e..021ca35a1f 100644
--- a/server/lib/testHelper.js
+++ b/server/lib/testHelper.js
@@ -313,7 +313,7 @@ export function resolveTestPython() {
return candidates.find((candidate) => {
try {
- execFileSync(candidate, ['-c', 'pass'], { stdio: 'ignore' });
+ execFileSync(candidate, ['-c', 'pass'], { stdio: 'ignore', windowsHide: true });
return true;
} catch {
return false;
diff --git a/server/routes/database.js b/server/routes/database.js
index 7526e37a6f..a50d8b7c29 100644
--- a/server/routes/database.js
+++ b/server/routes/database.js
@@ -25,7 +25,7 @@ const router = Router();
*/
function runCmd(cmd, args, timeout = 120_000, env = process.env) {
return new Promise((resolve) => {
- execFile(cmd, args, { cwd: rootDir, timeout, env }, (err, stdout, stderr) => {
+ execFile(cmd, args, { cwd: rootDir, timeout, env, windowsHide: true }, (err, stdout, stderr) => {
const exitCode = err ? (typeof err.code === 'number' ? err.code : 1) : 0;
if (exitCode !== 0) {
const detail = stripAnsi(stderr || stdout || err.message || '').replace(/\s+/g, ' ').trim();
@@ -321,7 +321,7 @@ export function importDumpFile(dumpFile, port, env, timeout = 120_000) {
const psql = spawn('psql', [
'-h', 'localhost', '-p', String(port), '-U', pgUser, '-d', pgDb,
'-v', 'ON_ERROR_STOP=1', '--single-transaction'
- ], { cwd: rootDir, env });
+ ], { cwd: rootDir, env, windowsHide: true });
// The dump read stream — declared up front so finish() can tear it down. If
// psql exits early (ON_ERROR_STOP rollback) or the timeout SIGKILLs it, the
diff --git a/server/services/agentTuiSpawning.js b/server/services/agentTuiSpawning.js
index 991bd11fbe..3addcf159c 100644
--- a/server/services/agentTuiSpawning.js
+++ b/server/services/agentTuiSpawning.js
@@ -231,7 +231,7 @@ function shellHasLiveChild(shellPid) {
return new Promise((resolve) => {
// `-Ao ppid=` is POSIX (all processes, ppid column only, no header) and
// works on both macOS (BSD ps) and Linux (procps).
- execFile('ps', ['-Ao', 'ppid='], { timeout: 2000 }, (err, stdout) => {
+ execFile('ps', ['-Ao', 'ppid='], { timeout: 2000, windowsHide: true }, (err, stdout) => {
if (err) { resolve(true); return; }
resolve(stdout.split('\n').some((line) => parseInt(line, 10) === shellPid));
});
diff --git a/server/services/autonomousJobs/scriptHandlers.js b/server/services/autonomousJobs/scriptHandlers.js
index c63a25d289..5df46db617 100644
--- a/server/services/autonomousJobs/scriptHandlers.js
+++ b/server/services/autonomousJobs/scriptHandlers.js
@@ -29,7 +29,8 @@ function runMoltworldExploration() {
return new Promise((resolve, reject) => {
const child = spawn('node', [scriptPath, durationMinutes], {
stdio: ['ignore', 'pipe', 'pipe'],
- env: { ...process.env }
+ env: { ...process.env },
+ windowsHide: true,
})
const output = []
diff --git a/server/services/backup.js b/server/services/backup.js
index 1d4b9259d3..b1881b4891 100644
--- a/server/services/backup.js
+++ b/server/services/backup.js
@@ -125,7 +125,7 @@ export function resolveRsyncBinary(env = process.env) {
function runRsync(srcDir, destDir, flags = []) {
return new Promise((resolve, reject) => {
const args = ['--archive', '--itemize-changes', ...flags, srcDir + '/', destDir];
- const proc = spawn(resolveRsyncBinary(), args, { shell: false });
+ const proc = spawn(resolveRsyncBinary(), args, { shell: false, windowsHide: true });
const changed = [];
let stderr = '';
@@ -342,6 +342,7 @@ export async function dumpPostgres(outputPath) {
'-f', outputPath
], {
shell: false,
+ windowsHide: true,
env: { ...process.env, PGPASSWORD: process.env.PGPASSWORD || 'portos' }
});
@@ -592,7 +593,7 @@ export async function restorePostgres(destPath, snapshotId, { dryRun = true } =
'-v', 'ON_ERROR_STOP=1',
'--single-transaction',
'-h', pgHost, '-p', pgPort, '-U', pgUser, '-d', pgDb, '-f', sqlPath
- ], { shell: false, env: { ...process.env, PGPASSWORD: process.env.PGPASSWORD || 'portos' } });
+ ], { shell: false, windowsHide: true, env: { ...process.env, PGPASSWORD: process.env.PGPASSWORD || 'portos' } });
let stderr = '';
proc.stderr.on('data', (chunk) => { stderr += chunk.toString(); });
diff --git a/server/services/claudeCodeUsage.js b/server/services/claudeCodeUsage.js
index 8ff26f2b22..3d2d05c2d9 100644
--- a/server/services/claudeCodeUsage.js
+++ b/server/services/claudeCodeUsage.js
@@ -217,7 +217,7 @@ function runUsageCli() {
return new Promise((resolve, reject) => {
const tz = systemTimeZone();
const env = tz ? { ...process.env, TZ: tz } : process.env;
- const child = spawn(CLI_COMMAND, CLI_ARGS, { stdio: ['pipe', 'pipe', 'pipe'], env });
+ const child = spawn(CLI_COMMAND, CLI_ARGS, { stdio: ['pipe', 'pipe', 'pipe'], env, windowsHide: true });
let stdout = '';
let stderr = '';
let settled = false;
diff --git a/server/services/imageGen/agy.js b/server/services/imageGen/agy.js
index da22ed1267..10a88d732e 100644
--- a/server/services/imageGen/agy.js
+++ b/server/services/imageGen/agy.js
@@ -109,7 +109,7 @@ export function listModels({ agyPath } = {}) {
const bin = agyPath || DEFAULT_BIN;
const { command, args } = prepareCliSpawn(bin, ['models']);
return new Promise((resolve) => {
- const proc = spawn(command, args, { shell: false, stdio: ['pipe', 'pipe', 'pipe'] });
+ const proc = spawn(command, args, { shell: false, stdio: ['pipe', 'pipe', 'pipe'], windowsHide: true });
let stdout = '';
let stderr = '';
let settled = false;
@@ -311,7 +311,7 @@ async function runAgy(job, jobId, bin, args, {
// Pin PWD to the spawn cwd — see withSpawnCwdEnv (#3193). agy reads
// process.cwd(), so this is defensive rather than a live fix; it keeps every
// scratch-dir spawn telling the child one consistent story about where it is.
- const proc = spawn(command, spawnArgs, { cwd: scratchDir, env: withSpawnCwdEnv(process.env, scratchDir), shell: false, stdio: ['ignore', 'pipe', 'pipe'] });
+ const proc = spawn(command, spawnArgs, { cwd: scratchDir, env: withSpawnCwdEnv(process.env, scratchDir), shell: false, stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true });
activeProcs.set(jobId, proc);
const removeScratch = () => rm(scratchDir, { recursive: true, force: true }).catch(() => {});
let stdoutTail = '';
diff --git a/server/services/imageGen/codex.js b/server/services/imageGen/codex.js
index 3cf1197c3a..02d3b79914 100644
--- a/server/services/imageGen/codex.js
+++ b/server/services/imageGen/codex.js
@@ -120,7 +120,7 @@ export async function checkConnection({ codexPath } = {}) {
// (which would consume the user's Codex quota); the settings UI just wants
// "yes the binary exists and is reachable".
const bin = codexPath || DEFAULT_BIN;
- const proc = spawn(bin, ['--version'], { shell: false, stdio: ['ignore', 'pipe', 'pipe'] });
+ const proc = spawn(bin, ['--version'], { shell: false, stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true });
let out = '';
proc.stdout.on('data', (c) => { out += c.toString(); });
proc.stderr.on('data', (c) => { out += c.toString(); });
@@ -304,7 +304,7 @@ export const noImageReason = (stdoutTail = '') => buildNoImageReason(stdoutTail,
});
async function runCodex(job, jobId, bin, args, outputPath, filename, meta, { cleanC2PA = false, denoise = false } = {}) {
- const proc = spawn(bin, args, { shell: false, stdio: ['ignore', 'pipe', 'pipe'] });
+ const proc = spawn(bin, args, { shell: false, stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true });
activeProcs.set(jobId, proc);
let sessionId = null;
diff --git a/server/services/imageGen/grok.js b/server/services/imageGen/grok.js
index f2203ac8f5..c8f7ef90f3 100644
--- a/server/services/imageGen/grok.js
+++ b/server/services/imageGen/grok.js
@@ -312,7 +312,7 @@ async function runGrok(job, jobId, bin, args, {
// Pin PWD to the spawn cwd — see withSpawnCwdEnv (#3193). grok reads
// process.cwd(), so this is defensive rather than a live fix; it keeps every
// scratch-dir spawn telling the child one consistent story about where it is.
- const proc = spawn(spawnBin, spawnArgs, { cwd: scratchDir, env: withSpawnCwdEnv(process.env, scratchDir), shell: false, stdio: [useStdin ? 'pipe' : 'ignore', 'pipe', 'pipe'] });
+ const proc = spawn(spawnBin, spawnArgs, { cwd: scratchDir, env: withSpawnCwdEnv(process.env, scratchDir), shell: false, stdio: [useStdin ? 'pipe' : 'ignore', 'pipe', 'pipe'], windowsHide: true });
activeProcs.set(jobId, proc);
const removeScratch = () => rm(scratchDir, { recursive: true, force: true }).catch(() => {});
diff --git a/server/services/imageGen/local.js b/server/services/imageGen/local.js
index 70b5018bf8..d9a9a8cfe5 100644
--- a/server/services/imageGen/local.js
+++ b/server/services/imageGen/local.js
@@ -31,6 +31,7 @@ import { killWithEscalation } from '../../lib/killWithEscalation.js';
import { createLineReader } from '../../lib/streamLines.js';
import { claimHeavyLocalJob } from '../../lib/heavyJobClaim.js';
import { prepareLocalMemory } from '../../lib/localMemory.js';
+import { safeChildProcessOptions } from '../../lib/processEnv.js';
import { IMAGE_GEN_MODE, LOCAL_IMAGEGEN_DEFAULT_MODEL } from './modes.js';
import { computePixelDelta } from './regen.js';
import { parseByteProgress, formatDownloadMessage } from '../videoGen/generateVideoHelpers.js';
@@ -558,7 +559,7 @@ export async function generateImage({ pythonPath, prompt = '', negativePrompt =
imageGenEvents.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: await hfChildEnv(), stdio: ['ignore', 'pipe', 'pipe'] });
+ const proc = spawn(bin, args, safeChildProcessOptions({ env: await hfChildEnv(), stdio: ['ignore', 'pipe', 'pipe'] }));
activeProcess = proc;
await heavyClaim.handoffTo?.(proc.pid);
// Spawn ENOENT (missing/non-executable pythonPath) fires BOTH 'error' and
diff --git a/server/services/localLlm.js b/server/services/localLlm.js
index d0def66d74..9ce95c4474 100644
--- a/server/services/localLlm.js
+++ b/server/services/localLlm.js
@@ -225,7 +225,7 @@ const manager = (backend) => (backend === 'ollama' ? ollamaManager : lmStudioMan
*/
function runStreaming(cmd, args, onLine, timeoutMs = 0) {
return new Promise((resolve) => {
- const child = spawn(cmd, args, { stdio: ['ignore', 'pipe', 'pipe'] })
+ const child = spawn(cmd, args, { stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true })
let buffer = ''
let settled = false
const tail = [] // recent non-empty lines, capped by char budget for the error message
diff --git a/server/services/loraTraining/displayPower.js b/server/services/loraTraining/displayPower.js
index 0ea4d0f2ea..e9c048636d 100644
--- a/server/services/loraTraining/displayPower.js
+++ b/server/services/loraTraining/displayPower.js
@@ -30,7 +30,7 @@ export function isDisplaySleepEnabled(settings) {
// can't block or outlive its purpose; errors are swallowed (telemetry-grade,
// never fatal to a training run).
function runPowerCmd(cmd, args) {
- const proc = spawn(cmd, args, { stdio: 'ignore' });
+ const proc = spawn(cmd, args, { stdio: 'ignore', windowsHide: true });
proc.on('error', () => {}); // command missing / not permitted → ignore
proc.unref();
return proc;
diff --git a/server/services/loraTraining/index.js b/server/services/loraTraining/index.js
index 858425a2fb..d1df13afb0 100644
--- a/server/services/loraTraining/index.js
+++ b/server/services/loraTraining/index.js
@@ -682,7 +682,7 @@ export async function runTraining({ jobId, runId, pythonPath = null, resumeCheck
// protection doesn't wait on the OS idle timeout. Best-effort — caffeinate
// exits with the child.
if (platform() === 'darwin' && proc.pid) {
- const caf = spawn('caffeinate', ['-is', '-w', String(proc.pid)], { stdio: 'ignore' });
+ const caf = spawn('caffeinate', ['-is', '-w', String(proc.pid)], { stdio: 'ignore', windowsHide: true });
caf.on('error', () => {});
caf.unref();
}
diff --git a/server/services/mediaService.js b/server/services/mediaService.js
index 2aa1a1088a..987b432e9a 100644
--- a/server/services/mediaService.js
+++ b/server/services/mediaService.js
@@ -1,6 +1,6 @@
import { spawn } from 'child_process';
import { PassThrough } from 'stream';
-import { safeChildProcessEnv } from '../lib/processEnv.js';
+import { safeChildProcessOptions } from '../lib/processEnv.js';
let videoProcess = null;
let audioProcess = null;
@@ -14,7 +14,7 @@ async function listDevices() {
'-f', 'avfoundation',
'-list_devices', 'true',
'-i', ''
- ], { env: safeChildProcessEnv() });
+ ], safeChildProcessOptions());
let output = '';
@@ -78,7 +78,7 @@ function startVideoStream(deviceId = '0') {
'-f', 'mjpeg',
'-q:v', '5',
'-'
- ], { env: safeChildProcessEnv() });
+ ], safeChildProcessOptions());
videoProcess = child;
videoStream = stream;
@@ -122,7 +122,7 @@ function startAudioStream(deviceId = '0') {
'-ar', '48000',
'-b:a', '128k',
'-'
- ], { env: safeChildProcessEnv() });
+ ], safeChildProcessOptions());
audioProcess = child;
audioStream = stream;
diff --git a/server/services/musicVideo/audioAnalysis.js b/server/services/musicVideo/audioAnalysis.js
index fcb857b783..7fdd0a277e 100644
--- a/server/services/musicVideo/audioAnalysis.js
+++ b/server/services/musicVideo/audioAnalysis.js
@@ -27,7 +27,7 @@
import { spawn } from 'child_process';
import { findFfmpeg } from '../../lib/ffmpeg.js';
-import { safeChildProcessEnv } from '../../lib/processEnv.js';
+import { safeChildProcessOptions } from '../../lib/processEnv.js';
// Fixed analysis sample rate. 22.05kHz retains the 40Hz–8kHz spectral bands
// used for onset work and halves the sample count vs 44.1kHz. Mono — beat
@@ -172,7 +172,7 @@ export async function decodeAudioToPcm(audioPath, { signal } = {}) {
'-acodec', 'pcm_f32le',
'pipe:1',
];
- const proc = spawn(ffmpeg, args, { env: safeChildProcessEnv(), stdio: ['ignore', 'pipe', 'ignore'] });
+ const proc = spawn(ffmpeg, args, safeChildProcessOptions({ stdio: ['ignore', 'pipe', 'ignore'] }));
const chunks = [];
let onAbort = null;
if (signal) {
diff --git a/server/services/musicVideo/render.js b/server/services/musicVideo/render.js
index ab94b688e9..4e956b638c 100644
--- a/server/services/musicVideo/render.js
+++ b/server/services/musicVideo/render.js
@@ -29,7 +29,7 @@ import { ensureDir, PATHS } from '../../lib/fileUtils.js';
import { ServerError } from '../../lib/errorHandler.js';
import { broadcastSse, attachSseClient as attachSse, closeJobAfterDelay } from '../../lib/sseUtils.js';
import { findFfmpeg, safeUnder, generateThumbnail, probeVideoDuration } from '../../lib/ffmpeg.js';
-import { safeChildProcessEnv } from '../../lib/processEnv.js';
+import { safeChildProcessOptions } from '../../lib/processEnv.js';
import { killWithEscalation } from '../../lib/killWithEscalation.js';
import { attachFfmpegRenderGuard } from '../../lib/ffmpegRenderGuard.js';
import { loadHistory, mutateVideoHistory } from '../videoGen/local.js';
@@ -306,7 +306,7 @@ export async function renderMusicVideo(projectId) {
console.log(`🎬 Rendering music video [${jobId.slice(0, 8)}]: project=${projectId.slice(0, 8)} clips=${clips.length} duration=${totalDuration.toFixed(2)}s`);
- const proc = spawn(ffmpeg, args, { env: safeChildProcessEnv(), stdio: ['ignore', 'ignore', 'pipe'] });
+ const proc = spawn(ffmpeg, args, safeChildProcessOptions({ stdio: ['ignore', 'ignore', 'pipe'] }));
job.process = proc;
let stderrBuf = '';
diff --git a/server/services/ollamaManager.js b/server/services/ollamaManager.js
index ebfd6a9edb..51be73daa5 100644
--- a/server/services/ollamaManager.js
+++ b/server/services/ollamaManager.js
@@ -244,6 +244,7 @@ async function startServer() {
const child = spawn('ollama', ['serve'], {
detached: true,
stdio: ['ignore', 'ignore', 'pipe'],
+ windowsHide: true,
env: process.env
})
rememberManagedProcess(child)
diff --git a/server/services/pipeline/musicGen.js b/server/services/pipeline/musicGen.js
index d724640d7b..56bbac6239 100644
--- a/server/services/pipeline/musicGen.js
+++ b/server/services/pipeline/musicGen.js
@@ -48,7 +48,7 @@ import {
import { getCudaCapability } from '../../lib/cudaCapability.js';
import { inspectModelCache } from '../../lib/hfCache.js';
import { ServerError } from '../../lib/errorHandler.js';
-import { safeChildProcessEnv } from '../../lib/processEnv.js';
+import { safeChildProcessOptions } from '../../lib/processEnv.js';
const execFileAsync = promisify(execFile);
@@ -336,10 +336,9 @@ export async function isEngineHealthy(engineId, { refresh = false } = {}) {
engineHealthCache.set(engine.id, true);
return true;
}
- const healthy = await execFileAsync(python, ['-c', engine.healthProbe], {
- env: safeChildProcessEnv(),
+ const healthy = await execFileAsync(python, ['-c', engine.healthProbe], safeChildProcessOptions({
timeout: 60_000,
- }).then(() => true).catch(() => false);
+ })).then(() => true).catch(() => false);
engineHealthCache.set(engine.id, healthy);
return healthy;
}
diff --git a/server/services/updateExecutor.js b/server/services/updateExecutor.js
index ea2dae7135..9e57232492 100644
--- a/server/services/updateExecutor.js
+++ b/server/services/updateExecutor.js
@@ -89,6 +89,7 @@ export async function executeUpdate(tag, emit, { forceCleanWorkspaces } = {}) {
? spawn(cmd, args, {
detached: true,
stdio: ['ignore', 'pipe', 'pipe'],
+ windowsHide: true,
cwd: PATHS.root,
env: childEnv
})
diff --git a/server/services/videoGen/grok.js b/server/services/videoGen/grok.js
index 63f7f48976..b66dcf9135 100644
--- a/server/services/videoGen/grok.js
+++ b/server/services/videoGen/grok.js
@@ -200,7 +200,7 @@ async function runGrokVideo(job, jobId, bin, args, {
// Pin PWD to the spawn cwd — see withSpawnCwdEnv (#3193). grok reads
// process.cwd(), so this is defensive rather than a live fix; it keeps every
// scratch-dir spawn telling the child one consistent story about where it is.
- const proc = spawn(spawnBin, spawnArgs, { cwd: scratchDir, env: withSpawnCwdEnv(process.env, scratchDir), shell: false, stdio: [useStdin ? 'pipe' : 'ignore', 'pipe', 'pipe'] });
+ const proc = spawn(spawnBin, spawnArgs, { cwd: scratchDir, env: withSpawnCwdEnv(process.env, scratchDir), shell: false, stdio: [useStdin ? 'pipe' : 'ignore', 'pipe', 'pipe'], windowsHide: true });
activeProcs.set(jobId, proc);
const removeScratch = () => rm(scratchDir, { recursive: true, force: true }).catch(() => {});
// The route stages a multipart source image into data/uploads and hands us
diff --git a/server/services/videoGen/local.js b/server/services/videoGen/local.js
index 100bce8a54..bf00ea0002 100644
--- a/server/services/videoGen/local.js
+++ b/server/services/videoGen/local.js
@@ -39,7 +39,7 @@ import {
} from '../../lib/videoContinuity.js';
import { hfChildEnv } from '../../lib/hfToken.js';
import { inspectModelCache, findCachedRepoFile, findCachedRepoFiles } from '../../lib/hfCache.js';
-import { safeChildProcessEnv } from '../../lib/processEnv.js';
+import { safeChildProcessEnv, safeChildProcessOptions } from '../../lib/processEnv.js';
import { makeVideoGenLineHandler, finalizeGeneratedVideo, isWatchdogSuccess, describeSignalDeath, describeRenderConditioning, RENDER_INPUTS_VERSION } from './generateVideoHelpers.js';
import { assertSafeLoraFilename, getLoraKeyLayout } from '../loras.js';
import { videoLoraFamily, isLtx2FamilyRuntime } from '../../lib/runners.js';
@@ -1280,7 +1280,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,
- ], { env: safeChildProcessEnv(), timeout: 10000 }).catch((err) => ({ error: err }));
+ ], safeChildProcessOptions({ 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 };
@@ -1388,7 +1388,7 @@ export async function generateVideo({ pythonPath, prompt, negativePrompt = '', m
'-r', String(parsedFps),
'-pix_fmt', 'yuv420p', '-an',
'-y', clipPaths[i],
- ], { env: safeChildProcessEnv(), timeout: 30000 }).catch((err) => ({ error: err }))));
+ ], safeChildProcessOptions({ timeout: 30000 })).catch((err) => ({ error: err }))));
const failedAt = encodes.findIndex((r) => r?.error);
if (failedAt !== -1) {
// Unlike the resizeImage fallback (which degrades to the original), there is
@@ -2368,7 +2368,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], { env: safeChildProcessEnv(), stdio: 'ignore' });
+ const proc = spawn(ffmpeg, ['-sseof', '-1.0', '-i', videoPath, '-update', '1', '-vframes', '1', '-q:v', '2', '-y', framePath], safeChildProcessOptions({ stdio: 'ignore' }));
proc.on('close', async (code) => {
// Wrap the body so a throw (e.g. writeSidecar) routes to reject() instead
// of leaking an unhandled rejection AND leaving this Promise forever
@@ -2512,7 +2512,7 @@ export async function stitchVideos(videoIds, opts = {}) {
// return, so a failure mid-encode would otherwise trail a run of them behind
// the line that matters.
const runFfmpeg = (args, { captureStderr = false } = {}) => new Promise((resolve, reject) => {
- const proc = spawn(ffmpeg, args, { env: safeChildProcessEnv(), stdio: captureStderr ? ['ignore', 'ignore', 'pipe'] : 'ignore' });
+ const proc = spawn(ffmpeg, args, safeChildProcessOptions({ stdio: captureStderr ? ['ignore', 'ignore', 'pipe'] : 'ignore' }));
let tail = '';
proc.stderr?.on('data', (d) => { tail = `${tail}${d}`.slice(-400); });
proc.on('close', (code) => code === 0
diff --git a/server/services/videoGen/runtimes.js b/server/services/videoGen/runtimes.js
index 5bd6d1caa8..4f2c81f86f 100644
--- a/server/services/videoGen/runtimes.js
+++ b/server/services/videoGen/runtimes.js
@@ -15,7 +15,7 @@ import { join } from 'path';
import { homedir, cpus, type as osType, release as osRelease } from 'os';
import { PATHS } from '../../lib/fileUtils.js';
import { ServerError } from '../../lib/errorHandler.js';
-import { safeChildProcessEnv } from '../../lib/processEnv.js';
+import { safeChildProcessOptions } from '../../lib/processEnv.js';
import { createSingleFlight } from '../../lib/singleFlight.js';
import { MINIMAX_H3_RUNTIMES, LTX2_FAMILY_RUNTIMES } from '../../lib/runners.js';
@@ -305,10 +305,9 @@ export async function isByovRuntimeReady(runtimeId) {
// wedged import can't pin a request open; any spawn/exit failure is `false`.
function runVenvProbe(venvPython, args) {
return new Promise((resolve) => {
- const child = spawn(venvPython, args, {
- env: safeChildProcessEnv(),
+ const child = spawn(venvPython, args, safeChildProcessOptions({
stdio: ['ignore', 'ignore', 'ignore'],
- });
+ }));
const timer = setTimeout(() => { if (!child.killed) child.kill('SIGKILL'); resolve(false); }, 30000);
child.on('close', (code) => { clearTimeout(timer); resolve(code === 0); });
child.on('error', () => { clearTimeout(timer); resolve(false); });
@@ -409,10 +408,9 @@ export async function isByovRuntimeCurrent(runtimeId) {
const args = info.sourcePath
? ['-C', info.repoDir, 'status', '--porcelain=v2', '--branch', '--untracked-files=all', '--', info.sourcePath]
: ['-C', info.repoDir, 'rev-parse', 'HEAD'];
- const child = spawn('git', args, {
- env: safeChildProcessEnv(),
+ const child = spawn('git', args, safeChildProcessOptions({
stdio: ['ignore', 'pipe', 'ignore'],
- });
+ }));
const timer = setTimeout(() => { if (!child.killed) child.kill('SIGKILL'); resolve(false); }, 10000);
child.stdout.on('data', (chunk) => { if (stdout.length < 128) stdout += chunk.toString(); });
child.on('close', (code) => {
@@ -473,7 +471,7 @@ async function probeRuntimeFingerprint(runtimeId) {
const child = spawn(
info.venvPython,
[RUNTIME_FINGERPRINT_SCRIPT, runtimeId, ...(info.fingerprintPackages || [])],
- { env: safeChildProcessEnv(), stdio: ['ignore', 'pipe', 'ignore'] },
+ safeChildProcessOptions({ stdio: ['ignore', 'pipe', 'ignore'] }),
);
const timer = setTimeout(() => { if (!child.killed) child.kill('SIGKILL'); resolve({ error: 'timeout' }); }, 15000);
child.stdout.on('data', (c) => { if (out.length < FINGERPRINT_STDOUT_CAP) out += c.toString(); });
diff --git a/server/services/videoTimeline/local.js b/server/services/videoTimeline/local.js
index 477a579fa1..1703660c60 100644
--- a/server/services/videoTimeline/local.js
+++ b/server/services/videoTimeline/local.js
@@ -24,7 +24,7 @@ import { ensureDir, PATHS, readJSONFile, atomicWrite } from '../../lib/fileUtils
import { 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 { safeChildProcessOptions } from '../../lib/processEnv.js';
import { killWithEscalation } from '../../lib/killWithEscalation.js';
import { attachFfmpegRenderGuard } from '../../lib/ffmpegRenderGuard.js';
import { loadHistory, mutateVideoHistory } from '../videoGen/local.js';
@@ -179,7 +179,7 @@ const probeAudio = async (videoPath) => {
'-show_entries', 'stream=codec_type',
'-of', 'default=nw=1:nk=1',
videoPath,
- ], { env: safeChildProcessEnv(), stdio: ['ignore', 'pipe', 'ignore'] });
+ ], safeChildProcessOptions({ stdio: ['ignore', 'pipe', 'ignore'] }));
let out = '';
proc.stdout.on('data', (c) => { out += c.toString(); });
proc.on('close', () => resolve(out.trim() === 'audio'));
@@ -373,7 +373,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, { env: safeChildProcessEnv(), stdio: ['ignore', 'ignore', 'pipe'] });
+ const proc = spawn(ffmpeg, args, safeChildProcessOptions({ stdio: ['ignore', 'ignore', 'pipe'] }));
job.process = proc;
// ffmpeg's -progress pipe:2 emits key=value lines, one per line, every
diff --git a/server/services/voice/tts-piper.js b/server/services/voice/tts-piper.js
index ef4326729a..e90183d059 100644
--- a/server/services/voice/tts-piper.js
+++ b/server/services/voice/tts-piper.js
@@ -7,6 +7,7 @@ import { tmpdir } from 'os';
import { delimiter, join } from 'path';
import { expandPath, piperVoiceTildePath, voiceHome, IS_WIN, PIPER_BIN_NAME } from './config.js';
import { PIPER_VOICES, findPiperVoice } from './piper-voices.js';
+import { safeChildProcessOptions } from '../../lib/processEnv.js';
const PIPER_TIMEOUT_MS = 30_000;
const VOICES_DIR = join(voiceHome(), 'voices');
@@ -52,7 +53,7 @@ export const synthesizePiper = (text, cfg, signal) => {
? `${piperLib}${delimiter}${process.env.LD_LIBRARY_PATH}`
: piperLib;
}
- const child = spawn(piperBin, args, { stdio: ['pipe', 'pipe', 'pipe'], env });
+ const child = spawn(piperBin, args, safeChildProcessOptions({ stdio: ['pipe', 'pipe', 'pipe'], env }));
const chunks = [];
let errBuf = '';
let killed = false;
diff --git a/server/services/youtubeIngest.js b/server/services/youtubeIngest.js
index 33b083226d..6f593c3d17 100644
--- a/server/services/youtubeIngest.js
+++ b/server/services/youtubeIngest.js
@@ -46,7 +46,7 @@ import { atomicWrite, ensureDir, PATHS, readJSONFile, shortId } from '../lib/fil
import { findFfmpeg } from '../lib/ffmpeg.js';
import { findYtDlp } from '../lib/ytdlp.js';
import { killWithEscalation } from '../lib/killWithEscalation.js';
-import { safeChildProcessEnv } from '../lib/processEnv.js';
+import { safeChildProcessOptions } from '../lib/processEnv.js';
import { attachSseClient as attachSse, broadcastSse, closeJobAfterDelay } from '../lib/sseUtils.js';
import { vttToPlainText } from '../lib/vttTranscript.js';
import { createMutex } from '../lib/asyncMutex.js';
@@ -256,7 +256,7 @@ export async function deleteIngest(videoId) {
// media downloads go through the shared audio/video cores instead.
function runYtDlp(ytDlp, args, { timeoutMs, registerProcess }) {
return new Promise((resolve) => {
- const proc = spawn(ytDlp, args, { env: safeChildProcessEnv(), stdio: ['ignore', 'pipe', 'pipe'] });
+ const proc = spawn(ytDlp, args, safeChildProcessOptions({ stdio: ['ignore', 'pipe', 'pipe'] }));
registerProcess?.(proc);
let stdout = '';
let stderr = '';
diff --git a/server/services/ytdlpAudioImport.js b/server/services/ytdlpAudioImport.js
index 19191b87bc..8b9864b852 100644
--- a/server/services/ytdlpAudioImport.js
+++ b/server/services/ytdlpAudioImport.js
@@ -28,7 +28,7 @@ import { join, dirname } from 'path';
import { ServerError } from '../lib/errorHandler.js';
import { findFfmpeg } from '../lib/ffmpeg.js';
import { findYtDlp } from '../lib/ytdlp.js';
-import { safeChildProcessEnv } from '../lib/processEnv.js';
+import { safeChildProcessOptions } from '../lib/processEnv.js';
import { createLineReader } from '../lib/streamLines.js';
const TITLE_PREFIX = 'PORTOS_TITLE:';
@@ -121,7 +121,7 @@ export async function downloadAudioToTempMp3({
url,
];
- const proc = spawn(ytDlp, args, { env: safeChildProcessEnv(), stdio: ['ignore', 'pipe', 'pipe'] });
+ const proc = spawn(ytDlp, args, safeChildProcessOptions({ stdio: ['ignore', 'pipe', 'pipe'] }));
registerProcess(proc);
const onLine = (line) => {
diff --git a/server/services/ytdlpVideoImport.js b/server/services/ytdlpVideoImport.js
index 498350bc04..a853ac413a 100644
--- a/server/services/ytdlpVideoImport.js
+++ b/server/services/ytdlpVideoImport.js
@@ -20,7 +20,7 @@ import { spawn } from 'child_process';
import { readdir, unlink } from 'fs/promises';
import { join, dirname } from 'path';
import { ensureDir } from '../lib/fileUtils.js';
-import { safeChildProcessEnv } from '../lib/processEnv.js';
+import { safeChildProcessOptions } from '../lib/processEnv.js';
import { createLineReader } from '../lib/streamLines.js';
const TITLE_PREFIX = 'PORTOS_TITLE:';
@@ -125,7 +125,7 @@ export async function downloadVideoToDir({
url,
];
- const proc = spawn(ytDlp, args, { env: safeChildProcessEnv(), stdio: ['ignore', 'pipe', 'pipe'] });
+ const proc = spawn(ytDlp, args, safeChildProcessOptions({ stdio: ['ignore', 'pipe', 'pipe'] }));
registerProcess(proc);
const onLine = (line) => {