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: escalate buffered spawn timeout cleanup (#5301)

[._.]/ Adam Eivyfc1b1a9c4380
diff --git a/server/lib/README.md b/server/lib/README.md
index d4e82b9667..ed46a47174 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -246,7 +246,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `interactiveShellResolver.js` | `resolveInteractiveShell()` — picks the shell binary a PTY session runs (Shell page, agent TUI shells). On Windows the old `COMSPEC` default meant `cmd.exe`, where no command a user would type reaches another drive: `cd I:` silently PRINTS that drive's cwd and stays put, a bare `I:\` is "not recognized as a command", and `cd 'I:\path'` is a syntax error (no single-quote quoting) — so a Windows install with its repos on a second drive was stuck on `C:`. Resolves PORTOS_SHELL → newest `pwsh.exe` under `%ProgramFiles%\PowerShell\<major>` (majors enumerated and sorted numerically, so a future 8 needs no code change) → any `pwsh.exe` on PATH via `findCommandOnPath` (scoop/choco/Store shim) → `powershell.exe` 5.1 (ships with Windows) → `cmd.exe` last. PowerShell crosses drives with every form. Unchanged on POSIX (`SHELL` → zsh). `resolveInteractiveShellWith({platform, env, exists, readdir, findOnPath})` is the un-memoized injectable form for tests. |
| `openFolder.js` | `openFolderInSystemExplorer(localPath)` — cross-platform "open in Finder/Explorer/Nautilus" via detached spawn; child `error` handler prevents spawn failures from crashing the process. |
| `childProcess.js` | Drop-in `child_process` replacement that defaults every spawn to `windowsHide: true` — `spawn` / `spawnSync` / `fork` / `exec` / `execSync` / `execFile` / `execFileSync`, plus a `ChildProcess` re-export. **Server runtime code must import from here, never from `child_process` directly** (enforced by `childProcess.guards.test.js`): a console-less PM2 fork spawning a console child without `CREATE_NO_WINDOW` makes Windows hand the new console to Windows Terminal, which flashes a focus-stealing window. `exec`/`execFile` carry `util.promisify.custom` so `promisify(execFile)` still resolves to `{ stdout, stderr }`. An explicit `windowsHide: false` is respected. Background: `docs/WINDOWS_CONSOLE.md`. |
-| `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`, `spawnFailureDetail(result, fallback)` (the most useful sentence from a failed result — prefers the spawn error, then a stderr line, then a stdout line that isn't bare JSON punctuation, because a `--json` CLI prints its payload to stdout even when it exits non-zero) — 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`. |
+| `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`, `spawnFailureDetail(result, fallback)` (the most useful sentence from a failed result — prefers the spawn error, then a stderr line, then a stdout line that isn't bare JSON punctuation, because a `--json` CLI prints its payload to stdout even when it exits non-zero) — shared buffered-spawn machinery with capped stdout/stderr, timeout SIGTERM plus fire-and-forget SIGKILL escalation (`killGraceMs`, default 8s), 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, env, cwd })` — does running `cmd args` succeed? A capability probe (`execFile`-based), not a PATH lookup like `processEnv.js`'s `whichFirst`; `env`/`cwd` let a caller check the exact child process configuration. 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). `usesCreativeDirectorScratchCwd(task)` / `creativeDirectorScratchCwd(agentId)` / `removeCreativeDirectorScratchCwd(agentId)` / `resolveAgentCliCwd({ workspacePath, fallbackRoot, task, agentId })` — Creative Director no-worktree tasks get a per-agent scratch cwd under `os.tmpdir()/portos-cd-cwd/<id>` (outside the PortOS git tree) instead of the PortOS root, so native CLI AGENTS.md / CLAUDE.md discovery cannot walk up into the repo (#4650). `removeCreativeDirectorScratchCwd` is the matching finalize cleanup. `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.
diff --git a/server/lib/bufferedSpawn.js b/server/lib/bufferedSpawn.js
index 9ae6c09480..71e4865d7d 100644
--- a/server/lib/bufferedSpawn.js
+++ b/server/lib/bufferedSpawn.js
@@ -277,10 +277,11 @@ export function killProcessTree(child, signal = 'SIGTERM', { processGroup = fals
* @param {string} [options.cwd]
* @param {NodeJS.ProcessEnv} [options.env] - complete child environment
* @param {number} [options.timeoutMs] - kill + resolve as timed-out after this
+ * @param {number} [options.killGraceMs=8000] - SIGTERM grace period before fire-and-forget SIGKILL cleanup
* @param {boolean} [options.shell] - defaults to `needsShell(cmd)`
* @returns {Promise<object>} structured result (never rejects)
*/
-export function bufferedSpawn(cmd, args, { cwd, env = process.env, timeoutMs, shell } = {}) {
+export function bufferedSpawn(cmd, args, { cwd, env = process.env, timeoutMs, killGraceMs = 8000, shell } = {}) {
return new Promise((resolve) => {
const child = spawn(cmd, args, {
cwd,
@@ -300,7 +301,20 @@ export function bufferedSpawn(cmd, args, { cwd, env = process.env, timeoutMs, sh
? setTimeout(() => {
if (!settled) {
settled = true;
- killProcessTree(child);
+ killProcessTree(child, 'SIGTERM');
+ if (!IS_WIN32) {
+ const escalationTimer = setTimeout(() => {
+ try {
+ if (child.exitCode === null && child.signalCode === null) {
+ console.log(`⚠️ ${cmd} didn't exit on SIGTERM — escalating to SIGKILL`);
+ killProcessTree(child, 'SIGKILL');
+ }
+ } catch (err) {
+ console.error(`❌ ${cmd} SIGKILL escalation failed: ${err.message}`);
+ }
+ }, killGraceMs);
+ escalationTimer.unref?.();
+ }
resolve({ success: false, code: -1, signal: null, stdout, stderr, timedOut: true });
}
}, timeoutMs)
diff --git a/server/lib/bufferedSpawn.test.js b/server/lib/bufferedSpawn.test.js
index 21e242365f..abc9b13b38 100644
--- a/server/lib/bufferedSpawn.test.js
+++ b/server/lib/bufferedSpawn.test.js
@@ -42,6 +42,8 @@ function makeFakeChild({ pid = 1234 } = {}) {
const child = new EventEmitter();
Object.setPrototypeOf(child, ChildProcess.prototype);
child.pid = pid;
+ child.exitCode = null;
+ child.signalCode = null;
child.stdout = new EventEmitter();
child.stderr = new EventEmitter();
child.kill = vi.fn();
@@ -401,11 +403,11 @@ describe('bufferedSpawn — structured result', () => {
expect(result.stdout.startsWith('a')).toBe(true);
});
- it('times out: kills the tree and resolves timedOut with buffered partial output', async () => {
+ it('times out: resolves at the deadline, then SIGKILLs a child that ignores SIGTERM after its grace period', async () => {
vi.useFakeTimers();
const child = makeFakeChild();
spawnMock.mockReturnValueOnce(child);
- const p = bufferedSpawn('hang', [], { timeoutMs: 1000 });
+ const p = bufferedSpawn('hang', [], { timeoutMs: 1000, killGraceMs: 80 });
child.stdout.emit('data', 'partial');
vi.advanceTimersByTime(1000);
const result = await p;
@@ -414,6 +416,21 @@ describe('bufferedSpawn — structured result', () => {
expect(result.code).toBe(-1);
expect(result.stdout).toBe('partial');
if (!IS_WIN32) expect(child.kill).toHaveBeenCalledWith('SIGTERM');
+ vi.advanceTimersByTime(80);
+ if (!IS_WIN32) expect(child.kill).toHaveBeenLastCalledWith('SIGKILL');
+ });
+
+ it('does not escalate when the child exits during the SIGTERM grace period', async () => {
+ vi.useFakeTimers();
+ const child = makeFakeChild();
+ spawnMock.mockReturnValueOnce(child);
+ const p = bufferedSpawn('hang', [], { timeoutMs: 1000, killGraceMs: 80 });
+ vi.advanceTimersByTime(1000);
+ await p;
+ child.exitCode = 0;
+ child.signalCode = 'SIGTERM';
+ vi.advanceTimersByTime(80);
+ if (!IS_WIN32) expect(child.kill).toHaveBeenCalledTimes(1);
});
it('a close after timeout does not double-resolve (settled guard)', async () => {