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: make the Windows runtime installers actually reach Git Bash
[._.]/ Adam Eivyeea226f183bc
diff --git a/.changelog/next/fixed-agent-6529e5b8.md b/.changelog/next/fixed-agent-6529e5b8.mdnew file mode 100644index 0000000000..13b294d177--- /dev/null+++ b/.changelog/next/fixed-agent-6529e5b8.md@@ -0,0 +1 @@+- Windows: the in-app runtime installers (Video Gen BYOV runtimes incl. MiniMax H3 CUDA, the music engines, the MuScriptor MIDI venv) and app `deploy.sh` runs now go through Git Bash instead of a bare `bash` that PM2 often resolves to WSL. The installer also gets a script path bash can open, a `PYTHON_BIN` that isn't the WindowsApps Store stub, and a cancel that takes uv / pip / git down with it.diff --git a/server/lib/README.md b/server/lib/README.mdindex 99d2138ee1..f775f94b47 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -183,9 +183,10 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| Module | Purpose ||---|---|| `agentGuard/` | `agentGuardEnv(baseEnv?)` + `AGENT_GUARD_BIN` — env patch that prepends a guarded `pm2` shim (`bin/pm2`) to a spawned AI agent's PATH so a confused `--dangerously-skip-permissions` agent can't `pm2 kill` / `pm2 delete all` the shared daemon (which would down every app, incl. PortOS). Blocked-subcommand list mirrors `validatePm2Command` in `commandSecurity.js`. POSIX-only (no-op on Windows). |-| `bashResolver.js` | `resolveBashBinary()` — resolves the POSIX `bash` for running bundled `*.sh` scripts (e.g. `scripts/db.sh`). On Windows a bare `bash` often resolves (via PM2's PATH) to WSL, which mounts drives at `/mnt/h` and can't see a `H:/...` drive path (exit 127); this prefers Git Bash (PORTOS_BASH override → standard install dirs → derived from `git` on PATH → bare `bash`). No-op (`bash`) on non-Windows. |+| `bashResolver.js` | `resolveBashBinary()` — resolves the POSIX `bash` for running bundled `*.sh` scripts (e.g. `scripts/db.sh`). On Windows a bare `bash` often resolves (via PM2's PATH) to WSL, which mounts drives at `/mnt/h` and can't see a `H:/...` drive path (exit 127); this prefers Git Bash (PORTOS_BASH override → standard install dirs → derived from `git` on PATH → bare `bash`). No-op (`bash`) on non-Windows. `toBashPath(p)` — the companion path rule: bash reads backslashes as escapes, so a Windows path must reach it with forward slashes. || `openFolder.js` | `openFolderInSystemExplorer(localPath)` — cross-platform "open in Finder/Explorer/Nautilus" via detached spawn; child `error` handler prevents spawn failures from crashing the process. |-| `bufferedSpawn.js` | `bufferedSpawn(cmd, args, opts)` (structured non-throwing result) + `bufferedSpawnOrThrow` (throwing adapter), plus `killProcessTree`, `resolveWindowsExecutable`, `prepareWindowsSafeSpawn`, `prepareCliSpawn(command, args, env)` (composed resolve+wrap for a `spawn()`-safe pair), `needsShell`, `IS_WIN32`, `WIN_CMD_SHIMS`, `MAX_OUTPUT_BYTES` — shared buffered-spawn machinery with capped stdout/stderr, timeout-kill, Windows `.cmd`/`.bat` shim resolution, and `taskkill /T /F` tree-kill. Used by `appBuilder.js`, `appUpdater.js`, and the CoS agent spawners. |+| `bufferedSpawn.js` | `bufferedSpawn(cmd, args, opts)` (structured non-throwing result) + `bufferedSpawnOrThrow` (throwing adapter), plus `killProcessTree`, `resolveWindowsExecutable`, `prepareWindowsSafeSpawn`, `prepareCliSpawn(command, args, env)` (composed resolve+wrap for a `spawn()`-safe pair), `needsShell`, `IS_WIN32`, `WIN_CMD_SHIMS`, `MAX_OUTPUT_BYTES` — shared buffered-spawn machinery with capped stdout/stderr, timeout-kill, Windows `.cmd`/`.bat` shim resolution, and `taskkill /T /F` tree-kill. `killProcessTree(child, signal, { processGroup })` takes the POSIX group down too when the child was spawned `detached` (Windows always tree-kills). Used by `appBuilder.js`, `appUpdater.js`, the CoS agent spawners, and `setupScriptRunner.js`. |+| `setupScriptRunner.js` | `spawnSetupScript(envVars)` / `stopSetupScript(child)` / `SETUP_IMAGE_VIDEO_SCRIPT` — the one way to run `scripts/setup-image-video.sh` (shared by the Video Gen BYOV runtimes, the music engines and the MuScriptor venv). Runs it under `resolveBashBinary()` with a `toBashPath` script path, and on Windows presets the `PYTHON_BIN` the script would otherwise default to `python3` for. Cancel via `stopSetupScript`, which tree-kills so uv / pip / git die with bash. || `commandExists.js` | `commandExists(cmd, args = ['--version'], { timeoutMs = 5_000 })` — does running `cmd args` succeed? A capability probe (`execFile`-based), not a PATH lookup like `processEnv.js`'s `whichFirst`. Consolidates the two previously-private copies in `localLlm.js`/`ollamaManager.js`; callers probing a heavier CLI (e.g. `codeReview.js`'s reviewer-binary probe) pass a longer `timeoutMs`. || `spawnCwd.js` | `resolveSpawnCwd(workspacePath, fallbackRoot, label)` — resolves and **logs** the working directory a run/agent spawns into (expanding `~`), and throws when a workspace was requested but is missing / not a directory. Behind `services/runner.js#resolveRunCwd`, which turns that throw into a normal failed-run record for the two spawning runners. Stops a bad app `repoPath` from silently spawning in the PortOS checkout (#3180). `withSpawnCwdEnv(env, cwd)` — returns a copy of `env` with `PWD` pinned to `cwd` (dropping stale case-variant keys), because `spawn({ cwd })` doesn't rewrite the inherited `PWD` and OpenCode resolves its project root as `process.env.PWD ?? process.cwd()` (#3193). Apply it at every spawn that names its own cwd — the shared wrappers (`bufferedSpawn`, `spawnDetached`) already do, so their callers inherit it. `spawnCwd.test.js` discovers cwd-passing spawns across `server/` and fails on any that neither pins nor is listed exempt.| `commandSecurity.js` | Allowlist of safe shell commands + `validatePm2Command(args)` (rejects daemon-wide `pm2 kill`/`startup`/`unstartup` and `<verb> all`). `validateCommand` runs the pm2 check for `pm2` base commands. Mirrored by the `agentGuard/` PATH shim for agentic paths. |@@ -201,7 +202,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`. |+| `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`). || `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. || `vttTranscript.js` | WebVTT/SRT → readable prose. `vttToPlainText(vtt)` (paragraph-joined transcript), `vttToLines(vtt)` (cleaned caption lines), `cleanCaptionLine(line)`. Collapses YouTube auto-captions' rolling repetition and strips inline `<c>`/timestamp markup. Used by the brain YouTube ingest. |diff --git a/server/lib/bashResolver.js b/server/lib/bashResolver.jsindex e4fd9e4f5f..c8230b503d 100644--- a/server/lib/bashResolver.js+++ b/server/lib/bashResolver.js@@ -65,6 +65,18 @@ function gitBashFromPath() {return existsSync(bash) ? bash : null;}+/**+ * A path in the form bash can open. Windows-native paths arrive with+ * backslashes, which bash reads as escape characters — `H:\repo\x.sh` collapses+ * to `H:repox.sh` and exits 127 ("No such file or directory"). Git Bash accepts+ * drive paths written with forward slashes. No-op on POSIX, which has no+ * backslashes to convert.+ *+ * @param {string} p+ * @returns {string}+ */+export const toBashPath = (p) => String(p).replace(/\\/g, '/');+let cached;/**diff --git a/server/lib/bufferedSpawn.js b/server/lib/bufferedSpawn.jsindex ca77fb94a5..987e8d38dc 100644--- a/server/lib/bufferedSpawn.js+++ b/server/lib/bufferedSpawn.js@@ -215,6 +215,14 @@ export const MAX_OUTPUT_BYTES = 64 * 1024;* ConPTY handle), leaking it — so any non-ChildProcess killable always uses* its own `.kill()` instead, on every platform.*+ * `processGroup` is for a child spawned `detached` on POSIX: without it the+ * non-Windows branch signals a single pid, which leaves a shell's own children+ * (the uv / pip / git an installer script shells out to) running. With it the+ * negative pid signals the whole group, falling back to the single pid when the+ * group is already gone. Windows needs no flag — `taskkill /T` is always the+ * tree. Off by default because a non-detached child shares its PARENT's group,+ * where a group signal would reach the wrong processes.+ ** `signal` applies to the **POSIX** branch only (`SIGTERM` default → the* graceful-then-`SIGKILL`-escalation pattern callers expect). On Windows there* is no real POSIX signal — `taskkill /T /F` force-kills the whole tree@@ -225,18 +233,24 @@ export const MAX_OUTPUT_BYTES = 64 * 1024;** @param {import('child_process').ChildProcess} child* @param {NodeJS.Signals} [signal] - POSIX signal to send (default `SIGTERM`); ignored on Windows+ * @param {{processGroup?: boolean}} [opts] - POSIX: signal the child's process group (it must have been spawned `detached`)*/-export function killProcessTree(child, signal = 'SIGTERM') {+export function killProcessTree(child, signal = 'SIGTERM', { processGroup = false } = {}) {if (IS_WIN32 && child.pid && child instanceof ChildProcess) {child.killed = true;spawn('taskkill', ['/T', '/F', '/PID', String(child.pid)], { stdio: 'ignore', windowsHide: true }).on('error', () => {}).unref();- } else {- child.kill(signal);+ return;+ }+ if (processGroup && child.pid) {+ try { process.kill(-child.pid, signal); return; }+ catch { /* ESRCH — the group is already gone; fall through to the pid */ }}+ child.kill(signal);}+/*** Spawn a command, buffer its (capped) stdout/stderr, enforce a timeout, and* resolve a structured result. NEVER rejects — every terminal conditiondiff --git a/server/lib/bufferedSpawn.test.js b/server/lib/bufferedSpawn.test.jsindex 0ce5e7539c..73b54e4014 100644--- a/server/lib/bufferedSpawn.test.js+++ b/server/lib/bufferedSpawn.test.js@@ -113,6 +113,38 @@ describe('killProcessTree', () => {expect(child.killed).toBe(true);});+ it('on non-Windows with processGroup signals the whole group, so a detached shell takes its children with it', () => {+ if (IS_WIN32) return; // platform-gated behavior+ const child = makeFakeChild({ pid: 555 });+ const killSpy = vi.spyOn(process, 'kill').mockImplementation(() => true);+ killProcessTree(child, undefined, { processGroup: true });+ expect(killSpy).toHaveBeenCalledWith(-555, 'SIGTERM');+ expect(child.kill).not.toHaveBeenCalled();+ killSpy.mockRestore();+ });++ it('on non-Windows falls back to the single pid when the group is already gone (ESRCH)', () => {+ if (IS_WIN32) return; // platform-gated behavior+ const child = makeFakeChild();+ const killSpy = vi.spyOn(process, 'kill').mockImplementation(() => { throw new Error('ESRCH'); });+ killProcessTree(child, 'SIGKILL', { processGroup: true });+ expect(child.kill).toHaveBeenCalledWith('SIGKILL');+ killSpy.mockRestore();+ });++ it('on Windows ignores processGroup — taskkill /T is already the tree', () => {+ if (!IS_WIN32) return; // platform-gated behavior+ const child = makeFakeChild({ pid: 777 });+ const tk = makeFakeChild();+ tk.unref = vi.fn();+ spawnMock.mockReturnValueOnce(tk);+ const killSpy = vi.spyOn(process, 'kill').mockImplementation(() => true);+ killProcessTree(child, undefined, { processGroup: true });+ expect(spawnMock).toHaveBeenCalledWith('taskkill', ['/T', '/F', '/PID', '777'], expect.anything());+ expect(killSpy).not.toHaveBeenCalled();+ killSpy.mockRestore();+ });+it('on Windows still uses .kill() (not taskkill) for a non-ChildProcess killable, e.g. a node-pty session', () => {if (!IS_WIN32) return; // can't simulate platform branch from outside// A killable that exposes .kill()/.pid like a ChildProcess but isn't onediff --git a/server/lib/index.js b/server/lib/index.jsindex 506073dd69..ebe3b5feac 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -183,6 +183,7 @@ export * from './bufferedSpawn.js';export * from './commandExists.js';export * from './commandSecurity.js';export * from './detachedSpawn.js';+export * from './setupScriptRunner.js';export * from './hostShutdown.js';export * from './execGit.js';export * from './ffmpeg.js';diff --git a/server/lib/processEnv.js b/server/lib/processEnv.jsindex 45057d4745..81596b53fd 100644--- a/server/lib/processEnv.js+++ b/server/lib/processEnv.js@@ -10,7 +10,7 @@//// The Malloc* family is documented in libmalloc(3) and only affects macOS;// stripping the prefix is a no-op on Linux/Windows.-import { execFile } from 'child_process';+import { execFile, execFileSync } from 'child_process';import { promisify } from 'util';const execFileAsync = promisify(execFile);@@ -32,6 +32,21 @@ export function safeChildProcessEnv(extra = {}) {// path of the first match, or `null` when the binary isn't on PATH or the// probe fails. Spawns through `safeChildProcessEnv()` (Malloc-stripped) with a// 5s timeout; `where` can return several lines, so we take the first.+// Synchronous `whichFirst`, for the few callers that resolve a binary while+// building a spawn and cannot await (pythonSetup's detectPythonSync, behind the+// installer spawn). Same contract: absolute path of the first match, or null.+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'],+ });+ return stdout.trim().split(/\r?\n/)[0] || null;+ } catch {+ return null; // not on PATH, or the probe itself failed+ }+}+export async function whichFirst(name) {const cmd = IS_WIN ? 'where' : 'which';const { stdout } = await execFileAsync(cmd, [name], { env: safeChildProcessEnv(), timeout: 5000 })diff --git a/server/lib/pythonSetup.js b/server/lib/pythonSetup.jsindex 0aeb36f4e4..8e056ec1a4 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 } from './processEnv.js';+import { safeChildProcessEnv, whichFirst, whichFirstSync } from './processEnv.js';import { createLineReader } from './streamLines.js';import { getCudaCapability } from './cudaCapability.js';@@ -116,6 +116,26 @@ const firstArchMatch = async (candidates, predicate) => {return idx >= 0 ? candidates[idx] : null;};+// First installed candidate — the synchronous half of detectPython(), for+// callers that cannot await (spawnSetupScript in lib/setupScriptRunner.js,+// where an extra await would open an abort window between the in-flight claim+// and the spawn). Prefer detectPython() when you can: the arch probe this+// skips is what keeps an x86_64 conda from beating an arm64 Homebrew python+// for mlx wheels on Apple Silicon.+export function detectPythonSync() {+ const present = PYTHON_CANDIDATES.find((p) => existsSync(p));+ if (present) return present;+ // Same PATH fallback detectPython() ends on — without it a Python installed+ // somewhere the candidate list does not name (scoop, chocolatey, a custom+ // dir) reads as "no Python at all", which is exactly the box where the+ // Windows installer then falls back to its broken `python3` default.+ const found = whichFirstSync(IS_WIN ? 'python' : 'python3');+ // The WindowsApps alias is a Store launcher, not an interpreter: it opens the+ // Microsoft Store and exits, so a venv built from it never appears.+ if (found && /\\Microsoft\\WindowsApps\\/i.test(found)) return null;+ return found || null;+}+export async function detectPython() {// mlx ships arm64-only wheels; prefer an arm64 interpreter on Apple Silicon// so /opt/anaconda3 (often x86_64) doesn't beat /opt/homebrew/bin/python3.diff --git a/server/lib/pythonSetup.test.js b/server/lib/pythonSetup.test.jsindex 6b6a7449b5..a6e233476b 100644--- a/server/lib/pythonSetup.test.js+++ b/server/lib/pythonSetup.test.js@@ -13,6 +13,7 @@ const mockState = {presentPaths: new Set(),archByPath: new Map(),execShouldFail: false,+ pathPython: null,};vi.mock('node:os', async () => {@@ -57,6 +58,14 @@ vi.mock('node:child_process', async () => {return { ...actual, execFile: fakeExecFile };});+// The PATH fallbacks shell out for real; stub them so a test box's own Python+// can't decide the result. safeChildProcessEnv stays real (probePythonArch uses it).+vi.mock('./processEnv.js', async (importOriginal) => ({+ ...(await importOriginal()),+ whichFirst: async () => mockState.pathPython,+ whichFirstSync: () => mockState.pathPython,+}));+vi.mock('./fileUtils.js', () => ({ PATHS: { data: '/data' } }));const loadModule = async () => {@@ -71,6 +80,7 @@ const resetState = () => {mockState.presentPaths = new Set();mockState.archByPath = new Map();mockState.execShouldFail = false;+ mockState.pathPython = null;};describe('HOST_ARCH', () => {@@ -168,6 +178,36 @@ describe('detectPython on darwin/arm64', () => {});});+describe('detectPythonSync', () => {+ beforeEach(resetState);++ it('returns the first present candidate without probing arch', async () => {+ mockState.presentPaths.add('/opt/anaconda3/bin/python3');+ mockState.presentPaths.add('/opt/homebrew/bin/python3');+ const { detectPythonSync } = await loadModule();+ expect(detectPythonSync()).toBe('/opt/anaconda3/bin/python3');+ });++ it('falls back to PATH when no candidate path exists — a scoop / chocolatey / custom-dir install still counts', async () => {+ mockState.platform = 'win32';+ mockState.pathPython = 'C:/tools/python311/python.exe';+ const { detectPythonSync } = await loadModule();+ expect(detectPythonSync()).toBe('C:/tools/python311/python.exe');+ });++ it('rejects the WindowsApps alias — it opens the Microsoft Store instead of building a venv', async () => {+ mockState.platform = 'win32';+ mockState.pathPython = 'C:\\Users\\example\\AppData\\Local\\Microsoft\\WindowsApps\\python.exe';+ const { detectPythonSync } = await loadModule();+ expect(detectPythonSync()).toBeNull();+ });++ it('returns null when there is no Python anywhere', async () => {+ const { detectPythonSync } = await loadModule();+ expect(detectPythonSync()).toBeNull();+ });+});+describe('detectArm64Python', () => {beforeEach(resetState);diff --git a/server/lib/setupScriptRunner.js b/server/lib/setupScriptRunner.jsnew file mode 100644index 0000000000..35ad44d84e--- /dev/null+++ b/server/lib/setupScriptRunner.js@@ -0,0 +1,65 @@+/**+ * Spawn (and cancel) `scripts/setup-image-video.sh` — the single installer the+ * Video Gen BYOV runtimes, the music engines and the MuScriptor MIDI venv all+ * shell out to, each with a different `INSTALL_*` env var set.+ *+ * The three routes that do this were each spawning a bare `bash`, which on+ * Windows resolves through PM2's PATH and is often WSL rather than the Git Bash+ * the script's own `is_windows()` is written for (see `bashResolver.js` for that+ * whole failure mode). Beyond picking the interpreter, running the script on+ * Windows needs two more things this owns: `toBashPath` on the script path, and+ * a `PYTHON_BIN` — the script defaults to `python3`, which on Windows is either+ * absent or the WindowsApps stub that opens the Microsoft Store instead of+ * creating a venv.+ */++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 { detectPythonSync } from './pythonSetup.js';+import { killProcessTree } from './bufferedSpawn.js';++const IS_WIN = process.platform === 'win32';++export const SETUP_IMAGE_VIDEO_SCRIPT = join(PATHS.root, 'scripts', 'setup-image-video.sh');++/**+ * Spawn the installer with `INSTALL_*` env vars pre-set. Takes no script path:+ * `PYTHON_BIN` is setup-image-video.sh's own variable, so this is that script's+ * runner, not a general `.sh` spawner.+ *+ * @param {Record<string,string>} [envVars] - extra env for the child+ * @returns {import('child_process').ChildProcess} stdout/stderr piped, stdin ignored+ */+export function spawnSetupScript(envVars = {}) {+ const env = { ...envVars };+ // An explicit PYTHON_BIN — from the caller or the environment — is the+ // documented override and wins over anything detected here.+ if (IS_WIN && !env.PYTHON_BIN && !process.env.PYTHON_BIN) {+ const python = detectPythonSync();+ if (python) env.PYTHON_BIN = toBashPath(python);+ }+ return spawn(resolveBashBinary(), [toBashPath(SETUP_IMAGE_VIDEO_SCRIPT)], {+ 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,+ });+}++/**+ * Terminate a running installer and its descendants. Safe to call on an+ * already-dead or never-spawned child.+ *+ * @param {import('child_process').ChildProcess|null} child+ * @param {NodeJS.Signals} [signal] - POSIX signal; ignored on Windows+ */+export function stopSetupScript(child, signal = 'SIGTERM') {+ if (!child?.pid || child.killed) return;+ killProcessTree(child, signal, { processGroup: true });+}diff --git a/server/lib/setupScriptRunner.test.js b/server/lib/setupScriptRunner.test.jsnew file mode 100644index 0000000000..3cec2e98c2--- /dev/null+++ b/server/lib/setupScriptRunner.test.js@@ -0,0 +1,142 @@+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';+import { EventEmitter } from 'events';++// Mock the collaborators so the behavior under test is observable without+// launching bash, probing the filesystem for a Python, or firing a real kill.+const spawnMock = vi.fn();+vi.mock('child_process', async (importOriginal) => {+ const actual = await importOriginal();+ return { ...actual, spawn: (...a) => spawnMock(...a) };+});+vi.mock('./bashResolver.js', async (importOriginal) => ({+ ...(await importOriginal()), // real toBashPath — its output is asserted below+ resolveBashBinary: () => 'C:/Program Files/Git/bin/bash.exe',+}));+const detectPythonSyncMock = vi.fn();+vi.mock('./pythonSetup.js', () => ({+ detectPythonSync: (...a) => detectPythonSyncMock(...a),+}));+const killProcessTreeMock = vi.fn();+vi.mock('./bufferedSpawn.js', () => ({+ killProcessTree: (...a) => killProcessTreeMock(...a),+}));++const REAL_PLATFORM = process.platform;++/**+ * Import a fresh copy of the module with `process.platform` pinned. The Windows+ * branches are the whole point of this module, so they have to be exercised+ * from a macOS/Linux runner too — and the module reads the platform once at+ * load, so each platform needs its own module instance.+ */+async function loadFor(platform) {+ Object.defineProperty(process, 'platform', { value: platform, configurable: true });+ vi.resetModules();+ return import('./setupScriptRunner.js');+}++function makeFakeChild({ pid = 4321, killed = false } = {}) {+ const child = new EventEmitter();+ child.pid = pid;+ child.killed = killed;+ child.kill = vi.fn();+ return child;+}++beforeEach(() => {+ spawnMock.mockReset();+ spawnMock.mockImplementation(() => makeFakeChild());+ detectPythonSyncMock.mockReset();+ detectPythonSyncMock.mockReturnValue(null);+ killProcessTreeMock.mockReset();+ delete process.env.PYTHON_BIN;+});++afterEach(() => {+ Object.defineProperty(process, 'platform', { value: REAL_PLATFORM, configurable: true });+ delete process.env.PYTHON_BIN;+});++describe('spawnSetupScript', () => {+ it('runs the bundled installer under the resolved bash, with a path bash can open', async () => {+ const { spawnSetupScript, SETUP_IMAGE_VIDEO_SCRIPT } = await loadFor('win32');+ spawnSetupScript({ INSTALL_MINIMAX_H3_CUDA: '1' });+ const [bin, argv, opts] = spawnMock.mock.calls[0];+ // Never a bare `bash` (PM2 may resolve that to WSL) and never a backslash+ // path (bash reads those as escapes and exits 127).+ expect(bin).toBe('C:/Program Files/Git/bin/bash.exe');+ expect(argv).toEqual([SETUP_IMAGE_VIDEO_SCRIPT.replace(/\\/g, '/')]);+ expect(argv[0]).toMatch(/\/scripts\/setup-image-video\.sh$/);+ expect(opts.stdio).toEqual(['ignore', 'pipe', 'pipe']);+ expect(opts.env.INSTALL_MINIMAX_H3_CUDA).toBe('1');+ });++ it('on Windows presets PYTHON_BIN — the script defaults to `python3`, which is absent or a Store stub there', async () => {+ detectPythonSyncMock.mockReturnValue('C:\\Users\\example\\AppData\\Local\\Programs\\Python\\Python312\\python.exe');+ const { spawnSetupScript } = await loadFor('win32');+ spawnSetupScript({ INSTALL_MINIMAX_H3_CUDA: '1' });+ // Forward slashes here too: bash's `command -v` reads this as a path.+ expect(spawnMock.mock.calls[0][2].env.PYTHON_BIN)+ .toBe('C:/Users/example/AppData/Local/Programs/Python/Python312/python.exe');+ });++ it('leaves PYTHON_BIN unset when no interpreter is found, so the script reports its own missing-Python error', async () => {+ detectPythonSyncMock.mockReturnValue(null);+ const { spawnSetupScript } = await loadFor('win32');+ spawnSetupScript({});+ expect(spawnMock.mock.calls[0][2].env.PYTHON_BIN).toBeUndefined();+ });++ it('never overrides an explicit PYTHON_BIN — from the caller or the environment', async () => {+ detectPythonSyncMock.mockReturnValue('C:/detected/python.exe');+ const { spawnSetupScript } = await loadFor('win32');++ spawnSetupScript({ PYTHON_BIN: 'C:/caller/python.exe' });+ expect(spawnMock.mock.calls[0][2].env.PYTHON_BIN).toBe('C:/caller/python.exe');++ process.env.PYTHON_BIN = 'C:/env/python.exe';+ spawnSetupScript({});+ expect(spawnMock.mock.calls[1][2].env.PYTHON_BIN).toBe('C:/env/python.exe');+ // Neither call had to look for one — the explicit value short-circuits.+ expect(detectPythonSyncMock).not.toHaveBeenCalled();+ });++ it('does not touch PYTHON_BIN off Windows — `python3` is the right default there', async () => {+ detectPythonSyncMock.mockReturnValue('/opt/homebrew/bin/python3');+ const { spawnSetupScript } = await loadFor('darwin');+ spawnSetupScript({});+ expect(spawnMock.mock.calls[0][2].env.PYTHON_BIN).toBeUndefined();+ expect(detectPythonSyncMock).not.toHaveBeenCalled();+ });++ it('detaches on POSIX (so a cancel can signal the group) but not on Windows', async () => {+ const posix = await loadFor('darwin');+ posix.spawnSetupScript({});+ expect(spawnMock.mock.calls[0][2].detached).toBe(true);++ const win = await loadFor('win32');+ win.spawnSetupScript({});+ const opts = spawnMock.mock.calls[1][2];+ expect(opts.detached).toBe(false);+ expect(opts.windowsHide).toBe(true);+ });+});++describe('stopSetupScript', () => {+ it('tree-kills with the process-group flag, so uv / pip / git die with bash', async () => {+ const { stopSetupScript } = await loadFor(REAL_PLATFORM);+ const child = makeFakeChild();+ stopSetupScript(child);+ expect(killProcessTreeMock).toHaveBeenCalledWith(child, 'SIGTERM', { processGroup: true });+ });++ it('no-ops on a child that was never spawned or is already killed', async () => {+ const { stopSetupScript } = await loadFor(REAL_PLATFORM);+ const noPid = makeFakeChild();+ noPid.pid = undefined; // spawn() failed — nothing to signal+ stopSetupScript(null);+ stopSetupScript(makeFakeChild({ killed: true }));+ stopSetupScript(noPid);+ expect(killProcessTreeMock).not.toHaveBeenCalled();+ });+});diff --git a/server/routes/database.js b/server/routes/database.jsindex ef4bc8e267..7526e37a6f 100644--- a/server/routes/database.js+++ b/server/routes/database.js@@ -8,15 +8,10 @@ import { checkHealth, query } from '../lib/db.js';import { PATHS } from '../lib/fileUtils.js';import { stripAnsi } from '../lib/ansiStrip.js';import { resolvePgDumpBinary } from '../lib/pgTools.js';-import { resolveBashBinary } from '../lib/bashResolver.js';+import { resolveBashBinary, toBashPath } from '../lib/bashResolver.js';const rootDir = PATHS.root;-// Pass the script path to bash with forward slashes. On Windows the native-// path is `H:\...\db.sh`; bash treats each backslash as an escape character-// and collapses it to `H:...db.sh` (exit 127, "No such file or directory").-// Git Bash accepts drive paths with forward slashes (`H:/.../db.sh`), so-// normalize separators here. POSIX paths are unaffected (no backslashes).-const dbScript = join(rootDir, 'scripts', 'db.sh').replace(/\\/g, '/');+const dbScript = toBashPath(join(rootDir, 'scripts', 'db.sh'));// Resolve the interpreter explicitly. A bare `bash` on Windows often resolves// (via PM2's PATH) to WSL, which mounts drives at /mnt/h and can't see the// `H:/...` drive path above — exit 127. resolveBashBinary() prefers Git Bash,diff --git a/server/routes/database.test.js b/server/routes/database.test.jsindex 57df27d90f..e80be2b9de 100644--- a/server/routes/database.test.js+++ b/server/routes/database.test.js@@ -11,7 +11,8 @@ import { request } from '../lib/testHelper.js';// resolveBashBinary and the db.sh path are resolved at module load — mock// the dependencies before the route is imported.-vi.mock('../lib/bashResolver.js', () => ({+vi.mock('../lib/bashResolver.js', async (importOriginal) => ({+ ...(await importOriginal()), // real toBashPath — only the binary needs pinningresolveBashBinary: vi.fn(() => 'bash'),}));diff --git a/server/routes/midiRuntime.js b/server/routes/midiRuntime.jsindex 29f5d05402..c5c0c827ae 100644--- a/server/routes/midiRuntime.js+++ b/server/routes/midiRuntime.js@@ -16,12 +16,9 @@import { Router } from 'express';import { existsSync } from 'fs';-import { spawn } from 'child_process';-import { join } from 'path';import { asyncHandler } from '../lib/errorHandler.js';-import { PATHS } from '../lib/fileUtils.js';-import { safeChildProcessEnv } from '../lib/processEnv.js';import { createLineReader } from '../lib/streamLines.js';+import { SETUP_IMAGE_VIDEO_SCRIPT, spawnSetupScript, stopSetupScript } from '../lib/setupScriptRunner.js';import { openSseStream } from '../lib/sseDownload.js';import { createInstallLogger } from '../lib/installLogger.js';import {@@ -70,14 +67,10 @@ router.get('/install', asyncHandler(async (req, res) => {installLog.cancel();if (finished) return;if (child) {- if (!child.killed && child.pid) {- // Negative pid signals the whole process group — setup-image-video.sh- // shells out to uv / pip / git, and a plain SIGTERM on bash leaves those- // running. Guard against ESRCH on an already-dead group.- try { process.kill(-child.pid, 'SIGTERM'); }- catch { child.kill('SIGTERM'); }- }- // Do NOT clear installInFlight here — the SIGTERM'd process group is only+ // setup-image-video.sh shells out to uv / pip / git; stopSetupScript+ // takes those down with bash rather than orphaning the download.+ stopSetupScript(child);+ // Do NOT clear installInFlight here — the installer has only been// signalled, not yet reaped, and a mid-download pip child can take seconds// to exit. Releasing the singleton now would let an immediate retry spawn a// second install against the same half-torn-down venv. child.on('close')@@ -110,23 +103,15 @@ router.get('/install', asyncHandler(async (req, res) => {return safeEnd();}- const scriptPath = join(PATHS.root, 'scripts', 'setup-image-video.sh');- if (!existsSync(scriptPath)) {+ if (!existsSync(SETUP_IMAGE_VIDEO_SCRIPT)) {installInFlight = null;- send({ type: 'error', message: `Installer script not found at ${scriptPath}` });+ send({ type: 'error', message: `Installer script not found at ${SETUP_IMAGE_VIDEO_SCRIPT}` });return safeEnd();}send({ type: 'log', message: `Starting MuScriptor install via ${MUSCRIPTOR_INSTALL_ENV}=1 bash scripts/setup-image-video.sh` });installLog.start();- // `detached: true` puts bash in its own process group so a cancel (client- // closing the SSE stream) can SIGTERM uv / pip / git children too — otherwise- // a multi-GB download keeps burning bandwidth after the modal closes.- child = spawn('bash', [scriptPath], {- env: safeChildProcessEnv({ [MUSCRIPTOR_INSTALL_ENV]: '1' }),- stdio: ['ignore', 'pipe', 'pipe'],- detached: true,- });+ child = spawnSetupScript({ [MUSCRIPTOR_INSTALL_ENV]: '1' });installInFlight = child;// `splitRe: /[\r\n]+/` so a bash/pip/tqdm progress bar that redraws with adiff --git a/server/routes/midiRuntime.test.js b/server/routes/midiRuntime.test.jsindex 3219d7d365..f2a590bfda 100644--- a/server/routes/midiRuntime.test.js+++ b/server/routes/midiRuntime.test.js@@ -14,6 +14,7 @@ vi.mock('../lib/pythonSetup.js', () => ({isMuscriptorRuntimeReady: async () => py.installed,invalidateMuscriptorPython: vi.fn(),MUSCRIPTOR_VENV_DEFAULT: '/home/x/.portos/venv-muscriptor/bin/python3',+ detectPythonSync: () => null, // setupScriptRunner's Windows PYTHON_BIN preset}));// Real SSE frames so supertest can read them off the response body.diff --git a/server/routes/music.js b/server/routes/music.jsindex 56a4909e5e..bc4d6002e1 100644--- a/server/routes/music.js+++ b/server/routes/music.js@@ -18,14 +18,11 @@import { Router } from 'express';import { existsSync } from 'fs';-import { spawn } from 'child_process';-import { join } from 'path';import { z } from 'zod';import { asyncHandler, ServerError } from '../lib/errorHandler.js';import { validateRequest } from '../lib/validation.js';-import { PATHS } from '../lib/fileUtils.js';-import { safeChildProcessEnv } from '../lib/processEnv.js';import { createLineReader } from '../lib/streamLines.js';+import { SETUP_IMAGE_VIDEO_SCRIPT, spawnSetupScript, stopSetupScript } from '../lib/setupScriptRunner.js';import { ENGINES, DEFAULT_ENGINE_ID, getEngine, isEngineReady, generateMusic } from '../services/pipeline/musicGen.js';import { listEngineModels, addAudioModel, removeAudioModel, isValidRepoId } from '../services/audioModels.js';import { startHfDownloadStream, openSseStream } from '../lib/sseDownload.js';@@ -130,10 +127,9 @@ router.get('/setup/runtime-install', asyncHandler(async (req, res) => {return safeEnd();}- const scriptPath = join(PATHS.root, 'scripts', 'setup-image-video.sh');- if (!existsSync(scriptPath)) {+ if (!existsSync(SETUP_IMAGE_VIDEO_SCRIPT)) {runtimeInstallInFlight.delete(engine.id);- send({ type: 'error', message: `Installer script not found at ${scriptPath}` });+ send({ type: 'error', message: `Installer script not found at ${SETUP_IMAGE_VIDEO_SCRIPT}` });return safeEnd();}@@ -143,11 +139,7 @@ router.get('/setup/runtime-install', asyncHandler(async (req, res) => {const installLog = createInstallLogger({ installer: engine.name, target: engine.venvDefault });const emit = (ev) => { installLog.onEvent(ev); send(ev); };installLog.start();- const child = spawn('bash', [scriptPath], {- env: safeChildProcessEnv({ [engine.installEnv]: '1' }),- stdio: ['ignore', 'pipe', 'pipe'],- detached: true,- });+ const child = spawnSetupScript({ [engine.installEnv]: '1' });runtimeInstallInFlight.set(engine.id, child);let finished = false;@@ -186,10 +178,7 @@ router.get('/setup/runtime-install', asyncHandler(async (req, res) => {req.on('close', () => {if (finished) return;installLog.cancel();- if (!child.killed && child.pid) {- try { process.kill(-child.pid, 'SIGTERM'); }- catch { child.kill('SIGTERM'); }- }+ stopSetupScript(child);safeEnd();});}));diff --git a/server/routes/videoGen.js b/server/routes/videoGen.jsindex af6113f354..1baa56b1f8 100644--- a/server/routes/videoGen.js+++ b/server/routes/videoGen.js@@ -8,13 +8,11 @@import { Router } from 'express';import { existsSync } from 'fs';-import { join, basename } from 'path';-import { spawn } from 'child_process';+import { basename } from 'path';import os from 'os';import { z } from 'zod';import { asyncHandler, ServerError, failValidation } from '../lib/errorHandler.js';import { uploadFields } from '../lib/multipart.js';-import { PATHS } from '../lib/fileUtils.js';import { videoModelTermsSchema } from '../lib/validation.js';import { grokVideoDurationSchema } from '../lib/sharedSchemas.js';import { MIN_CONTEXT_FRAMES, MAX_CONTEXT_FRAMES } from '../lib/videoContinuity.js';@@ -25,8 +23,8 @@ import {import { IMAGE_GEN_MODE } from '../services/imageGen/modes.js';import { getSettings, updateSettingsWith } from '../services/settings.js';import { checkPackages, isAllowedPython } from '../lib/pythonSetup.js';-import { safeChildProcessEnv } from '../lib/processEnv.js';import { createLineReader } from '../lib/streamLines.js';+import { SETUP_IMAGE_VIDEO_SCRIPT, spawnSetupScript, stopSetupScript } from '../lib/setupScriptRunner.js';import {listVideoModels,defaultVideoModelId,@@ -463,10 +461,7 @@ router.get('/setup/runtime-install', asyncHandler(async (req, res) => {if (info && runtimeInstallInFlight.get(info.id) === null) {runtimeInstallInFlight.delete(info.id);}- if (child && !child.killed && child.pid) {- try { process.kill(-child.pid, 'SIGTERM'); }- catch { child.kill('SIGTERM'); }- }+ stopSetupScript(child);});if (!info) {@@ -507,10 +502,9 @@ router.get('/setup/runtime-install', asyncHandler(async (req, res) => {invalidateByovLoraCapabilityCache(info.id);invalidateRuntimeFingerprintCache(info.id);- const scriptPath = join(PATHS.root, 'scripts', 'setup-image-video.sh');- if (!existsSync(scriptPath)) {+ if (!existsSync(SETUP_IMAGE_VIDEO_SCRIPT)) {runtimeInstallInFlight.delete(info.id);- send({ type: 'error', message: `Installer script not found at ${scriptPath}` });+ send({ type: 'error', message: `Installer script not found at ${SETUP_IMAGE_VIDEO_SCRIPT}` });return safeEnd();}@@ -520,20 +514,13 @@ router.get('/setup/runtime-install', asyncHandler(async (req, res) => {const installLog = createInstallLogger({ installer: info.label, target: info.venvPython });const emit = (ev) => { installLog.onEvent(ev); send(ev); };installLog.start();- // `detached: true` puts bash in its own process group so a cancel from the- // client can take down uv / pip / git children too. Without it, SIGTERM on- // bash leaves a multi-GB `git clone` (and any subsequent pip downloads)- // orphaned to init — the user sees the modal close but the bandwidth keeps- // burning until the network drops or the snapshot completes.const installEnv = {[info.installEnvVar]: '1',...(info.pinEnvVar && info.expectedRevision ? { [info.pinEnvVar]: info.expectedRevision } : {}),};- child = spawn('bash', [scriptPath], {- env: safeChildProcessEnv(installEnv),- stdio: ['ignore', 'pipe', 'pipe'],- detached: true,- });+ // spawnSetupScript owns the interpreter / path / process-group details that a+ // cancel and a Windows box each depend on — see lib/setupScriptRunner.js.+ child = spawnSetupScript(installEnv);runtimeInstallInFlight.set(info.id, child);// `splitRe: /[\r\n]+/` so a bash/pip/tqdm progress bar that redraws with adiff --git a/server/routes/videoGen.test.js b/server/routes/videoGen.test.jsindex d3e3eb7a0e..b35ea75280 100644--- a/server/routes/videoGen.test.js+++ b/server/routes/videoGen.test.js@@ -57,6 +57,7 @@ vi.mock('../services/tracks/index.js', () => ({vi.mock('../lib/pythonSetup.js', () => ({checkPackages: vi.fn(async () => ({ installed: ['mflux', 'mlx'], missing: [], missingPip: [] })),isAllowedPython: vi.fn(() => true),+ detectPythonSync: vi.fn(() => null), // setupScriptRunner's Windows PYTHON_BIN preset}));vi.mock('../services/videoGen/local.js', () => ({@@ -438,17 +439,19 @@ describe('videoGen routes', () => {expect(r.status).toBe(200);expect(r.text).toContain('"type":"complete"');expect(r.text).toContain('Wan 2.2 MLX ready');- expect(installProcess.spawn).toHaveBeenCalledWith(- 'bash',- [join('/mock', 'scripts', 'setup-image-video.sh')],- expect.objectContaining({- detached: true,- env: expect.objectContaining({- INSTALL_WAN22: '1',- WAN22_PIN: '2452f0c12edcc8886eebf15772205ce9c417a618',- }),+ const [bin, argv, opts] = installProcess.spawn.mock.calls.at(-1);+ // A bash, but never the WSL one PM2's PATH may resolve first, and never a+ // backslash path — bash reads those as escapes and exits 127.+ expect(bin).toMatch(/bash(.exe)?$/i);+ expect(bin.toLowerCase()).not.toContain('system32');+ expect(argv).toEqual(['/mock/scripts/setup-image-video.sh']);+ expect(opts).toMatchObject({+ detached: process.platform !== 'win32',+ env: expect.objectContaining({+ INSTALL_WAN22: '1',+ WAN22_PIN: '2452f0c12edcc8886eebf15772205ce9c417a618',}),- );+ });});});diff --git a/server/services/appDeployer.js b/server/services/appDeployer.jsindex c4899ffa0c..e89d4e450e 100644--- a/server/services/appDeployer.js+++ b/server/services/appDeployer.js@@ -3,6 +3,7 @@ import { existsSync } from 'fs';import { join } from 'path';import { NON_PM2_TYPES } from './streamingDetect.js';import { getAppById } from './apps.js';+import { resolveBashBinary } from '../lib/bashResolver.js';export const DEPLOY_FLAGS = ['--ios', '--macos', '--watch', '--all', '--skip-tests'];const VALID_FLAGS = new Set(DEPLOY_FLAGS);@@ -63,7 +64,9 @@ export function deployApp(app, flags, emit) {};return new Promise((resolve) => {- const child = spawn('bash', ['deploy.sh', ...safeFlags], {+ // Not a bare `bash`: under PM2 on Windows that often resolves to WSL, which+ // would run the app's deploy against a Linux toolchain (see bashResolver.js).+ const child = spawn(resolveBashBinary(), ['deploy.sh', ...safeFlags], {cwd: dir,shell: false,windowsHide: true,