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
converge spawnDetached's two Windows branches, retiring windowsDetached (#6170)
[._.]/ Adam Eivy536200876779
diff --git a/docs/SELF_UPDATE.md b/docs/SELF_UPDATE.mdindex 922eb9c909..dd325437ba 100644--- a/docs/SELF_UPDATE.md+++ b/docs/SELF_UPDATE.md@@ -69,7 +69,7 @@ To prevent that confusion, `POST /api/update/execute` rejects fork runs with **4`update.sh` deletes and restarts every PortOS PM2 entry. PM2's TreeKill walks **PPID**, so a script left attached to `portos-server` is killed by its own `pm2 delete` step — mid-list, before it can run the closing `pm2 start` — and the install is left headless. `spawnDetached`'s double-fork (`server/lib/detachedSpawn.js`) is what reparents the script to init so it survives; `executeUpdate()` in `server/services/updateExecutor.js` is the single launcher that applies it, along with the `STEP:` progress parsing, the still-running-script guard, and `recordUpdateResult()`.-**Windows needs the same escape, and cannot get it from `detached: true`.** PM2 kills there with `taskkill /pid <app> /T /F`, which walks the identical parent→child tree, so an attached `update.ps1` dies at `pm2-stop` exactly as an attached `update.sh` would. But Node's `detached: true` maps to **`DETACHED_PROCESS`** on Windows, which denies the child a console — and a console host like `powershell.exe` given no console exits **0 within ~100ms without running a single line**. That combination is why the in-app update silently did nothing on Windows while reporting a successful update to the target release (#6169): the script never ran, `executeUpdate` saw exit 0, and stamped the triggering tag onto a "Success" result. So `executeUpdate` passes `windowsDetached: true` and `spawnDetached` launches a short-lived PowerShell launcher that `Process.Start`s a **supervisor** (with `CreateNoWindow`, per [WINDOWS_CONSOLE.md](WINDOWS_CONSOLE.md)) and exits. The supervisor's parent is then gone, so `taskkill /T` from the server never reaches it; it redirects the script's output into the control dir and records its pid and exit status there, so the same tailer streams `STEP:` progress on both platforms.+**Windows needs the same escape, and cannot get it from `detached: true`.** PM2 kills there with `taskkill /pid <app> /T /F`, which walks the identical parent→child tree, so an attached `update.ps1` dies at `pm2-stop` exactly as an attached `update.sh` would. But Node's `detached: true` maps to **`DETACHED_PROCESS`** on Windows, which denies the child a console — and a console host like `powershell.exe` given no console exits **0 within ~100ms without running a single line**. That combination is why the in-app update silently did nothing on Windows while reporting a successful update to the target release (#6169): the script never ran, `executeUpdate` saw exit 0, and stamped the triggering tag onto a "Success" result. So on Windows `spawnDetached` launches a short-lived PowerShell launcher that `Process.Start`s a **supervisor** (with `CreateNoWindow`, per [WINDOWS_CONSOLE.md](WINDOWS_CONSOLE.md)) and exits. The supervisor's parent is then gone, so `taskkill /T` from the server never reaches it; it redirects the script's output into the control dir and records its pid and exit status there, so the same tailer streams `STEP:` progress on both platforms. This is the *only* win32 path — it shipped in #6169 behind a `windowsDetached` opt-in, because the plain-spawn fallback beside it handed back a real `ChildProcess` whose `kill` tree-killed the job's own descendants and the supervisor path could then only signal the job's pid; #6170 routed the supervisor handle's `kill` (and the boot-time orphan reaper) through the same `taskkill /T /F`, which removed the trade-off and with it the option.Two guards keep a launch that did nothing from being reported as an update:diff --git a/server/lib/README.md b/server/lib/README.mdindex 53411080ea..21cb99dff0 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -285,7 +285,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `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`. Sibling `commandOutput(cmd, args, opts)` runs the same probe but returns the trimmed stdout (or `null` when it could not run / exited non-zero), so a caller can read a `--version` banner or a `models` listing without spawning the same child twice. || `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.| `commandSecurity.js` | Two allowlists, one parser. `validateCommand(cmd)` gates the OPERATOR-driven runner against `ALLOWED_COMMANDS` (+ `validatePm2Command(args)`, which rejects daemon-wide `pm2 kill`/`startup`/`unstartup` and `<verb> all`). `validateUnattendedCommand(cmd)` gates the UNATTENDED lane (Layered Intelligence `cmd` sources) against the far narrower `UNATTENDED_READONLY_COMMANDS` — read-only inspection binaries only, no `npx`/`node`/`python`/`pip`/`curl`/`wget`/`brew`, since those execute network code with no shell metacharacter — then applies a per-binary SUBCOMMAND gate to the multi-purpose survivors, so `git reset --hard` / `git commit`, `find -delete` / `-exec`, and `gh`/`glab` writes (`api -X POST`, `pr merge`) are rejected while `git log`, `find -name` and `gh pr list` pass. Both share one parse + `DANGEROUS_SHELL_CHARS` body. Mirrored by the `agentGuard/` PATH shim for agentic paths. |-| `detachedSpawn.js` | `spawnDetached(bin, args, {controlDir,env,cwd,killProcessGroup?,windowsDetached?})` → ChildProcess-like handle for a long media job that SURVIVES `pm2 restart portos-server`. A pure-`sh` double-fork reparents the job to init (escaping pm2's PPID-based TreeKill — `detached:true` alone doesn't, since it only changes the process group); the server tails on-disk log files for `stdout`/`stderr`/`close`. Group-kill mode persists a marker so cancel, reattach, and orphan reaping terminate a group-leader wrapper plus every runtime child together. Windows defaults to a plain-spawn fallback, so its handle's `kill` delegates to `killProcessTree` (`taskkill /T /F`) — a cancel there takes the runner's children with it; pass `windowsDetached` instead when SURVIVING the restart is the point (a powershell supervisor started by a launcher that exits writes the same control files — never `detached:true`, which on Windows means DETACHED_PROCESS and leaves a console host no console to run in). Used by loraTraining + videoGen. Also exports `reattachDetached(controlDir)` / `isReattachable(controlDir)` to RE-ATTACH a survivor after a restart, `isDetachedRunning(controlDir, expectedProcess?)` with optional executable/argument validation for fixed-command control dirs, and `reapDetached` to checkpoint-kill one when re-attach isn't possible. |+| `detachedSpawn.js` | `spawnDetached(bin, args, {controlDir,env,cwd,killProcessGroup?})` → ChildProcess-like handle for a long media job that SURVIVES `pm2 restart portos-server`. A pure-`sh` double-fork reparents the job to init (escaping pm2's PPID-based TreeKill — `detached:true` alone doesn't, since it only changes the process group); the server tails on-disk log files for `stdout`/`stderr`/`close`. Group-kill mode persists a marker so cancel, reattach, and orphan reaping terminate a group-leader wrapper plus every runtime child together. Windows reaches the same place through a powershell supervisor started by a launcher that exits (never `detached:true`, which there means DETACHED_PROCESS and leaves a console host no console to run in), writing the same control files — so both platforms survive the restart AND take the runner's children down on cancel (`taskkill /T /F` there, the process group on POSIX). Used by loraTraining + videoGen. Also exports `reattachDetached(controlDir)` / `isReattachable(controlDir)` to RE-ATTACH a survivor after a restart, `isDetachedRunning(controlDir, expectedProcess?)` with optional executable/argument validation for fixed-command control dirs, and `reapDetached` to checkpoint-kill one when re-attach isn't possible. || `hostShutdown.js` | Tells "PortOS was restarted out from under a running agent" apart from "the agent failed" (#3202). `markHostShuttingDown()` / `isHostShuttingDown()` are the in-process latch the SIGTERM/SIGINT handler sets first thing; `shouldAbandonForHostShutdown({sentinelPresent,terminatedByUser,paused})` keeps every spawn path on the same preserve-vs-finalize policy. `writeHostShutdownMarker({agentIds,signal})` / `readHostShutdownMarker()` / `clearHostShutdownMarker()` persist that verdict to `data/cos/host-shutdown.json` so the NEXT boot's orphan sweep can requeue those agents as *interrupted* — no orphan-retry charge, no 30-minute cooldown. All non-throwing: a missing marker degrades to the ordinary orphan path. || `execGit.js` | `execGit(args, cwd, options)` utility imported by `git.js` + worktree manager. `cwd` is REQUIRED — it rejects on a missing/blank one rather than letting `spawn` fall back to `process.cwd()` and run git against PortOS's own checkout (#4554). || `ffmpeg.js` | Shared ffmpeg helpers (videoGen + videoTimeline). Includes `probeFrameCount(videoPath)` (metadata `nb_frames`, falling back to a real `-count_frames` pass — expensive, so call it once per file) and `trimVideoFromFrame(videoPath, outPath, {startFrame, fps})` — a frame-EXACT head cut via the `trim` filter (an `-ss` seek can drift a frame, which reads as a stutter at a stitch seam), keeping audio in sync with `atrim` when the clip has a soundtrack and taking `-an` when it doesn't. Re-encodes by necessity, so a later concat must re-encode too; `outPath` may equal the input (temp-file + rename install). Used by the chained-render context window — see `videoContinuity.js`. `buildTrimConcatArgs({inputs, outPath, width, height, fps, withAudio})` builds the argv for the other half of that job: a concat that drops leading frames from some of its inputs inside a `filter_complex` graph, so the cuts ride along with the timeline encode instead of costing one pre-encode per clip (pass `withAudio` only when EVERY input has an audio stream — check with `hasAudioStream`). `H264_ENCODE_ARGS` / `AAC_ENCODE_ARGS` are the shared encode profile: clips produced by different paths here get concatenated together, so a mismatch shows up as one segment graded differently from its neighbours — spread these rather than re-typing the flags. Every re-encode here also pins BT.709: `BT709_CONTAINER_ARGS` (the `colr` atom, always emitted) plus `bt709TagFilter()` → the `BT709_TAG_FILTER` `setparams=…` string, or `null` on an ffmpeg without that filter (`supportsSetparamsFilter()` probes `-filters` once per process; `null` = not probed, and a probe that couldn't run stays uncached). Both halves are required — from ffmpeg 8 the encoder reads color properties off the FRAMES, silently overriding the container flags, so a flags-only output decodes washed-out. `buildTrimConcatArgs` takes the filter as its `colorTagFilter` option rather than probing, to stay pure. |diff --git a/server/lib/bufferedSpawn.js b/server/lib/bufferedSpawn.jsindex 66bbcaeeff..d9df674fe6 100644--- a/server/lib/bufferedSpawn.js+++ b/server/lib/bufferedSpawn.js@@ -207,13 +207,21 @@ export const MAX_OUTPUT_BYTES = 64 * 1024;* object, so without this the flag would stay `false` for the process's* entire lifetime and those guards would never engage on Windows.*- * The win32 branch is gated on `instanceof ChildProcess` — some callers (the- * aiToolkit runner's `stopRun`, via `registerExternalRun`) pass this a- * killable that isn't a `child_process` spawn at all, e.g. a node-pty `IPty`- * TUI session, which also exposes `.kill()`/`.pid`. A raw `taskkill` against- * a pty's pid bypasses node-pty's own Windows teardown (releasing its native- * ConPTY handle), leaking it — so any non-ChildProcess killable always uses- * its own `.kill()` instead, on every platform.+ * The win32 branch is gated on the target OWNING a `.kill()` of its own — some+ * callers (the aiToolkit runner's `stopRun`, via `registerExternalRun`) pass+ * this a killable that isn't a `child_process` spawn at all, e.g. a node-pty+ * `IPty` TUI session, which also exposes `.kill()`/`.pid`. A raw `taskkill`+ * against a pty's pid bypasses node-pty's own Windows teardown (releasing its+ * native ConPTY handle), leaking it — so any non-ChildProcess killable that+ * brings its own `.kill()` always uses it instead, on every platform.+ *+ * A bare `{ pid }` target is the third shape: a process this server never held+ * a handle to at all — `spawnDetached`'s Windows supervisor job, and the orphan+ * `reapDetached` finds through a control dir's pid file — so there is no+ * `.kill()` to prefer and the pid is the only address it has. It takes the same+ * tree-kill a ChildProcess does, which is what gives a detached Windows job the+ * "the runner's ffmpeg/python descendants die with it" guarantee POSIX gets+ * from a process-group signal (#4171, #6170).** node-pty's Windows backend additionally throws `Signals not supported on* windows.` for ANY signal argument, so `kill(signal)` against a pty there never@@ -251,14 +259,17 @@ export const MAX_OUTPUT_BYTES = 64 * 1024;* this rather than `child.kill()`, or on Windows only the `cmd.exe` shim dies* and the real CLI child is orphaned.*- * @param {import('child_process').ChildProcess} child+ * @param {import('child_process').ChildProcess|{pid: number, kill?: Function}} child - a ChildProcess, any killable exposing `.pid`/`.kill()`, or a bare `{ pid }`* @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`)* @param {boolean} [isWin32] - platform override, injected so the Windows branches are testable off Windows (same shape as `resolveWindowsExecutable`)*/export function killProcessTree(child, signal = 'SIGTERM', { processGroup = false } = {}, isWin32 = IS_WIN32) {const isChildProcess = child instanceof ChildProcess;- if (isWin32 && child.pid && isChildProcess) {+ // A target with no `.kill()` of its own is addressable only by pid — nothing+ // to prefer over the platform's own tree/group kill below.+ const isPidOnly = !isChildProcess && typeof child.kill !== 'function';+ if (isWin32 && child.pid && (isChildProcess || isPidOnly)) {child.killed = true;spawn('taskkill', ['/T', '/F', '/PID', String(child.pid)], { stdio: 'ignore' }).on('error', () => {})@@ -269,6 +280,15 @@ export function killProcessTree(child, signal = 'SIGTERM', { processGroup = falstry { process.kill(-child.pid, signal); return; }catch { /* ESRCH — the group is already gone; fall through to the pid */ }}+ if (isPidOnly) {+ // POSIX, pid-only: the group signal above either landed or the group is+ // gone, so this is the plain per-pid signal — swallowing ESRCH exactly as+ // the group attempt does, since a target that already exited is not a+ // failure to report.+ try { process.kill(child.pid, signal); }+ catch { /* ESRCH — already gone */ }+ return;+ }if (isWin32 && !isChildProcess) {// node-pty rejects the signal outright on Windows (see the note above);// every other killable here accepts and forwards it, so ask first and onlydiff --git a/server/lib/bufferedSpawn.test.js b/server/lib/bufferedSpawn.test.jsindex 8541a2bfa5..f0aaf0e6ce 100644--- a/server/lib/bufferedSpawn.test.js+++ b/server/lib/bufferedSpawn.test.js@@ -225,6 +225,50 @@ describe('killProcessTree', () => {killProcessTree(ptyLike, 'SIGKILL');expect(ptyLike.kill).toHaveBeenCalledWith('SIGKILL');});++ // A bare `{ pid }` — a detached job this process holds no handle to at all+ // (spawnDetached's reparented job, reapDetached's pid-file orphan). The+ // platform is INJECTED, so both branches are asserted on any host.+ it('tree-kills a bare { pid } target on Windows', () => {+ const tk = makeFakeChild();+ spawnMock.mockReturnValueOnce(tk);+ killProcessTree({ pid: 8080 }, 'SIGKILL', {}, true);+ // Without this, a pid-only cancel fell through to the node-pty branch and+ // threw `child.kill is not a function` — or, worse, silently killed only+ // the job leaf and orphaned everything it spawned (#6170).+ expect(spawnMock).toHaveBeenCalledWith(+ 'taskkill', ['/T', '/F', '/PID', '8080'],+ expect.objectContaining({ stdio: 'ignore' })+ );+ });++ it('maps processGroup onto the same tree-kill on Windows, which has no process groups', () => {+ const tk = makeFakeChild();+ spawnMock.mockReturnValueOnce(tk);+ const killSpy = vi.spyOn(process, 'kill').mockImplementation(() => true);+ killProcessTree({ pid: 8081 }, 'SIGTERM', { processGroup: true }, true);+ expect(spawnMock).toHaveBeenCalledWith('taskkill', ['/T', '/F', '/PID', '8081'], expect.anything());+ // `process.kill(-pid)` means nothing on Windows — the win32 branch has to+ // win the race with the process-group branch, whatever the flag says.+ expect(killSpy).not.toHaveBeenCalled();+ killSpy.mockRestore();+ });++ it('signals a bare { pid } target off Windows, group first then the pid', () => {+ const killSpy = vi.spyOn(process, 'kill').mockImplementation(() => true);+ killProcessTree({ pid: 8082 }, 'SIGKILL', { processGroup: true }, false);+ expect(killSpy).toHaveBeenCalledWith(-8082, 'SIGKILL');+ killSpy.mockReset();+ killProcessTree({ pid: 8083 }, 'SIGKILL', {}, false);+ expect(killSpy).toHaveBeenCalledWith(8083, 'SIGKILL');+ killSpy.mockRestore();+ });++ it('swallows ESRCH for a bare { pid } target that already exited', () => {+ const killSpy = vi.spyOn(process, 'kill').mockImplementation(() => { throw new Error('ESRCH'); });+ expect(() => killProcessTree({ pid: 8084 }, 'SIGKILL', {}, false)).not.toThrow();+ killSpy.mockRestore();+ });});describe('resolveWindowsExecutable', () => {diff --git a/server/lib/detachedSpawn.js b/server/lib/detachedSpawn.jsindex 77cf30ed41..308ba536f9 100644--- a/server/lib/detachedSpawn.js+++ b/server/lib/detachedSpawn.js@@ -32,6 +32,14 @@// we rely on Node's `detached` for the new session plus reparent-to-init from// the double-fork — no external launcher binary needed.)//+// Windows has no `sh` and no reparent-to-init, so it reaches the same place by+// a different route — a launcher that exits and leaves a supervisor behind (see+// the block above `WINDOWS_SUPERVISOR`). Both arms write the same control dir+// and hand back the same handle, so this module has exactly ONE code path per+// caller; the platforms differ only in how a cancel reaches the job's+// descendants — a process-group signal on POSIX, `taskkill /T /F` on Windows+// (#6170).+//// The returned object is ChildProcess-LIKE — it exposes `pid`, `stdout`,// `stderr` (EventEmitters emitting `data`/`end`), `on('close', (code,// signal))`, `on('error', err)`, `kill(signal)`, `killed`, `exitCode`,@@ -71,7 +79,39 @@ const PID_TIMEOUT_MS = 10000;const REAP_GRACE_MS = 12000;const GROUP_KILL_MARKER = 'kill-process-group';+const isAlive = (pid) => {+ try { process.kill(pid, 0); return true; } catch { return false; }+};++// Signal a detached job we hold no child handle for — the reparented POSIX+// double-fork job, the Windows supervisor's job, and the boot-time orphan+// reaper's pid-file target all reach their process only by number.+//+// Windows has neither process groups nor real signals, so `process.kill(pid,+// …)` there is a TerminateProcess of the job LEAF: whatever the runner spawned+// (the ffmpeg mux a CUDA video runtime shells out to, a model download) is+// orphaned still holding the output file and GPU memory. `taskkill /T /F` is+// the only tree there, so both the plain and the `killProcessGroup` form of a+// cancel collapse onto it — which is what gives a Windows job the same+// descendants-die-with-it guarantee POSIX gets from the negative pid (#4171,+// #6170). Note taskkill ignores the requested signal and force-kills, so a+// SIGTERM cancel is not graceful there; that is killProcessTree's documented+// Windows contract.const signalPid = (pid, signal, killProcessGroup = false) => {+ const isWindows = process.platform === 'win32';+ if (isWindows) {+ // Signal 0 is an existence PROBE, not a kill — answer it instead of+ // force-killing the tree.+ if (signal === 0 || signal === '0') return isAlive(pid);+ // `taskkill /T /F` is destructive and Windows recycles PIDs freely, so it+ // must never fire at a job that already exited — a late escalation (the+ // reaper's grace-deadline SIGKILL) would tree-kill whatever inherited the+ // number. Node's own `kill` is safe there because a ChildProcess holds a+ // process HANDLE; taskkill only gets the pid.+ if (!isAlive(pid)) return false;+ killProcessTree({ pid }, signal, { processGroup: killProcessGroup }, isWindows);+ return true;+ }if (killProcessGroup) {try {process.kill(-pid, signal);@@ -89,6 +129,10 @@ const signalPid = (pid, signal, killProcessGroup = false) => {}};+// The signal a win32 cancel ASKED for, remembered on the handle so the tailer+// can report the death the way Node would — see createDetachedHandle below.+const KILL_SIGNAL = Symbol('detachedKillSignal');+// `wait` reports a signal-terminated child as 128+signum. Invert os signal// constants once so we can decode that back into Node's ('code', 'signal')// close convention (exactly one of the two is non-null).@@ -96,6 +140,58 @@ const SIGNAL_BY_NUMBER = Object.fromEntries(Object.entries(osConstants.signals).map(([name, num]) => [num, name]));+/**+ * Build the ChildProcess-like handle shared by spawnDetached and+ * reattachDetached, with `kill` wired to the platform's cancel semantics.+ *+ * `kill()` accepts a NUMBER while `close` reports NAMES, and an unknown signal+ * must still throw `ERR_UNKNOWN_SIGNAL` rather than silently force-killing a+ * tree — so the signal is decoded and validated exactly as ChildProcess.kill()+ * does before anything is dispatched.+ *+ * On Windows the dispatch is `taskkill /T /F`, which terminates the job OUT OF+ * BAND: the supervisor then records whatever ordinary non-zero status Windows+ * left behind, and the tailer would report `close(1, null)` where Node's own+ * `kill()` reported `close(null, 'SIGKILL')`. Callers classify a cancel on+ * exactly that signal — videoGen's watchdog-success check keeps a finished+ * .mp4 only when `signal === 'SIGKILL'`, and `describeSignalDeath` reads it for+ * the failure reason — so remember the signal we ASKED for and let the tailer+ * stamp it. That records the request without waiting to confirm the tree died+ * from it, which is precisely what libuv does for a native kill (it stamps+ * exit_signal at request time). POSIX needs none of this: the supervisor's+ * `wait` status carries the real signal, decoded as 128+signum below.+ */+function createDetachedHandle({ pid = null, killProcessGroup = false } = {}) {+ const handle = new EventEmitter();+ handle.stdout = new EventEmitter();+ handle.stderr = new EventEmitter();+ handle.pid = pid;+ handle.killed = false;+ handle.exitCode = null;+ handle.signalCode = null;+ handle[KILL_SIGNAL] = null;+ handle.kill = (signal = 'SIGTERM') => {+ const isProbe = signal === 0 || signal === '0';+ const signalName = typeof signal === 'number' ? SIGNAL_BY_NUMBER[signal] : signal;+ // Validate BEFORE anything is dispatched or recorded, so a typo throws with+ // the handle untouched — as ChildProcess.kill() leaves a child untouched.+ if (!isProbe && (!signalName || !(signalName in osConstants.signals))) {+ const err = new TypeError(`Unknown signal: ${signal}`);+ err.code = 'ERR_UNKNOWN_SIGNAL';+ throw err;+ }+ handle.killed = true;+ if (!handle.pid) return false;+ const dispatched = signalPid(handle.pid, signal, killProcessGroup);+ // Only a kill that actually went out gets stamped: a probe is not a death,+ // and a refused dispatch (the job already exited) must leave the status the+ // supervisor recorded alone.+ if (dispatched && !isProbe && process.platform === 'win32') handle[KILL_SIGNAL] = signalName;+ return dispatched;+ };+ return handle;+}+// Double-fork launcher. argv: <controlDir> <bin> <bin-args…> — passed as// positional params (NOT interpolated into the script string) so paths/args// with spaces or shell metacharacters can't break quoting or inject.@@ -177,8 +273,9 @@ try {$p.WaitForExit()# ExitCode is a SIGNED int, so a status at or above 0x80000000 (0xC0000005 and# the rest of the NTSTATUS crash codes) reads back negative. Node's own- # ChildProcess — and so the plain-spawn fallback beside this — reports those- # unsigned; mask back to that so both win32 arms agree on the same crash.+ # ChildProcess reports those UNSIGNED, and the POSIX arm passes the shell wait+ # status straight through; mask back to that so a caller classifying a crash+ # by its code sees the same number on either platform.# The L suffix is required: PowerShell types a bare 0xFFFFFFFF as Int32 -1,# and masking against -1 is the identity, silently leaving the value negative.$code = [int64]$p.ExitCode -band 0xFFFFFFFFL@@ -322,6 +419,14 @@ function createLogTailer(handle, { controlDir, pollMs, cleanup }) {} else {code = 1; // exit file missing/garbled — treat as generic failure}+ // A Windows cancel went out through `taskkill /T /F`, out of band of the+ // job's own exit, so re-stamp the signal it asked for (set only on win32 —+ // see createDetachedHandle). A CLEAN exit is left alone: a cancel that+ // raced completion by microseconds means the job really did finish.+ if (handle[KILL_SIGNAL] && signal === null && code !== 0) {+ code = null;+ signal = handle[KILL_SIGNAL];+ }handle.exitCode = code;handle.signalCode = signal;handle.emit('close', code, signal);@@ -369,105 +474,20 @@ function createLogTailer(handle, { controlDir, pollMs, cleanup }) {* @param {boolean} [opts.killProcessGroup] - signal `-pid` on cancel/reap so a* group-leader wrapper and every runtime child terminate together. The job is* responsible for establishing its own process group before spawning children.- * POSIX-only — the win32 fallback's `kill` always tree-kills, group or not.- * @param {boolean} [opts.windowsDetached] - on Windows, launch through the- * supervisor above so the job survives pm2's `taskkill /T` instead of taking- * the plain-spawn fallback. Opt-in because the fallback hands back a real- * ChildProcess whose `kill` tree-kills the job's own descendants; the- * supervisor path can only signal the job's PID. Pass it when outliving a- * pm2 restart is the point (the self-update script) rather than cancellation.+ * POSIX-only in mechanism: Windows has no process group, and its cancel is+ * always the `taskkill /T /F` tree, group flag or not.* @returns {Promise<object>} ChildProcess-like handle (resolves once the PID is known)*/export async function spawnDetached(bin, args = [], {env, cwd, controlDir, pollMs = DEFAULT_POLL_MS, cleanup = false, killProcessGroup = false,- windowsDetached = false,} = {}) {if (!controlDir) throw new Error('spawnDetached requires a controlDir');const isWindows = process.platform === 'win32';- // Windows has no POSIX `sh` for the double-fork, so unless the caller opted- // into the supervisor launcher above it falls back to a normal child process:- // a real ChildProcess already satisfies the handle contract (pid / stdout /- // stderr / on('close',code,signal) / kill / exitCode / signalCode), so- // callers are unaffected. Surviving a pm2 restart is then not a guarantee;- // Windows keeps its prior spawn semantics apart from `kill`, which is- // replaced with a tree-kill below.- if (isWindows && !windowsDetached) {- const child = spawn(bin, args, { env: withSpawnCwdEnv(env ?? process.env, cwd), cwd, stdio: ['ignore', 'pipe', 'pipe'] });- // 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- // model download) survives as an orphan still holding the output file and- // GPU memory. Delegate to the shared tree-killer instead — `taskkill /T /F`- // on Windows, the POSIX group signal elsewhere (#4171). Note `taskkill /T /F`- // ignores the requested signal and force-kills, so a SIGTERM cancel is not- // graceful here; that is killProcessTree's documented Windows contract.- const nativeKill = child.kill.bind(child);- // What we hand killProcessTree: inherits from `child` (so `pid` reads- // through and `instanceof ChildProcess` still holds — the taskkill branch is- // gated on it) but exposes Node's own kill, so killProcessTree's POSIX- // fall-through can never re-enter the override below.- const treeKillTarget = Object.create(child, { kill: { value: nativeKill } });- // `taskkill` terminates the tree OUT OF BAND, so libuv never records an- // exit_signal and the child reports `close(1, null)` where Node's own- // `kill()` reported `close(null, 'SIGKILL')`. Callers classify on exactly- // that signal — videoGen's watchdog-success test keeps a finished .mp4 only- // when `signal === 'SIGKILL'`, and `describeSignalDeath` reads it for the- // failure reason — so re-stamp the signal we asked for onto the terminal- // events, matching both a native kill and the POSIX handle's decoded close.- // A concurrent clean exit (code 0) is left alone: the job really did finish.- // The stamp records the signal we ASKED for without waiting to confirm the- // tree died from it — exactly what Node's own `kill()` does (libuv stamps- // exit_signal at request time), and the guard above already refuses to fire- // at an exited child, so the only ambiguity left is a nonzero exit racing- // our kill by microseconds. Both readings mean "cancelled", so no async- // taskkill-completion plumbing is warranted here.- let killSignal = null;- const nativeEmit = child.emit.bind(child);- child.emit = (event, ...rest) => {- if (killSignal && (event === 'close' || event === 'exit') && rest[1] == null && rest[0] !== 0) {- child.exitCode = null;- child.signalCode = killSignal;- return nativeEmit(event, null, killSignal);- }- return nativeEmit(event, ...rest);- };- child.kill = (signal = 'SIGTERM') => {- // `taskkill /T /F` is destructive and Windows recycles PIDs freely, so it- // must never fire at a child that already exited — a late escalation- // (killWithEscalation's 8s SIGKILL) would tree-kill whatever inherited the- // number. Node's own kill is safe there because it holds a process HANDLE,- // not a pid; taskkill only gets the pid.- if (!child.pid || child.exitCode !== null || child.signalCode !== null) return false;- // Signal 0 is an existence PROBE, not a kill — hand it to Node so callers- // keep that meaning instead of force-killing the tree.- if (signal === 0 || signal === '0') return nativeKill(signal);- // Decode and validate the signal exactly as ChildProcess.kill() does:- // `kill()` also accepts a NUMBER while `close` reports NAMES (stamping a- // raw 9 would break every `signal === 'SIGKILL'` comparison), and an- // unknown signal must still throw ERR_UNKNOWN_SIGNAL rather than silently- // force-killing the tree. SIGNAL_BY_NUMBER is the same inverted table the- // POSIX handle decodes `wait` statuses with.- const signalName = typeof signal === 'number' ? SIGNAL_BY_NUMBER[signal] : signal;- if (!signalName || !(signalName in osConstants.signals)) return nativeKill(signal);- killSignal = signalName;- child.killed = true;- killProcessTree(treeKillTarget, signalName, { processGroup: true });- return true;- };- return child;- }-- const handle = new EventEmitter();- handle.stdout = new EventEmitter();- handle.stderr = new EventEmitter();- handle.pid = null;- handle.killed = false;- handle.exitCode = null;- handle.signalCode = null;- // Default no-op so a setup failure (below) returns a usable handle.- handle.kill = () => false;+ // `kill` reports false until the supervisor records a PID, so a setup failure+ // (below) still returns a usable handle.+ const handle = createDetachedHandle({ killProcessGroup });const pidFile = join(controlDir, 'pid');const exitFile = join(controlDir, 'exit');@@ -555,14 +575,6 @@ export async function spawnDetached(bin, args = [], {}};- // Signal the reparented job by PID, or by its persisted opt-in process group- // when the wrapper owns runtime descendants that must never outlive it.- handle.kill = (signal = 'SIGTERM') => {- handle.killed = true;- if (!handle.pid) return false;- return signalPid(handle.pid, signal, killProcessGroup);- };-await awaitPid();// Kick off tailing (or the launch-failure path) AFTER returning, so the@@ -580,10 +592,6 @@ export async function spawnDetached(bin, args = [], {return handle;}-const isAlive = (pid) => {- try { process.kill(pid, 0); return true; } catch { return false; }-};-/*** Cheap boot-time probe: is there a detached child worth re-attaching to under* this control dir? True when the recorded PID is still alive (job still@@ -642,10 +650,8 @@ export async function isReattachable(controlDir) {export async function reattachDetached(controlDir, { pollMs = DEFAULT_POLL_MS, cleanup = false } = {}) {// No platform gate: whether there is a survivor to re-attach to is a fact// about the CONTROL DIR, and the pid/exit probe below already answers it.- // spawnDetached's win32 plain-spawn fallback writes neither file, so its- // callers get the same `null` they got from an explicit platform check —- // while a `windowsDetached` job, which does leave a live control dir, is no- // longer told there is nothing there.+ // Every platform now writes those files (#6169, #6170), so a Windows job is+ // re-attachable on exactly the same evidence a POSIX one is.const pidRaw = await readFile(join(controlDir, 'pid'), 'utf8').catch(() => '');const pid = Number.parseInt(pidRaw, 10);if (!Number.isFinite(pid) || pid <= 0) return null;@@ -655,19 +661,9 @@ export async function reattachDetached(controlDir, { pollMs = DEFAULT_POLL_MS, c// (the RESULT line was never written). Let the caller reap+fail.if (!exitWritten && !isAlive(pid)) return null;- const handle = new EventEmitter();- handle.stdout = new EventEmitter();- handle.stderr = new EventEmitter();- handle.pid = pid;- handle.killed = false;- handle.exitCode = null;- handle.signalCode = null;- // Mirror spawnDetached's exact PID/group behavior so cancel/stall paths work- // identically on a re-attached run.- handle.kill = (signal = 'SIGTERM') => {- handle.killed = true;- return signalPid(pid, signal, killProcessGroup);- };+ // Mirrors spawnDetached's exact PID/group/tree-kill behavior, so cancel and+ // stall paths work identically on a re-attached run.+ const handle = createDetachedHandle({ pid, killProcessGroup });const { tick } = createLogTailer(handle, { controlDir, pollMs, cleanup });// Defer the first tick so the caller's synchronous .on('data'|'close'|'error')@@ -800,6 +796,10 @@ export async function isDetachedRunning(controlDir, expectedProcess = null) {* with it). SIGTERM first so the trainer/render checkpoints, then escalate to* SIGKILL after the grace window — turning a restart from a mid-op SIGINT* crash into a clean checkpointed stop the existing resume path recovers from.+ * On Windows both rungs are the same `taskkill /T /F` (no real signals there,+ * and `process.kill` was already an unconditional TerminateProcess of the job+ * LEAF), so the reap is not graceful — but it now takes the job's descendants+ * with it instead of orphaning them (#6170).* This is the fallback when reattachDetached can't (or shouldn't) re-attach —* e.g. a render lane with no re-attach path, or a probe that came back* non-reattachable. A caller that CAN re-attach (LoRA training, #1332) shoulddiff --git a/server/lib/detachedSpawn.test.js b/server/lib/detachedSpawn.test.jsindex 5e0dfbb74f..e1c3a904f0 100644--- a/server/lib/detachedSpawn.test.js+++ b/server/lib/detachedSpawn.test.js@@ -2,16 +2,18 @@ import { describe, it, expect, afterEach, vi } from 'vitest';import { mkdir, mkdtemp, readFile, rm, stat, writeFile } from 'fs/promises';import { tmpdir } from 'os';import { basename, join } from 'path';-import { ChildProcess, execFile, spawn } from './childProcess.js';+import { execFile, spawn } from './childProcess.js';import { promisify } from 'util';import { pathToFileURL } from 'url';import { pinPlatform } from './testHelper.js';import { killProcessTree } from './bufferedSpawn.js';import { spawnDetached, reapDetached, reapAndCleanDetachedDirs, reattachDetached, isReattachable, isDetachedRunning, __detachedSpawnTesting } from './detachedSpawn.js';-// Only the win32 fallback's kill() reaches killProcessTree, so stubbing it is-// inert for every POSIX test here — and it lets the win32 test assert the-// delegation on a platform where `taskkill` doesn't exist.+// Only a win32 cancel reaches killProcessTree, so stubbing it is inert for+// every POSIX test here — and it lets the win32 tests assert the delegation on+// a platform where `taskkill` doesn't exist. The one test that needs the real+// tree-kill (a Windows host, killing a job with a live grandchild) restores it+// for itself with `mockImplementationOnce`.vi.mock('./bufferedSpawn.js', async (importOriginal) => ({...(await importOriginal()),killProcessTree: vi.fn(),@@ -19,14 +21,13 @@ vi.mock('./bufferedSpawn.js', async (importOriginal) => ({const execFileAsync = promisify(execFile);-// spawnDetached's POSIX `sh` double-fork — and with it the whole control-dir-// contract (pid/exit sentinels, reap, re-attach, reparent-to-init survival) —-// does not exist on Windows: that platform takes an explicit plain-spawn-// fallback (see the win32 branch in detachedSpawn.js), where pm2 is-// taskkill-based and surviving a restart is not a guarantee PortOS makes.-// Tests that assert the double-fork mechanism are gated on IS_POSIX rather-// than rewritten, because there is no Windows behavior for them to assert.-// The win32 fallback itself is covered by its own test below.+// Both platforms produce the same control-dir contract (pid/exit sentinels,+// reap, re-attach, survive-the-restart) — but by different mechanisms: a POSIX+// `sh` double-fork, and a powershell launcher+supervisor on Windows. Tests that+// assert one MECHANISM are gated on the platform that has it (`sh -c` fixtures+// and PPID walks on IS_POSIX; the real powershell launcher on !IS_POSIX).+// Tests of the shared handle CONTRACT run everywhere, driving `node -e`+// fixtures rather than `sh -c` so they work on a Windows checkout too.const IS_POSIX = process.platform !== 'win32';const dirs = [];const tmpControlDir = async () => {@@ -244,33 +245,14 @@ describe('spawnDetached', () => {expect(handle.pid).toBeNull();});- it('falls back to a plain spawn on win32 (no POSIX sh double-fork)', async () => {- const restorePlatform = pinPlatform('win32');- try {- const controlDir = await tmpControlDir();- // Real `sh` exists on the test runner, so the plain-spawn fallback runs;- // the point is that it returns a working ChildProcess, not the file-tailed- // handle. (controlDir is unused on this path but still required.)- const handle = await spawnDetached('sh', ['-c', 'printf "hi\\n"; exit 0'], { controlDir });- expect(handle.pid).toBeGreaterThan(0);- expect(typeof handle.kill).toBe('function');- const getOut = collect(handle.stdout);- const { code } = await onClose(handle);- expect(code).toBe(0);- expect(getOut()).toBe('hi\n');- } finally {- restorePlatform();- }- });-- // The `windowsDetached` launcher is real powershell, so it can only be- // exercised on a Windows host — pinning the platform elsewhere would just+ // The Windows launcher is real powershell, so it can only be exercised on a+ // Windows host — pinning the platform elsewhere would just// fail to find the binary. Regression for #6169: the plain// `spawn(..., { detached: true })` this replaced meant DETACHED_PROCESS,// which denies a console host any console, so the job exited 0 in ~100ms// having produced no output and run no part of the script. Asserting real// streamed output plus the job's own exit code is what catches that.- it.runIf(!IS_POSIX)('windowsDetached runs the job and streams its output through the control dir', async () => {+ it.runIf(!IS_POSIX)('runs the job and streams its output through the control dir', async () => {const controlDir = await tmpControlDir();const handle = await spawnDetached(process.execPath,@@ -278,7 +260,7 @@ describe('spawnDetached', () => {// supervisor needs: .NET Framework's ProcessStartInfo takes one flat// argument STRING, so a mis-quoted path would silently split.['-e', 'process.stdout.write(process.argv[1] + "\\n"); process.exit(3);', 'a b "c"'],- { controlDir, windowsDetached: true }+ { controlDir });const getOut = collect(handle.stdout);expect(handle.pid).toBeGreaterThan(0);@@ -288,7 +270,7 @@ describe('spawnDetached', () => {expect(getOut()).toBe('a b "c"\n');});- // The whole POINT of the windowsDetached launcher: pm2 kills on Windows with+ // The whole POINT of the Windows launcher: pm2 kills on Windows with// `taskkill /pid <app> /T /F`, which walks the parent tree, so a job spawned// as a plain child of portos-server dies at update.sh's own `pm2-stop` step// and leaves the install headless (#5976, and #6169 on Windows). Nothing in@@ -296,7 +278,7 @@ describe('spawnDetached', () => {// by dropping the launcher hop and starting the supervisor directly, so this// asserts the survival itself: tree-kill the spawning process, and the job// must still be running and still writing.- it.runIf(!IS_POSIX)('windowsDetached survives a tree-kill of the process that spawned it', async () => {+ it.runIf(!IS_POSIX)('survives a tree-kill of the process that spawned it', async () => {const controlDir = await tmpControlDir();const marker = join(controlDir, 'go');const heartbeat = join(controlDir, 'heartbeat');@@ -309,7 +291,7 @@ describe('spawnDetached', () => {" 'const {existsSync,appendFileSync}=require(\"fs\");const t=setInterval(()=>{appendFileSync(process.argv[2],\"x\");if(existsSync(process.argv[1])){clearInterval(t);process.exit(0);}},20);',",` ${JSON.stringify(marker)},`,` ${JSON.stringify(heartbeat)},`,- `], { controlDir: ${JSON.stringify(controlDir)}, windowsDetached: true });`,+ `], { controlDir: ${JSON.stringify(controlDir)} });`,'setInterval(() => {}, 1000);',].join('\n'));@@ -337,29 +319,29 @@ describe('spawnDetached', () => {});// PowerShell's ExitCode is a SIGNED int, so an NTSTATUS crash status reads- // back negative — while Node's own ChildProcess (and so the plain-spawn- // fallback beside this) reports it unsigned. Without the mask the two win32- // arms disagree about the same crash, and a caller classifying a crash by its- // code silently stops recognizing one of them.- it.runIf(!IS_POSIX)('windowsDetached reports a crash status unsigned, as Node does', async () => {+ // back negative — while Node's own ChildProcess, and the POSIX arm's raw wait+ // status, report it unsigned. Without the mask the two platforms disagree+ // about the same crash, and a caller classifying one by its code silently+ // stops recognizing it on Windows.+ it.runIf(!IS_POSIX)('reports a crash status unsigned, as Node does', async () => {const controlDir = await tmpControlDir();const handle = await spawnDetached('powershell',['-NoProfile', '-NonInteractive', '-Command', '[Environment]::Exit(-1073741819)'],- { controlDir, windowsDetached: true }+ { controlDir });const { code, signal } = await onClose(handle);expect(code).toBe(3221225477); // 0xC0000005, not -1073741819expect(signal).toBeNull();});- it.runIf(!IS_POSIX)('windowsDetached identifies a live job by its executable', async () => {+ it.runIf(!IS_POSIX)('identifies a live job by its executable', async () => {const controlDir = await tmpControlDir();const marker = join(controlDir, 'go');const handle = await spawnDetached(process.execPath,['-e', 'const {existsSync}=require("fs");const t=setInterval(()=>{if(existsSync(process.argv[1])){clearInterval(t);process.exit(0);}},5);', marker],- { controlDir, windowsDetached: true }+ { controlDir });const closed = onClose(handle);expect(await isDetachedRunning(controlDir, { executable: process.execPath })).toBe(true);@@ -370,42 +352,69 @@ describe('spawnDetached', () => {await closed;});- // A child that runs until a marker file appears, then exits with a code and- // NO signal — the shape `taskkill /T /F` produces on Windows, where the kill- // happens out of band so libuv records no exit_signal. Driven by `node -e`- // rather than `sh -c` because these tests are NOT gated on IS_POSIX: they- // pin the platform and must run on a real Windows checkout, which has no- // guaranteed POSIX shell.- const spawnWin32Fallback = async (exitCode = 1) => {+ // A job that runs until a marker file appears, then exits with a code and NO+ // signal — the shape `taskkill /T /F` leaves behind on Windows, where the kill+ // happens out of band so nothing records an exit_signal. Driven by `node -e`+ // rather than `sh -c` because these tests are NOT gated on IS_POSIX: they run+ // against the control-dir handle both platforms now return, and must work on a+ // real Windows checkout, which has no guaranteed POSIX shell.+ //+ // The handle is built by whichever launcher the HOST has; only `kill`'s+ // dispatch is platform-dependent, so each test pins win32 around the cancel+ // and holds the pin until 'close' (the tailer decodes the exit status+ // per-platform too). On a Windows host the pin is a no-op and these run+ // against the real supervisor handle end to end.+ const spawnMarkerJob = async (exitCode = 1, opts = {}) => {const controlDir = await tmpControlDir();const marker = join(controlDir, 'go');const handle = await spawnDetached(process.execPath,['-e', `const {existsSync}=require('fs');const t=setInterval(()=>{if(existsSync(process.argv[1])){clearInterval(t);process.exit(${exitCode});}},5);`, marker],- { controlDir }+ { controlDir, pollMs: 25, ...opts });- return { handle, terminate: () => writeFile(marker, '1') };+ return { handle, controlDir, terminate: () => writeFile(marker, '1') };};- it('win32 fallback kill() tree-kills so the runner\'s children die with it', async () => {+ it('win32 kill() tree-kills by pid so the runner\'s children die with it', async () => {const restorePlatform = pinPlatform('win32');try {killProcessTree.mockClear();- const { handle, terminate } = await spawnWin32Fallback();+ const { handle, terminate } = await spawnMarkerJob();const closed = onClose(handle);expect(handle.kill('SIGKILL')).toBe(true);expect(handle.killed).toBe(true);expect(killProcessTree).toHaveBeenCalledTimes(1);- const [target, signal, opts] = killProcessTree.mock.calls[0];+ const [target, signal, opts, isWin32] = killProcessTree.mock.calls[0];expect(signal).toBe('SIGKILL');+ expect(opts).toEqual({ processGroup: false });+ expect(isWin32).toBe(true);+ // The job reparented away from this process, so a bare `{ pid }` is the+ // only address there is — killProcessTree's taskkill branch has to accept+ // it, or the cancel silently degrades to a leaf kill that orphans the+ // ffmpeg/python the runner spawned (#4171).+ expect(target).toEqual({ pid: handle.pid });+ expect(target.kill).toBeUndefined();+ await terminate();+ await closed;+ } finally {+ restorePlatform();+ }+ });++ it('win32 maps killProcessGroup onto the same tree-kill (no process groups there)', async () => {+ const restorePlatform = pinPlatform('win32');+ try {+ killProcessTree.mockClear();+ const { handle, terminate } = await spawnMarkerJob(1, { killProcessGroup: true });+ const closed = onClose(handle);+ expect(handle.kill('SIGTERM')).toBe(true);+ const [target, , opts, isWin32] = killProcessTree.mock.calls[0];+ // Forwarded as-is: killProcessTree's win32 branch runs BEFORE its+ // process-group branch, so the flag can never reach a `process.kill(-pid)`+ // that Windows has no meaning for.expect(opts).toEqual({ processGroup: true });- // The target must still be a real ChildProcess — killProcessTree's- // `taskkill /T /F` branch is gated on `instanceof ChildProcess` — and must- // carry Node's own kill, not the override, so its POSIX fall-through- // can't recurse back into it.- expect(target).toBeInstanceOf(ChildProcess);- expect(target.pid).toBe(handle.pid);- expect(target.kill).not.toBe(handle.kill);+ expect(isWin32).toBe(true);+ expect(target).toEqual({ pid: handle.pid });await terminate();await closed;} finally {@@ -413,14 +422,14 @@ describe('spawnDetached', () => {}});- it('win32 fallback reports the requested signal on close (taskkill kills out of band)', async () => {+ it('win32 reports the requested signal on close (taskkill kills out of band)', async () => {const restorePlatform = pinPlatform('win32');try {killProcessTree.mockClear();- const { handle, terminate } = await spawnWin32Fallback();+ const { handle, terminate } = await spawnMarkerJob();const closed = onClose(handle);handle.kill('SIGKILL');- // The stubbed tree-kill didn't terminate anything; let the child exit the+ // The stubbed tree-kill didn't terminate anything; let the job exit the// way a taskkill'd one does — a plain non-zero code, no signal.await terminate();const { code, signal } = await closed;@@ -435,11 +444,11 @@ describe('spawnDetached', () => {}});- it('win32 fallback leaves a clean exit alone when a cancel races completion', async () => {+ it('win32 leaves a clean exit alone when a cancel races completion', async () => {const restorePlatform = pinPlatform('win32');try {killProcessTree.mockClear();- const { handle, terminate } = await spawnWin32Fallback(0);+ const { handle, terminate } = await spawnMarkerJob(0);const closed = onClose(handle);handle.kill('SIGTERM');await terminate();@@ -451,10 +460,10 @@ describe('spawnDetached', () => {}});- it('win32 fallback stamps a numeric signal as its NAME on close', async () => {+ it('win32 stamps a numeric signal as its NAME on close', async () => {const restorePlatform = pinPlatform('win32');try {- const { handle, terminate } = await spawnWin32Fallback();+ const { handle, terminate } = await spawnMarkerJob();const closed = onClose(handle);// kill() accepts a number; ChildProcess reports names, so a raw 9 would// break every `signal === 'SIGKILL'` comparison downstream.@@ -469,49 +478,53 @@ describe('spawnDetached', () => {}});- it('win32 fallback refuses to tree-kill a child that already exited', async () => {+ it('win32 refuses to tree-kill a job that already exited', async () => {const restorePlatform = pinPlatform('win32');try {- const { handle, terminate } = await spawnWin32Fallback();+ const { handle, terminate } = await spawnMarkerJob();const closed = onClose(handle);await terminate();await closed;- // Windows recycles PIDs, so a late escalation must not taskkill whatever- // inherited the number.+ // Windows recycles PIDs, so a late escalation (reapDetached's grace+ // deadline) must not taskkill whatever inherited the number.killProcessTree.mockClear();expect(handle.kill('SIGKILL')).toBe(false);expect(killProcessTree).not.toHaveBeenCalled();+ // ...and the status the supervisor recorded survives the refused kill.+ expect(handle.exitCode).toBe(1);+ expect(handle.signalCode).toBeNull();} finally {restorePlatform();}});- it('win32 fallback treats signal 0 as an existence probe, not a kill', async () => {+ it('win32 treats signal 0 as an existence probe, not a kill', async () => {const restorePlatform = pinPlatform('win32');try {killProcessTree.mockClear();- const { handle, terminate } = await spawnWin32Fallback();+ const { handle, terminate } = await spawnMarkerJob();const closed = onClose(handle);- // Node's own kill(0) answers the probe (and sets `killed`, as it always- // has); what matters is that no taskkill went out.expect(handle.kill(0)).toBe(true);expect(killProcessTree).not.toHaveBeenCalled();await terminate();- await closed;+ const { code, signal } = await closed;+ // A probe is not a death: it must not stamp a signal onto the close.+ expect(code).toBe(1);+ expect(signal).toBeNull();} finally {restorePlatform();}});- it('win32 fallback rejects an unknown signal instead of force-killing the tree', async () => {+ it('win32 rejects an unknown signal instead of force-killing the tree', async () => {const restorePlatform = pinPlatform('win32');try {killProcessTree.mockClear();- const { handle, terminate } = await spawnWin32Fallback();+ const { handle, terminate } = await spawnMarkerJob();const closed = onClose(handle);// ChildProcess.kill() throws ERR_UNKNOWN_SIGNAL on a typo'd name; the- // override must not turn that into a silent whole-tree force-kill.- expect(() => handle.kill('SIGKLL')).toThrow();+ // handle must not turn that into a silent whole-tree force-kill.+ expect(() => handle.kill('SIGKLL')).toThrow(/Unknown signal/);expect(killProcessTree).not.toHaveBeenCalled();await terminate();await closed;@@ -520,6 +533,77 @@ describe('spawnDetached', () => {}});+ // The convergence itself (#6170): on a real Windows host, a cancel must take+ // the job's OWN descendants with it — the ffmpeg mux a video runtime shells+ // out to, the pip a trainer launches. `process.kill(pid)` there terminates the+ // job leaf and orphans them still holding the output file and GPU memory,+ // which is exactly why the supervisor path used to be opt-in. Needs the REAL+ // killProcessTree, so restore it for this one call.+ //+ // The runner is POWERSHELL, not node: libuv assigns a Node-spawned child to a+ // job object that closes (and kills the child) when its Node parent dies, so a+ // node-parent fixture passes even against a leaf-only kill and asserts+ // nothing. A real trainer/render runner — python, a shell — has no such tie,+ // and its ffmpeg keeps running. That is the orphan under test.+ it.runIf(!IS_POSIX)('cancels a Windows job together with the grandchild it spawned', async () => {+ const { killProcessTree: realKillProcessTree } = await vi.importActual('./bufferedSpawn.js');+ killProcessTree.mockImplementationOnce(realKillProcessTree);++ const controlDir = await tmpControlDir();+ const grandchildPidFile = join(controlDir, 'grandchild-pid');+ const heartbeat = join(controlDir, 'heartbeat');+ const grandchildPath = join(controlDir, 'grandchild.cjs');+ const runnerPath = join(controlDir, 'runner.ps1');+ // A heartbeat file rather than a pid probe: on Windows a terminated process+ // stays openable while any handle to it is alive, so `kill(pid, 0)` can+ // still answer for a process that is gone. Output that STOPS is unambiguous.+ await writeFile(grandchildPath, [+ "const { appendFileSync } = require('fs');",+ "setInterval(() => appendFileSync(process.env.PORTOS_TEST_HEARTBEAT, 'x'), 20);",+ ].join('\n'));+ // The paths reach the grandchild through the environment, not argv: Windows+ // PowerShell 5.1's `Start-Process -ArgumentList` joins its array on spaces+ // without quoting, so a temp path under a user name containing a space+ // would silently split.+ await writeFile(runnerPath, [+ 'param([string]$NodeExe, [string]$ScriptPath, [string]$PidFile, [string]$Heartbeat)',+ '$env:PORTOS_TEST_HEARTBEAT = $Heartbeat',+ '$g = Start-Process -FilePath $NodeExe -ArgumentList @((\'"\' + $ScriptPath + \'"\')) -PassThru -NoNewWindow',+ 'Set-Content -LiteralPath $PidFile -Value $g.Id',+ 'while ($true) { Start-Sleep -Milliseconds 200 }',+ ].join('\n'));++ const handle = await spawnDetached(+ 'powershell',+ ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-File', runnerPath,+ process.execPath, grandchildPath, grandchildPidFile, heartbeat],+ { controlDir, pollMs: 25 }+ );+ const closed = onClose(handle);++ const beats = async () => (await readFile(heartbeat, 'utf8').catch(() => '')).length;+ // Two powershell hops plus a Start-Process, so this is slower than the+ // node-only fixtures above.+ expect(await waitUntil(async () => (await beats()) > 0, { timeoutMs: 30000 })).toBe(true);+ const grandchildPid = Number.parseInt(await readFile(grandchildPidFile, 'utf8'), 10);+ expect(grandchildPid).toBeGreaterThan(0);++ try {+ expect(handle.kill('SIGKILL')).toBe(true);+ await closed;+ // Stopped writing — a leaf-only kill leaves it beating forever.+ const settled = await waitUntil(async () => {+ const before = await beats();+ await new Promise((r) => setTimeout(r, 150));+ return (await beats()) === before;+ }, { timeoutMs: 10000 });+ expect(settled).toBe(true);+ } finally {+ // Never leave a real orphan behind when the assertion above is what failed.+ try { process.kill(grandchildPid, 'SIGKILL'); } catch { /* already gone */ }+ }+ });+it.runIf(IS_POSIX)('leaves the POSIX path on its own pid/group signalling (no tree-kill)', async () => {killProcessTree.mockClear();const controlDir = await tmpControlDir();diff --git a/server/services/appUpdater.js b/server/services/appUpdater.jsindex 1d0fd1dc7e..8c6ad246d9 100644--- a/server/services/appUpdater.js+++ b/server/services/appUpdater.js@@ -60,10 +60,10 @@ async function startDashboardHandoff(app) {const handoff = await spawnDetached(process.execPath,[scriptPath],- // windowsDetached: pm2 kills on Windows with `taskkill /T`, which walks the- // same parent tree — without it the handoff dies with portos-server there- // exactly as it would on POSIX without the double-fork.- { cwd: app.repoPath, controlDir: DASHBOARD_OPEN_CONTROL_DIR, cleanup: true, windowsDetached: true },+ // spawnDetached leaves this process's tree on every platform — pm2 kills on+ // Windows with `taskkill /T`, which walks the same parent tree the POSIX+ // double-fork escapes, so without it the handoff dies with portos-server.+ { cwd: app.repoPath, controlDir: DASHBOARD_OPEN_CONTROL_DIR, cleanup: true },).catch((err) => {console.error(`⚠️ Dashboard auto-open could not start: ${err.message}`);return null;diff --git a/server/services/updateExecutor.js b/server/services/updateExecutor.jsindex f4bd4fd974..8cc1191453 100644--- a/server/services/updateExecutor.js+++ b/server/services/updateExecutor.js@@ -19,12 +19,13 @@ const UPDATE_PS1 = join(PATHS.root, 'update.ps1');* `pm2 start` (the reconcile/update "shuts down but never comes back" failure).* See the rationale in `server/lib/detachedSpawn.js`.*- * Windows needs `windowsDetached` for the same reason (pm2 kills there with+ * Windows escapes the same way for the same reason (pm2 kills there with* `taskkill /T`, which walks the identical tree), and CANNOT use a plain* `detached: true`: on Windows that flag means DETACHED_PROCESS, which denies* the child a console — powershell then exits 0 within ~100ms without running a* single line of update.ps1, and this function used to report that as a- * successful update to the target release (#6169).+ * successful update to the target release (#6169). spawnDetached's Windows+ * supervisor handles that internally, so no option is needed here.** The scripts pull the latest code via `git pull --rebase --autostash` and* write the actual resulting version to `data/update-complete.json`.@@ -99,7 +100,6 @@ export async function executeUpdate(tag, emit, { forceCleanWorkspaces, onLaunchecwd: PATHS.root,env: childEnv,controlDir,- windowsDetached: true,// The default 250ms cadence is calibrated for trainer/render output; this// job emits one human-paced `STEP:` line per multi-second stage, so a// quarter of the syscalls buys the same perceived progress.diff --git a/server/services/updateExecutor.test.js b/server/services/updateExecutor.test.jsindex 2d69498e74..579d12222e 100644--- a/server/services/updateExecutor.test.js+++ b/server/services/updateExecutor.test.js@@ -76,12 +76,12 @@ beforeEach(() => {});describe('executeUpdate', () => {- // Windows goes through spawnDetached too, with `windowsDetached` set. The- // plain `spawn(..., { detached: true })` this replaced meant- // DETACHED_PROCESS, which denies powershell a console — update.ps1 exited 0- // within ~100ms without running a line, and pm2's `taskkill /T` would have- // killed an attached one mid-update anyway (#6169).- it('launches powershell through spawnDetached with windowsDetached on win32', async () => {+ // Windows goes through spawnDetached too — its supervisor launcher is what+ // makes update.ps1 survive. The plain `spawn(..., { detached: true })` this+ // replaced meant DETACHED_PROCESS, which denies powershell a console:+ // update.ps1 exited 0 within ~100ms without running a line, and pm2's+ // `taskkill /T` would have killed an attached one mid-update anyway (#6169).+ it('launches powershell through spawnDetached on win32', async () => {// Re-pin over the file-level linux default; the file-level afterEach still// restores the pristine descriptor, so a failure here can't leak win32.pinPlatform('win32');@@ -97,7 +97,7 @@ describe('executeUpdate', () => {expect(spawnDetached).toHaveBeenCalledWith('powershell',expect.arrayContaining(['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-File']),- expect.objectContaining({ windowsDetached: true })+ expect.objectContaining({ controlDir: expect.stringContaining('update-detached') }));// The still-running guard covers Windows too now that the script survives there.expect(isDetachedRunning).toHaveBeenCalledWith(