Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: hold the update lock and report a failed health verify honestly (#5976)
[._.]/ Adam Eivy15f030cb24b6
diff --git a/docs/SELF_UPDATE.md b/docs/SELF_UPDATE.mdindex dd480f93d2..88556a6e21 100644--- a/docs/SELF_UPDATE.md+++ b/docs/SELF_UPDATE.md@@ -69,7 +69,9 @@ To prevent that confusion, `POST /api/update/execute` rejects fork runs with **4**PortOS is also a managed app**, so an update started from **App Management** reaches `update.sh` through `appUpdater.js` rather than `routes/update.js`. That path delegates to `executeUpdate()` for the PortOS record instead of spawning the script itself — a second detached-spawn implementation would be one more thing to keep in sync, and the attached one it replaced produced exactly the headless failure above (#5976). `appUpdater` also **skips its own `restart` step** for that case: the script runs `pm2 start ecosystem.config.cjs` itself, so restarting on top of it would be redundant and would race the script.-A PortOS record carrying a custom `updateCommand` keeps the ordinary attached path — delegating there would silently run `update.sh` instead of the configured command. Non-PortOS managed apps are unaffected.+Both entry points take the same atomic `setUpdateInProgress(true)` lock before launching, so they cannot run `update.sh` concurrently — and because that flag is what `subAgentSpawner`, `agentLifecycle` and `persistentMindSupervisor` gate on, holding it also stops a CoS agent from being spawned into a process the script is about to `pm2 delete` (#4124).++A PortOS record carrying a custom `updateCommand`, or a `repoPath` that is not this checkout, keeps the ordinary attached path — delegating there would silently run `update.sh` instead of the configured command. That decision is logged rather than silent, since the attached path is the one that failed. The `repoPath` comparison resolves symlinks and case-folds on macOS/Windows: `repoPath` is user-editable and not force-synced, so a trailing slash or a different spelling must not be mistaken for a different checkout. Non-PortOS managed apps are unaffected, and still get their own PM2 restart and dashboard handoff from `appUpdater`.## Post-update health verification@@ -77,6 +79,8 @@ A PortOS record carrying a custom `updateCommand` keeps the ordinary attached paThe probe tries the loopback HTTP mirror (`:5553`) first, then the API port over HTTP and HTTPS, because the listening scheme depends on whether a cert is provisioned; `/api/system/health` is in the always-public set, so it works with the optional instance password on. The recovery only fires when the probe fails, so it cannot make a healthy update worse.+**When the probe still fails after the recovery, the scripts say so and exit non-zero** — the closing banner reads "Update applied, but PortOS is DOWN" instead of "Update Complete". The script outlives the server it restarts, so its exit status and the tail of `data/update.log` are the only signals a wrapper, a CI job, or an operator still has; printing a success banner over a confirmed-headless install is how the failure went unnoticed for hours in the first place.+## Syncing a fork`POST /api/update/sync-fork` shells out to:diff --git a/scripts/verify-server-health.js b/scripts/verify-server-health.jsindex d93d51284e..f9c2b79c84 100644--- a/scripts/verify-server-health.js+++ b/scripts/verify-server-health.js@@ -38,6 +38,22 @@ const DEFAULT_TIMEOUT_MS = 120_000;const DEFAULT_INTERVAL_MS = 2_000;const PROBE_TIMEOUT_MS = 5_000;+/**+ * Read a non-negative millisecond budget from the environment. `|| DEFAULT`+ * would be wrong here: it collapses "unset" and "not a number" together with a+ * deliberate `0` (fail fast, one pass and out), which `waitForHealthy`+ * explicitly supports.+ *+ * @param {string|undefined} raw+ * @param {number} fallback+ * @returns {number}+ */+export function parseTimeoutMs(raw, fallback = DEFAULT_TIMEOUT_MS) {+ if (raw === undefined || raw === null || String(raw).trim() === '') return fallback;+ const parsed = Number(raw);+ return Number.isFinite(parsed) && parsed >= 0 ? parsed : fallback;+}+/*** The loopback URLs a healthy PortOS could be answering on, in the order worth* trying: the plain-HTTP mirror first (always cert-free), then the API port@@ -136,7 +152,7 @@ export async function waitForHealthy({async function runCli() {const apiPort = Number(process.env.PORT) || PORTS.API;const mirrorPort = Number(process.env.PORTOS_HTTP_PORT) || PORTS.API_LOCAL;- const timeoutMs = Number(process.env.PORTOS_HEALTH_WAIT_MS) || DEFAULT_TIMEOUT_MS;+ const timeoutMs = parseTimeoutMs(process.env.PORTOS_HEALTH_WAIT_MS);const urls = healthProbeUrls({ apiPort, mirrorPort });const result = await waitForHealthy({ urls, timeoutMs });diff --git a/scripts/verify-server-health.test.js b/scripts/verify-server-health.test.jsindex bc8354136d..d9699f61a9 100644--- a/scripts/verify-server-health.test.js+++ b/scripts/verify-server-health.test.js@@ -1,6 +1,6 @@import { describe, expect, it, vi } from 'vitest';import { createServer } from 'node:http';-import { healthProbeUrls, probeHealth, waitForHealthy } from './verify-server-health.js';+import { healthProbeUrls, parseTimeoutMs, probeHealth, waitForHealthy } from './verify-server-health.js';/** Start a loopback server that answers one canned response, and return its URL. */async function withServer(handler, run) {@@ -97,10 +97,22 @@ describe('post-update server health verification', () => {expect(result.healthy).toBe(false);expect(result.url).toBe(null);- // The deadline is only checked after a full pass, so passes run at t=0,- // 2000 and 4000, plus the one at t=6000 that finds the budget spent — and- // every candidate URL is asked on every pass.- expect(probe).toHaveBeenCalledTimes(8);+ // The contract is "kept asking for the whole budget, then stopped", not a+ // particular pass schedule: every candidate is asked on every pass, at+ // least one full pass happened, and it only gave up past the deadline.+ expect(probe.mock.calls.length % 2).toBe(0);+ expect(probe.mock.calls.length).toBeGreaterThanOrEqual(2);+ expect(clock).toBeGreaterThanOrEqual(5_000);+ });++ it('reads a deliberate zero budget from the environment instead of falling back', () => {+ // `|| DEFAULT` would turn a fail-fast 0 — and a typo — into a silent 120s.+ expect(parseTimeoutMs('0')).toBe(0);+ expect(parseTimeoutMs('30000')).toBe(30_000);+ expect(parseTimeoutMs(undefined)).toBe(120_000);+ expect(parseTimeoutMs('')).toBe(120_000);+ expect(parseTimeoutMs('12O')).toBe(120_000);+ expect(parseTimeoutMs('-1')).toBe(120_000);});it('still makes one full pass when the budget is already exhausted', async () => {diff --git a/server/services/appUpdater.js b/server/services/appUpdater.jsindex 82a010fad8..812e4c063a 100644--- a/server/services/appUpdater.js+++ b/server/services/appUpdater.js@@ -1,13 +1,16 @@-import { existsSync } from 'fs';-import { join } from 'path';+import { existsSync, realpathSync } from 'fs';+import { join, resolve } from 'path';import { readFile } from 'fs/promises';+import { tmpdir } from 'os';import * as gitService from './git.js';import * as pm2Service from './pm2.js';import { bufferedSpawnOrThrow } from '../lib/bufferedSpawn.js';import { parseCommandArgs, validateCommand } from '../lib/commandSecurity.js';+import { isDetachedRunning, spawnDetached } from '../lib/detachedSpawn.js';import { PATHS } from '../lib/fileUtils.js';import { PORTOS_APP_ID } from '../lib/appIdentity.js';import { executeUpdate } from './updateExecutor.js';+import { setUpdateInProgress } from './updateChecker.js';import { syncManagedAppFork } from './managedAppRepositories.js';const CMD_TIMEOUT_MS = 5 * 60 * 1000;@@ -23,6 +26,80 @@ function runCommand(cmd, args, cwd) {// Per-app lock to prevent concurrent updatesconst updatingApps = new Set();+const DASHBOARD_OPEN_SCRIPT = 'scripts/open-ui-in-browser.js';+const DASHBOARD_OPEN_CONTROL_DIR = join(tmpdir(), 'portos-dashboard-open');++/**+ * Start the post-update dashboard handoff before any PortOS process is+ * restarted. The handoff is deliberately detached through the shared+ * double-fork helper: PM2's tree-kill would otherwise take the helper down+ * with portos-server before it can wait for the browser to return.+ *+ * Only the paths that restart PortOS from HERE need it. The delegated+ * self-update does not: update.sh runs `open-ui-in-browser.js` itself once the+ * ecosystem is back up.+ *+ * @param {object} app+ * @returns {Promise<void>}+ */+async function startDashboardHandoff(app) {+ if (app.id !== PORTOS_APP_ID) return;++ const scriptPath = join(app.repoPath, DASHBOARD_OPEN_SCRIPT);+ const alreadyRunning = await isDetachedRunning(DASHBOARD_OPEN_CONTROL_DIR, {+ executable: process.execPath,+ args: [scriptPath],+ }).catch((err) => {+ // Do not let an unreadable control dir be mistaken for an idle one: the+ // detached helper clears stale sentinels before launching and could then+ // race a handoff that is still alive after the previous PM2 restart.+ console.error(`⚠️ Dashboard auto-open status check failed: ${err.message}`);+ return true;+ });+ if (alreadyRunning) return;++ const handoff = await spawnDetached(+ process.execPath,+ [scriptPath],+ { cwd: app.repoPath, controlDir: DASHBOARD_OPEN_CONTROL_DIR, cleanup: true },+ ).catch((err) => {+ console.error(`⚠️ Dashboard auto-open could not start: ${err.message}`);+ return null;+ });+ handoff?.on('error', (err) => {+ console.error(`⚠️ Dashboard auto-open failed: ${err.message}`);+ });+}++/**+ * Whether two filesystem paths name the same directory. A trailing slash, a+ * symlinked checkout, or a different case on APFS/NTFS all spell one path more+ * than one way — and the caller below turns "these differ" into "take the+ * ATTACHED spawn", which is exactly the headless failure of #5976. Resolve+ * symlinks where possible, and case-fold on the platforms whose filesystems+ * are case-insensitive by default (mirrors `scripts/lib/directInvocation.js`).+ *+ * @param {string} a+ * @param {string} b+ * @returns {boolean}+ */+function isSamePath(a, b) {+ if (!a || !b) return false;+ const caseFold = process.platform === 'win32' || process.platform === 'darwin';+ const normalize = (path) => {+ // realpath throws when the path does not exist yet; resolve() alone still+ // collapses a trailing slash and any '..' segment.+ const absolute = (() => {+ try {+ return realpathSync(resolve(path));+ } catch {+ return resolve(path);+ }+ })();+ return caseFold ? absolute.toLowerCase() : absolute;+ };+ return normalize(a) === normalize(b);+}/*** Run a full update cycle for an app:@@ -108,7 +185,12 @@ async function _doUpdate(app, emit, { syncFork }) {// PortOS record carrying a custom `updateCommand`, or pointing somewhere// other than this checkout, keeps the ordinary attached path rather than// silently running a different script than the one configured.- const detachSelfUpdate = app.id === PORTOS_APP_ID && usesStandardScript && dir === PATHS.root;+ const detachSelfUpdate = app.id === PORTOS_APP_ID && usesStandardScript && isSamePath(dir, PATHS.root);+ if (app.id === PORTOS_APP_ID && !detachSelfUpdate) {+ // Never silent: this is the branch that runs update.sh attached, and an+ // attached run is what left the install headless in #5976.+ console.log(`⚠️ PortOS update is using the attached path — ${usesStandardScript ? 'repoPath is not this checkout' : 'a custom update command is configured'}`);+ }if (configuredUpdate || pkg?.scripts?.['portos:update'] || usesStandardScript) {// A configured runtime may be an absolute Bun path, which is trusted app// configuration but not a commandSecurity allowlist token. Only free-form@@ -138,8 +220,20 @@ async function _doUpdate(app, emit, { syncFork }) {// delegate rather than keeping a second detached-spawn implementation// in sync here. The version is only a logging/fallback label; the true// post-update version comes from the script's completion marker.+ // Acquiring the update flag is what holds CoS agent spawns off a process+ // update.sh is about to `pm2 delete` (#4124) — `subAgentSpawner`,+ // `agentLifecycle` and `persistentMindSupervisor` all gate on it. It is+ // also the atomic lock `POST /api/update/execute` takes, so the two entry+ // points into update.sh cannot launch it concurrently.+ const acquired = await setUpdateInProgress(true);+ if (!acquired) throw new Error('A PortOS update is already in progress');const version = typeof pkg?.version === 'string' ? pkg.version : 'unknown';- const outcome = await executeUpdate(version, emit);+ // Every outcome executeUpdate REPORTS clears the flag again through+ // recordUpdateResult; a rejection from the launcher itself reports none.+ const outcome = await executeUpdate(version, emit).catch(async (err) => {+ await setUpdateInProgress(false);+ throw err;+ });if (!outcome.success) {throw new Error(outcome.errorMessage || `PortOS update failed at step "${outcome.failedStep || 'unknown'}"`);}@@ -157,6 +251,7 @@ async function _doUpdate(app, emit, { syncFork }) {const processNames = detachSelfUpdate ? [] : (app.pm2ProcessNames || []);if (processNames.length > 0) {emit('restart', 'running', 'Restarting app...');+ await startDashboardHandoff(app);const restartResults = await Promise.all(processNames.map(name =>pm2Service.restartApp(name, app.pm2Home).then(() => null, e => e)diff --git a/server/services/appUpdater.test.js b/server/services/appUpdater.test.jsindex 6e2d618bc3..2e212293a5 100644--- a/server/services/appUpdater.test.js+++ b/server/services/appUpdater.test.js@@ -11,6 +11,10 @@ const mock = vi.hoisted(() => ({updateDefaultBranch: vi.fn(),spawn: vi.fn(),executeUpdate: vi.fn(),+ setUpdateInProgress: vi.fn(),+ dashboardOpen: vi.fn(),+ dashboardRunning: vi.fn(),+ dashboardHandle: { on: vi.fn() },restart: vi.fn(),syncFork: vi.fn(),}));@@ -26,6 +30,11 @@ vi.mock('../lib/bufferedSpawn.js', async (importOriginal) => {return { ...actual, bufferedSpawnOrThrow: mock.spawn };});vi.mock('./updateExecutor.js', () => ({ executeUpdate: mock.executeUpdate }));+vi.mock('./updateChecker.js', () => ({ setUpdateInProgress: mock.setUpdateInProgress }));+vi.mock('../lib/detachedSpawn.js', () => ({+ isDetachedRunning: mock.dashboardRunning,+ spawnDetached: mock.dashboardOpen,+}));vi.mock('./managedAppRepositories.js', () => ({ syncManagedAppFork: mock.syncFork }));import { updateApp } from './appUpdater.js';@@ -43,6 +52,9 @@ describe('managed app updates', () => {mock.updateDefaultBranch.mockResolvedValue({ branch: 'main', output: 'Already up to date' });mock.spawn.mockResolvedValue({ stdout: '', stderr: '' });mock.executeUpdate.mockResolvedValue({ success: true, version: '9.9.9' });+ mock.setUpdateInProgress.mockResolvedValue(true);+ mock.dashboardRunning.mockResolvedValue(false);+ mock.dashboardOpen.mockResolvedValue(mock.dashboardHandle);mock.restart.mockResolvedValue({ success: true });mock.syncFork.mockResolvedValue({alreadyUpToDate: false,@@ -52,6 +64,10 @@ describe('managed app updates', () => {});afterEach(async () => {+ await Promise.all(mock.dashboardOpen.mock.calls+ .map(([, , options]) => options?.controlDir)+ .filter(Boolean)+ .map((controlDir) => rm(controlDir, { recursive: true, force: true })));await rm(repo, { recursive: true, force: true });});@@ -114,6 +130,11 @@ describe('managed app updates', () => {expect(result.success).toBe(true);expect(mock.executeUpdate).toHaveBeenCalledWith('2.56.0', emit);expect(mock.spawn).not.toHaveBeenCalled();+ // The flag CoS spawn gates read (#4124) has to be up before the script that+ // deletes portos-cos starts, not after.+ expect(mock.setUpdateInProgress).toHaveBeenCalledWith(true);+ expect(mock.setUpdateInProgress.mock.invocationCallOrder[0])+ .toBeLessThan(mock.executeUpdate.mock.invocationCallOrder[0]);expect(emit).toHaveBeenCalledWith('app-update', 'done', 'App update routine complete');});@@ -133,6 +154,8 @@ describe('managed app updates', () => {expect(mock.restart).not.toHaveBeenCalled();expect(result.steps.some((step) => step.step === 'restart')).toBe(false);expect(emit).not.toHaveBeenCalledWith('restart', expect.anything(), expect.anything());+ // update.sh runs open-ui-in-browser.js itself once the ecosystem is back.+ expect(mock.dashboardOpen).not.toHaveBeenCalled();});it('surfaces a failed PortOS update instead of reporting success', async () => {@@ -149,6 +172,43 @@ describe('managed app updates', () => {}, vi.fn())).rejects.toThrow('Update failed at step "npm-install" (exit code 1)');});+ it('refuses to launch a second update while one already holds the flag', async () => {+ // The same atomic lock POST /api/update/execute takes — the two entry points+ // into update.sh must not launch it concurrently.+ await writeFile(join(repo, 'update.sh'), '#!/bin/sh\nexit 0\n');+ await writeFile(join(repo, 'update.ps1'), 'exit 0\n');+ mock.setUpdateInProgress.mockResolvedValue(false);++ await expect(updateApp({+ id: 'portos-default',+ name: 'PortOS',+ type: 'express',+ repoPath: repo,+ pm2ProcessNames: ['portos-server'],+ }, vi.fn())).rejects.toThrow(/already in progress/i);++ expect(mock.executeUpdate).not.toHaveBeenCalled();+ });++ it('still delegates when the record spells this checkout differently', async () => {+ // repoPath is user-editable and not force-synced, so a trailing slash or a+ // '..' segment is a realistic spelling — and treating it as "not this+ // checkout" would silently re-arm the attached spawn of #5976.+ await writeFile(join(repo, 'update.sh'), '#!/bin/sh\nexit 0\n');+ await writeFile(join(repo, 'update.ps1'), 'exit 0\n');++ await updateApp({+ id: 'portos-default',+ name: 'PortOS',+ type: 'express',+ repoPath: `${repo}/client/..`,+ pm2ProcessNames: ['portos-server'],+ }, vi.fn());++ expect(mock.executeUpdate).toHaveBeenCalled();+ expect(mock.spawn).not.toHaveBeenCalled();+ });+it('does not delegate when the PortOS record points outside this checkout', async () => {// executeUpdate resolves update.sh from PATHS.root, not from the record —// delegating a record aimed elsewhere would run a different script than the@@ -207,6 +267,10 @@ describe('managed app updates', () => {expect(mock.executeUpdate).not.toHaveBeenCalled();expect(mock.spawn).toHaveBeenCalledWith('npm', ['run', 'update'], expect.objectContaining({ cwd: repo }));expect(mock.restart).toHaveBeenCalledWith('portos-server', undefined);+ // This path still restarts PortOS itself, so it still owns the dashboard+ // handoff — only the delegated one hands that to update.sh.+ expect(mock.dashboardOpen).toHaveBeenCalled();+ expect(mock.dashboardOpen.mock.invocationCallOrder[0]).toBeLessThan(mock.restart.mock.invocationCallOrder[0]);});it('runs an explicit update command before restarting', async () => {diff --git a/update.ps1 b/update.ps1index e452994855..8168aa4a6b 100644--- a/update.ps1+++ b/update.ps1@@ -400,6 +400,7 @@ Write-SafeHost ""# this script is the only PortOS process still running to notice. Poll# /api/system/health, and on failure spend one more `pm2 start` before saying# so loudly. Mirrors update.sh.+$verifyFailed = 0Step "verify" "running" "Verifying PortOS came back..."Invoke-Logged node scripts/verify-server-health.jsif ($LASTEXITCODE -eq 0) {@@ -413,6 +414,7 @@ if ($LASTEXITCODE -eq 0) {Step "verify" "done" "PortOS recovered after a second pm2 start"Write-SafeHost "PortOS recovered after a second pm2 start" -ForegroundColor Green} else {+ $verifyFailed = 1Step "verify" "warning" "PortOS is not answering /api/system/health"Write-SafeHost "PortOS is STILL not answering /api/system/health." -ForegroundColor RedWrite-SafeHost " Recover with: node ./node_modules/pm2/bin/pm2 start ecosystem.config.cjs" -ForegroundColor Red@@ -428,9 +430,18 @@ Write-SafeHost ""Invoke-Logged node scripts/open-ui-in-browser.js$global:LASTEXITCODE = 0-Write-SafeHost "===================================" -ForegroundColor Green-Write-SafeHost " ✅ Update Complete!" -ForegroundColor Green-Write-SafeHost "===================================" -ForegroundColor Green+if ($verifyFailed -eq 0) {+ Write-SafeHost "===================================" -ForegroundColor Green+ Write-SafeHost " ✅ Update Complete!" -ForegroundColor Green+ Write-SafeHost "===================================" -ForegroundColor Green+} else {+ # The source update finished, but the install is down. Say so where the+ # banner would have been — a wrapper reading only the tail of the log, or+ # this script's exit status, must not read a headless install as a clean run.+ Write-SafeHost "===================================" -ForegroundColor Red+ Write-SafeHost " ⚠️ Update applied, but PortOS is DOWN" -ForegroundColor Red+ Write-SafeHost "===================================" -ForegroundColor Red+}Write-SafeHost ""# Tell the user where to open PortOS — leads with the working local URL@@ -464,3 +475,7 @@ if ($stashedForBranch) {}Write-SafeHost " The stash entry is at the top of 'git stash list'." -ForegroundColor Cyan}++# Exit non-zero when the install did not come back. This script outlives the+# server it restarts, so its status is the only signal a caller still has.+exit $verifyFaileddiff --git a/update.sh b/update.shindex 8ee2461545..9b14b08043 100755--- a/update.sh+++ b/update.sh@@ -364,6 +364,7 @@ log ""# /api/system/health, and on failure spend one more `pm2 start` before saying# so loudly. A recovery that only fires when the probe fails cannot make a# healthy update worse.+verify_failed=0step "verify" "running" "Verifying PortOS came back..."if run node scripts/verify-server-health.js; thenstep "verify" "done" "PortOS is answering /api/system/health"@@ -374,6 +375,7 @@ elsestep "verify" "done" "PortOS recovered after a second pm2 start"log "✅ PortOS recovered after a second pm2 start"else+ verify_failed=1step "verify" "warning" "PortOS is not answering /api/system/health"log "❌ PortOS is STILL not answering /api/system/health."log " Recover with: node ./node_modules/pm2/bin/pm2 start ecosystem.config.cjs"@@ -385,9 +387,18 @@ log ""# the update return.run node scripts/open-ui-in-browser.js || true-log "==================================="-log " ✅ Update Complete!"-log "==================================="+if [ "$verify_failed" -eq 0 ]; then+ log "==================================="+ log " ✅ Update Complete!"+ log "==================================="+else+ # The source update finished, but the install is down. Say so where the+ # banner would have been — a wrapper reading only the tail of the log, or+ # this script's exit status, must not read a headless install as a clean run.+ log "==================================="+ log " ⚠️ Update applied, but PortOS is DOWN"+ log "==================================="+filog ""# Tell the user where to open PortOS — leads with the working local URL@@ -416,3 +427,7 @@ if [ -n "$stashed_for_branch" ]; thenfilog " The stash entry is at the top of 'git stash list'."fi++# Exit non-zero when the install did not come back. This script outlives the+# server it restarts, so its status is the only signal a caller still has.+exit "$verify_failed"