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(windows): make the in-app update actually run instead of reporting a phantom success (#6169)

[._.]/ Adam Eivyfbe172acc7c0
diff --git a/client/src/hooks/usePortosRestartWatch.js b/client/src/hooks/usePortosRestartWatch.js
index b754be3849..9537ad91a4 100644
--- a/client/src/hooks/usePortosRestartWatch.js
+++ b/client/src/hooks/usePortosRestartWatch.js
@@ -6,7 +6,21 @@ import { useAutoRefetch } from './useAutoRefetch';
import useMounted from './useMounted';
const POLL_MS = 2000;
-const MAX_ATTEMPTS = 30;
+// The watch has two phases with wildly different budgets, so one flat ceiling is
+// wrong for both. Until the server is seen DOWN the update has not reached
+// `pm2-stop` — or the launch failed outright — and a stall there should be
+// reported quickly rather than parked under an indefinite "restarting" toast.
+// Once it IS down, the poll has to outlast the window it stays down: `pm2-stop`
+// through the client build is npm install + setup + migrations + build, minutes
+// on a warm tree and tens of them on a cold `node_modules`. The old flat 60s
+// budget was the second phase measured with the first phase's ruler, so every
+// real update timed out while it was still going fine in the background (#6169).
+//
+// Budgets are wall clock, not attempt counts: `useAutoRefetch` skips its tick
+// while the tab is hidden, so counting attempts would silently stretch the
+// ceiling by however long PortOS sat in a background tab.
+const DOWN_WAIT_MS = 60 * 1000;
+const RECOVERY_TIMEOUT_MS = 30 * 60 * 1000;
// A raw 'disconnect' is not proof the update tore the process down — PortOS is
// commonly used remotely over Tailscale, and a network blip during the early
// steps (git-pull/submodules, while the server is very much alive) fires one
@@ -52,7 +66,7 @@ export function usePortosRestartWatch({ enabled = true, active = false, onRestar
const mountedRef = useMounted();
const activeRef = useRef(active);
const pollingRef = useRef(false);
- const attemptsRef = useRef(0);
+ const pollStartedAtRef = useRef(0);
const preUpdateVersionRef = useRef(null);
// Whether health went down during this poll cycle — a down→up transition is
// what proves a same-version reconcile actually restarted.
@@ -87,7 +101,7 @@ export function usePortosRestartWatch({ enabled = true, active = false, onRestar
if (pollingRef.current) return;
activeRef.current = false;
pollingRef.current = true;
- attemptsRef.current = 0;
+ pollStartedAtRef.current = Date.now();
healthWentDownRef.current = healthDown;
setPolling(true);
toast.loading('PortOS is restarting...', { id: TOAST_ID, duration: Infinity });
@@ -152,7 +166,6 @@ export function usePortosRestartWatch({ enabled = true, active = false, onRestar
}, [arm, enabled, mountedRef, stopPolling]);
const pollHealth = useCallback(async () => {
- attemptsRef.current += 1;
// silent: true — the server being unreachable is the EXPECTED state for most
// of this poll (that's the down→up transition it watches for), not an error;
// the generic toast would spam "Server unreachable" every 2s throughout the
@@ -188,9 +201,14 @@ export function usePortosRestartWatch({ enabled = true, active = false, onRestar
if (ok && typeof ok.uptime === 'number' && ok.uptime > maxUptimeRef.current) {
maxUptimeRef.current = ok.uptime;
}
- if (attemptsRef.current >= MAX_ATTEMPTS) {
+ // Checked LAST, so a tick arriving after a long hidden-tab gap still gets
+ // to recognize a finished restart above before the budget applies.
+ const budget = healthWentDownRef.current ? RECOVERY_TIMEOUT_MS : DOWN_WAIT_MS;
+ if (Date.now() - pollStartedAtRef.current >= budget) {
stopPolling();
- toast.error('Restart timed out — try reloading manually', { id: TOAST_ID });
+ toast.error(healthWentDownRef.current
+ ? 'Restart timed out — try reloading manually'
+ : 'PortOS never went down — the update may not have started', { id: TOAST_ID });
}
}, [stopPolling]);
diff --git a/docs/SELF_UPDATE.md b/docs/SELF_UPDATE.md
index e61d00aecd..922eb9c909 100644
--- a/docs/SELF_UPDATE.md
+++ b/docs/SELF_UPDATE.md
@@ -69,6 +69,13 @@ 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.
+
+Two guards keep a launch that did nothing from being reported as an update:
+
+- A run that exits 0 having emitted **no `STEP:` line at all** is recorded as a failure, not a success — both scripts emit `git-pull:running` before touching anything, so silence means the script never ran.
+- When `data/update-complete.json` is missing (usually because the restarted server already consumed it), the recorded version comes from **package.json on disk**, never from the triggering tag: the tag is only what the update aimed at.
+
**PortOS is also a managed app**, so an update started from **App Management**'s Git tab reaches `update.sh` through `appUpdater.js` rather than `routes/update.js`. Both entry points call the same `startPortosSelfUpdate()` (`server/services/portosSelfUpdate.js`), which owns the whole lifecycle: the preflight refusals, the atomic `setUpdateInProgress(true)` lock, the post-lock re-check, and the `executeUpdate()` launch. They differ only in `mode`:
| Surface | Mode | Gate |
diff --git a/server/lib/README.md b/server/lib/README.md
index de47ad8970..53411080ea 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?})` → 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 has no double-fork (plain-spawn fallback), so its handle's `kill` delegates to `killProcessTree` (`taskkill /T /F`) — a cancel there takes the runner's children with it. 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?,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. |
| `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/detachedSpawn.js b/server/lib/detachedSpawn.js
index eaa1cb4c24..ccf8ccee2d 100644
--- a/server/lib/detachedSpawn.js
+++ b/server/lib/detachedSpawn.js
@@ -52,6 +52,7 @@ import { promisify } from 'util';
import { killProcessTree } from './bufferedSpawn.js';
import { ensureDir, sleep } from './fileUtils.js';
import { safeChildProcessOptions } from './processEnv.js';
+import { quoteForShell } from './shellCd.js';
import { withSpawnCwdEnv } from './spawnCwd.js';
const execFileAsync = promisify(execFile);
@@ -113,6 +114,108 @@ d="$1"; shift
} &
`;
+// ─── Windows equivalent of the double-fork ───────────────────────────────────
+//
+// Windows has no `sh` and no reparent-to-init, but pm2 kills an app there with
+// `taskkill /pid <app> /T /F`, which walks the SAME parent→child tree the POSIX
+// launcher escapes — so a plain child of portos-server dies with it exactly as
+// it does on POSIX. The escape is a launcher that exits immediately, leaving
+// the supervisor with a dead parent and therefore outside the server's tree:
+//
+// server ──spawn──▶ launcher powershell (exits in ~200ms)
+// │ Process.Start
+// ▼
+// supervisor powershell (parent already gone, so
+// │ `taskkill /T` from the server
+// ▼ never reaches it)
+// job process
+//
+// The supervisor redirects the job's stdout/stderr into the control dir and
+// records its pid and exit status there, so the shared tailer below streams a
+// Windows job exactly as it streams a POSIX one.
+//
+// Reading the job spec from `job.json` (rather than interpolating it into the
+// script) keeps paths with spaces, quotes, or `$` out of PowerShell's parser.
+// `$null = $p.Handle` caches the process handle BEFORE the wait: without it
+// `Start-Process -PassThru` hands back an object whose `ExitCode` reads back
+// empty once the process is gone, and the tailer would never see a status.
+const WINDOWS_SUPERVISOR = `$dir = Split-Path -Parent $MyInvocation.MyCommand.Path
+try {
+ $ErrorActionPreference = 'Stop'
+ $job = Get-Content -LiteralPath (Join-Path $dir 'job.json') -Raw -Encoding UTF8 | ConvertFrom-Json
+ $params = @{
+ FilePath = $job.bin
+ RedirectStandardOutput = (Join-Path $dir 'stdout.log')
+ RedirectStandardError = (Join-Path $dir 'stderr.log')
+ WindowStyle = 'Hidden'
+ PassThru = $true
+ }
+ if ($job.arguments) { $params.ArgumentList = $job.arguments }
+ if ($job.cwd) { $params.WorkingDirectory = $job.cwd }
+ $p = Start-Process @params
+ $null = $p.Handle
+ [System.IO.File]::WriteAllText((Join-Path $dir 'pid'), "$($p.Id)")
+ $p.WaitForExit()
+ [System.IO.File]::WriteAllText((Join-Path $dir 'exit'), "$($p.ExitCode)")
+} catch {
+ [System.IO.File]::WriteAllText((Join-Path $dir 'stderr.log'), $_.Exception.ToString())
+ [System.IO.File]::WriteAllText((Join-Path $dir 'exit'), '1')
+}
+`;
+
+// Quote one argv entry for a Windows command line (CommandLineToArgvW rules).
+// Windows PowerShell 5.1 runs on .NET Framework, whose ProcessStartInfo has
+// only the flat `Arguments` string — no `ArgumentList` — so a single correctly
+// quoted string is the only faithful way to carry an argv containing spaces.
+const quoteWindowsArg = (arg) => {
+ const s = String(arg);
+ if (s.length > 0 && !/[\s"]/.test(s)) return s;
+ // Backslashes are literal EXCEPT in the run immediately before a quote (the
+ // embedded ones and the closing one), where each must be doubled.
+ return `"${s.replace(/(\\*)"/g, '$1$1\\"').replace(/(\\*)$/, '$1$1')}"`;
+};
+
+/**
+ * Write the control dir's job spec + supervisor script and launch the
+ * short-lived launcher that starts the supervisor outside our process tree.
+ * The supervisor is started with an explicit `CreateNoWindow`, not through
+ * `Start-Process`, so this hop out of the console-less PM2 fork can never
+ * trigger Windows' default-terminal handoff — see docs/WINDOWS_CONSOLE.md.
+ * (The supervisor's own `Start-Process` of the job redirects to files, which
+ * already forces `UseShellExecute = false`.)
+ */
+async function launchWindowsSupervisor({ controlDir, bin, args, env, cwd }) {
+ const supervisorPath = join(controlDir, 'supervisor.ps1');
+ // Independent files — write them together rather than serializing two
+ // round-trips in front of every launch.
+ await Promise.all([
+ writeFile(join(controlDir, 'job.json'), JSON.stringify({
+ bin,
+ arguments: args.map(quoteWindowsArg).join(' '),
+ cwd: cwd || null,
+ }), 'utf8'),
+ writeFile(supervisorPath, WINDOWS_SUPERVISOR, 'utf8'),
+ ]);
+ const supervisorArgs = `-NoProfile -NonInteractive -ExecutionPolicy Bypass -File ${quoteWindowsArg(supervisorPath)}`;
+ const startSupervisor = [
+ '$psi = New-Object System.Diagnostics.ProcessStartInfo;',
+ "$psi.FileName = 'powershell';",
+ `$psi.Arguments = ${quoteForShell(supervisorArgs, 'powershell')};`,
+ '$psi.UseShellExecute = $false;',
+ '$psi.CreateNoWindow = $true;',
+ '[void][System.Diagnostics.Process]::Start($psi)',
+ ].join(' ');
+ return spawn('powershell', [
+ '-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-Command', startSupervisor,
+ ], {
+ // Pin PWD to the spawn cwd — see withSpawnCwdEnv (#3193). The supervisor
+ // and the job both inherit this environment.
+ env: withSpawnCwdEnv(env ?? process.env, cwd),
+ cwd,
+ stdio: 'ignore',
+ });
+}
+
/**
* Build the log-tailer for a spawnDetached control dir. Holds a persistent fd
* per log (opened lazily once the supervisor creates the file) plus the byte
@@ -183,7 +286,10 @@ function createLogTailer(handle, { controlDir, pollMs, cleanup }) {
let code = null;
let signal = null;
if (Number.isFinite(status)) {
- if (status > 128 && SIGNAL_BY_NUMBER[status - 128]) signal = SIGNAL_BY_NUMBER[status - 128];
+ // 128+signum is a POSIX `wait` convention. On Windows the supervisor
+ // records the raw ExitCode, where values above 128 are ordinary statuses
+ // (0xC0000005 & friends), so decoding one as a signal would invent it.
+ if (process.platform !== 'win32' && status > 128 && SIGNAL_BY_NUMBER[status - 128]) signal = SIGNAL_BY_NUMBER[status - 128];
else code = status;
} else {
code = 1; // exit file missing/garbled — treat as generic failure
@@ -236,21 +342,30 @@ function createLogTailer(handle, { controlDir, pollMs, cleanup }) {
* 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.
* @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');
- // Windows has no POSIX `sh` for the double-fork, and pm2's process management
- // there is taskkill-based rather than the PPID-walk this works around. Fall
- // 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 a POSIX-only guarantee; Windows keeps its prior spawn semantics apart
- // from `kill`, which is replaced with a tree-kill below.
- if (process.platform === 'win32') {
+ const 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
@@ -354,21 +469,28 @@ export async function spawnDetached(bin, args = [], {
// Launch the double-fork. `detached` gives the outer sh its own session;
// `stdio: 'ignore'` because all job output is redirected to files by the
// launcher; `.unref()` so the server never waits on the (instantly-exiting)
- // outer sh.
- const launcher = spawn('sh', ['-c', LAUNCHER, 'sh', controlDir, bin, ...args], {
- // Pin PWD to the spawn cwd — see withSpawnCwdEnv (#3193).
- env: withSpawnCwdEnv(env ?? process.env, cwd),
- cwd,
- detached: true,
- stdio: 'ignore',
- });
+ // outer sh. Windows takes the supervisor launcher instead — see its header
+ // block above for why `detached` cannot appear on that arm.
// The outer sh exits in ~1ms; a spawn error (e.g. no `sh`) is the only real
// launcher failure. Capture it so the deferred kickoff below surfaces it as
// the handle's 'error' AFTER the caller has attached listeners — emitting it
- // synchronously here could throw as an unhandled 'error'.
+ // synchronously here could throw as an unhandled 'error'. The Windows path
+ // writes two control files before it spawns, so it can fail with a rejection
+ // too; route that into the same slot rather than letting it reject
+ // spawnDetached, for the reason ensureControlDir above spells out.
let launcherSpawnError = null;
- launcher.on('error', (err) => { launcherSpawnError = err; });
- launcher.unref();
+ const launcher = isWindows
+ ? await launchWindowsSupervisor({ controlDir, bin, args, env, cwd })
+ .catch((err) => { launcherSpawnError = err; return null; })
+ : spawn('sh', ['-c', LAUNCHER, 'sh', controlDir, bin, ...args], {
+ // Pin PWD to the spawn cwd — see withSpawnCwdEnv (#3193).
+ env: withSpawnCwdEnv(env ?? process.env, cwd),
+ cwd,
+ detached: true,
+ stdio: 'ignore',
+ });
+ launcher?.on('error', (err) => { launcherSpawnError = err; });
+ launcher?.unref();
// Tail the on-disk log files and watch for the supervisor's exit sentinel,
// streaming new bytes as stdout/stderr 'data' and emitting 'close' on exit.
@@ -490,9 +612,12 @@ export async function isReattachable(controlDir) {
* @returns {Promise<object|null>} ChildProcess-like handle, or null if not reattachable
*/
export async function reattachDetached(controlDir, { pollMs = DEFAULT_POLL_MS, cleanup = false } = {}) {
- // Detached survival is a POSIX-only guarantee (see spawnDetached's win32
- // fallback) — there is never a reparented orphan to re-attach to on Windows.
- if (process.platform === 'win32') return null;
+ // 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.
const pidRaw = await readFile(join(controlDir, 'pid'), 'utf8').catch(() => '');
const pid = Number.parseInt(pidRaw, 10);
if (!Number.isFinite(pid) || pid <= 0) return null;
@@ -562,7 +687,30 @@ const processCommandMatches = (command, { executable, args }) => {
return actualArgs === args.map(String).join(' ');
};
+// Windows has no cheap argv probe — `tasklist` reports only the image name —
+// so identity there is the executable alone. That is all this guard needs: it
+// exists to stop a stale PID file whose number some unrelated process inherited
+// from blocking the control dir forever.
+//
+// One `tasklist` SPAWN per call, and it enumerates the whole process table
+// before applying the filter (~100-300ms). Fine for the one-per-launch probes
+// that reach it today; a fan-out or polled caller must instead take a single
+// `tasklist /FO CSV /NH` snapshot and match every PID against it.
+const processMatchesWin32 = async (pid, { executable }) => {
+ const { stdout } = await execFileAsync(
+ 'tasklist', ['/FI', `PID eq ${pid}`, '/NH', '/FO', 'CSV'], safeChildProcessOptions({ timeout: 5000 })
+ );
+ // No match prints an unquoted `INFO: No tasks are running …` banner instead
+ // of a CSV row, and tasklist exits 0 either way — so a missing quoted first
+ // field IS the not-running answer.
+ const image = stdout.trim().match(/^"([^"]*)"/)?.[1];
+ if (!image) return false;
+ const normalize = (value) => basename(value).toLowerCase().replace(/\.exe$/, '');
+ return normalize(image) === normalize(executable);
+};
+
const processMatches = async (pid, expectedProcess) => {
+ if (process.platform === 'win32') return processMatchesWin32(pid, expectedProcess);
const { stdout } = await execFileAsync(
'ps', ['-ww', '-p', String(pid), '-o', 'command='], safeChildProcessOptions({ timeout: 5000 })
).catch((err) => {
diff --git a/server/lib/detachedSpawn.test.js b/server/lib/detachedSpawn.test.js
index 25655b2f75..7843991c29 100644
--- a/server/lib/detachedSpawn.test.js
+++ b/server/lib/detachedSpawn.test.js
@@ -256,6 +256,48 @@ describe('spawnDetached', () => {
}
});
+ // The `windowsDetached` 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 () => {
+ const controlDir = await tmpControlDir();
+ const handle = await spawnDetached(
+ process.execPath,
+ // The spaced/quoted argv entry pins the Windows command-line quoting the
+ // 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 }
+ );
+ const getOut = collect(handle.stdout);
+ expect(handle.pid).toBeGreaterThan(0);
+ const { code, signal } = await onClose(handle);
+ expect(code).toBe(3);
+ expect(signal).toBeNull();
+ expect(getOut()).toBe('a b "c"\n');
+ });
+
+ it.runIf(!IS_POSIX)('windowsDetached 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 }
+ );
+ const closed = onClose(handle);
+ expect(await isDetachedRunning(controlDir, { executable: process.execPath })).toBe(true);
+ // A PID some unrelated process inherited must not keep the control dir
+ // blocked — that would wedge every later update at "already running".
+ expect(await isDetachedRunning(controlDir, { executable: 'notepad' })).toBe(false);
+ await writeFile(marker, '1');
+ 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`
diff --git a/server/lib/spawnCwd.test.js b/server/lib/spawnCwd.test.js
index 02d86756ba..cc27c0f3be 100644
--- a/server/lib/spawnCwd.test.js
+++ b/server/lib/spawnCwd.test.js
@@ -280,7 +280,6 @@ describe('every cwd-passing spawn pins PWD', () => {
['services/appDeployer.js', 'deploy shell commands, not an AI CLI'],
['services/xcodeScripts.js', 'xcodebuild/ls, not an AI CLI'],
['services/imageTo3d/laneRunner.js', 'git/bash/python install + render steps inside a target install root, not an AI CLI'],
- ['services/updateExecutor.js', "PortOS's own update scripts, run in the PortOS root by design"],
['services/dbAdmin.js', 'psql/pg_dump, not an AI CLI'],
['routes/scaffold.js', 'npm/git scaffolding, not an AI CLI'],
['routes/scaffoldVite.js', 'npm scaffolding, not an AI CLI'],
diff --git a/server/services/appUpdater.js b/server/services/appUpdater.js
index ad8a99fb37..1d0fd1dc7e 100644
--- a/server/services/appUpdater.js
+++ b/server/services/appUpdater.js
@@ -60,7 +60,10 @@ async function startDashboardHandoff(app) {
const handoff = await spawnDetached(
process.execPath,
[scriptPath],
- { cwd: app.repoPath, controlDir: DASHBOARD_OPEN_CONTROL_DIR, cleanup: true },
+ // 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 },
).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.js
index d47af06948..f4bd4fd974 100644
--- a/server/services/updateExecutor.js
+++ b/server/services/updateExecutor.js
@@ -1,9 +1,8 @@
-import { spawn } from '../lib/childProcess.js';
import { readFile, unlink } from 'fs/promises';
import { join } from 'path';
import { PATHS } from '../lib/fileUtils.js';
import { spawnDetached, isDetachedRunning } from '../lib/detachedSpawn.js';
-import { recordUpdateResult } from './updateChecker.js';
+import { getCurrentVersion, recordUpdateResult } from './updateChecker.js';
const UPDATE_SH = join(PATHS.root, 'update.sh');
const UPDATE_PS1 = join(PATHS.root, 'update.ps1');
@@ -11,19 +10,21 @@ const UPDATE_PS1 = join(PATHS.root, 'update.ps1');
/**
* Execute the PortOS update script (git pull to latest).
*
- * On POSIX the script is launched via spawnDetached's double-fork so it
- * reparents to init and SURVIVES pm2's TreeKill. A plain
- * `spawn(..., { detached: true })` does NOT survive: pm2 walks PPID
- * (`ps -e -o pid=,ppid=`), not the process group, so when update.sh reaches
- * its `pm2-stop` step (`pm2 delete ecosystem.config.cjs`) the script itself —
- * still a PPID-child of portos-server — was tree-killed with the server,
- * leaving every app stopped with nothing alive to run the final `pm2 start`
- * (the reconcile/update "shuts down but never comes back" failure). See the
- * rationale in `server/lib/detachedSpawn.js`.
+ * The script is launched via spawnDetached so it leaves this process's tree and
+ * SURVIVES pm2's TreeKill. A plain `spawn(..., { detached: true })` does NOT
+ * survive: pm2 walks PPID (`ps -e -o pid=,ppid=`), not the process group, so
+ * when update.sh reaches its `pm2-stop` step (`pm2 delete ecosystem.config.cjs`)
+ * the script itself — still a PPID-child of portos-server — was tree-killed with
+ * the server, leaving every app stopped with nothing alive to run the final
+ * `pm2 start` (the reconcile/update "shuts down but never comes back" failure).
+ * See the rationale in `server/lib/detachedSpawn.js`.
*
- * Windows keeps the prior plain-spawn behavior (pm2 there is taskkill-based;
- * detached survival is a POSIX-only guarantee — same trade-off as
- * spawnDetached's own win32 fallback).
+ * Windows needs `windowsDetached` 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).
*
* The scripts pull the latest code via `git pull --rebase --autostash` and
* write the actual resulting version to `data/update-complete.json`.
@@ -43,6 +44,7 @@ const UPDATE_PS1 = join(PATHS.root, 'update.ps1');
const CLEANABLE_WORKSPACES = new Set(['.', 'client', 'server', 'autofixer']);
export async function executeUpdate(tag, emit, { forceCleanWorkspaces, onLaunched } = {}) {
+ const targetVersion = tag.replace(/^v/, '');
const isWindows = process.platform === 'win32';
const cmd = isWindows ? 'powershell' : 'bash';
const args = isWindows
@@ -66,13 +68,14 @@ export async function executeUpdate(tag, emit, { forceCleanWorkspaces, onLaunche
delete childEnv.PORTOS_FORCE_CLEAN_WORKSPACES;
}
- // POSIX: double-fork via spawnDetached so the script reparents to init and
- // survives the pm2 TreeKill its own `pm2 delete`/`pm2 start` steps trigger.
- // The returned handle is ChildProcess-like (stdout/stderr 'data', 'close',
- // 'error'), streamed by tailing the control dir's log files — so the STEP:
- // progress parsing below works unchanged. The control dir is reused across
- // updates (spawnDetached truncates stale files) and kept afterward as the
- // post-mortem record of the launch.
+ // spawnDetached launches the script outside this process's tree (POSIX
+ // double-fork, Windows supervisor) so it survives the pm2 TreeKill its own
+ // `pm2 delete`/`pm2 start` steps trigger. The returned handle is
+ // ChildProcess-like (stdout/stderr 'data', 'close', 'error'), streamed by
+ // tailing the control dir's log files — so the STEP: progress parsing below
+ // works unchanged. The control dir is reused across updates (spawnDetached
+ // truncates stale files) and kept afterward as the post-mortem record of the
+ // launch.
const controlDir = join(PATHS.data, 'update-detached');
// Refuse to reuse the control dir while a prior update script is still
@@ -80,10 +83,10 @@ export async function executeUpdate(tag, emit, { forceCleanWorkspaces, onLaunche
// triggers, and its supervisor's late `exit` write into a truncated control
// dir would prematurely close the new handle with the OLD script's status).
// A still-running script also means a second update is wrong regardless.
- if (!isWindows && await isDetachedRunning(controlDir, { executable: cmd, args })) {
+ if (await isDetachedRunning(controlDir, { executable: cmd, args })) {
const errorMessage = 'A previous update script is still running — wait for it to finish before starting another update';
await recordUpdateResult({
- version: tag.replace(/^v/, ''),
+ version: targetVersion,
success: false,
completedAt: new Date().toISOString(),
log: errorMessage
@@ -92,18 +95,16 @@ export async function executeUpdate(tag, emit, { forceCleanWorkspaces, onLaunche
return { success: false, failedStep: 'starting', errorMessage };
}
- const child = isWindows
- ? spawn(cmd, args, {
- detached: true,
- stdio: ['ignore', 'pipe', 'pipe'],
- cwd: PATHS.root,
- env: childEnv
- })
- : await spawnDetached(cmd, args, {
- cwd: PATHS.root,
- env: childEnv,
- controlDir
- });
+ const child = await spawnDetached(cmd, args, {
+ cwd: 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.
+ pollMs: 1000
+ });
// The script is running from here on. Everything ABOVE can still refuse (a
// prior update script is still alive) or throw (spawn error); nothing below
@@ -114,6 +115,10 @@ export async function executeUpdate(tag, emit, { forceCleanWorkspaces, onLaunche
return new Promise((resolve) => {
let lastStep = 'starting';
+ // Whether the script ever reported a step. A run that exits 0 without one
+ // never executed the script — the scripts emit `git-pull:running` before
+ // touching anything — so it must not be recorded as a completed update.
+ let sawStep = false;
// Parse STEP:name:status:message lines from stdout/stderr streams
const makeLineHandler = () => {
@@ -127,6 +132,13 @@ export async function executeUpdate(tag, emit, { forceCleanWorkspaces, onLaunche
const match = line.match(/STEP:([^:]+):([^:]+):(.+)/);
if (match) {
const [, name, status, message] = match;
+ // The synthetic 'starting' step means "we launched the script"; the
+ // first real step proves that, so close it out instead of leaving
+ // it spinning for the rest of the update.
+ if (!sawStep) {
+ sawStep = true;
+ emit('starting', 'done', 'Update script running');
+ }
lastStep = name;
emit(name, status, message);
}
@@ -146,31 +158,45 @@ export async function executeUpdate(tag, emit, { forceCleanWorkspaces, onLaunche
}
child.on('close', async (code, signal) => {
- const success = code === 0;
- const exitDetail = signal ? `killed by ${signal}` : `exit code ${code}`;
+ // Exit 0 alone is not proof the update ran. A launch that never executed
+ // the script exits 0 with no output at all, and stamping the triggering
+ // tag onto that is how a Windows install reported "v2.57.0 — Success"
+ // while still sitting on the old version (#6169). Both scripts emit
+ // `git-pull:running` before they touch anything, so no step at all means
+ // no update — the same absent-vs-empty distinction the LLM-merge rule in
+ // AGENTS.md draws, applied to progress output.
+ const success = code === 0 && sawStep;
+ const errorMessage = code === 0
+ ? 'Update script exited 0 without reporting any progress — it never ran'
+ : `Update failed at step "${lastStep}" (${signal ? `killed by ${signal}` : `exit code ${code}`})`;
// Record result for both success and failure so updateInProgress gets
// cleared even if PM2 restart doesn't kill this process.
if (!success) {
await recordUpdateResult({
- version: tag.replace(/^v/, ''),
+ version: targetVersion,
success: false,
completedAt: new Date().toISOString(),
- log: `Process ${exitDetail}`
+ log: errorMessage
}).catch(e => console.error(`❌ Failed to record update result: ${e.message}`));
}
if (success) {
// Read the actual version from the completion marker written by the script.
// Always record a success result so updateInProgress gets cleared even if
- // PM2 restart doesn't kill this process. Falls back to the triggering tag
- // when the marker isn't readable yet.
- let actualVersion = tag.replace(/^v/, '');
- let completedAt = new Date().toISOString();
+ // PM2 restart doesn't kill this process.
+ let actualVersion = null;
+ let completedAt = null;
const markerPath = join(PATHS.data, 'update-complete.json');
try {
const marker = JSON.parse(await readFile(markerPath, 'utf-8'));
- actualVersion = marker.version || actualVersion;
- completedAt = marker.completedAt || completedAt;
- } catch { /* marker may not be readable yet — fall back to triggering tag */ }
+ actualVersion = marker.version || null;
+ completedAt = marker.completedAt || null;
+ } catch { /* marker consumed/unreadable — fall back below */ }
+ // No marker usually means the restarted server already consumed it, so
+ // the version that stands is the one on disk — NOT the triggering tag:
+ // package.json is what the install actually runs, while the tag is only
+ // what we aimed at (#6169).
+ if (!actualVersion) actualVersion = await getCurrentVersion().catch(() => targetVersion);
+ if (!completedAt) completedAt = new Date().toISOString();
let recorded = false;
try {
await recordUpdateResult({
@@ -191,14 +217,14 @@ export async function executeUpdate(tag, emit, { forceCleanWorkspaces, onLaunche
emit('complete', 'done', 'Update complete — restarting');
resolve({ success: true, version: actualVersion });
} else {
- emit(lastStep, 'error', `Update failed at step "${lastStep}" (${exitDetail})`);
- resolve({ success: false, failedStep: lastStep, errorMessage: `Update failed at step "${lastStep}" (${exitDetail})` });
+ emit(lastStep, 'error', errorMessage);
+ resolve({ success: false, failedStep: lastStep, errorMessage });
}
});
child.on('error', async (err) => {
await recordUpdateResult({
- version: tag.replace(/^v/, ''),
+ version: targetVersion,
success: false,
completedAt: new Date().toISOString(),
log: err.message
@@ -208,9 +234,7 @@ export async function executeUpdate(tag, emit, { forceCleanWorkspaces, onLaunche
resolve({ success: false, failedStep: 'starting', errorMessage });
});
- // Unref so the parent process doesn't wait for the detached child.
- // The spawnDetached handle has no unref (its launcher already unref'd);
- // only the Windows plain-spawn child needs it.
- child.unref?.();
+ // Nothing to unref: spawnDetached's handle is a plain EventEmitter tailing
+ // the control dir, and its launcher already unref'd the process it spawned.
});
}
diff --git a/server/services/updateExecutor.test.js b/server/services/updateExecutor.test.js
index 6cbf2e49df..2d69498e74 100644
--- a/server/services/updateExecutor.test.js
+++ b/server/services/updateExecutor.test.js
@@ -2,10 +2,6 @@ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { EventEmitter } from 'events';
import { pinPlatform } from '../lib/testHelper.js';
-vi.mock('../lib/childProcess.js', () => ({
- spawn: vi.fn()
-}));
-
vi.mock('../lib/fileUtils.js', () => ({
tryReadFile: vi.fn().mockResolvedValue(null),
PATHS: { root: '/mock', data: '/mock/data' }
@@ -22,18 +18,17 @@ vi.mock('fs/promises', () => ({
}));
vi.mock('./updateChecker.js', () => ({
- recordUpdateResult: vi.fn().mockResolvedValue(undefined)
+ recordUpdateResult: vi.fn().mockResolvedValue(undefined),
+ getCurrentVersion: vi.fn().mockResolvedValue('1.0.0')
}));
-import { spawn } from '../lib/childProcess.js';
import { spawnDetached, isDetachedRunning } from '../lib/detachedSpawn.js';
import { readFile } from 'fs/promises';
-import { recordUpdateResult } from './updateChecker.js';
+import { getCurrentVersion, recordUpdateResult } from './updateChecker.js';
import { executeUpdate } from './updateExecutor.js';
// The spawnDetached handle deliberately has NO unref (its launcher already
-// unref'd) — executeUpdate must use `child.unref?.()`. Only the win32
-// plain-spawn test adds a real ChildProcess-style unref to its mock.
+// unref'd), so executeUpdate must never call one.
function createMockChild() {
const child = new EventEmitter();
child.stdout = new EventEmitter();
@@ -42,6 +37,12 @@ function createMockChild() {
return child;
}
+// A run that reports no progress at all is treated as "the script never ran"
+// (#6169), so any test asserting a SUCCESSFUL update has to look like a real
+// one and emit at least one STEP line before closing.
+const emitStep = (child, line = 'STEP:git-pull:running:Pulling latest changes\n') =>
+ child.stdout.emit('data', Buffer.from(line));
+
// executeUpdate awaits spawnDetached before wiring its event listeners, so
// tests must flush the microtask/immediate queue after calling it and before
// emitting child events, or the emission fires into the void.
@@ -55,12 +56,11 @@ async function startUpdate(...args) {
return { promise };
}
-// executeUpdate branches on process.platform, and every test below except the
-// first asserts the POSIX (spawnDetached) launch path. Pin the platform so
-// they exercise that path on a Windows host too — otherwise they take the
-// powershell branch, the cleared spawn() mock returns undefined, and each one
-// hangs to the timeout. Safe here: updateExecutor.js and its (mocked) deps
-// load no native addon that picks its binary from process.platform.
+// executeUpdate picks its interpreter from process.platform, and every test
+// below except the win32 one asserts the bash/update.sh command. Pin the
+// platform so they see that on a Windows host too. Safe here: updateExecutor.js
+// and its (mocked) deps load no native addon that picks a binary from
+// process.platform.
let restorePlatform = () => {};
afterEach(() => restorePlatform());
@@ -70,29 +70,40 @@ beforeEach(() => {
vi.clearAllMocks();
// Default: marker file not found (tests that need it override this)
readFile.mockRejectedValue(new Error('ENOENT'));
+ getCurrentVersion.mockResolvedValue('1.0.0');
// Default: no prior update script still running
isDetachedRunning.mockResolvedValue(false);
});
describe('executeUpdate', () => {
- it('spawns powershell on Windows (plain spawn, not spawnDetached)', async () => {
+ // 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 () => {
// 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');
const child = createMockChild();
- child.unref = vi.fn();
- spawn.mockReturnValue(child);
+ spawnDetached.mockResolvedValue(child);
const { promise } = await startUpdate('v1.0.0', () => {});
+ emitStep(child);
child.emit('close', 0);
- await promise;
+ const result = await promise;
- expect(spawn).toHaveBeenCalledWith(
+ expect(result.success).toBe(true);
+ expect(spawnDetached).toHaveBeenCalledWith(
'powershell',
expect.arrayContaining(['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-File']),
- expect.any(Object)
+ expect.objectContaining({ windowsDetached: true })
+ );
+ // The still-running guard covers Windows too now that the script survives there.
+ expect(isDetachedRunning).toHaveBeenCalledWith(
+ expect.stringContaining('update-detached'),
+ { executable: 'powershell', args: expect.any(Array) }
);
- expect(spawnDetached).not.toHaveBeenCalled();
});
// Regression for the reconcile "shuts down but never restarts" failure: a
@@ -105,10 +116,10 @@ describe('executeUpdate', () => {
spawnDetached.mockResolvedValue(child);
const { promise } = await startUpdate('v1.0.0', () => {});
+ emitStep(child);
child.emit('close', 0);
await promise;
- expect(spawn).not.toHaveBeenCalled();
expect(isDetachedRunning).toHaveBeenCalledWith(
expect.stringContaining('update-detached'),
{
@@ -132,6 +143,7 @@ describe('executeUpdate', () => {
spawnDetached.mockResolvedValue(child);
const { promise } = await startUpdate('v1.0.0', () => {});
+ emitStep(child);
child.emit('close', 0);
const result = await promise;
@@ -153,7 +165,6 @@ describe('executeUpdate', () => {
expect(result.success).toBe(false);
expect(result.failedStep).toBe('starting');
expect(spawnDetached).not.toHaveBeenCalled();
- expect(spawn).not.toHaveBeenCalled();
expect(recordUpdateResult).toHaveBeenCalledWith(
expect.objectContaining({ success: false, log: expect.stringContaining('still running') })
);
@@ -179,21 +190,66 @@ describe('executeUpdate', () => {
expect(emits.some(e => e[0] === 'git-pull' && e[1] === 'done')).toBe(true);
});
- it('records update result on success with tag fallback when marker missing', async () => {
+ // Marker missing usually means the restarted server already consumed it, so
+ // the version that stands is the one on disk — the triggering tag is only
+ // what the update AIMED at, and stamping it produced a "Success" line naming
+ // a release the install was never running (#6169).
+ it('records the on-disk version, not the triggering tag, when the marker is missing', async () => {
const child = createMockChild();
spawnDetached.mockResolvedValue(child);
+ getCurrentVersion.mockResolvedValue('2.0.0');
- const { promise } = await startUpdate('v1.0.0', () => {});
+ const { promise } = await startUpdate('v9.9.9', () => {});
+ emitStep(child);
child.emit('close', 0);
const result = await promise;
expect(result.success).toBe(true);
- expect(result.version).toBe('1.0.0');
+ expect(result.version).toBe('2.0.0');
expect(recordUpdateResult).toHaveBeenCalledWith(
- expect.objectContaining({ version: '1.0.0', success: true })
+ expect.objectContaining({ version: '2.0.0', success: true })
);
});
+ // The failure this whole change exists for: a launch that never executed the
+ // script exits 0 with no output whatsoever. Both update scripts emit
+ // `git-pull:running` before touching anything, so silence means no update ran
+ // — recording it as a success left the UI offering the same release forever.
+ it('records a failure when the script exits 0 without reporting any progress', async () => {
+ const child = createMockChild();
+ spawnDetached.mockResolvedValue(child);
+
+ const emits = [];
+ const { promise } = await startUpdate('v2.0.0', (...args) => emits.push(args));
+ child.emit('close', 0);
+ const result = await promise;
+
+ expect(result.success).toBe(false);
+ expect(result.errorMessage).toMatch(/never ran/);
+ expect(recordUpdateResult).toHaveBeenCalledWith(
+ expect.objectContaining({ version: '2.0.0', success: false, log: expect.stringContaining('never ran') })
+ );
+ expect(emits.some(e => e[0] === 'complete')).toBe(false);
+ expect(emits.some(e => e[1] === 'error')).toBe(true);
+ });
+
+ // 'starting' is synthetic — it only means "we launched the script". The first
+ // real step proves that, so it must not keep spinning for the whole update.
+ it('closes out the synthetic starting step once the script reports progress', async () => {
+ const child = createMockChild();
+ spawnDetached.mockResolvedValue(child);
+
+ const emits = [];
+ const { promise } = await startUpdate('v1.0.0', (...args) => emits.push(args));
+ emitStep(child);
+ emitStep(child, 'STEP:git-pull:done:Latest changes pulled\n');
+ child.emit('close', 0);
+ await promise;
+
+ const startingStatuses = emits.filter(e => e[0] === 'starting').map(e => e[1]);
+ expect(startingStatuses).toEqual(['running', 'done']);
+ });
+
it('records failure on non-zero exit code', async () => {
const child = createMockChild();
spawnDetached.mockResolvedValue(child);
@@ -234,6 +290,7 @@ describe('executeUpdate', () => {
readFile.mockResolvedValue(JSON.stringify({ version: '2.0.0', completedAt: '2026-01-01T00:00:00Z' }));
const { promise } = await startUpdate('v1.0.0', () => {});
+ emitStep(child);
child.emit('close', 0);
const result = await promise;