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

Show and update the Node.js runtime from the Update tab

Claude0dae9e95d7ba
diff --git a/client/src/components/apps/tabs/NodeRuntimePanel.jsx b/client/src/components/apps/tabs/NodeRuntimePanel.jsx
new file mode 100644
index 0000000000..e381882506
--- /dev/null
+++ b/client/src/components/apps/tabs/NodeRuntimePanel.jsx
@@ -0,0 +1,203 @@
+import { useEffect, useState } from 'react';
+import { AlertTriangle, Check, Copy, Cpu, Loader2, ShieldAlert } from 'lucide-react';
+import * as api from '../../../services/api';
+import { useSocketResource } from '../../../hooks/useSocketResource';
+import { copyToClipboard } from '../../../lib/clipboard';
+import { formatDateNumeric } from '../../../utils/formatters';
+
+const STATUS_EVENTS = ['portos:node-runtime:changed'];
+
+const SOURCE_LABELS = { nvm: 'nvm', homebrew: 'Homebrew', other: 'system' };
+
+/**
+ * The Node.js runtime PortOS runs on, with in-place updates of Node (via nvm)
+ * and pm2. Both actions restart PortOS through the ordinary update lifecycle,
+ * so they launch through the Update tab's `onLaunch` — that is what arms the
+ * restart watch and renders the step list below the buttons.
+ */
+export default function NodeRuntimePanel({ onLaunch, busy = false }) {
+ const { data: status, loading, refetch } = useSocketResource(
+ () => api.getNodeRuntimeStatus({ silent: true }), { events: STATUS_EVENTS }
+ );
+ const offers = status?.releases?.offers || [];
+ const [selected, setSelected] = useState(null);
+ const [pending, setPending] = useState(null);
+
+ useEffect(() => {
+ if (!offers.length) setSelected(null);
+ else if (!offers.some((offer) => offer.version === selected)) setSelected(offers[0].version);
+ }, [offers, selected]);
+
+ if (loading && !status) {
+ return (
+ <div className="p-4 rounded-lg border border-port-border bg-port-card text-sm text-gray-400 flex items-center gap-2">
+ <Loader2 size={14} className="animate-spin" /> Reading Node.js runtime…
+ </div>
+ );
+ }
+ if (!status) return null;
+
+ const { node, nvm, releases, pm2, startup } = status;
+ const jobRunning = Boolean(status.job);
+ const disabled = busy || jobRunning || pending !== null;
+ const pm2Behind = pm2.daemonStale || pm2.cliBehind;
+
+ const launch = async (kind, call) => {
+ setPending(kind);
+ await onLaunch(call);
+ setPending(null);
+ };
+
+ // No restart, so it does not go through the Update tab's launch.
+ const fixStartup = async () => {
+ setPending('startup');
+ const result = await api.repairNodeStartup().catch(() => null);
+ setPending(null);
+ if (result?.fixed) refetch();
+ };
+
+ return (
+ <div className="p-4 rounded-lg border border-port-border bg-port-card space-y-4">
+ <div>
+ <div className="text-sm text-white font-medium flex items-center gap-2">
+ <Cpu size={15} className="text-port-accent" /> Node.js runtime
+ </div>
+ <div className="mt-2 flex flex-wrap items-center gap-2">
+ <span className="text-lg font-mono text-white">{node.version}</span>
+ <span className="px-2 py-0.5 rounded-full bg-port-border text-xs text-gray-300">{SOURCE_LABELS[node.source] || node.source}</span>
+ {releases?.securityUpdate && (
+ <span className="px-2 py-0.5 rounded-full bg-port-error/20 text-port-error text-xs flex items-center gap-1">
+ <ShieldAlert size={12} /> Security update
+ </span>
+ )}
+ </div>
+ <div className="mt-1 text-xs text-gray-500 font-mono break-all">{node.execPath}</div>
+ {!node.inSupportedRange && (
+ <div className="mt-2 text-xs text-port-warning flex items-start gap-1">
+ <AlertTriangle size={12} className="mt-0.5 shrink-0" /> Outside PortOS’s supported range ({node.supportedRange}).
+ </div>
+ )}
+ </div>
+
+ {status.releasesError && <div role="status" className="text-xs text-gray-400">{status.releasesError}</div>}
+
+ {releases && offers.length === 0 && (
+ <div className="text-sm text-port-success flex items-center gap-2">
+ <Check size={14} /> Latest stable Node for this line
+ </div>
+ )}
+
+ {offers.length > 0 && (
+ <fieldset className="space-y-2">
+ <legend className="text-xs text-gray-500 uppercase tracking-wide mb-2">Update to</legend>
+ {offers.map((offer) => (
+ <label
+ key={offer.version}
+ htmlFor={`node-offer-${offer.version}`}
+ className={`flex items-center gap-3 p-3 rounded-lg border cursor-pointer ${selected === offer.version ? 'border-port-accent bg-port-accent/10' : 'border-port-border'}`}
+ >
+ <input
+ id={`node-offer-${offer.version}`}
+ type="radio"
+ name="node-offer"
+ className="accent-port-accent"
+ checked={selected === offer.version}
+ onChange={() => setSelected(offer.version)}
+ disabled={disabled}
+ />
+ <span className="font-mono text-white">{offer.version}</span>
+ <span className="text-xs text-gray-400 flex-1">
+ {offer.label}{offer.lts ? ` · ${offer.lts}` : ''}
+ </span>
+ {offer.date && <span className="text-xs text-gray-500">{formatDateNumeric(offer.date)}</span>}
+ </label>
+ ))}
+ {status.canUpdate ? (
+ <button
+ type="button"
+ onClick={() => launch('node', () => api.updateNodeRuntime(selected))}
+ disabled={disabled || !selected}
+ className="w-full sm:w-auto px-4 py-2 bg-port-accent text-white rounded-lg text-sm flex items-center justify-center gap-2 hover:bg-port-accent/80 disabled:opacity-50"
+ >
+ {pending === 'node' || status.job?.kind === 'node-update' ? <Loader2 size={14} className="animate-spin" /> : null}
+ Update Node to {selected} and restart
+ </button>
+ ) : (
+ <div className="text-xs text-port-warning">{status.blockedReason}</div>
+ )}
+ <div className="text-xs text-gray-500">Waits for renders, agents and jobs to finish. Also pulls the latest PortOS.</div>
+ </fieldset>
+ )}
+
+ {nvm && (
+ <div className="text-xs text-gray-400">
+ nvm default <span className="font-mono text-gray-300">{nvm.defaultVersion || '—'}</span> · {nvm.installed.length} installed
+ {node.pinned ? null : <> · PortOS uses the first <span className="font-mono">node</span> on pm2’s PATH</>}
+ </div>
+ )}
+
+ <div className="pt-3 border-t border-port-border">
+ <div className="text-xs text-gray-500 uppercase tracking-wide mb-2">pm2</div>
+ <dl className="grid grid-cols-[auto,1fr] gap-x-3 gap-y-1 text-sm">
+ <dt className="text-gray-400">PortOS</dt>
+ <dd className="font-mono text-white">
+ {pm2.shipped || '—'}
+ {pm2.latest && pm2.shipped && pm2.latest !== pm2.shipped && (
+ <span className="ml-2 text-xs text-gray-500 font-sans">npm has {pm2.latest}</span>
+ )}
+ </dd>
+ <dt className="text-gray-400">Daemon</dt>
+ <dd className={`font-mono ${pm2.daemonStale ? 'text-port-warning' : 'text-white'}`}>
+ {pm2.daemon ? `${pm2.daemon.pm2Version || '?'} on Node ${pm2.daemon.nodeVersion || '?'}` : 'unreachable'}
+ </dd>
+ <dt className="text-gray-400">Terminal</dt>
+ <dd className={`font-mono ${pm2.cliBehind ? 'text-port-warning' : 'text-white'}`}>{pm2.cli || 'not installed'}</dd>
+ </dl>
+ {pm2Behind && (
+ <button
+ type="button"
+ onClick={() => launch('pm2', () => api.updatePm2Runtime())}
+ disabled={disabled}
+ className="mt-3 w-full sm:w-auto px-4 py-2 bg-port-border text-white rounded-lg text-sm flex items-center justify-center gap-2 hover:bg-port-border/80 disabled:opacity-50"
+ >
+ {pending === 'pm2' || status.job?.kind === 'pm2-update' ? <Loader2 size={14} className="animate-spin" /> : null}
+ Update pm2 to {pm2.shipped}{pm2.daemonStale ? ' and restart' : ''}
+ </button>
+ )}
+ </div>
+
+ {startup && startup.current !== true && (
+ <div className="pt-3 border-t border-port-border">
+ <div className="text-sm text-port-warning flex items-start gap-2">
+ <AlertTriangle size={14} className="mt-0.5 shrink-0" />
+ {startup.configured ? 'Start-on-boot still uses another Node.' : 'PortOS doesn’t start on boot.'}
+ </div>
+ {startup.fixable ? (
+ <button
+ type="button"
+ onClick={fixStartup}
+ disabled={pending !== null}
+ className="mt-2 w-full sm:w-auto px-4 py-2 bg-port-border text-white rounded-lg text-sm flex items-center justify-center gap-2 hover:bg-port-border/80 disabled:opacity-50"
+ >
+ {pending === 'startup' ? <Loader2 size={14} className="animate-spin" /> : null}
+ Use {node.pinned ? 'PortOS’s Node' : 'this Node'} at boot
+ </button>
+ ) : (<>
+ <div className="text-xs text-gray-400 mt-1">Needs your password, so run it once in Terminal:</div>
+ <div className="mt-2 flex items-start gap-2">
+ <code className="flex-1 p-2 rounded bg-port-bg border border-port-border text-xs text-gray-300 font-mono break-all">{startup.command}</code>
+ <button
+ type="button"
+ onClick={() => copyToClipboard(startup.command, 'Command copied')}
+ className="p-2 rounded-lg bg-port-border text-gray-300 hover:text-white shrink-0"
+ aria-label="Copy start-on-boot command"
+ >
+ <Copy size={14} />
+ </button>
+ </div>
+ </>)}
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/client/src/components/apps/tabs/NodeRuntimePanel.test.jsx b/client/src/components/apps/tabs/NodeRuntimePanel.test.jsx
new file mode 100644
index 0000000000..4c820ac646
--- /dev/null
+++ b/client/src/components/apps/tabs/NodeRuntimePanel.test.jsx
@@ -0,0 +1,89 @@
+import { cleanup, render, screen } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import NodeRuntimePanel from './NodeRuntimePanel';
+
+const api = vi.hoisted(() => ({
+ getNodeRuntimeStatus: vi.fn(),
+ updateNodeRuntime: vi.fn(),
+ updatePm2Runtime: vi.fn(),
+ repairNodeStartup: vi.fn(),
+}));
+vi.mock('../../../services/api', () => api);
+const clipboard = vi.hoisted(() => ({ copyToClipboard: vi.fn() }));
+vi.mock('../../../lib/clipboard', () => clipboard);
+vi.mock('../../../services/socket', () => ({ default: { on: vi.fn(), off: vi.fn() } }));
+afterEach(cleanup);
+
+const status = (overrides = {}) => ({
+ node: { version: 'v26.0.0', execPath: '/opt/homebrew/bin/node', source: 'homebrew', pinned: null, supportedRange: '>=26.0.0', inSupportedRange: true },
+ nvm: { dir: '/home/example/.nvm', defaultVersion: 'v26.12.1', installed: ['v26.12.1'] },
+ releases: {
+ securityUpdate: true,
+ offers: [
+ { version: 'v26.12.1', label: 'Latest 26.x', lts: null, date: '2026-10-21' },
+ { version: 'v27.1.0', label: 'Latest release', lts: null, date: '2026-10-20' },
+ ],
+ },
+ releasesError: null,
+ pm2: { shipped: '7.0.4', latest: '7.0.4', daemon: { pm2Version: '7.0.4', nodeVersion: '26.0.0' }, cli: '7.0.4', cliBehind: false, daemonStale: false },
+ startup: null,
+ canUpdate: true,
+ blockedReason: null,
+ job: null,
+ ...overrides,
+});
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ api.updateNodeRuntime.mockResolvedValue({ started: true, restart: true });
+});
+
+describe('NodeRuntimePanel', () => {
+ it('launches the update for the picked release through the Update tab', async () => {
+ api.getNodeRuntimeStatus.mockResolvedValue(status());
+ const onLaunch = vi.fn((call) => call());
+ render(<NodeRuntimePanel onLaunch={onLaunch} />);
+
+ expect(await screen.findByText('Security update')).toBeInTheDocument();
+ await userEvent.click(screen.getByLabelText(/v27\.1\.0/));
+ await userEvent.click(screen.getByRole('button', { name: 'Update Node to v27.1.0 and restart' }));
+
+ expect(onLaunch).toHaveBeenCalledTimes(1);
+ expect(api.updateNodeRuntime).toHaveBeenCalledWith('v27.1.0');
+ });
+
+ it('shows why an install cannot update instead of a button', async () => {
+ api.getNodeRuntimeStatus.mockResolvedValue(status({ canUpdate: false, blockedReason: 'nvm is not installed.' }));
+ render(<NodeRuntimePanel onLaunch={vi.fn()} />);
+ expect(await screen.findByText('nvm is not installed.')).toBeInTheDocument();
+ expect(screen.queryByRole('button', { name: /Update Node/ })).toBeNull();
+ });
+
+ it('offers the pm2 refresh and the start-on-boot command only when they are behind', async () => {
+ api.getNodeRuntimeStatus.mockResolvedValue(status({
+ releases: { securityUpdate: false, offers: [] },
+ pm2: { shipped: '7.0.4', latest: '7.0.4', daemon: { pm2Version: '7.0.4', nodeVersion: '26.10.0' }, cli: '7.0.4', cliBehind: false, daemonStale: true },
+ startup: { system: 'systemd', configured: true, current: false, fixable: false, command: 'sudo env PATH=$PATH:/x/bin /x/bin/pm2 startup systemd -u example --hp /home/example' },
+ }));
+ render(<NodeRuntimePanel onLaunch={vi.fn()} />);
+
+ expect(await screen.findByRole('button', { name: 'Update pm2 to 7.0.4 and restart' })).toBeInTheDocument();
+ await userEvent.click(screen.getByRole('button', { name: 'Copy start-on-boot command' }));
+ expect(clipboard.copyToClipboard).toHaveBeenCalledWith(expect.stringContaining('pm2 startup systemd'), 'Command copied');
+ });
+
+ it('repoints a macOS boot script in place instead of asking for sudo', async () => {
+ api.getNodeRuntimeStatus.mockResolvedValue(status({
+ node: { ...status().node, pinned: '/home/example/.nvm/versions/node/v26.12.1/bin/node' },
+ releases: { securityUpdate: false, offers: [] },
+ startup: { system: 'launchd', configured: true, current: false, fixable: true, command: 'sudo …' },
+ }));
+ api.repairNodeStartup.mockResolvedValue({ fixed: true });
+ render(<NodeRuntimePanel onLaunch={vi.fn()} />);
+
+ await userEvent.click(await screen.findByRole('button', { name: 'Use PortOS’s Node at boot' }));
+ expect(api.repairNodeStartup).toHaveBeenCalledTimes(1);
+ expect(screen.queryByText(/Needs your password/)).toBeNull();
+ });
+});
diff --git a/client/src/components/apps/tabs/UpdateTab.jsx b/client/src/components/apps/tabs/UpdateTab.jsx
index 3a8d84fe5e..cdfc06163e 100644
--- a/client/src/components/apps/tabs/UpdateTab.jsx
+++ b/client/src/components/apps/tabs/UpdateTab.jsx
@@ -5,6 +5,7 @@ import BrailleSpinner from '../../BrailleSpinner';
import MarkdownOutput from '../../cos/MarkdownOutput';
import Banner from '../../ui/Banner';
import AutoUpdatePanel from './AutoUpdatePanel';
+import NodeRuntimePanel from './NodeRuntimePanel';
import * as api from '../../../services/api';
import socket from '../../../services/socket';
import { formatDateTime, formatDateNumeric, formatTimeOfDaySeconds } from '../../../utils/formatters';
@@ -15,6 +16,10 @@ const STATUS_EVENTS = ['portos:update:checked', 'portos:update:available', 'port
const STEP_LABELS = {
starting: 'Starting update',
+ 'node-install': 'Installing Node.js',
+ 'node-default': 'Setting nvm default',
+ 'pm2-cli': 'Installing pm2 CLI',
+ 'node-pin': 'Pinning PortOS to Node',
'git-pull': 'Pulling latest changes',
'pm2-stop': 'Stopping apps',
'npm-install': 'Installing dependencies',
@@ -93,7 +98,9 @@ export default function UpdateTab() {
// `fromStatus` lets callers (e.g. handleSyncForkAndUpdate) pass the freshly
// fetched status object instead of relying on the closure capture — `setStatus`
// only schedules a render; the action passes its fresh response directly.
- const runUpdate = useCallback(async (opts = {}, fromStatus = null) => {
+ // `launch` lets the Node runtime panel start its restart through the same
+ // baseline, step list and restart watch as a release update.
+ const runUpdate = useCallback(async (opts = {}, fromStatus = null, launch = api.executePortosUpdate) => {
const s = fromStatus || status;
// Record the version and uptime of the still-running server, so even an
// instant restart (whose first post-restart poll already reports a small
@@ -102,11 +109,14 @@ export default function UpdateTab() {
setUpdating(true);
setSteps([]);
setUpdateError(null);
- return api.executePortosUpdate(opts).catch(err => {
+ const result = await launch(opts).catch(err => {
setUpdateError(err.message);
setUpdating(false);
return null;
});
+ // A pm2 CLI refresh finishes without restarting PortOS.
+ if (result?.restart === false) setUpdating(false);
+ return result;
}, [captureBaseline, status]);
const handleUpdate = () => runUpdate();
@@ -459,6 +469,11 @@ export default function UpdateTab() {
</div>
)}
+ <NodeRuntimePanel
+ busy={updating || polling || syncingFork}
+ onLaunch={(call) => runUpdate({}, null, call)}
+ />
+
{/* Update Progress */}
{steps.length > 0 && (
<div>
diff --git a/client/src/components/apps/tabs/UpdateTab.test.jsx b/client/src/components/apps/tabs/UpdateTab.test.jsx
index ea8326bbde..4100e3af5f 100644
--- a/client/src/components/apps/tabs/UpdateTab.test.jsx
+++ b/client/src/components/apps/tabs/UpdateTab.test.jsx
@@ -30,6 +30,7 @@ vi.mock('../../../services/api', () => ({
}));
vi.mock('./AutoUpdatePanel', () => ({ default: () => null }));
+vi.mock('./NodeRuntimePanel', () => ({ default: () => null }));
const UpdateTab = (await import('./UpdateTab')).default;
diff --git a/client/src/services/apiSystem.js b/client/src/services/apiSystem.js
index 07fcea091b..c9339751b7 100644
--- a/client/src/services/apiSystem.js
+++ b/client/src/services/apiSystem.js
@@ -69,6 +69,15 @@ export const executePortosUpdate = (opts) => {
const body = opts && Object.keys(opts).length ? JSON.stringify(opts) : undefined;
return request('/update/execute', body ? { method: 'POST', body } : { method: 'POST' });
};
+// Node.js runtime: version, newer stable/security releases, nvm, pm2 and the
+// boot script; the two actions restart PortOS through the update lifecycle.
+export const getNodeRuntimeStatus = (options) => request('/update/node-runtime', options);
+export const updateNodeRuntime = (version) => request('/update/node-runtime', {
+ method: 'POST',
+ body: JSON.stringify({ version })
+});
+export const updatePm2Runtime = () => request('/update/pm2', { method: 'POST' });
+export const repairNodeStartup = () => request('/update/node-runtime/startup', { method: 'POST' });
export const syncPortosFork = (opts = {}, requestOpts = {}) => request('/update/sync-fork', {
method: 'POST',
body: JSON.stringify(opts),
diff --git a/docs/SELF_UPDATE.md b/docs/SELF_UPDATE.md
index 8a7254155c..29b2067763 100644
--- a/docs/SELF_UPDATE.md
+++ b/docs/SELF_UPDATE.md
@@ -203,6 +203,16 @@ first line, `useWorktree: false`) and waits. That agent then counts as activity,
update lands in the first idle window after it finishes. The escalation is switchable
(`resolveBlockersWithAgent`), since it costs a provider call.
+## Node.js runtime and pm2
+
+The Update tab's **Node.js runtime** panel (`client/src/components/apps/tabs/NodeRuntimePanel.jsx`, `GET /api/update/node-runtime`) reports the Node the server process is actually running (`process.version`, not `node -v`), newer releases from nodejs.org's index inside `SUPPORTED_NODE_RANGE` (the running line's latest patch, the newest LTS, the newest release, with a security flag), nvm, and pm2 three ways: the version PortOS ships, the daemon's own `getReport`, and the terminal's global CLI.
+
+Why the runtime has to be pinned: `interpreter: 'node'` resolves against the pm2 daemon's PATH, and `pm2 resurrect` reuses each app's saved PATH, so an install can keep running an older Homebrew node after nvm's default moved. `ecosystem.config.cjs` therefore launches every PortOS app on `PORTOS_NODE_INTERPRETER` (exported env, then `.env`), falling back to `node` when the value is not an absolute path to an existing node binary (`server/lib/nodeInterpreterPin.js`).
+
+`POST /api/update/node-runtime { version }` (offered versions only, host-control gated) refuses unless the system is idle, then: `nvm install`, `nvm alias default`, `npm install -g pm2@<shipped>` under the new Node, pins `PORTOS_NODE_INTERPRETER`, repoints a macOS pm2 LaunchAgent's nvm paths, and launches the detached update script in `refresh` mode. `launchUpdate` puts the pin first on the script's PATH and exports it, so npm install and the trusted native rebuilds target the new Node, `pm2-daemon-refresh.js` reloads a daemon still on another Node, and `pm2 delete` + `pm2 start` makes pm2 read the new interpreter. A refused launch restores the previous pin. The run also pulls `main`, like any refresh.
+
+`POST /api/update/pm2` aligns a global CLI or daemon that is older than the shipped pm2 (a restart only for the daemon). A systemd boot script still needs `sudo pm2 startup`; the panel shows the exact command.
+
## Syncing a fork
`POST /api/update/sync-fork` shells out to:
diff --git a/ecosystem.config.cjs b/ecosystem.config.cjs
index 70d36bbbab..241ecd4b94 100644
--- a/ecosystem.config.cjs
+++ b/ecosystem.config.cjs
@@ -39,6 +39,20 @@ const PG_HOST = databaseSettings.host;
// Express bind for portos-server only: nonempty exported HOST → .env → all interfaces (#10946).
const SERVER_HOST = process.env.HOST || envValue('HOST') || '0.0.0.0';
+// The Node binary every PortOS app runs on. A bare 'node' is resolved against
+// the pm2 DAEMON's PATH, which is how an install ends up running an older
+// Homebrew node while nvm and the terminal report a newer one. The Node
+// runtime panel pins an absolute path here (exported env, then .env); a value
+// that is not an absolute path to an existing node binary is ignored so a
+// removed nvm version falls back to PATH instead of stranding pm2. Same rule as
+// server/lib/nodeInterpreterPin.js.
+const isUsableNodeInterpreter = (candidate) => typeof candidate === 'string'
+ && path.isAbsolute(candidate)
+ && ['node', 'node.exe'].includes(path.basename(candidate).toLowerCase())
+ && require('fs').existsSync(candidate);
+const NODE_INTERPRETER = [process.env.PORTOS_NODE_INTERPRETER, envValue('PORTOS_NODE_INTERPRETER')]
+ .find(isUsableNodeInterpreter) || 'node';
+
// pm2 restarts portos-server when its RSS crosses this — originally a memory-leak
// safety valve. The committed default stays modest so the guard still fires on a
// small install (a fork on an 8 GB box), but it's overridable per-machine via
@@ -179,7 +193,7 @@ module.exports = {
name: 'portos-server',
script: 'server/start.js',
cwd: __dirname,
- interpreter: 'node',
+ interpreter: NODE_INTERPRETER,
log_date_format: LOG_DATE_FORMAT,
windowsHide: IS_WIN,
env: {
@@ -266,7 +280,7 @@ module.exports = {
name: 'portos-cos',
script: 'server/cos-runner/index.js',
cwd: __dirname,
- interpreter: 'node',
+ interpreter: NODE_INTERPRETER,
log_date_format: LOG_DATE_FORMAT,
windowsHide: IS_WIN,
// CoS Agent Runner - isolated process for spawning Claude CLI agents
@@ -306,7 +320,7 @@ module.exports = {
// Explicit, unlike the inferred-from-.js default the other apps could rely
// on: this is the one script PortOS does not own, so pin the interpreter
// that node_args attach to rather than let a Vite release change it.
- interpreter: 'node',
+ interpreter: NODE_INTERPRETER,
log_date_format: LOG_DATE_FORMAT,
windowsHide: IS_WIN,
args: `--configLoader runner --host 0.0.0.0 --port ${PORTS.UI}`,
@@ -336,7 +350,7 @@ module.exports = {
name: 'portos-autofixer',
script: 'autofixer/server.js',
cwd: __dirname,
- interpreter: 'node',
+ interpreter: NODE_INTERPRETER,
log_date_format: LOG_DATE_FORMAT,
windowsHide: IS_WIN,
env: {
@@ -355,7 +369,7 @@ module.exports = {
name: 'portos-autofixer-ui',
script: 'autofixer/ui.js',
cwd: __dirname,
- interpreter: 'node',
+ interpreter: NODE_INTERPRETER,
log_date_format: LOG_DATE_FORMAT,
windowsHide: IS_WIN,
env: {
@@ -373,7 +387,7 @@ module.exports = {
name: 'portos-browser',
script: 'browser/server.js',
cwd: __dirname,
- interpreter: 'node',
+ interpreter: NODE_INTERPRETER,
log_date_format: LOG_DATE_FORMAT,
windowsHide: IS_WIN,
// Security: CDP binds to 127.0.0.1 by default (set CDP_HOST=0.0.0.0 to expose)
diff --git a/scripts/ecosystem-memory-bounds.test.js b/scripts/ecosystem-memory-bounds.test.js
index 8a332560af..0d29a7374c 100644
--- a/scripts/ecosystem-memory-bounds.test.js
+++ b/scripts/ecosystem-memory-bounds.test.js
@@ -42,7 +42,8 @@ const APP_CASES = apps.map((app) => [app.name, app]);
// meaningless for those — scope the heap-cap assertion to the Node-interpreted
// entries so a future non-Node app doesn't force the guard to be deleted.
const NODE_APP_CASES = APP_CASES.filter(([, app]) =>
- app.interpreter === 'node' || (!app.interpreter && /\.[cm]?js$/i.test(app.script)));
+ // `interpreter` is 'node' or the absolute pinned binary (PORTOS_NODE_INTERPRETER).
+ /(^|[\\/])node(\.exe)?$/i.test(app.interpreter || '') || (!app.interpreter && /\.[cm]?js$/i.test(app.script)));
describe('ecosystem.config.cjs memory bounds', () => {
it('restarts the development UI before CoS reports a 2048 MiB warning', () => {
diff --git a/scripts/ecosystem-node-interpreter.test.js b/scripts/ecosystem-node-interpreter.test.js
new file mode 100644
index 0000000000..679ab13f53
--- /dev/null
+++ b/scripts/ecosystem-node-interpreter.test.js
@@ -0,0 +1,46 @@
+import { afterEach, describe, expect, it } from 'vitest';
+import { createRequire } from 'module';
+import { fileURLToPath } from 'url';
+import path from 'path';
+import { resolvePinnedNodeInterpreter } from '../server/lib/nodeInterpreterPin.js';
+
+/**
+ * The pinned interpreter decides which Node pm2 starts PortOS on, so a bad pin
+ * must degrade to PATH's `node` instead of leaving pm2 unable to start the
+ * server — the case is an nvm version removed after the Node panel pinned it.
+ * The ecosystem file carries a CJS copy of the server rule; both are checked
+ * against the same inputs here so they cannot drift.
+ */
+const require = createRequire(import.meta.url);
+const configPath = path.join(path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..'), 'ecosystem.config.cjs');
+
+const loadInterpreters = () => {
+ delete require.cache[require.resolve(configPath)];
+ return [...new Set(require(configPath).apps.map((app) => app.interpreter))];
+};
+
+const original = process.env.PORTOS_NODE_INTERPRETER;
+afterEach(() => {
+ if (original === undefined) delete process.env.PORTOS_NODE_INTERPRETER;
+ else process.env.PORTOS_NODE_INTERPRETER = original;
+});
+
+describe('pinned Node interpreter', () => {
+ it('launches every PortOS app on an existing pinned node binary', () => {
+ process.env.PORTOS_NODE_INTERPRETER = process.execPath;
+ expect(loadInterpreters()).toEqual([process.execPath]);
+ expect(resolvePinnedNodeInterpreter({ envPath: '/nonexistent/.env' })).toBe(process.execPath);
+ });
+
+ it.each([
+ ['a removed version', path.join(path.dirname(process.execPath), 'missing', 'node')],
+ ['a relative path', 'bin/node'],
+ ['a binary that is not node', path.join(path.dirname(process.execPath), 'npm')],
+ ])('falls back to PATH resolution for %s', (_label, candidate) => {
+ process.env.PORTOS_NODE_INTERPRETER = candidate;
+ expect(resolvePinnedNodeInterpreter({ envPath: '/nonexistent/.env' })).toBeNull();
+ // The real .env may pin a usable binary on a developer machine; either way
+ // the bad exported value never reaches pm2.
+ expect(loadInterpreters()).not.toContain(candidate);
+ });
+});
diff --git a/scripts/pm2-daemon-refresh.js b/scripts/pm2-daemon-refresh.js
index 1c9d196b51..e98b7bc98d 100644
--- a/scripts/pm2-daemon-refresh.js
+++ b/scripts/pm2-daemon-refresh.js
@@ -69,9 +69,11 @@ export function daemonEntryFromArgv(argv) {
* @param {object|null} options.report - the daemon's `getReport` payload
* @param {string} options.expectedEntry - path to this checkout's pm2 lib/Daemon.js
* @param {string} options.expectedVersion - this checkout's installed pm2 version
+ * @param {string|null} [options.expectedNodeVersion] - the Node PortOS is pinned
+ * to (`PORTOS_NODE_INTERPRETER`), or null to leave the daemon's Node alone
* @returns {{ needed: boolean, reason: string }}
*/
-export function daemonNeedsRefresh({ report, expectedEntry, expectedVersion }) {
+export function daemonNeedsRefresh({ report, expectedEntry, expectedVersion, expectedNodeVersion = null }) {
if (!report) return { needed: true, reason: 'daemon did not report its identity' };
const entry = daemonEntryFromArgv(report.argv);
@@ -89,6 +91,13 @@ export function daemonNeedsRefresh({ report, expectedEntry, expectedVersion }) {
};
}
+ // Only a pinned install asks for this: an unpinned one never chose a Node, and
+ // reloading the shared daemon restarts every co-located app.
+ const daemonNode = report.node_version && report.node_version !== 'N/A' ? String(report.node_version) : null;
+ if (expectedNodeVersion && daemonNode && daemonNode !== expectedNodeVersion) {
+ return { needed: true, reason: `daemon runs Node ${daemonNode}, PortOS is pinned to ${expectedNodeVersion}` };
+ }
+
return { needed: false, reason: 'daemon already runs this checkout of pm2' };
}
@@ -156,6 +165,9 @@ async function runCli() {
report: await fetchReport(pm2),
expectedEntry: join(pm2Dir, 'lib', 'Daemon.js'),
expectedVersion: JSON.parse(readFileSync(join(pm2Dir, 'package.json'), 'utf8')).version,
+ // launchUpdate exports the pin and puts its bin first on PATH, so this
+ // process already runs on the pinned Node.
+ expectedNodeVersion: process.env.PORTOS_NODE_INTERPRETER ? process.versions.node : null,
});
} catch (err) {
verdict = { needed: true, reason: `daemon probe failed: ${redactPaths(err.message)}` };
diff --git a/scripts/pm2-daemon-refresh.test.js b/scripts/pm2-daemon-refresh.test.js
index f3c148535d..2a2cf938e8 100644
--- a/scripts/pm2-daemon-refresh.test.js
+++ b/scripts/pm2-daemon-refresh.test.js
@@ -69,6 +69,16 @@ describe('daemonNeedsRefresh', () => {
expect(check({ argv: [] }).needed).toBe(true);
});
+ it('moves the daemon onto the pinned Node, and leaves an unpinned install alone', () => {
+ const pinned = (nodeVersion, expectedNodeVersion) => daemonNeedsRefresh({
+ report: report({ node_version: nodeVersion }), expectedEntry: OURS, expectedVersion: VERSION, expectedNodeVersion,
+ }).needed;
+ expect(pinned('26.10.0', '26.12.1')).toBe(true);
+ expect(pinned('26.12.1', '26.12.1')).toBe(false);
+ // No pin: a daemon on another Node must not cost every co-located app a restart.
+ expect(pinned('26.10.0', null)).toBe(false);
+ });
+
it('treats a differently-spelled path to the same file as a match', () => {
const spelled = join(FIXTURE_DIR, 'lib', '..', 'lib', 'Daemon.js');
expect(check({ argv: ['/usr/bin/node', spelled] }).needed).toBe(false);
diff --git a/server/lib/README.md b/server/lib/README.md
index 1b05a19f8f..72c1fb7216 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -385,6 +385,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `fileCore.js` | Cross-cutting filesystem primitives (`atomicWrite`, `writeFileGuarded`, `appendFileGuarded`, `copyFileGuarded`, `renameGuarded`, `rmGuarded`, `unlinkGuarded`, `createWriteStreamGuarded`, directory helpers, `parseFilesystemStats(stats)` → canonical/byte-alias metrics or `null`, bounded tail reads/watchers), time/format helpers, directory sizing, and SHA-256 helpers. |
| `familySettingsMap.js` | The merge rule every per-provider-family map in `data/settings.json` shares (plan prices, plan tiers) — `normalizeFamilyMap(raw, normalizeValue)` and `mergeFamilyMap(stored, patch, normalizeValue)`, which hold the absent-vs-present-but-empty contract in ONE place: an omitted family keeps its stored value, one sent empty is an intentional clear and is deleted. Each store supplies only its value normalizer. Pure. |
| `fileUtils.js` | Backward-compatible facade re-exporting the focused file utility modules so existing deep imports need no caller changes. |
+| `nodeInterpreterPin.js` | `resolvePinnedNodeInterpreter` reads the absolute Node binary PortOS's pm2 apps are pinned to (`PORTOS_NODE_INTERPRETER`, exported value then `.env`; a missing or non-`node` path falls back to PATH), `isUsableNodeInterpreter`, and `withNodeBinOnPath` for scripts that must run on that runtime. CJS twin in `ecosystem.config.cjs`. |
| `portosEnv.js` | Single server-side helper for PortOS's own `.env` (`PORTOS_ENV_PATH` anchored to `installRoot` per #1947, `parseEnvContents`, `readPortosEnvValue`, `upsertPortosEnvLine` + `upsertEnvLine`), with replacer-function guard for `$`-patterns and `process.env` wins precedence; `scripts/lib/envFile.js` stays as the zero-dependency boundary copy. |
| `portosRootPlaceholder.js` | Expand leftover `__PORTOS_ROOT__` tokens in apps registry fields (`repoPath`, `appIconPath`, etc.) so a partial/restored `data/` tree cannot leave Apps → Git looking for a non-existent checkout. `PORTOS_ROOT_TOKEN`, `expandPortosRootToken`, `expandPortosRootInApp`, `containsPortosRootToken`. Used by `services/apps.js` on load and by `scripts/setup-data.js` / `scripts/lib/rewriteAppsPortosRoot.js` when seeding or rewriting `data/apps.json`. |
| `pm2Jlist.js` | Sole owner of the strict `pm2 jlist` stdout parser: `parsePm2JlistStdout(stdout)` returns the parsed process array (incl. `[]` for a genuine empty read) or `null` when the read effectively failed (empty/garbage/non-array stdout) — the absent-vs-empty contract from issue #968, consolidated by #8164. Zero imports so `autofixer/shared.js` can use it without the server dependency graph. `services/pm2.js` re-exports it as `parseJlistStdout` for compatibility; `services/pm2.js#listProcessesStrict` and `autofixer/shared.js` are the only non-test callers permitted to execute raw `pm2 jlist`. |
diff --git a/server/lib/hostControlRoutes.js b/server/lib/hostControlRoutes.js
index 224bdaab5e..1ae21b68e6 100644
--- a/server/lib/hostControlRoutes.js
+++ b/server/lib/hostControlRoutes.js
@@ -1009,6 +1009,10 @@ export const HOST_CONTROL_ROUTES = Object.freeze([
// record a preference — left open.
'POST /api/update/execute',
'POST /api/update/sync-fork',
+ // Node runtime (nvm install + global pm2 + restart) and pm2 alignment.
+ 'POST /api/update/node-runtime',
+ 'POST /api/update/node-runtime/startup',
+ 'POST /api/update/pm2',
// Brain links (#8742): git clone/pull in the linked repo, opening a host
// app, or queuing a CoS malware-scan/repo-study agent. `buckets` CRUD,
diff --git a/server/lib/index.js b/server/lib/index.js
index 8eede914c4..5b9e2db34d 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -330,6 +330,7 @@ export * as fileUtils from './fileUtils.js';
export * from './fileWriteQueue.js';
export * from './forgeIssueCli.js';
export * from './forgeIssueState.js';
+export * from './nodeInterpreterPin.js';
export * from './portosEnv.js';
export * from './portosRootPlaceholder.js';
export * from './pm2Jlist.js';
diff --git a/server/lib/nodeInterpreterPin.js b/server/lib/nodeInterpreterPin.js
new file mode 100644
index 0000000000..d5c731a6a1
--- /dev/null
+++ b/server/lib/nodeInterpreterPin.js
@@ -0,0 +1,54 @@
+/**
+ * The Node.js interpreter PortOS's own pm2 apps are pinned to.
+ *
+ * `ecosystem.config.cjs` used to launch every app with `interpreter: 'node'`,
+ * which pm2 resolves against the DAEMON's PATH — so the Node that actually ran
+ * PortOS was whichever `node` came first there (often Homebrew's), not the one
+ * nvm installed or the one the terminal reports. Recording an absolute path in
+ * `.env` as `PORTOS_NODE_INTERPRETER` makes the runtime an explicit choice the
+ * Node runtime panel can change and report.
+ *
+ * Precedence follows `portosEnv.js`: an exported value wins over the saved one.
+ * A candidate that is not an absolute path to an existing `node` binary is
+ * skipped rather than trusted — an nvm version removed after it was pinned must
+ * fall back to PATH resolution, never leave pm2 unable to start the server.
+ * `ecosystem.config.cjs` carries the CJS twin of `resolvePinnedNodeInterpreter`
+ * (it cannot import ESM); keep the two rules identical.
+ */
+
+import { existsSync } from 'fs';
+import { basename, delimiter, dirname, isAbsolute } from 'path';
+import { readPortosEnvValue } from './portosEnv.js';
+
+export const NODE_INTERPRETER_ENV_KEY = 'PORTOS_NODE_INTERPRETER';
+
+const NODE_BINARY_NAMES = new Set(['node', 'node.exe']);
+
+export function isUsableNodeInterpreter(candidate, exists = existsSync) {
+ return typeof candidate === 'string'
+ && isAbsolute(candidate)
+ && NODE_BINARY_NAMES.has(basename(candidate).toLowerCase())
+ && exists(candidate);
+}
+
+/**
+ * The pinned interpreter in effect, or null when PortOS runs on PATH's `node`.
+ * @param {{ env?: object, envPath?: string, exists?: (path: string) => boolean }} [options]
+ */
+export function resolvePinnedNodeInterpreter({ env = process.env, envPath, exists = existsSync } = {}) {
+ const exported = env[NODE_INTERPRETER_ENV_KEY];
+ if (isUsableNodeInterpreter(exported, exists)) return exported;
+ const saved = readPortosEnvValue(NODE_INTERPRETER_ENV_KEY, envPath);
+ return isUsableNodeInterpreter(saved, exists) ? saved : null;
+}
+
+/**
+ * `env` with the interpreter's bin directory first on PATH, so a script that
+ * calls bare `node`/`npm` (update.sh) runs on the pinned runtime and rebuilds
+ * native modules for it. Returns `env` unchanged when nothing is pinned.
+ */
+export function withNodeBinOnPath(env, interpreter) {
+ if (!interpreter) return env;
+ const pathKey = Object.keys(env).find((key) => key.toUpperCase() === 'PATH') || 'PATH';
+ return { ...env, [pathKey]: [dirname(interpreter), env[pathKey]].filter(Boolean).join(delimiter) };
+}
diff --git a/server/routes/hostControlFamiliesUpdate.test.js b/server/routes/hostControlFamiliesUpdate.test.js
index cb9617dd7c..87ea98d3d4 100644
--- a/server/routes/hostControlFamiliesUpdate.test.js
+++ b/server/routes/hostControlFamiliesUpdate.test.js
@@ -23,6 +23,14 @@ const selfUpdate = vi.hoisted(() => ({
}));
vi.mock('../services/portosSelfUpdate.js', () => selfUpdate);
+const nodeRuntime = vi.hoisted(() => ({
+ getNodeRuntimeStatus: vi.fn(),
+ startNodeUpdate: vi.fn(),
+ startPm2Update: vi.fn(),
+ repairStartup: vi.fn(),
+}));
+vi.mock('../services/nodeRuntime.js', () => nodeRuntime);
+
const brainService = vi.hoisted(() => ({
getLinkById: vi.fn(),
}));
@@ -107,6 +115,9 @@ describe('host-control gate on update, brain-link and ask promote writes (#8742)
const writes = [
['post', '/api/update/execute', {}],
['post', '/api/update/sync-fork', {}],
+ ['post', '/api/update/node-runtime', { version: 'v26.12.1' }],
+ ['post', '/api/update/pm2', {}],
+ ['post', '/api/update/node-runtime/startup', {}],
['post', '/api/brain/links/link-1/pull', {}],
['post', '/api/ask/conv-1/turns/turn-1/promote', { target: 'task' }],
];
@@ -115,6 +126,9 @@ describe('host-control gate on update, brain-link and ask promote writes (#8742)
expectRefused(await call(local(), write, '192.0.2.10'));
}
expect(selfUpdate.startPortosSelfUpdate).not.toHaveBeenCalled();
+ expect(nodeRuntime.startNodeUpdate).not.toHaveBeenCalled();
+ expect(nodeRuntime.startPm2Update).not.toHaveBeenCalled();
+ expect(nodeRuntime.repairStartup).not.toHaveBeenCalled();
expect(updateChecker.getRemoteInfo).not.toHaveBeenCalled();
expect(repoCloner.pullRepo).not.toHaveBeenCalled();
expect(askPromote.promoteTurnById).not.toHaveBeenCalled();
diff --git a/server/routes/update.js b/server/routes/update.js
index 67b267d9f7..c11fdfefe8 100644
--- a/server/routes/update.js
+++ b/server/routes/update.js
@@ -4,6 +4,7 @@ import { asyncHandler, ServerError } from '../lib/errorHandler.js';
import { validateRequest } from '../lib/validation.js';
import { UPSTREAM_FULL_NAME } from '../lib/gitRemote.js';
import * as updateChecker from '../services/updateChecker.js';
+import { getNodeRuntimeStatus, repairStartup, startNodeUpdate, startPm2Update } from '../services/nodeRuntime.js';
import { startPortosSelfUpdate } from '../services/portosSelfUpdate.js';
import {
AUTO_UPDATE_MIN_INTERVAL_HOURS_MAX,
@@ -21,6 +22,10 @@ const ignoreSchema = z.object({
version: z.string().min(1, 'version is required')
});
+const nodeUpdateSchema = z.object({
+ version: z.string().regex(/^v\d+\.\d+\.\d+$/, 'version must look like v26.12.1')
+});
+
const syncForkSchema = z.object({
branch: z.string().min(1).max(255).regex(/^[A-Za-z0-9._/-]+$/, 'branch contains invalid characters').optional()
});
@@ -192,4 +197,35 @@ router.post('/execute', asyncHandler(async (req, res) => {
res.json({ started, tag });
}));
+// GET /api/update/node-runtime — the Node.js PortOS runs on, newer stable and
+// security releases, nvm, pm2 (shipped, daemon, terminal CLI) and the boot script.
+router.get('/node-runtime', asyncHandler(async (req, res) => {
+ res.json(await getNodeRuntimeStatus());
+}));
+
+// POST /api/update/node-runtime — install an offered Node with nvm and restart
+// PortOS on it. Refuses while anything a restart would kill is running.
+// Progress streams on `portos:update:step`.
+router.post('/node-runtime', asyncHandler(async (req, res) => {
+ const { version } = validateRequest(nodeUpdateSchema, req.body || {});
+ res.status(202).json(await startNodeUpdate({ version, io: req.app.get('io') }));
+}));
+
+// POST /api/update/node-runtime/startup — repoint the macOS pm2 LaunchAgent at
+// PortOS's Node. No restart; launchd reads it at the next login.
+router.post('/node-runtime/startup', asyncHandler(async (req, res) => {
+ const fixed = await repairStartup();
+ if (!fixed) {
+ throw new ServerError('Start-on-boot can\'t be updated from PortOS here. Run the command shown instead.', { status: 409, code: 'STARTUP_NOT_FIXABLE' });
+ }
+ req.app.get('io')?.emit('portos:node-runtime:changed', { reason: 'startup' });
+ res.json({ fixed });
+}));
+
+// POST /api/update/pm2 — align the terminal's pm2 CLI and the daemon with the
+// pm2 PortOS ships; restarts PortOS only when the daemon is behind.
+router.post('/pm2', asyncHandler(async (req, res) => {
+ res.status(202).json(await startPm2Update({ io: req.app.get('io') }));
+}));
+
export default router;
diff --git a/server/services/nodeRuntime.js b/server/services/nodeRuntime.js
new file mode 100644
index 0000000000..3fcb4474a4
--- /dev/null
+++ b/server/services/nodeRuntime.js
@@ -0,0 +1,497 @@
+/**
+ * The Node.js runtime PortOS runs on: what it is, whether a newer stable or
+ * security release exists, and the in-place update through nvm.
+ *
+ * Node ships security releases often enough that "which Node is PortOS on?"
+ * has to be answerable from the UI, and answering it from a terminal is
+ * misleading: pm2 resolves `interpreter: 'node'` against the DAEMON's PATH, so
+ * the running server can be on a different Node than `node -v` or nvm's
+ * default. Everything here reads the running process (`process.version`) and
+ * the daemon's own report rather than PATH.
+ *
+ * An update never mutates a live runtime. It installs the target with nvm,
+ * aligns that Node's global pm2 CLI with the version PortOS ships, pins
+ * `PORTOS_NODE_INTERPRETER` (lib/nodeInterpreterPin.js), and only then hands
+ * off to the ordinary self-update lifecycle (`startPortosSelfUpdate`, mode
+ * `refresh`). That lifecycle already owns everything a runtime switch needs:
+ * the restart refusals, the update lock, rebuilding native modules on the new
+ * Node (launchUpdate puts the pin first on PATH), the daemon reload
+ * (pm2-daemon-refresh.js compares the daemon's Node with the pin), and the
+ * `pm2 delete` + `pm2 start` that makes pm2 read the new interpreter.
+ *
+ * The boot script (`pm2 startup`) needs sudo, so it is reported with the exact
+ * command to run, never run from here.
+ */
+
+import { existsSync, readdirSync, readFileSync } from 'fs';
+import { homedir, userInfo } from 'os';
+import { dirname, join } from 'path';
+import { ServerError } from '../lib/errorHandler.js';
+import { PATHS, atomicWrite } from '../lib/fileUtils.js';
+import { runStreamingCommand } from '../lib/streamingSpawn.js';
+import { withoutServerSecretsEnv } from '../lib/processEnv.js';
+import {
+ NODE_INTERPRETER_ENV_KEY,
+ resolvePinnedNodeInterpreter,
+ withNodeBinOnPath,
+} from '../lib/nodeInterpreterPin.js';
+import { readPortosEnvValue, upsertPortosEnvLine } from '../lib/portosEnv.js';
+import {
+ SUPPORTED_NODE_RANGE,
+ compareVersions,
+ satisfiesVersionRequirement,
+} from '../../scripts/checkNodeVersion.js';
+
+const IS_WIN = process.platform === 'win32';
+const VERSION_RE = /^v\d+\.\d+\.\d+$/;
+const NODE_INDEX_URL = 'https://nodejs.org/dist/index.json';
+const PM2_LATEST_URL = 'https://registry.npmjs.org/pm2/latest';
+const FETCH_TIMEOUT_MS = 10_000;
+const LATEST_TTL_MS = 6 * 60 * 60 * 1000;
+const LATEST_ERROR_TTL_MS = 10 * 60 * 1000;
+const NVM_INSTALL_TIMEOUT_MS = 15 * 60 * 1000;
+const NPM_INSTALL_TIMEOUT_MS = 10 * 60 * 1000;
+
+// Homebrew's nvm formula ships nvm.sh outside NVM_DIR, which then holds only
+// versions/ and alias/.
+const NVM_SCRIPT_CANDIDATES = [
+ '/opt/homebrew/opt/nvm/nvm.sh',
+ '/usr/local/opt/nvm/nvm.sh',
+ '/home/linuxbrew/.linuxbrew/opt/nvm/nvm.sh',
+];
+
+/** nvm's directory and loader script, or null when nvm is not installed. */
+function resolveNvm({ env = process.env, exists = existsSync, home = homedir() } = {}) {
+ const dir = env.NVM_DIR || join(home, '.nvm');
+ if (!exists(dir)) return null;
+ const script = [join(dir, 'nvm.sh'), ...NVM_SCRIPT_CANDIDATES].find((candidate) => exists(candidate));
+ return script ? { dir, script } : null;
+}
+
+const nvmNodeBinary = (dir, version) => join(dir, 'versions', 'node', version, 'bin', 'node');
+
+function listNvmVersions(dir) {
+ let entries = [];
+ try {
+ entries = readdirSync(join(dir, 'versions', 'node'));
+ } catch {
+ return [];
+ }
+ return entries.filter((name) => VERSION_RE.test(name)).sort((a, b) => compareVersions(b, a));
+}
+
+/** nvm's default alias when it names an exact version; `lts/*`-style aliases read as null. */
+function readNvmDefault(dir) {
+ let alias = '';
+ try {
+ alias = readFileSync(join(dir, 'alias', 'default'), 'utf8').trim();
+ } catch {
+ return null;
+ }
+ const version = alias.startsWith('v') ? alias : `v${alias}`;
+ return VERSION_RE.test(version) ? version : null;
+}
+
+/** Where a node binary came from, for the label next to its version. */
+function classifyNodeSource(execPath, nvmDir) {
+ const path = String(execPath || '');
+ if (nvmDir && path.startsWith(join(nvmDir, 'versions', 'node'))) return 'nvm';
+ if (/\/(homebrew|linuxbrew|Cellar)\//.test(path)) return 'homebrew';
+ return 'other';
+}
+
+/**
+ * The update choices for a running version, from nodejs.org's release index.
+ *
+ * Offers the newest release on the running major line (the security patch),
+ * the newest LTS, and the newest release overall, each only when it is newer
+ * than what runs and inside PortOS's supported range. `securityUpdate` is true
+ * when a release newer than the running one on its own line is flagged as a
+ * security release.
+ */
+function summarizeNodeReleases(releases, runningVersion) {
+ const supported = (Array.isArray(releases) ? releases : [])
+ .filter((release) => VERSION_RE.test(release?.version || ''))
+ .filter((release) => satisfiesVersionRequirement(release.version, SUPPORTED_NODE_RANGE) === true)
+ .sort((a, b) => compareVersions(b.version, a.version));
+ const major = (version) => Number(version.slice(1).split('.')[0]);
+ const runningMajor = major(runningVersion);
+ const newer = (release) => compareVersions(release.version, runningVersion) > 0;
+
+ const latestInLine = supported.find((release) => major(release.version) === runningMajor) || null;
+ const latestLts = supported.find((release) => release.lts) || null;
+ const latestCurrent = supported[0] || null;
+ const securityUpdate = supported.some((release) => release.security && newer(release) && major(release.version) === runningMajor);
+
+ const offers = [];
+ const offer = (release, label) => {
+ if (!release || !newer(release) || offers.some((entry) => entry.version === release.version)) return;
+ offers.push({
+ version: release.version,
+ label,
+ lts: release.lts ? String(release.lts) : null,
+ date: release.date || null,
+ });
+ };
+ offer(latestInLine, `Latest ${runningMajor}.x`);
+ offer(latestLts, 'Latest LTS');
+ offer(latestCurrent, 'Latest release');
+
+ const pick = (release) => (release ? { version: release.version, lts: release.lts ? String(release.lts) : null, date: release.date || null } : null);
+ return {
+ latestInLine: pick(latestInLine),
+ latestLts: pick(latestLts),
+ latestCurrent: pick(latestCurrent),
+ securityUpdate,
+ offers,
+ };
+}
+
+// nodejs.org's index and npm's pm2 dist-tag, cached. `value: null` is the
+// not-fetched sentinel; a failure backs off for the short TTL instead of
+// poisoning the cache or refetching on every panel load.
+const caches = { node: { value: null, fetchedAt: 0 }, pm2: { value: null, fetchedAt: 0 } };
+
+function resetNodeRuntimeCaches() {
+ caches.node = { value: null, fetchedAt: 0 };
+ caches.pm2 = { value: null, fetchedAt: 0 };
+}
+
+async function cachedFetch(key, url, pickValue) {
+ const entry = caches[key];
+ const age = Date.now() - entry.fetchedAt;
+ if (entry.value && age < LATEST_TTL_MS) return entry.value;
+ if (!entry.value && entry.fetchedAt && age < LATEST_ERROR_TTL_MS) return null;
+ const value = await fetch(url, {
+ headers: { 'User-Agent': 'PortOS', Accept: 'application/json' },
+ signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
+ }).then((res) => (res.ok ? res.json() : null)).then((body) => (body ? pickValue(body) : null)).catch(() => null);
+ caches[key] = { value, fetchedAt: Date.now() };
+ return value;
+}
+
+const getNodeReleaseIndex = () => cachedFetch('node', NODE_INDEX_URL, (body) => (Array.isArray(body) ? body : null));
+const getLatestPm2Version = () => cachedFetch('pm2', PM2_LATEST_URL, (body) => (typeof body?.version === 'string' ? body.version : null));
+
+function readPackageVersion(packageJsonPath) {
+ try {
+ const version = JSON.parse(readFileSync(packageJsonPath, 'utf8')).version;
+ return typeof version === 'string' ? version : null;
+ } catch {
+ return null;
+ }
+}
+
+/** The pm2 PortOS ships (its pinned root dependency). */
+const shippedPm2Version = () => readPackageVersion(join(PATHS.root, 'node_modules', 'pm2', 'package.json'));
+
+/** The global pm2 CLI installed under a node binary's prefix, or null. */
+function globalPm2Version(nodeBinary) {
+ if (!nodeBinary || IS_WIN) return null;
+ return readPackageVersion(join(dirname(dirname(nodeBinary)), 'lib', 'node_modules', 'pm2', 'package.json'));
+}
+
+const NVM_BIN_SEGMENT = /(\/\.nvm\/versions\/node\/)v\d+\.\d+\.\d+(\/bin)/g;
+const nvmVersionOf = (binDir) => binDir.match(/\/\.nvm\/versions\/node\/(v\d+\.\d+\.\d+)\/bin$/)?.[1] || null;
+
+/**
+ * A launchd agent's nvm Node paths moved to `binDir`'s version, or null when
+ * there is nothing PortOS can safely rewrite: the target is not an nvm Node,
+ * or the agent names no nvm Node at all (pm2 startup generated it elsewhere).
+ */
+function rewriteLaunchAgent(contents, binDir) {
+ const version = nvmVersionOf(binDir);
+ if (!version || typeof contents !== 'string' || !NVM_BIN_SEGMENT.test(contents)) return null;
+ NVM_BIN_SEGMENT.lastIndex = 0;
+ return contents.replace(NVM_BIN_SEGMENT, `$1${version}$2`);
+}
+
+function startupFileFor(system, home, user) {
+ return system === 'launchd'
+ ? join(home, 'Library', 'LaunchAgents', `pm2.${user}.plist`)
+ : `/etc/systemd/system/pm2-${user}.service`;
+}
+
+/**
+ * Whether the boot-time `pm2 resurrect` still runs from an older Node. A macOS
+ * LaunchAgent lives in the user's own Library, so PortOS can repoint its nvm
+ * paths itself (`fixable`); anything else gets the sudo command that
+ * regenerates it. Null where PortOS can't tell (Windows, no supported init).
+ */
+function getStartupStatus({ nodeBinary, platform = process.platform, home = homedir(), user = safeUserName(), readText = readTextOrNull } = {}) {
+ const system = platform === 'darwin' ? 'launchd' : platform === 'linux' ? 'systemd' : null;
+ if (!system || !nodeBinary || !user) return null;
+ const binDir = dirname(nodeBinary);
+ const contents = readText(startupFileFor(system, home, user));
+ const current = contents === null ? null : contents.includes(binDir);
+ return {
+ system,
+ configured: contents !== null,
+ current,
+ fixable: system === 'launchd' && current === false && rewriteLaunchAgent(contents, binDir) !== null,
+ command: `sudo env PATH=$PATH:${binDir} ${join(binDir, 'pm2')} startup ${system} -u ${user} --hp ${home}`,
+ };
+}
+
+/**
+ * Repoint the LaunchAgent at `nodeBinary`'s nvm version. Takes effect at the
+ * next login; nothing is restarted.
+ * @returns {Promise<boolean>} whether the file was rewritten
+ */
+export async function repairStartup(nodeBinary = resolvePinnedNodeInterpreter() || process.execPath) {
+ const user = safeUserName();
+ const status = getStartupStatus({ nodeBinary, user });
+ if (!status?.fixable) return false;
+ const file = startupFileFor(status.system, homedir(), user);
+ const next = rewriteLaunchAgent(readTextOrNull(file), dirname(nodeBinary));
+ if (next === null) return false;
+ await atomicWrite(file, next);
+ return true;
+}
+
+function safeUserName() {
+ try {
+ return userInfo().username;
+ } catch {
+ return null;
+ }
+}
+
+function readTextOrNull(file) {
+ try {
+ return readFileSync(file, 'utf8');
+ } catch {
+ return null;
+ }
+}
+
+async function readDaemonIdentity() {
+ const { getDaemonIdentity } = await import('./pm2.js');
+ return getDaemonIdentity().catch(() => null);
+}
+
+/** Everything the Node runtime panel renders. */
+export async function getNodeRuntimeStatus() {
+ const nvm = IS_WIN ? null : resolveNvm();
+ const running = process.version;
+ const pinned = resolvePinnedNodeInterpreter();
+ const [releases, latestPm2, daemon] = await Promise.all([
+ getNodeReleaseIndex(),
+ getLatestPm2Version(),
+ readDaemonIdentity(),
+ ]);
+ const summary = releases ? summarizeNodeReleases(releases, running) : null;
+ const shipped = shippedPm2Version();
+ const cliNode = pinned || process.execPath;
+ const cli = globalPm2Version(cliNode);
+
+ const blockedReason = IS_WIN
+ ? 'Updating Node from PortOS needs nvm, which is not available on Windows. Update Node with your installer, then update PortOS.'
+ : !nvm
+ ? 'nvm is not installed. Install nvm (https://github.com/nvm-sh/nvm) to update Node from PortOS.'
+ : null;
+
+ // Behind, not merely different: a newer pm2 someone installed globally is not
+ // worth a restart. The daemon follows the pin; an unpinned install never asked it to move.
+ const older = (version) => Boolean(version && shipped && compareVersions(version, shipped) < 0);
+ const daemonStale = Boolean(daemon && (
+ older(daemon.pm2Version) || (pinned && daemon.nodeVersion && `v${daemon.nodeVersion}` !== running)
+ ));
+
+ return {
+ node: {
+ version: running,
+ execPath: process.execPath,
+ source: classifyNodeSource(process.execPath, nvm?.dir),
+ pinned,
+ supportedRange: SUPPORTED_NODE_RANGE,
+ inSupportedRange: satisfiesVersionRequirement(running, SUPPORTED_NODE_RANGE) === true,
+ },
+ nvm: nvm ? {
+ dir: nvm.dir,
+ defaultVersion: readNvmDefault(nvm.dir),
+ installed: listNvmVersions(nvm.dir),
+ } : null,
+ releases: summary,
+ releasesError: releases ? null : 'Could not reach nodejs.org for the release list.',
+ pm2: {
+ shipped,
+ latest: latestPm2,
+ daemon,
+ cli,
+ cliBehind: older(cli),
+ daemonStale,
+ },
+ // The command runs that Node's global pm2, so offer it only where one exists.
+ startup: cli === null ? null : getStartupStatus({ nodeBinary: cliNode }),
+ canUpdate: blockedReason === null,
+ blockedReason,
+ job: currentJob ? { kind: currentJob.kind, startedAt: currentJob.startedAt } : null,
+ };
+}
+
+// One runtime job at a time; the self-update lock takes over once it launches.
+let currentJob = null;
+
+/** Refuse unless nothing is running that a restart would kill. */
+async function assertIdleForRestart() {
+ const [{ getSystemActivity }, { describeActivityBlockers }, { checkPortosUpdatePreflight }] = await Promise.all([
+ import('./activeProcessing.js'),
+ import('../lib/systemIdle.js'),
+ import('./updatePreflight.js'),
+ ]);
+ const processing = await getSystemActivity().catch(() => null);
+ if (!processing?.activity) {
+ throw new ServerError('Could not confirm PortOS is idle. Try again in a moment.', { status: 503, code: 'ACTIVITY_UNAVAILABLE' });
+ }
+ if (!processing.activity.idle) {
+ throw new ServerError(
+ `PortOS is busy (${describeActivityBlockers(processing.activity.blockers)}). Switching Node restarts PortOS, so it waits until that finishes.`,
+ { status: 409, code: 'SYSTEM_BUSY' },
+ );
+ }
+ // A fork's own main is what it runs; a runtime switch is not the moment to
+ // demand a fork sync.
+ await checkPortosUpdatePreflight({ acknowledgeFork: true });
+}
+
+const childEnvFor = (nodeBinary) => withNodeBinOnPath(withoutServerSecretsEnv(process.env), nodeBinary);
+
+function nvmCommand(nvm, args) {
+ // Arguments travel as positional parameters, never interpolated into the script.
+ return ['bash', ['-c', 'export NVM_DIR="$1"; . "$2" --no-use; shift 2; nvm "$@"', 'portos-nvm', nvm.dir, nvm.script, ...args]];
+}
+
+async function runStep(emit, step, label, command, args, { timeoutMs, env }) {
+ emit(step, 'running', label);
+ let last = '';
+ const run = await runStreamingCommand(command, args, (line) => {
+ const text = String(line).trim();
+ if (!text || text === last) return;
+ last = text;
+ emit(step, 'running', text.slice(0, 200));
+ }, { timeoutMs, env });
+ if (!run.success) {
+ throw new ServerError(`${label} failed: ${run.error || 'unknown error'}`, { status: 502, code: 'NODE_RUNTIME_STEP_FAILED' });
+ }
+ emit(step, 'done', label.replace(/…$/, ''));
+}
+
+async function installGlobalPm2(emit, nodeBinary, version) {
+ await runStep(emit, 'pm2-cli', `Installing pm2 ${version} for Node ${nodeVersionOf(nodeBinary)}…`,
+ join(dirname(nodeBinary), 'npm'), ['install', '-g', `pm2@${version}`],
+ { timeoutMs: NPM_INSTALL_TIMEOUT_MS, env: childEnvFor(nodeBinary) });
+}
+
+const nodeVersionOf = (nodeBinary) => nodeBinary.match(/(v\d+\.\d+\.\d+)/)?.[1] || 'current';
+
+/**
+ * Pin PortOS to `nodeBinary` and run the restart lifecycle on it. Restores the
+ * previous pin when the launch is refused, so a later plain restart never picks
+ * up a runtime whose native modules were not rebuilt.
+ */
+async function pinAndRestart({ io, emit, nodeBinary }) {
+ await assertIdleForRestart();
+ const previous = readPortosEnvValue(NODE_INTERPRETER_ENV_KEY);
+ if (nodeBinary) {
+ emit('node-pin', 'running', 'Pinning PortOS to the new Node…');
+ await upsertPortosEnvLine(NODE_INTERPRETER_ENV_KEY, nodeBinary);
+ emit('node-pin', 'done', `PortOS will run ${nodeBinary}`);
+ // Best effort: a stale boot script only matters at the next login, and the
+ // panel still shows the command when this could not fix it.
+ await repairStartup(nodeBinary)
+ .then((fixed) => { if (fixed) emit('pm2-startup', 'done', 'Start-on-boot now uses the new Node'); })
+ .catch((error) => console.warn(`⚠️ Could not update the pm2 LaunchAgent: ${error.message}`));
+ }
+ const { startPortosSelfUpdate } = await import('./portosSelfUpdate.js');
+ await startPortosSelfUpdate({ io, acknowledgeFork: true, preflightAlreadyRun: true, mode: 'refresh' }).catch(async (error) => {
+ if (nodeBinary) await upsertPortosEnvLine(NODE_INTERPRETER_ENV_KEY, previous ?? '');
+ throw error;
+ });
+}
+
+function launchJob(kind, io, work, { restart = true } = {}) {
+ if (currentJob) {
+ throw new ServerError('A Node or pm2 update is already running.', { status: 409, code: 'NODE_RUNTIME_BUSY' });
+ }
+ currentJob = { kind, startedAt: new Date().toISOString() };
+ const emit = (step, status, message) => io?.emit('portos:update:step', { step, status, message, timestamp: Date.now() });
+ // Runs past the response: nvm downloads take minutes, and the restart this
+ // ends in outlives the request anyway. Progress and failure go out on the
+ // same `portos:update:*` channel the Update tab already renders.
+ Promise.resolve()
+ .then(() => work(emit))
+ .catch((error) => {
+ console.error(`❌ ${kind} failed: ${error.message}`);
+ io?.emit('portos:update:error', { message: error.message, step: kind });
+ })
+ .finally(() => { currentJob = null; });
+ // `restart: false` tells the Update tab not to wait for a restart.
+ return { started: true, restart };
+}
+
+/**
+ * Install `version` with nvm, make it nvm's default, give it the pm2 CLI
+ * PortOS ships, then restart PortOS on it.
+ */
+export async function startNodeUpdate({ version, io }) {
+ if (!VERSION_RE.test(version || '')) {
+ throw new ServerError('version must look like v26.12.1', { status: 400, code: 'VALIDATION_ERROR' });
+ }
+ const status = await getNodeRuntimeStatus();
+ if (!status.canUpdate) throw new ServerError(status.blockedReason, { status: 409, code: 'NODE_UPDATE_UNAVAILABLE' });
+ if (!status.releases?.offers.some((offer) => offer.version === version)) {
+ throw new ServerError(`${version} is not an available update for Node ${status.node.version}.`, { status: 400, code: 'NODE_VERSION_NOT_OFFERED' });
+ }
+ // Refuse up front so a busy install isn't left with a download it can't use yet.
+ await assertIdleForRestart();
+ const nvm = resolveNvm();
+ const nodeBinary = nvmNodeBinary(nvm.dir, version);
+
+ return launchJob('node-update', io, async (emit) => {
+ const [cmd, args] = nvmCommand(nvm, ['install', version]);
+ await runStep(emit, 'node-install', `Installing Node ${version} with nvm…`, cmd, args,
+ { timeoutMs: NVM_INSTALL_TIMEOUT_MS, env: withoutServerSecretsEnv(process.env) });
+ if (!existsSync(nodeBinary)) {
+ throw new ServerError(`nvm finished but ${nodeBinary} is missing.`, { status: 502, code: 'NODE_RUNTIME_STEP_FAILED' });
+ }
+ const [aliasCmd, aliasArgs] = nvmCommand(nvm, ['alias', 'default', version]);
+ await runStep(emit, 'node-default', `Making ${version} nvm's default…`, aliasCmd, aliasArgs,
+ { timeoutMs: 60_000, env: withoutServerSecretsEnv(process.env) });
+ if (status.pm2.shipped) await installGlobalPm2(emit, nodeBinary, status.pm2.shipped);
+ await pinAndRestart({ io, emit, nodeBinary });
+ });
+}
+
+/**
+ * Bring pm2 in line with the version PortOS ships: the terminal's global CLI
+ * under PortOS's Node, and the daemon (reloaded by the restart lifecycle) when
+ * it runs an older pm2 or Node. No restart when only the CLI was behind.
+ */
+export async function startPm2Update({ io }) {
+ const status = await getNodeRuntimeStatus();
+ const { shipped, cliBehind, daemonStale } = status.pm2;
+ if (!shipped) throw new ServerError('PortOS\'s own pm2 is missing. Run the PortOS update first.', { status: 409, code: 'PM2_MISSING' });
+ const cliNode = status.node.pinned || process.execPath;
+ if (!cliBehind && !daemonStale) {
+ throw new ServerError(`pm2 is already on ${shipped}.`, { status: 409, code: 'PM2_CURRENT' });
+ }
+ if (daemonStale) await assertIdleForRestart();
+
+ return launchJob('pm2-update', io, async (emit) => {
+ if (cliBehind) await installGlobalPm2(emit, cliNode, shipped);
+ if (daemonStale) {
+ await pinAndRestart({ io, emit, nodeBinary: null });
+ } else {
+ io?.emit('portos:node-runtime:changed', { reason: 'pm2-cli' });
+ }
+ }, { restart: daemonStale });
+}
+
+export const __testing = {
+ getStartupStatus,
+ resetNodeRuntimeCaches,
+ resolveNvm,
+ rewriteLaunchAgent,
+ summarizeNodeReleases,
+};
diff --git a/server/services/nodeRuntime.test.js b/server/services/nodeRuntime.test.js
new file mode 100644
index 0000000000..ff6112f9ff
--- /dev/null
+++ b/server/services/nodeRuntime.test.js
@@ -0,0 +1,95 @@
+import { describe, expect, it } from 'vitest';
+import { join } from 'path';
+import { __testing } from './nodeRuntime.js';
+
+const { getStartupStatus, resolveNvm, rewriteLaunchAgent, summarizeNodeReleases } = __testing;
+
+// Shape of https://nodejs.org/dist/index.json entries (only the fields read).
+const release = (version, { lts = false, security = false, date = '2026-10-01' } = {}) => ({ version, lts, security, date });
+
+const INDEX = [
+ release('v26.12.1', { security: true, date: '2026-10-21' }),
+ release('v26.12.0'),
+ release('v26.0.0'),
+ release('v25.9.0', { security: true }), // odd line PortOS does not support
+ release('v24.22.1', { lts: 'Krypton', security: true }),
+ release('v24.22.0', { lts: 'Krypton' }),
+ release('v22.22.3', { lts: 'Jod' }),
+];
+
+describe('summarizeNodeReleases', () => {
+ it('offers the line patch first, then the newest LTS, flagging a pending security fix', () => {
+ const summary = summarizeNodeReleases(INDEX, 'v24.22.0');
+ expect(summary.offers.map((offer) => [offer.version, offer.label])).toEqual([
+ ['v24.22.1', 'Latest 24.x'],
+ ['v26.12.1', 'Latest release'],
+ ]);
+ expect(summary.securityUpdate).toBe(true);
+ expect(summary.latestLts.version).toBe('v24.22.1');
+ });
+
+ it('never offers an unsupported line or a downgrade', () => {
+ const summary = summarizeNodeReleases(INDEX, 'v26.0.0');
+ expect(summary.offers.map((offer) => offer.version)).toEqual(['v26.12.1']);
+ expect(summary.offers.some((offer) => offer.version.startsWith('v25.'))).toBe(false);
+ // The LTS is older than what runs, so it is reported but not offered.
+ expect(summary.latestLts.version).toBe('v24.22.1');
+ });
+
+ it('reads as current with nothing to offer on the newest release', () => {
+ const summary = summarizeNodeReleases(INDEX, 'v26.12.1');
+ expect(summary.offers).toEqual([]);
+ expect(summary.securityUpdate).toBe(false);
+ });
+
+ it('does not call a newer non-security patch a security update', () => {
+ expect(summarizeNodeReleases(INDEX, 'v22.22.2').securityUpdate).toBe(false);
+ });
+});
+
+describe('resolveNvm', () => {
+ it('finds Homebrew’s nvm.sh when NVM_DIR holds only versions and aliases', () => {
+ const present = new Set(['/home/example/.nvm', '/opt/homebrew/opt/nvm/nvm.sh']);
+ expect(resolveNvm({ env: {}, home: '/home/example', exists: (path) => present.has(path) }))
+ .toEqual({ dir: '/home/example/.nvm', script: '/opt/homebrew/opt/nvm/nvm.sh' });
+ });
+
+ it('reports no nvm when neither the directory nor a loader exists', () => {
+ expect(resolveNvm({ env: {}, home: '/home/example', exists: () => false })).toBeNull();
+ expect(resolveNvm({ env: {}, home: '/home/example', exists: (path) => path === '/home/example/.nvm' })).toBeNull();
+ });
+});
+
+describe('getStartupStatus', () => {
+ const nodeBinary = '/home/example/.nvm/versions/node/v26.12.1/bin/node';
+ const binDir = '/home/example/.nvm/versions/node/v26.12.1/bin';
+
+ it('flags a boot script that still launches an older Node and gives the sudo command', () => {
+ const status = getStartupStatus({
+ nodeBinary, platform: 'darwin', home: '/Users/example', user: 'example',
+ readText: (file) => (file === join('/Users/example', 'Library', 'LaunchAgents', 'pm2.example.plist')
+ ? '<string>/Users/example/.nvm/versions/node/v24.14.1/bin</string>' : null),
+ });
+ expect(status).toMatchObject({ system: 'launchd', configured: true, current: false, fixable: true });
+ expect(status.command).toBe(`sudo env PATH=$PATH:${binDir} ${join(binDir, 'pm2')} startup launchd -u example --hp /Users/example`);
+ });
+
+ it('repoints every nvm Node path in a LaunchAgent, and refuses what it cannot safely rewrite', () => {
+ const agent = '<string>/Users/example/.nvm/versions/node/v24.14.1/bin/pm2</string><string>PATH=/Users/example/.nvm/versions/node/v24.14.1/bin:/usr/bin</string>';
+ expect(rewriteLaunchAgent(agent, binDir)).toBe(agent.replaceAll('v24.14.1', 'v26.12.1'));
+ // A Homebrew target, or an agent with no nvm path, is left to `pm2 startup`.
+ expect(rewriteLaunchAgent(agent, '/opt/homebrew/bin')).toBeNull();
+ expect(rewriteLaunchAgent('<string>/opt/homebrew/bin/pm2</string>', binDir)).toBeNull();
+ });
+
+ it('reads a boot script on the pinned Node as current, and a missing one as unconfigured', () => {
+ const current = getStartupStatus({ nodeBinary, platform: 'linux', home: '/home/example', user: 'example', readText: () => `PATH=${binDir}` });
+ expect(current).toMatchObject({ system: 'systemd', configured: true, current: true });
+ const missing = getStartupStatus({ nodeBinary, platform: 'linux', home: '/home/example', user: 'example', readText: () => null });
+ expect(missing).toMatchObject({ configured: false, current: null });
+ });
+
+ it('stays silent where PortOS cannot generate a boot script', () => {
+ expect(getStartupStatus({ nodeBinary, platform: 'win32', user: 'example' })).toBeNull();
+ });
+});
diff --git a/server/services/nodeRuntime.update.test.js b/server/services/nodeRuntime.update.test.js
new file mode 100644
index 0000000000..1343c3109f
--- /dev/null
+++ b/server/services/nodeRuntime.update.test.js
@@ -0,0 +1,108 @@
+import { afterAll, afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'fs';
+import { tmpdir } from 'os';
+import { dirname, join } from 'path';
+
+// The update contract: refusals happen before anything is downloaded, nvm gets
+// its arguments positionally, and PortOS is pinned to the new Node only for a
+// restart that actually launches.
+
+const TMP = mkdtempSync(join(tmpdir(), 'node-runtime-'));
+const NVM_DIR = join(TMP, 'nvm');
+const ENV_PATH = join(TMP, '.env');
+mkdirSync(NVM_DIR, { recursive: true });
+writeFileSync(join(NVM_DIR, 'nvm.sh'), '# fixture\n');
+
+const mocks = vi.hoisted(() => ({
+ activity: { idle: true, blockers: [] },
+ runStreamingCommand: vi.fn(),
+ startPortosSelfUpdate: vi.fn(),
+ checkPortosUpdatePreflight: vi.fn(),
+}));
+
+vi.mock('../lib/streamingSpawn.js', () => ({ runStreamingCommand: mocks.runStreamingCommand }));
+vi.mock('./activeProcessing.js', () => ({ getSystemActivity: async () => ({ activity: mocks.activity }) }));
+vi.mock('./updatePreflight.js', () => ({ checkPortosUpdatePreflight: mocks.checkPortosUpdatePreflight }));
+vi.mock('./portosSelfUpdate.js', () => ({ startPortosSelfUpdate: mocks.startPortosSelfUpdate }));
+vi.mock('./pm2.js', () => ({ getDaemonIdentity: async () => ({ pm2Version: '7.0.4', nodeVersion: '26.0.0' }) }));
+vi.mock('../lib/portosEnv.js', async (importOriginal) => {
+ const actual = await importOriginal();
+ return {
+ ...actual,
+ readPortosEnvValue: (key) => actual.readPortosEnvValue(key, ENV_PATH),
+ upsertPortosEnvLine: (key, value) => actual.upsertPortosEnvLine(key, value, ENV_PATH),
+ };
+});
+
+const { __testing, startNodeUpdate } = await import('./nodeRuntime.js');
+
+const running = process.version;
+const [major, minor, patch] = running.slice(1).split('.').map(Number);
+const NEXT = `v${major}.${minor}.${patch + 1}`;
+const nodeBinary = join(NVM_DIR, 'versions', 'node', NEXT, 'bin', 'node');
+const io = { emit: vi.fn() };
+
+const readPin = () => readFileSync(ENV_PATH, 'utf8');
+
+beforeEach(() => {
+ process.env.NVM_DIR = NVM_DIR;
+ __testing.resetNodeRuntimeCaches();
+ writeFileSync(ENV_PATH, 'PGMODE=docker\n');
+ mocks.activity = { idle: true, blockers: [] };
+ mocks.checkPortosUpdatePreflight.mockResolvedValue({});
+ mocks.startPortosSelfUpdate.mockResolvedValue({ started: true, tag: `v${major}.0.0` });
+ mocks.runStreamingCommand.mockImplementation(async (cmd, args) => {
+ if (cmd === 'bash' && args.includes('install')) {
+ mkdirSync(dirname(nodeBinary), { recursive: true });
+ writeFileSync(nodeBinary, '');
+ }
+ return { success: true };
+ });
+ vi.stubGlobal('fetch', vi.fn(async (url) => ({
+ ok: true,
+ json: async () => (String(url).includes('nodejs.org')
+ ? [{ version: NEXT, lts: false, security: true, date: '2026-10-21' }, { version: running, lts: false, security: false }]
+ : { version: '7.0.4' }),
+ })));
+});
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+ vi.clearAllMocks();
+});
+
+afterAll(() => rmSync(TMP, { recursive: true, force: true }));
+
+describe('startNodeUpdate', () => {
+ it('installs with nvm, pins PortOS to the new binary and launches the restart', async () => {
+ await expect(startNodeUpdate({ version: NEXT, io })).resolves.toEqual({ started: true, restart: true });
+ await vi.waitFor(() => expect(mocks.startPortosSelfUpdate).toHaveBeenCalled());
+
+ const install = mocks.runStreamingCommand.mock.calls.find(([, args]) => args.includes('install'));
+ // The script body is constant; the version only ever arrives as "$@".
+ expect(install[1][1]).not.toContain(NEXT);
+ expect(install[1].slice(-2)).toEqual(['install', NEXT]);
+ expect(readPin()).toContain(`PORTOS_NODE_INTERPRETER=${nodeBinary}`);
+ expect(mocks.startPortosSelfUpdate).toHaveBeenCalledWith(expect.objectContaining({ mode: 'refresh', preflightAlreadyRun: true }));
+ });
+
+ it('refuses a version that is not on offer before running anything', async () => {
+ await expect(startNodeUpdate({ version: 'v99.0.0', io })).rejects.toMatchObject({ code: 'NODE_VERSION_NOT_OFFERED' });
+ expect(mocks.runStreamingCommand).not.toHaveBeenCalled();
+ });
+
+ it('refuses while PortOS is busy, naming what it waits for', async () => {
+ mocks.activity = { idle: false, blockers: [{ label: '1 video render' }] };
+ await expect(startNodeUpdate({ version: NEXT, io })).rejects.toMatchObject({ code: 'SYSTEM_BUSY', message: expect.stringContaining('1 video render') });
+ expect(mocks.runStreamingCommand).not.toHaveBeenCalled();
+ });
+
+ it('restores the previous pin when the restart is refused after the install', async () => {
+ mocks.startPortosSelfUpdate.mockRejectedValue(Object.assign(new Error('Update already in progress'), { code: 'UPDATE_IN_PROGRESS' }));
+ await startNodeUpdate({ version: NEXT, io });
+ await vi.waitFor(() => expect(io.emit).toHaveBeenCalledWith('portos:update:error', expect.anything()));
+
+ expect(readPin()).not.toContain(nodeBinary);
+ expect(io.emit).toHaveBeenCalledWith('portos:update:error', expect.objectContaining({ message: 'Update already in progress' }));
+ });
+});
diff --git a/server/services/pm2.js b/server/services/pm2.js
index d1d7ecacfb..45ec495d58 100644
--- a/server/services/pm2.js
+++ b/server/services/pm2.js
@@ -554,6 +554,21 @@ export async function listProcessesStrict(pm2Home = null) {
return list.map(mapProcess);
}
+/**
+ * The running daemon's own pm2 and Node versions — what the Node runtime panel
+ * compares against the pm2 PortOS ships. Only those two fields leave this
+ * function: the daemon's report also carries its whole environment.
+ * @returns {Promise<{pm2Version: string|null, nodeVersion: string|null}|null>} null when unreachable
+ */
+export async function getDaemonIdentity() {
+ const report = await connectAndRun(client => new Promise((resolve, reject) => {
+ client.Client.executeRemote('getReport', {}, (error, value) => error ? reject(error) : resolve(value));
+ }), JLIST_TIMEOUT_MS).catch(() => null);
+ if (!report) return null;
+ const text = (value) => (typeof value === 'string' && value && value !== 'N/A' ? value : null);
+ return { pm2Version: text(report.pm2_version), nodeVersion: text(report.node_version) };
+}
+
/** Internal maintenance inventory: fresh daemon read, no UI cache or env dump. */
export async function listMaintenanceProcesses() {
return connectAndRun(pm2 => new Promise((resolve, reject) => {
diff --git a/server/services/updateExecutor.js b/server/services/updateExecutor.js
index eae739c69b..046ca2e39f 100644
--- a/server/services/updateExecutor.js
+++ b/server/services/updateExecutor.js
@@ -4,6 +4,7 @@ import { canonicalStringify } from '../lib/objects.js';
import { assertPeerExecutionCapability } from '../lib/maintenanceExclusive.js';
import { join } from 'path';
import { PATHS } from '../lib/fileUtils.js';
+import { NODE_INTERPRETER_ENV_KEY, resolvePinnedNodeInterpreter, withNodeBinOnPath } from '../lib/nodeInterpreterPin.js';
import { spawnDetached, isDetachedRunning } from '../lib/detachedSpawn.js';
import { getCurrentVersion, recordUpdateResult } from './updateChecker.js';
@@ -65,7 +66,13 @@ export async function launchUpdate(tag, emit, { forceCleanWorkspaces, peerExecut
const cleanList = Array.isArray(forceCleanWorkspaces)
? forceCleanWorkspaces.filter(w => CLEANABLE_WORKSPACES.has(w))
: [];
- const childEnv = { ...process.env };
+ // The script's bare `node`/`npm` must be the pinned runtime pm2 will launch:
+ // its npm install and native rebuilds target whichever Node runs them.
+ // Exporting the pin also tells pm2-daemon-refresh.js to move the daemon onto
+ // it when the daemon still runs an older Node.
+ const pinnedNode = resolvePinnedNodeInterpreter();
+ const childEnv = withNodeBinOnPath({ ...process.env }, pinnedNode);
+ if (pinnedNode) childEnv[NODE_INTERPRETER_ENV_KEY] = pinnedNode;
// Never inherit peer-only pinning from an operator's ambient environment.
delete childEnv.PORTOS_PEER_UPDATE_TARGET_SHA;
delete childEnv.PORTOS_PEER_UPDATE_EXPECTED_SHA;