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

stop awaiting update.sh from the app-update path, which froze the Git tab at pm2-stop

[._.]/ Adam Eivyc37436856326
diff --git a/client/src/components/apps/AppOperationBanner.jsx b/client/src/components/apps/AppOperationBanner.jsx
index c406abf40f..35f748b24a 100644
--- a/client/src/components/apps/AppOperationBanner.jsx
+++ b/client/src/components/apps/AppOperationBanner.jsx
@@ -12,7 +12,7 @@ const LABELS = {
* app list rather than inside the expanded row so collapsing the row — or
* returning to /apps mid-operation — still shows what is running (#3435).
*/
-export default function AppOperationBanner({ appName, type, steps, error, completed, onDismiss, completedMessage }) {
+export default function AppOperationBanner({ appName, type, steps, error, completed, onDismiss, completedMessage, restarting = false }) {
const labels = LABELS[type] || LABELS.update;
const name = appName || 'app';
const heading = error ? `${labels.failed} ${name}` : completed ? `${labels.done} ${name}` : `${labels.running} ${name}…`;
@@ -44,7 +44,9 @@ export default function AppOperationBanner({ appName, type, steps, error, comple
? error
: completed
? completedMessage || 'You can start another operation now.'
- : 'This keeps running if you collapse the row or leave the page.'}
+ : restarting
+ ? 'PortOS is restarting — this page reloads once it answers again.'
+ : 'This keeps running if you collapse the row or leave the page.'}
</div>
</div>
{onDismiss && (
diff --git a/client/src/components/apps/tabs/OverviewTab.jsx b/client/src/components/apps/tabs/OverviewTab.jsx
index 139f528eb4..0dd04aca34 100644
--- a/client/src/components/apps/tabs/OverviewTab.jsx
+++ b/client/src/components/apps/tabs/OverviewTab.jsx
@@ -31,7 +31,7 @@ export default function OverviewTab({ app, onRefresh }) {
const onComplete = useMemo(() => () => onRefresh(), [onRefresh]);
// Scoped to this app: the shared hook otherwise reports whichever operation
// is running, which would stream another app's steps into this tab.
- const { steps, isOperating, operationType, error, completed, startUpdate, startStandardize } = useAppOperation({ onComplete, appId: app?.id });
+ const { steps, isOperating, operationType, error, completed, restarting, startUpdate, startStandardize } = useAppOperation({ onComplete, appId: app?.id });
const updating = isOperating && operationType === 'update';
const standardizing = isOperating && operationType === 'standardize';
@@ -306,11 +306,11 @@ export default function OverviewTab({ app, onRefresh }) {
</button>
<button
onClick={handleUpdate}
- disabled={isOperating}
+ disabled={isOperating || restarting}
className="px-3 py-1.5 bg-port-success/20 text-port-success hover:bg-port-success/30 rounded-lg text-xs flex items-center gap-1 disabled:opacity-50"
>
<Download size={14} className={updating ? 'animate-bounce' : ''} />
- {updating ? 'Updating...' : 'Update'}
+ {updating ? 'Updating...' : restarting ? 'Restarting...' : 'Update'}
</button>
<button
onClick={handleRefreshConfig}
diff --git a/client/src/components/apps/tabs/RepositorySourcePanel.jsx b/client/src/components/apps/tabs/RepositorySourcePanel.jsx
index aa79f738dd..c6d61e5ffe 100644
--- a/client/src/components/apps/tabs/RepositorySourcePanel.jsx
+++ b/client/src/components/apps/tabs/RepositorySourcePanel.jsx
@@ -173,10 +173,11 @@ export default function RepositorySourcePanel({ appId, appName, onUpdated, refre
error: operationError,
errorCode: operationErrorCode,
completed: operationCompleted,
+ restarting,
startUpdate,
} = useAppOperation({ appId, onComplete: handleOperationComplete });
const updating = isOperating && operationType === 'update';
- const operationBusy = isOperating;
+ const operationBusy = isOperating || restarting;
useEffect(() => {
if (updating) setUpdateRequested(true);
@@ -273,7 +274,7 @@ export default function RepositorySourcePanel({ appId, appName, onUpdated, refre
</button>
</div>
- {(isOperating || operationError || operationCompleted) && (
+ {(isOperating || restarting || operationError || operationCompleted) && (
<div className="mt-4">
<AppOperationBanner
appName={appName}
@@ -282,6 +283,7 @@ export default function RepositorySourcePanel({ appId, appName, onUpdated, refre
error={operationError}
completed={operationCompleted}
completedMessage={operationType === 'update' ? 'Reload this page before starting another update.' : undefined}
+ restarting={restarting}
/>
{/* Refusals PortOS's shared update preflight raises (server/services/updatePreflight.js)
carry an explicit acknowledgement the user can opt into and retry with. */}
diff --git a/client/src/components/apps/tabs/RepositorySourcePanel.test.jsx b/client/src/components/apps/tabs/RepositorySourcePanel.test.jsx
index 3d4f43a948..085f382e9c 100644
--- a/client/src/components/apps/tabs/RepositorySourcePanel.test.jsx
+++ b/client/src/components/apps/tabs/RepositorySourcePanel.test.jsx
@@ -347,3 +347,24 @@ describe('managed app repository sources', () => {
expect(screen.getByRole('button', { name: 'Update app' })).toBeInTheDocument();
});
});
+
+describe('PortOS self-update restart handoff', () => {
+ it('swaps the banner copy to the restart notice once useAppOperation reports it', async () => {
+ // The detection itself lives in useAppOperation (see its own suite). What
+ // this panel owes the user is telling them the page will come back rather
+ // than leaving "Stopping PortOS apps..." on screen with no explanation.
+ useAppOperation.mockReturnValue({
+ steps: [{ step: 'pm2-stop', status: 'running', message: 'Stopping PortOS apps...' }],
+ isOperating: true, operationType: 'update', error: null, errorCode: null, completed: false,
+ restarting: true,
+ startUpdate: vi.fn(),
+ });
+ render(<RepositorySourcePanel appId="portos-default" appName="PortOS" />);
+
+ expect(await screen.findByText(
+ 'PortOS is restarting — this page reloads once it answers again.',
+ )).toBeInTheDocument();
+ // Every action stays locked while the install is coming back.
+ expect(screen.getByRole('button', { name: 'Check sources' })).toBeDisabled();
+ });
+});
diff --git a/client/src/components/apps/tabs/UpdateTab.jsx b/client/src/components/apps/tabs/UpdateTab.jsx
index 57274c68cd..6543b33ea0 100644
--- a/client/src/components/apps/tabs/UpdateTab.jsx
+++ b/client/src/components/apps/tabs/UpdateTab.jsx
@@ -1,4 +1,4 @@
-import { useState, useEffect, useCallback, useRef } from 'react';
+import { useState, useEffect, useCallback } from 'react';
import { RefreshCw, Download, XCircle, Check, Loader, AlertTriangle, Trash2, ExternalLink, Tag, GitFork, GitBranch } from 'lucide-react';
import toast from '../../ui/Toast';
import BrailleSpinner from '../../BrailleSpinner';
@@ -8,7 +8,7 @@ import * as api from '../../../services/api';
import socket from '../../../services/socket';
import { formatDateTime, formatDateNumeric, formatTimeOfDaySeconds } from '../../../utils/formatters';
import { useAutoRefetch } from '../../../hooks/useAutoRefetch';
-import useMounted from '../../../hooks/useMounted';
+import { usePortosRestartWatch } from '../../../hooks/usePortosRestartWatch';
const STEP_LABELS = {
starting: 'Starting update',
@@ -43,31 +43,20 @@ export default function UpdateTab() {
const [updating, setUpdating] = useState(false);
const [steps, setSteps] = useState([]);
const [updateError, setUpdateError] = useState(null);
- const [polling, setPolling] = useState(false);
const [syncingFork, setSyncingFork] = useState(false);
const [forkSyncError, setForkSyncError] = useState(null);
- const attemptsRef = useRef(0);
- const targetVersionRef = useRef(null);
- const preUpdateVersionRef = useRef(null);
- // Mirrors `updating` for the socket 'disconnect' listener below, which is
- // registered once on mount and would otherwise close over a stale `false`.
- const updatingRef = useRef(false);
- // Guards the disconnect-confirmation setTimeout below: without this, an
- // unmount (e.g. the user navigates away) while the timer is pending lets
- // the deferred callback still fire, pop an undismissable "PortOS is
- // restarting..." toast (duration: Infinity), and set state on an unmounted
- // component — nothing is left running to ever dismiss it.
- const mountedRef = useMounted();
- // Tracks whether the health endpoint went down during a restart poll. A
- // reconcile (issue #1779) often lands the SAME version (new commits, no
- // release bump), so version-change detection alone can't confirm completion —
- // a down→up transition does.
- const healthWentDownRef = useRef(false);
- // Highest /system/health uptime seen so far. The server's uptime resets to
- // ~0 on restart, so an uptime that drops well below the previous peak proves
- // a restart happened — catching a same-version reconcile whose restart is too
- // fast for the 2s poll to ever sample the down window.
- const maxUptimeRef = useRef(0);
+
+ // There is no completion event to wait for once update.sh pm2-deletes this
+ // server, so the restart handoff — arming, health polling, the reload — lives
+ // in the shared watch that every PortOS self-update surface uses.
+ const { polling, captureBaseline } = usePortosRestartWatch({
+ active: updating,
+ onRestart: () => setUpdating(false),
+ onFailure: ({ message }) => {
+ setUpdating(false);
+ if (message) setUpdateError(message);
+ },
+ });
const fetchStatus = useCallback(async () => {
const data = await api.getUpdateStatus().catch(() => null);
@@ -80,26 +69,9 @@ export default function UpdateTab() {
fetchStatus();
}, [fetchStatus]);
+ // Step frames for the activity list. The restart handoff these frames end in
+ // is the shared watch's job, not this component's.
useEffect(() => {
- updatingRef.current = updating;
- }, [updating]);
-
- // Socket event listeners for update progress
- useEffect(() => {
- // Shared by the 'restart' step, 'portos:update:complete', and the
- // 'disconnect' fallback below — all three mean "the server is (or is
- // about to be) restarting, stop trusting the socket and start polling."
- // Sets `updatingRef` synchronously (not just via the syncing effect,
- // which only runs after the next commit) so a 'disconnect' arriving in
- // the same tick right after an error/complete can't read a stale `true`
- // and spuriously re-arm polling for an update that already ended.
- const armRestartPolling = () => {
- updatingRef.current = false;
- setUpdating(false);
- setPolling(true);
- toast.loading('PortOS is restarting...', { id: 'portos-update-restart', duration: Infinity });
- };
-
const handleStep = ({ step, status: stepStatus, message }) => {
setSteps(prev => {
const existing = prev.findIndex(s => s.step === step);
@@ -111,133 +83,12 @@ export default function UpdateTab() {
}
return [...prev, entry];
});
- // When the server signals it's restarting, begin health polling immediately.
- // The PM2 restart may kill the server before portos:update:complete fires.
- if ((step === 'restarting' || step === 'restart') && stepStatus !== 'error' && targetVersionRef.current) {
- armRestartPolling();
- }
- };
-
- const handleComplete = ({ success, newVersion, versionKnown }) => {
- if (!success) {
- updatingRef.current = false;
- setUpdating(false);
- return;
- }
- // Use server-reported actual version when available; fall back to target
- if (versionKnown && newVersion) {
- targetVersionRef.current = newVersion;
- }
- armRestartPolling();
- };
-
- const handleError = ({ message }) => {
- updatingRef.current = false;
- setUpdating(false);
- setPolling(false);
- toast.dismiss('portos-update-restart');
- setUpdateError(message);
- };
-
- // `pm2 delete ecosystem.config.cjs` (the update's own "pm2-stop" step) kills
- // this server process — and its socket — well before update.sh reaches its
- // 'restart' step. That step event, and 'portos:update:complete', are then
- // never emitted, and the UI hangs on "Reconciling..."/"Stopping apps"
- // forever even though update.sh finishes fine in the background. A raw
- // 'disconnect' isn't proof of that by itself, though — PortOS is commonly
- // used remotely over Tailscale, and a transient network blip during the
- // pre-pm2-stop steps (git-pull/submodules, while the server is still very
- // much alive) would fire 'disconnect' too. Confirm the server is actually
- // unreachable before treating this as "the update just tore the process
- // down" — otherwise a blip prematurely arms polling, which can time out
- // with a false "Restart timed out" error while the real update finishes
- // fine in the background with nothing left watching it.
- const handleDisconnect = () => {
- if (!updatingRef.current) return;
- setTimeout(async () => {
- if (!updatingRef.current || !mountedRef.current) return;
- // silent: true — a failed check here just means "confirmed, arm
- // polling"; the generic "Server unreachable" toast would otherwise
- // fire right alongside (and ahead of) the intended "restarting" toast
- // on the exact real-disconnect case this confirmation exists for.
- const ok = await api.checkHealth({ silent: true }).catch(() => null);
- if (!ok && updatingRef.current && mountedRef.current) armRestartPolling();
- }, 1500);
};
socket.on('portos:update:step', handleStep);
- socket.on('portos:update:complete', handleComplete);
- socket.on('portos:update:error', handleError);
- socket.on('disconnect', handleDisconnect);
-
- return () => {
- socket.off('portos:update:step', handleStep);
- socket.off('portos:update:complete', handleComplete);
- socket.off('portos:update:error', handleError);
- socket.off('disconnect', handleDisconnect);
- };
- }, []);
-
- // Poll health endpoint after restart to detect new version. The hook's
- // `enabled: polling` gate handles teardown automatically when polling flips
- // off; attemptsRef resets on every fresh polling cycle.
- useEffect(() => {
- if (polling) {
- attemptsRef.current = 0;
- healthWentDownRef.current = false;
- }
- }, [polling]);
-
- const pollHealth = useCallback(async () => {
- attemptsRef.current += 1;
- // silent: true — the server being unreachable is the EXPECTED state for
- // most of this restart poll (that's the down→up transition it's
- // watching for), not an error; the generic toast would spam "Server
- // unreachable" on every 2s tick throughout the "PortOS is restarting..."
- // loading toast's own lifetime.
- const ok = await api.checkHealth({ silent: true }).catch(() => null);
- const preUpdateVersion = preUpdateVersionRef.current;
- if (!ok) {
- // Server is mid-restart (PM2 stopped it) — record the dip so a same-version
- // recovery still counts as "restarted".
- healthWentDownRef.current = true;
- } else if (preUpdateVersion && ok.version && ok.version !== preUpdateVersion) {
- // The running version differs from before the update — restart confirmed.
- // (We don't gate on === targetVersion: that clause would fire on the FIRST
- // healthy poll of a same-version reconcile, where target === preUpdate, and
- // declare success before the server ever went down.)
- setPolling(false);
- toast.success(`Updated to v${ok.version}`, { id: 'portos-update-restart' });
- setTimeout(() => window.location.reload(), 1000);
- return;
- } else if (
- ok.version &&
- (healthWentDownRef.current ||
- (typeof ok.uptime === 'number' && ok.uptime < maxUptimeRef.current - 5))
- ) {
- // Same version, but the restart is proven either by a down→up dip or by
- // the server's uptime resetting below its pre-restart peak (the 5s slack
- // absorbs clock jitter). Catches a reconcile whose restart was too fast
- // for the 2s poll to ever sample the down window.
- setPolling(false);
- toast.success('Install reconciled — reloading', { id: 'portos-update-restart' });
- setTimeout(() => window.location.reload(), 1000);
- return;
- }
- // Track the running peak so a later uptime drop is detectable. Guard on
- // `ok` — the !ok (server-down) branch falls through to here, and a null
- // deref would throw before the attempts>=30 timeout check below, hanging the
- // UI on a restart that never recovers.
- if (ok && typeof ok.uptime === 'number' && ok.uptime > maxUptimeRef.current) {
- maxUptimeRef.current = ok.uptime;
- }
- if (attemptsRef.current >= 30) {
- setPolling(false);
- toast.error('Restart timed out — try reloading manually', { id: 'portos-update-restart' });
- }
+ return () => socket.off('portos:update:step', handleStep);
}, []);
- useAutoRefetch(pollHealth, 2000, { enabled: polling, pollOnly: true });
// Keep the status fresh while there's an update/reconcile surface on screen,
// so the agent block appears AND clears without a manual re-check: if an agent
@@ -265,29 +116,19 @@ export default function UpdateTab() {
// single source of truth for the just-loaded state.
const runUpdate = useCallback(async (opts = {}, fromStatus = null) => {
const s = fromStatus || status;
- if (s?.latestRelease?.version) {
- targetVersionRef.current = s.latestRelease.version;
- }
- preUpdateVersionRef.current = s?.currentVersion || null;
- // Seed the uptime peak with the still-running server's uptime, so even an
+ // Record the version and uptime of the still-running server, so even an
// instant restart (whose first post-restart poll already reports a small
// uptime) is detected as a drop below this pre-update value.
- const preHealth = await api.checkHealth().catch(() => null);
- maxUptimeRef.current = typeof preHealth?.uptime === 'number' ? preHealth.uptime : 0;
+ await captureBaseline(s?.currentVersion);
setUpdating(true);
setSteps([]);
setUpdateError(null);
- const result = await api.executePortosUpdate(opts).catch(err => {
+ return api.executePortosUpdate(opts).catch(err => {
setUpdateError(err.message);
- updatingRef.current = false;
setUpdating(false);
return null;
});
- if (result?.tag) {
- targetVersionRef.current = result.tag.replace(/^v/, '');
- }
- return result;
- }, [status]);
+ }, [captureBaseline, status]);
const handleUpdate = () => runUpdate();
diff --git a/client/src/hooks/README.md b/client/src/hooks/README.md
index 441c59f6a7..74710729ab 100644
--- a/client/src/hooks/README.md
+++ b/client/src/hooks/README.md
@@ -84,6 +84,7 @@ grep -i "what you want to do" client/src/hooks/README.md
| `useShellSession` | All Socket.IO `shell:*` session/terminal state + lifecycle for the Shell page: owns the xterm instance, the attach/detach/generation-guard contract (`pendingAttachRef {target,generation}`, `claim`, `userIdleRef`, `mountedRef`), URL sync, and every session action. Returns `{ terminalRef, connected, sessions, activeSessionId, activeSession, interactiveCount, liveRunCount, isLiveRun, emitShellInput, sendImage, sendCommand, sendCd, sendCtrlB, sendCtrlC, sendNavKey, restartSession, stopSession, startNewSession, switchToSession, killOtherSession }` so the route stays presentational. `sendCd(path)` sends a FOLDER over `shell:cd` rather than composing a `cd` line — the server renders it for the session's actual shell (`server/lib/shellCd.js`), which is the only form that works on a Windows cmd.exe session. `sendCommand(cmd)` submits with CR, never `\n` (see `SUBMIT_KEY` in `server/lib/tuiHandshake.js`). `sendImage(file, message)` is the one operation that leaves the socket — it POSTs to `/api/shell/sessions/:id/image` so a running agent TUI gets the photo's path pasted into its prompt. | The Shell page (`pages/Shell.jsx`) — don't re-roll the single-subscriber PTY attach lifecycle. |
| `useUpdateChecker` | Update-available + install-out-of-sync advisories as *state* (`{ update, outOfSync, ignoreUpdate, dismissUpdate, clearOutOfSync, dismissOutOfSync }`), never toasts — a non-transient advisory must not occlude the screen's primary action (#3786). Out-of-sync dismissals persist per on-disk commit in `safeStorage`, so a later `git pull` re-raises; `clearOutOfSync` is the session-only clear used when the user acts on it. | Never call it directly — `components/UpdateBanners` owns the single instance and Layout renders that once at the app root. A second caller means a second status fetch and socket subscription. |
| `useMounted` | `mountedRef` whose `.current` is true while mounted. | Async deferred work that must abort on unmount. |
+| `usePortosRestartWatch` | Watches PortOS restarting ITSELF and reloads the page once it answers again: arms on the update stream's restart step, on `portos:update:complete`, or on a socket disconnect confirmed unreachable, then polls `/api/system/health` for a version change, a down→up dip, or an uptime reset. `update.sh` pm2-deletes the server mid-run, so there is no completion event to await. | Only a surface that launches a PortOS self-update WITHOUT going through an app operation — today just the Update page. `useAppOperation` already wires it, so App Management surfaces read `restarting` from there instead. |
| `usePrevious` | Returns the value from the previous render — snapshot updated in a `useEffect`. | Compare-and-act on prop/state change from inside a `useEffect`. |
| `usePreviousSync` | Same shape, but snapshot updated *during* render. | The prior value gates an in-render `setState` (React's "adjusting state on prop change" pattern); the during-render update avoids an extra discard/rerun cycle. |
| `useTimeTick` | Singleton-backed wall-clock tick (`Date.now()`); N subscribers at the same cadence share one `setInterval`. | A widget renders something derived from `Date.now()` (relative timestamps, threshold-based health labels, countdowns) and is also fed by a deduped `useAutoRefetch` — without this the label goes stale until the data changes. |
diff --git a/client/src/hooks/index.js b/client/src/hooks/index.js
index d2af021ce0..3f95bbd845 100644
--- a/client/src/hooks/index.js
+++ b/client/src/hooks/index.js
@@ -121,6 +121,7 @@ export * from './useInstallStream.js';
export * from './useProcessLogs.js';
export * from './useOpenClawStream.js';
export * from './usePipelineProgress.js';
+export * from './usePortosRestartWatch.js';
export * from './useReaderPanel.js';
export * from './useSeriesEditorial.js';
export * from './useImageTo3dTargets.js';
diff --git a/client/src/hooks/useAppOperation.js b/client/src/hooks/useAppOperation.js
index 5779d371bf..dcdf6e683e 100644
--- a/client/src/hooks/useAppOperation.js
+++ b/client/src/hooks/useAppOperation.js
@@ -1,6 +1,8 @@
import { useState, useCallback, useEffect, useRef } from 'react';
import socket from '../services/socket';
import toast from '../components/ui/Toast';
+import { PORTOS_APP_ID } from '../lib/appIdentity.js';
+import { usePortosRestartWatch } from './usePortosRestartWatch.js';
const CLEAR_DELAY_MS = 5000;
@@ -27,12 +29,28 @@ const isLive = (op) => !!op && !op.completed && !op.error;
*
* `appId` scopes a single-app surface (an app's Overview tab) to its own
* operation; omit it on the multi-app list, which reports every operation.
+ *
+ * PortOS is itself a managed app, and updating it runs its own update.sh —
+ * which pm2-deletes this server partway through, so `app:update:complete` never
+ * arrives and the operation stays "in flight" forever. That case is handled
+ * HERE rather than at each surface: every caller of `startUpdate` inherits the
+ * baseline capture, the restart detection, and the `restarting` flag, so a new
+ * surface cannot regress to the hang by forgetting to wire them.
*/
export function useAppOperation({ onComplete, appId: scopeAppId } = {}) {
const [operations, setOperations] = useState({});
const clearTimersRef = useRef({});
const onCompleteRef = useRef(onComplete);
+ // A surface scoped to another app can never see a PortOS update, so it
+ // registers no listeners at all.
+ const watchable = !scopeAppId || scopeAppId === PORTOS_APP_ID;
+ const portosOperation = operations[PORTOS_APP_ID];
+ const { polling: restarting, captureBaseline, arm } = usePortosRestartWatch({
+ enabled: watchable,
+ active: watchable && portosOperation?.type === 'update' && isLive(portosOperation),
+ });
+
useEffect(() => { onCompleteRef.current = onComplete; });
useEffect(() => () => {
@@ -95,7 +113,13 @@ export function useAppOperation({ onComplete, appId: scopeAppId } = {}) {
});
};
- const onStep = (data) => patch(data, current => ({ ...current, steps: mergeStep(current.steps, data) }));
+ const onStep = (data) => {
+ // The last frame that can reach us from a PortOS self-update: the script's
+ // own `pm2 delete` kills this server moments later.
+ if (data?.appId === PORTOS_APP_ID && data.status !== 'error'
+ && (data.step === 'restart' || data.step === 'restarting')) arm();
+ patch(data, current => ({ ...current, steps: mergeStep(current.steps, data) }));
+ };
const onError = (data) => {
// A refused duplicate dispatch says nothing about the run already in
@@ -154,14 +178,20 @@ export function useAppOperation({ onComplete, appId: scopeAppId } = {}) {
socket.off('app:standardize:complete', onDone);
socket.off('connect', requestActive);
};
- }, [scopeAppId, drop]);
+ }, [arm, scopeAppId, drop]);
const start = useCallback((type, appId, appName, options = {}) => {
clearTimeout(clearTimersRef.current[appId]);
delete clearTimersRef.current[appId];
setOperations(prev => ({ ...prev, [appId]: { appId, appName, type, steps: [], error: null, errorCode: null, completed: false } }));
+ // Record the running server's version and uptime while it can still answer —
+ // the restart watch compares against them. Deliberately NOT awaited: nothing
+ // reads the baseline for at least a second, and blocking the dispatch on a
+ // health round-trip is visible latency on every click (PortOS is normally
+ // driven remotely over Tailscale).
+ if (type === 'update' && appId === PORTOS_APP_ID) captureBaseline();
socket.emit(type === 'update' ? 'app:update' : 'app:standardize', { appId, ...options });
- }, []);
+ }, [captureBaseline]);
const startUpdate = useCallback((appId, appName, options = {}) => start('update', appId, appName, options), [start]);
const startStandardize = useCallback((appId, appName) => start('standardize', appId, appName), [start]);
@@ -175,6 +205,9 @@ export function useAppOperation({ onComplete, appId: scopeAppId } = {}) {
// Derived, not a separate flag: a stale `isOperating` was how the old hook
// let a finished operation keep every row's buttons disabled.
isOperating: list.some(isLive),
+ // PortOS is restarting itself out from under this page; it reloads when the
+ // server answers again.
+ restarting,
steps: primary?.steps || [],
error: primary?.error ?? null,
errorCode: primary?.errorCode ?? null,
diff --git a/client/src/hooks/useAppOperation.test.jsx b/client/src/hooks/useAppOperation.test.jsx
new file mode 100644
index 0000000000..a05525a495
--- /dev/null
+++ b/client/src/hooks/useAppOperation.test.jsx
@@ -0,0 +1,106 @@
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+import { act, renderHook, waitFor } from '@testing-library/react';
+
+// Capture the socket handlers so a test can fire the 'disconnect' a dying
+// server produces, and inspect what the hook emitted.
+const socketHandlers = new Map();
+const emitted = [];
+vi.mock('../services/socket', () => ({
+ default: {
+ on: (event, fn) => { socketHandlers.set(event, fn); },
+ off: (event, fn) => { if (socketHandlers.get(event) === fn) socketHandlers.delete(event); },
+ emit: (event, payload) => { emitted.push({ event, payload }); },
+ },
+}));
+const mockToast = vi.hoisted(() => Object.assign(vi.fn(), {
+ success: vi.fn(), error: vi.fn(), loading: vi.fn(), dismiss: vi.fn(),
+}));
+vi.mock('../components/ui/Toast', () => ({ default: mockToast }));
+const mockCheckHealth = vi.fn();
+vi.mock('../services/api', () => ({ checkHealth: (...a) => mockCheckHealth(...a) }));
+
+import { useAppOperation } from './useAppOperation';
+import { PORTOS_APP_ID } from '../lib/appIdentity';
+
+// Fires 'disconnect' and advances past the unreachability-confirmation delay,
+// flushing the checkHealth() microtask through it. The pending-effect flush
+// first is what syncs the hook's `active` ref to the state a real dispatch
+// would have reached over network time.
+const disconnectAndConfirm = async () => {
+ await act(async () => {});
+ vi.useFakeTimers();
+ socketHandlers.get('disconnect')();
+ await act(async () => { await vi.advanceTimersByTimeAsync(1500); });
+ vi.useRealTimers();
+};
+
+describe('useAppOperation — PortOS self-update handoff', () => {
+ beforeEach(() => {
+ socketHandlers.clear();
+ emitted.length = 0;
+ vi.clearAllMocks();
+ mockCheckHealth.mockResolvedValue({ version: '2.24.0', uptime: 120 });
+ });
+
+ afterEach(() => { vi.useRealTimers(); });
+
+ it('records the running version before dispatching, without blocking the emit', () => {
+ const { result } = renderHook(() => useAppOperation({ appId: PORTOS_APP_ID }));
+
+ act(() => { result.current.startUpdate(PORTOS_APP_ID, 'PortOS'); });
+
+ // Both in the same tick: the baseline probe must not sit between the click
+ // and the dispatch, or every update pays a health round-trip of latency.
+ expect(mockCheckHealth).toHaveBeenCalled();
+ expect(emitted.some((e) => e.event === 'app:update' && e.payload.appId === PORTOS_APP_ID)).toBe(true);
+ });
+
+ it('reports `restarting` when the update takes the server down mid-run', async () => {
+ // update.sh's `pm2 delete` kills the server — and this socket — during
+ // pm2-stop, so `app:update:complete` never arrives and the operation stays
+ // "in flight" forever. Every surface reading this hook would otherwise sit
+ // on "Stopping PortOS apps..." indefinitely, even though the update
+ // finishes fine in the background and the install comes back.
+ const { result } = renderHook(() => useAppOperation({ appId: PORTOS_APP_ID }));
+ act(() => { result.current.startUpdate(PORTOS_APP_ID, 'PortOS'); });
+ expect(result.current.restarting).toBe(false);
+
+ // A raw disconnect proves nothing on its own (PortOS is used remotely over
+ // Tailscale) — the watch confirms the server is really unreachable first.
+ mockCheckHealth.mockResolvedValue(null);
+ await disconnectAndConfirm();
+
+ await waitFor(() => expect(result.current.restarting).toBe(true));
+ expect(mockToast.loading).toHaveBeenCalledWith(
+ 'PortOS is restarting...', expect.objectContaining({ id: 'portos-update-restart' }),
+ );
+ });
+
+ it('ignores a blip that leaves the server reachable', async () => {
+ const { result } = renderHook(() => useAppOperation({ appId: PORTOS_APP_ID }));
+ act(() => { result.current.startUpdate(PORTOS_APP_ID, 'PortOS'); });
+
+ // Health still answers — the socket dropped, the server did not.
+ await disconnectAndConfirm();
+
+ expect(result.current.restarting).toBe(false);
+ expect(mockToast.loading).not.toHaveBeenCalled();
+ });
+
+ it('registers no restart listeners on a surface scoped to another app', async () => {
+ // Another app's update never restarts PortOS, so that surface must neither
+ // poll for a restart that is not coming nor hold dead handlers.
+ renderHook(() => useAppOperation({ appId: 'example-managed-app' }));
+
+ expect(socketHandlers.has('disconnect')).toBe(false);
+ expect(socketHandlers.has('portos:update:step')).toBe(false);
+ });
+
+ it('does not seed a baseline for a non-PortOS update', () => {
+ const { result } = renderHook(() => useAppOperation({ appId: 'example-managed-app' }));
+
+ act(() => { result.current.startUpdate('example-managed-app', 'Example App'); });
+
+ expect(mockCheckHealth).not.toHaveBeenCalled();
+ });
+});
diff --git a/client/src/hooks/usePortosRestartWatch.js b/client/src/hooks/usePortosRestartWatch.js
new file mode 100644
index 0000000000..b9a35b5d02
--- /dev/null
+++ b/client/src/hooks/usePortosRestartWatch.js
@@ -0,0 +1,192 @@
+import { useCallback, useEffect, useRef, useState } from 'react';
+import toast from '../components/ui/Toast';
+import socket from '../services/socket';
+import * as api from '../services/api';
+import { useAutoRefetch } from './useAutoRefetch';
+import useMounted from './useMounted';
+
+const POLL_MS = 2000;
+const MAX_ATTEMPTS = 30;
+// A raw 'disconnect' is not proof the update tore the process down — PortOS is
+// commonly used remotely over Tailscale, and a network blip during the early
+// steps (git-pull/submodules, while the server is very much alive) fires one
+// too. Confirm the server is actually unreachable before arming.
+const DISCONNECT_CONFIRM_MS = 1500;
+// Slack absorbing clock jitter when comparing the server's post-restart uptime
+// against its pre-restart peak.
+const UPTIME_DROP_SLACK_S = 5;
+const TOAST_ID = 'portos-update-restart';
+
+/**
+ * Watch for PortOS restarting itself, and reload the page once it is back.
+ *
+ * Any surface that launches a PortOS self-update needs this, because there is
+ * no completion event to wait for: `update.sh` runs `pm2 delete
+ * ecosystem.config.cjs` partway through, so the server — and this socket — die
+ * well before the script reaches its 'restart' step. Without this watch the UI
+ * simply hangs on "Stopping apps..." forever while the update finishes fine in
+ * the background. The server side of that contract is
+ * `server/services/portosSelfUpdate.js`.
+ *
+ * `useAppOperation` wires this for every App Management surface, so a component
+ * updating an app gets it without asking. Call it directly only from a surface
+ * that launches a self-update WITHOUT going through an app operation — today
+ * just the Update page.
+ *
+ * Detection is deliberately over-determined, because a reconcile often lands
+ * the SAME version (new commits, no release bump) and its restart can be too
+ * fast for a 2s poll to ever sample the down window:
+ * - the version reported by /api/system/health differs from before, OR
+ * - health went down and came back, OR
+ * - the server's uptime reset below its pre-restart peak.
+ *
+ * @param {object} options
+ * @param {boolean} [options.enabled] - false skips the socket subscriptions entirely
+ * @param {boolean} [options.active] - an update this surface launched is in flight
+ * @param {() => void} [options.onRestart] - the restart was detected; stop treating the update as in-flight
+ * @param {(detail: {message: string|null}) => void} [options.onFailure] - the update reported failure instead
+ * @returns {{polling: boolean, captureBaseline: (currentVersion?: string|null) => Promise<void>, arm: () => void}}
+ */
+export function usePortosRestartWatch({ enabled = true, active = false, onRestart, onFailure } = {}) {
+ const [polling, setPolling] = useState(false);
+ const mountedRef = useMounted();
+ const activeRef = useRef(active);
+ const pollingRef = useRef(false);
+ const attemptsRef = useRef(0);
+ const preUpdateVersionRef = useRef(null);
+ // Whether health went down during this poll cycle — a down→up transition is
+ // what proves a same-version reconcile actually restarted.
+ const healthWentDownRef = useRef(false);
+ // Highest uptime seen so far, seeded by captureBaseline from the still-running
+ // server so even an instant restart reads as a drop.
+ const maxUptimeRef = useRef(0);
+ const callbacksRef = useRef({ onRestart, onFailure });
+
+ useEffect(() => { callbacksRef.current = { onRestart, onFailure }; });
+ useEffect(() => { activeRef.current = active; }, [active]);
+
+ const captureBaseline = useCallback(async (currentVersion = null) => {
+ const preHealth = await api.checkHealth().catch(() => null);
+ preUpdateVersionRef.current = currentVersion || preHealth?.version || null;
+ maxUptimeRef.current = typeof preHealth?.uptime === 'number' ? preHealth.uptime : 0;
+ }, []);
+
+ // "The server is (or is about to be) restarting — stop trusting the socket and
+ // start polling." `activeRef` is cleared SYNCHRONOUSLY (not just via the
+ // syncing effect, which only runs after the next commit) so a 'disconnect'
+ // arriving in the same tick right after this can't read a stale `true`.
+ const arm = useCallback(() => {
+ if (pollingRef.current) return;
+ activeRef.current = false;
+ pollingRef.current = true;
+ attemptsRef.current = 0;
+ healthWentDownRef.current = false;
+ setPolling(true);
+ toast.loading('PortOS is restarting...', { id: TOAST_ID, duration: Infinity });
+ callbacksRef.current.onRestart?.();
+ }, []);
+
+ const stopPolling = useCallback(() => {
+ pollingRef.current = false;
+ setPolling(false);
+ }, []);
+
+ useEffect(() => {
+ if (!enabled) return undefined;
+
+ const fail = (message) => {
+ activeRef.current = false;
+ stopPolling();
+ toast.dismiss(TOAST_ID);
+ callbacksRef.current.onFailure?.({ message });
+ };
+
+ const handleStep = ({ step, status }) => {
+ // The PM2 restart may kill the server before portos:update:complete fires,
+ // so this step is usually the last thing that reaches us.
+ if ((step === 'restarting' || step === 'restart') && status !== 'error' && activeRef.current) arm();
+ };
+
+ const handleComplete = ({ success }) => {
+ if (success === false) {
+ fail(null);
+ return;
+ }
+ if (activeRef.current) arm();
+ };
+
+ const handleError = ({ message }) => fail(message || 'Update failed');
+
+ const handleDisconnect = () => {
+ if (!activeRef.current) return;
+ setTimeout(async () => {
+ if (!activeRef.current || !mountedRef.current) return;
+ // silent: true — a failed check here just means "confirmed, arm
+ // polling"; the generic "Server unreachable" toast would otherwise fire
+ // right alongside (and ahead of) the intended "restarting" toast on the
+ // exact real-disconnect case this confirmation exists for.
+ const ok = await api.checkHealth({ silent: true }).catch(() => null);
+ if (!ok && activeRef.current && mountedRef.current) arm();
+ }, DISCONNECT_CONFIRM_MS);
+ };
+
+ socket.on('portos:update:step', handleStep);
+ socket.on('portos:update:complete', handleComplete);
+ socket.on('portos:update:error', handleError);
+ socket.on('disconnect', handleDisconnect);
+
+ return () => {
+ socket.off('portos:update:step', handleStep);
+ socket.off('portos:update:complete', handleComplete);
+ socket.off('portos:update:error', handleError);
+ socket.off('disconnect', handleDisconnect);
+ };
+ }, [arm, enabled, mountedRef, stopPolling]);
+
+ const pollHealth = useCallback(async () => {
+ attemptsRef.current += 1;
+ // silent: true — the server being unreachable is the EXPECTED state for most
+ // of this poll (that's the down→up transition it watches for), not an error;
+ // the generic toast would spam "Server unreachable" every 2s throughout the
+ // "PortOS is restarting..." loading toast's own lifetime.
+ const ok = await api.checkHealth({ silent: true }).catch(() => null);
+ const preUpdateVersion = preUpdateVersionRef.current;
+ if (!ok) {
+ // Server is mid-restart (PM2 stopped it) — record the dip so a
+ // same-version recovery still counts as "restarted".
+ healthWentDownRef.current = true;
+ } else if (preUpdateVersion && ok.version && ok.version !== preUpdateVersion) {
+ // The running version differs from before the update — restart confirmed.
+ stopPolling();
+ toast.success(`Updated to v${ok.version}`, { id: TOAST_ID });
+ setTimeout(() => window.location.reload(), 1000);
+ return;
+ } else if (
+ ok.version &&
+ (healthWentDownRef.current ||
+ (typeof ok.uptime === 'number' && ok.uptime < maxUptimeRef.current - UPTIME_DROP_SLACK_S))
+ ) {
+ // Same version, but the restart is proven either by a down→up dip or by
+ // the uptime resetting below its pre-restart peak.
+ stopPolling();
+ toast.success('Install reconciled — reloading', { id: TOAST_ID });
+ setTimeout(() => window.location.reload(), 1000);
+ return;
+ }
+ // Track the running peak so a later uptime drop is detectable. Guard on
+ // `ok` — the server-down branch falls through to here, and a null deref
+ // would throw before the timeout check below, hanging the UI on a restart
+ // that never recovers.
+ if (ok && typeof ok.uptime === 'number' && ok.uptime > maxUptimeRef.current) {
+ maxUptimeRef.current = ok.uptime;
+ }
+ if (attemptsRef.current >= MAX_ATTEMPTS) {
+ stopPolling();
+ toast.error('Restart timed out — try reloading manually', { id: TOAST_ID });
+ }
+ }, [stopPolling]);
+
+ useAutoRefetch(pollHealth, POLL_MS, { enabled: polling, pollOnly: true });
+
+ return { polling, captureBaseline, arm };
+}
diff --git a/client/src/pages/Apps.jsx b/client/src/pages/Apps.jsx
index 39009385e4..4efc77e134 100644
--- a/client/src/pages/Apps.jsx
+++ b/client/src/pages/Apps.jsx
@@ -53,7 +53,7 @@ export default function Apps() {
setLoading(false);
}, []);
- const { operations, isOperating, startUpdate, startStandardize, dismiss } = useAppOperation({ onComplete: fetchApps });
+ const { operations, isOperating, restarting, startUpdate, startStandardize, dismiss } = useAppOperation({ onComplete: fetchApps });
useEffect(() => {
fetchApps();
@@ -254,6 +254,7 @@ export default function Apps() {
steps={op.steps}
error={op.error}
completed={op.completed}
+ restarting={restarting && op.appId === api.PORTOS_APP_ID}
onDismiss={op.error || op.completed ? () => dismiss(op.appId) : null}
/>
))}
diff --git a/docs/SELF_UPDATE.md b/docs/SELF_UPDATE.md
index 3b407df194..e61d00aecd 100644
--- a/docs/SELF_UPDATE.md
+++ b/docs/SELF_UPDATE.md
@@ -2,7 +2,7 @@
How PortOS notices a new release and updates itself. PortOS is distributed software — many people run it, and a large share run it from a **personal fork**, so every step here is fork-aware. Breaking that assumption produces silent no-op updates.
-Code: `server/services/updateChecker.js`, `server/services/updateExecutor.js`, `server/services/appUpdater.js`, `server/routes/update.js`, `server/lib/gitRemote.js`, `server/lib/detachedSpawn.js`, `update.sh` / `update.ps1`, `scripts/verify-server-health.js`, `client/src/components/apps/tabs/UpdateTab.jsx`.
+Code: `server/services/updateChecker.js`, `server/services/portosSelfUpdate.js`, `server/services/updateExecutor.js`, `server/services/appUpdater.js`, `server/routes/update.js`, `server/lib/gitRemote.js`, `server/lib/detachedSpawn.js`, `update.sh` / `update.ps1`, `scripts/verify-server-health.js`, `client/src/components/apps/tabs/UpdateTab.jsx`, `client/src/hooks/usePortosRestartWatch.js`, `client/src/hooks/useAppOperation.js`.
## Release polling always targets upstream
@@ -69,9 +69,27 @@ To prevent that confusion, `POST /api/update/execute` rejects fork runs with **4
`update.sh` deletes and restarts every PortOS PM2 entry. PM2's TreeKill walks **PPID**, so a script left attached to `portos-server` is killed by its own `pm2 delete` step — mid-list, before it can run the closing `pm2 start` — and the install is left headless. `spawnDetached`'s double-fork (`server/lib/detachedSpawn.js`) is what reparents the script to init so it survives; `executeUpdate()` in `server/services/updateExecutor.js` is the single launcher that applies it, along with the `STEP:` progress parsing, the still-running-script guard, and `recordUpdateResult()`.
-**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.
+**PortOS is also a managed app**, so an update started from **App Management**'s Git tab reaches `update.sh` through `appUpdater.js` rather than `routes/update.js`. Both entry points call the same `startPortosSelfUpdate()` (`server/services/portosSelfUpdate.js`), which owns the whole lifecycle: the preflight refusals, the atomic `setUpdateInProgress(true)` lock, the post-lock re-check, and the `executeUpdate()` launch. They differ only in `mode`:
-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).
+| Surface | Mode | Gate |
+|---|---|---|
+| Update page — "Update Now" | `release` | needs a newer release tag |
+| Update page — "Reconcile Now" | `reconcile` | needs `installState.outOfSync` |
+| App Management — "Update app" | `refresh` | none; the caller has already advanced the checkout onto its origin default branch |
+
+`refresh` exists because App Management moves HEAD before handing off. Gating it on out-of-sync would only re-ask whether the pull it just did happened — and that same pull makes `update.sh`'s own `git pull` a no-op, so the script's commit-diff dependency detection sees nothing. The launcher therefore passes `installState`'s stale workspaces through as `forceCleanWorkspaces` for both non-release modes, which is what keeps deps from surviving the update (#1779).
+
+The socket path runs `checkPortosUpdatePreflight` itself before it pulls — a refusal must land before the checkout moves, and its `code` is what the panel's acknowledge-and-retry buttons key on — then passes `preflightAlreadyRun` so the launcher reads a fresh `getUpdateStatus()` (post-pull, for the stale workspaces) without re-running guards that already answered. The post-lock re-check is authoritative for both callers either way.
+
+Because the lock is taken in one place, the two entry points 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).
+
+`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.
+
+### Nothing awaits the script, on either side
+
+`startPortosSelfUpdate()` resolves as soon as the detached script is RUNNING. It cannot report the outcome, because `update.sh` `pm2 delete`s this server partway through and the process awaiting it dies there — an awaited launch simply never runs its own completion code. The Git tab used to await it, which is why it hung: `app:update:complete` never fired, the operation was never cleared, and the row sat on "Stopping PortOS apps..." forever while the update finished fine in the background. So `appUpdater` returns `{ selfUpdateStarted: true }` at the launch, and `server/sockets/apps.js` deliberately **leaves the operation registered** and emits no completion — the map dies with the process, and the remaining `STEP:` frames keep rendering right up to the moment the server goes down.
+
+The client half of that contract is `usePortosRestartWatch` (`client/src/hooks/usePortosRestartWatch.js`). **App Management surfaces do not wire it themselves** — `useAppOperation` owns it and exposes `restarting`, so every caller of `startUpdate` inherits the baseline capture and the restart detection and a new surface cannot regress to the hang by forgetting them. The Update page, which does not go through an app operation, uses the hook directly. It arms on the update stream's `restart` step, on `portos:update:complete`, or on a socket `disconnect` **confirmed unreachable** (a raw disconnect is not proof — PortOS is commonly used remotely over Tailscale, and a network blip fires one too). Once armed it polls `/api/system/health` and reloads on a version change, a down→up dip, or an uptime reset below the pre-update peak — three signals, because a reconcile often lands the same version and its restart can be too fast to sample the down window.
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 from `appUpdater`. The dashboard handoff it starts before that restart is PortOS-only — it opens the PortOS dashboard, so it would be meaningless after another app's update.
diff --git a/server/routes/update.js b/server/routes/update.js
index 5e8c930893..d5a9d94ad2 100644
--- a/server/routes/update.js
+++ b/server/routes/update.js
@@ -4,15 +4,10 @@ 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 { executeUpdate } from '../services/updateExecutor.js';
-import { withStateLock } from '../services/cosState.js';
+import { startPortosSelfUpdate } from '../services/portosSelfUpdate.js';
import {
countActiveCosAgents,
- agentsActiveError,
getPersistentMindImageWorkGuard,
- persistentMindImageWorkError,
- persistentMindStateUntrustedError,
- checkPortosUpdatePreflight,
} from '../services/updatePreflight.js';
const router = Router();
@@ -128,129 +123,18 @@ router.post('/sync-fork', asyncHandler(async (req, res) => {
router.post('/execute', asyncHandler(async (req, res) => {
const { acknowledgeFork, acknowledgePersistentMindImageBackup, reconcile } = validateRequest(executeSchema, req.body || {});
- // Never restart PortOS out from under a live CoS agent, in-flight Persistent
- // Mind image work, or an unacknowledged fork. Both a normal update and a
- // reconcile run update.sh, which pm2-restarts THIS server process and severs
- // any in-flight agent (each agent's PTY/child process is a child of it).
- // checkPortosUpdatePreflight() is shared with the App Management socket path
- // (server/sockets/apps.js `app:update`) so both entry points refuse
- // identically (#5984). Fast-fail here so it covers reconcile, normal update,
- // and both fork variants (all funnel through /execute) before doing the
- // git/fork work below; a second re-check after the lock (below) closes the
- // window an agent could start in during that work.
- const status = await checkPortosUpdatePreflight({ acknowledgeFork, acknowledgePersistentMindImageBackup });
-
- // Two distinct entry points:
- // - Normal update: requires a known, newer release tag to update TO.
- // - Reconcile (issue #1779): finishes a bare `git pull` by running update.sh
- // even with no newer release. It must be gated on the install ACTUALLY
- // being out of sync — branch on `reconcile` first so a cached release tag
- // can't let `reconcile: true` force update.sh on an in-sync install (or
- // target a stale release). update.sh pulls main regardless of the tag, so
- // the tag here is purely for logging; prefer the current version.
- let tag;
- if (reconcile) {
- if (!status.installState) {
- // installState is best-effort (.catch(() => null) in getUpdateStatus); a
- // transient git/fs hiccup shouldn't read as "already in sync".
- throw new ServerError('Could not determine install state — try again', { status: 503, code: 'INSTALL_STATE_UNAVAILABLE' });
- }
- if (!status.installState.outOfSync) {
- throw new ServerError('Install is already in sync — nothing to reconcile', { status: 400, code: 'ALREADY_IN_SYNC' });
- }
- tag = `v${status.currentVersion}`;
- } else {
- if (!status.latestRelease?.tag) {
- throw new ServerError('No release available to update to', { status: 400, code: 'NO_RELEASE' });
- }
- tag = status.latestRelease.tag;
- }
-
- // Validate tag is a well-formed semver release (e.g. "v1.27.0" or "v1.27.0-rc.1") to prevent option injection
- if (!/^v\d+\.\d+\.\d+(-[a-zA-Z0-9.]+)?$/.test(tag)) {
- throw new ServerError('Invalid release tag format', { status: 400, code: 'INVALID_TAG' });
- }
-
- // Atomic check-and-set: rejects if already in progress, preventing concurrent updates
- const acquired = await updateChecker.setUpdateInProgress(true);
- if (!acquired) {
- throw new ServerError('Update already in progress', { status: 409, code: 'UPDATE_IN_PROGRESS' });
- }
-
- // Re-check after acquiring the lock: an agent (e.g. a scheduled/autopilot
- // spawn) may have started live during the git/fork awaits between the
- // fast-fail pre-check and here. If so, release the lock and reject rather than
- // restart out from under it. A spawn that begins AFTER this, during update.sh
- // itself, is closed from the spawn side: the lock we just acquired flips
- // `updateChecker.isUpdateInProgress()`, which subAgentSpawner's `task:ready`
- // listener and `spawnAgentForTask` both check, holding the task as `pending`
- // until after the restart (issue #4124).
- const postLock = await countActiveCosAgents();
- if (postLock > 0) {
- await updateChecker.setUpdateInProgress(false);
- throw agentsActiveError(postLock);
- }
- const postLockImageCheck = await withStateLock(() => getPersistentMindImageWorkGuard()).catch(async (error) => {
- await updateChecker.setUpdateInProgress(false);
- throw error;
- });
- if (!postLockImageCheck.trusted || (!postLockImageCheck.safe && !acknowledgePersistentMindImageBackup)) {
- await updateChecker.setUpdateInProgress(false);
- if (!postLockImageCheck.trusted) throw persistentMindStateUntrustedError();
- throw persistentMindImageWorkError(postLockImageCheck);
- }
-
- const io = req.app.get('io');
-
- // Start update in background, stream progress via socket
- const emit = (step, stepStatus, message) => {
- if (io) {
- io.emit('portos:update:step', { step, status: stepStatus, message, timestamp: Date.now() });
- }
- };
-
- // Don't await — respond immediately, progress streams via socket.
- // The update script runs `git pull --rebase` to get the latest code,
- // so the actual post-update version may differ from `tag` if new commits
- // landed after the release. The script writes the true version to
- // data/update-complete.json, which the server reads on boot.
- //
- // For a reconcile, hand the updater the workspaces whose installed deps are
- // stale (per installState's receipt check) so it force-reinstalls exactly
- // those — a bare `git pull` (possibly already restarted) leaves the scripts'
- // commit-diff dependency detection empty. 'root' maps to update.sh's '.' token.
- const forceCleanWorkspaces = reconcile
- ? (status.installState.staleDeps?.workspaces || [])
- .filter(w => w.stale)
- .map(w => (w.name === 'root' ? '.' : w.name))
- : undefined;
- executeUpdate(tag, emit, { forceCleanWorkspaces }).then(result => {
- // Note: this .then() may never fire if the update script's PM2 restart
- // kills this server process first. The client handles this by polling
- // /api/system/health after receiving the 'restart' step.
- if (io) {
- if (result.success) {
- io.emit('portos:update:complete', { success: true, newVersion: result.version || tag.replace(/^v/, ''), versionKnown: !!result.version });
- } else {
- io.emit('portos:update:error', { message: result.errorMessage ?? 'Update failed', step: result.failedStep ?? 'unknown' });
- }
- }
- }).catch(async err => {
- console.error(`❌ Update launch failed for ${tag}: ${err.message}`);
- if (io) {
- io.emit('portos:update:error', { message: err.message, step: 'unknown' });
- }
- // A rejection means executeUpdate never reached `recordUpdateResult`, which
- // is what normally clears the lock on both its resolved outcomes. Without
- // this release the lock we acquired above stays set until the 30-minute
- // stale timeout — wedging every later update at 409 UPDATE_IN_PROGRESS and
- // blocking every CoS agent spawn in the meantime (issue #6036).
- await updateChecker.setUpdateInProgress(false).catch(releaseErr => {
- console.error(`❌ Failed to release update lock after launch failure: ${releaseErr.message}`);
- });
+ // Every refusal, the update lock, and the fire-and-forget launch live in
+ // `portosSelfUpdate` — shared with App Management's Git tab so both entry
+ // points into update.sh behave identically (#5984, and the Git tab hang the
+ // shared launcher was extracted to fix).
+ const { started, tag } = await startPortosSelfUpdate({
+ io: req.app.get('io'),
+ acknowledgeFork,
+ acknowledgePersistentMindImageBackup,
+ mode: reconcile ? 'reconcile' : 'release',
});
- res.json({ started: true, tag });
+ res.json({ started, tag });
}));
export default router;
diff --git a/server/services/appUpdater.js b/server/services/appUpdater.js
index 6be5fd9ff0..ad8a99fb37 100644
--- a/server/services/appUpdater.js
+++ b/server/services/appUpdater.js
@@ -9,8 +9,7 @@ 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 { startPortosSelfUpdate } from './portosSelfUpdate.js';
import { syncManagedAppFork } from './managedAppRepositories.js';
const CMD_TIMEOUT_MS = 5 * 60 * 1000;
@@ -112,15 +111,21 @@ function isSamePath(a, b) {
* whose lifecycle does not resemble PortOS.
*
* PortOS itself is a managed app, and its comprehensive update.sh/update.ps1
- * lifecycle is delegated to `updateExecutor` — which also owns the restart and
- * the dashboard handoff for that case. See the app-update step in `_doUpdate`.
+ * lifecycle is delegated to `portosSelfUpdate` — the same launcher the Update
+ * page uses — which owns the restart and the dashboard handoff for that case.
+ * That branch resolves as soon as the detached script is RUNNING and reports
+ * `selfUpdateStarted`, because this process does not outlive the script's
+ * `pm2 delete`.
*
* @param {object} app - The app object (must have repoPath, pm2ProcessNames, pm2Home)
* @param {function} emit - Callback (step, status, message) for progress updates
- * @param {{syncFork?: boolean}} options
- * @returns {Promise<{success: boolean, steps: object[]}>}
+ * @param {object} [options]
+ * @param {boolean} [options.syncFork] - fast-forward the origin fork first
+ * @param {boolean} [options.acknowledgeFork] - PortOS preflight acknowledgement
+ * @param {boolean} [options.acknowledgePersistentMindImageBackup] - PortOS preflight acknowledgement
+ * @returns {Promise<{success: boolean, steps: object[], selfUpdateStarted?: boolean}>}
*/
-export async function updateApp(app, emit, { syncFork = false } = {}) {
+export async function updateApp(app, emit, options = {}) {
const dir = app.repoPath;
if (updatingApps.has(dir)) {
return { success: false, steps: [{ step: 'lock', success: false, message: 'Update already in progress' }] };
@@ -128,13 +133,17 @@ export async function updateApp(app, emit, { syncFork = false } = {}) {
updatingApps.add(dir);
try {
- return await _doUpdate(app, emit, { syncFork });
+ return await _doUpdate(app, emit, options);
} finally {
updatingApps.delete(dir);
}
}
-async function _doUpdate(app, emit, { syncFork }) {
+async function _doUpdate(app, emit, {
+ syncFork = false,
+ acknowledgeFork = false,
+ acknowledgePersistentMindImageBackup = false,
+}) {
const dir = app.repoPath;
const steps = [];
const packageManager = app.type === 'bun' ? 'bun' : 'npm';
@@ -214,39 +223,30 @@ async function _doUpdate(app, emit, { syncFork }) {
emit('app-update', 'running', 'Running the app update routine...');
if (detachSelfUpdate) {
// PortOS is itself a managed app, so an App Management update reaches
- // update.sh through THIS path — and the script's own
- // `pm2 delete ecosystem.config.cjs` step tree-kills portos-server.
- // PM2 walks PPID, so an attached spawn dies with the server it just
- // deleted, taking the in-flight `pm2 delete` with it and never reaching
- // the closing `pm2 start`: the install is left headless, with only the
- // entries declared after portos-cos still online (#5976).
+ // update.sh through THIS path. `portosSelfUpdate` owns everything about
+ // launching that script — including why nothing may await it — and this
+ // returns the moment it is running. Read that module before changing this.
//
- // updateExecutor already owns the double-fork launch that survives that,
- // plus the STEP: progress parsing that maps straight onto this emit
- // contract, the still-running-script guard and recordUpdateResult — so
- // 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';
- // 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;
+ // `refresh`, not `reconcile`: the git-pull step above already advanced
+ // this checkout, so the out-of-sync gate would only be re-asking whether
+ // the pull we just did happened.
+ //
+ // No `io`: App Management renders the run from its own `app:update:step`
+ // frames (`onStep`), so mirroring the whole stream onto
+ // `portos:update:*` as well would double the fan-out for no new reader.
+ await startPortosSelfUpdate({
+ acknowledgeFork,
+ acknowledgePersistentMindImageBackup,
+ preflightAlreadyRun: true,
+ mode: 'refresh',
+ onStep: emit,
});
- if (!outcome.success) {
- throw new Error(outcome.errorMessage || `PortOS update failed at step "${outcome.failedStep || 'unknown'}"`);
- }
- } else {
- await runCommand(command.baseCommand, command.args, dir);
+ const launched = 'PortOS update running — this process restarts as part of it';
+ emit('app-update', 'running', launched);
+ steps.push({ step: 'app-update', success: true, message: launched });
+ return { success: true, steps, selfUpdateStarted: true };
}
+ await runCommand(command.baseCommand, command.args, dir);
emit('app-update', 'done', 'App update routine complete');
steps.push({ step: 'app-update', success: true });
}
diff --git a/server/services/appUpdater.test.js b/server/services/appUpdater.test.js
index 2e212293a5..1425a6ad65 100644
--- a/server/services/appUpdater.test.js
+++ b/server/services/appUpdater.test.js
@@ -4,14 +4,13 @@ import { join } from 'path';
import { tmpdir } from 'os';
const mock = vi.hoisted(() => ({
- // updateExecutor resolves update.sh from PATHS.root, so the delegation is
- // gated on the app record pointing at this checkout — point it at the
+ // The shared launcher resolves update.sh from PATHS.root, so the delegation
+ // is gated on the app record pointing at this checkout — point it at the
// per-test temp repo instead.
paths: { root: '' },
updateDefaultBranch: vi.fn(),
spawn: vi.fn(),
- executeUpdate: vi.fn(),
- setUpdateInProgress: vi.fn(),
+ startPortosSelfUpdate: vi.fn(),
dashboardOpen: vi.fn(),
dashboardRunning: vi.fn(),
dashboardHandle: { on: vi.fn() },
@@ -29,8 +28,7 @@ vi.mock('../lib/bufferedSpawn.js', async (importOriginal) => {
const actual = await importOriginal();
return { ...actual, bufferedSpawnOrThrow: mock.spawn };
});
-vi.mock('./updateExecutor.js', () => ({ executeUpdate: mock.executeUpdate }));
-vi.mock('./updateChecker.js', () => ({ setUpdateInProgress: mock.setUpdateInProgress }));
+vi.mock('./portosSelfUpdate.js', () => ({ startPortosSelfUpdate: mock.startPortosSelfUpdate }));
vi.mock('../lib/detachedSpawn.js', () => ({
isDetachedRunning: mock.dashboardRunning,
spawnDetached: mock.dashboardOpen,
@@ -51,8 +49,7 @@ describe('managed app updates', () => {
await writeFile(join(repo, 'client', 'package.json'), JSON.stringify({}));
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.startPortosSelfUpdate.mockResolvedValue({ started: true, tag: 'v9.9.9' });
mock.dashboardRunning.mockResolvedValue(false);
mock.dashboardOpen.mockResolvedValue(mock.dashboardHandle);
mock.restart.mockResolvedValue({ success: true });
@@ -109,11 +106,13 @@ describe('managed app updates', () => {
);
});
- it('launches PortOS\'s own update through the detached executor, never the attached spawn', async () => {
+ it('hands PortOS\'s own update to the shared launcher and returns without awaiting update.sh', async () => {
// PortOS is a managed app, so App Management updates route through here —
// and update.sh's `pm2 delete` tree-kills the server that would be this
// spawn's PPID parent, taking the script down mid-delete (#5976). The
- // detached launcher in updateExecutor is what survives it.
+ // shared launcher owns the detached spawn that survives it, the preflight
+ // and the update lock; this path must not re-roll any of them, and must
+ // not await a script that outlives the process awaiting it.
await writeFile(join(repo, 'update.sh'), '#!/bin/sh\nexit 0\n');
await writeFile(join(repo, 'update.ps1'), 'exit 0\n');
await writeFile(join(repo, 'package.json'), JSON.stringify({ version: '2.56.0' }));
@@ -125,17 +124,27 @@ describe('managed app updates', () => {
type: 'express',
repoPath: repo,
pm2ProcessNames: ['portos-server', 'portos-cos', 'portos-browser'],
- }, emit);
-
- expect(result.success).toBe(true);
- expect(mock.executeUpdate).toHaveBeenCalledWith('2.56.0', emit);
+ }, emit, { acknowledgeFork: true });
+
+ expect(result).toMatchObject({ success: true, selfUpdateStarted: true });
+ // `refresh`, because the git-pull step above already moved the checkout —
+ // a reconcile's out-of-sync gate would only be re-asking whether that pull
+ // happened. No `io`: App Management renders the run from `onStep`, and
+ // mirroring the same frames onto portos:update:* would double the fan-out.
+ expect(mock.startPortosSelfUpdate).toHaveBeenCalledWith({
+ acknowledgeFork: true,
+ acknowledgePersistentMindImageBackup: false,
+ preflightAlreadyRun: true,
+ mode: 'refresh',
+ onStep: 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');
+ // Never "done": the script is still running, and claiming completion is
+ // what let the Git tab clear its progress row mid-update.
+ expect(emit).not.toHaveBeenCalledWith('app-update', 'done', expect.anything());
+ expect(emit).toHaveBeenCalledWith(
+ 'app-update', 'running', 'PortOS update running — this process restarts as part of it',
+ );
});
it('leaves the PM2 restart to update.sh instead of double-restarting PortOS', async () => {
@@ -158,10 +167,13 @@ describe('managed app updates', () => {
expect(mock.dashboardOpen).not.toHaveBeenCalled();
});
- it('surfaces a failed PortOS update instead of reporting success', async () => {
+ it('surfaces a refused PortOS update instead of reporting success', async () => {
+ // Only the LAUNCH is awaited, so the failures this path can still report
+ // are the launcher's own refusals (preflight, the lock, a spawn that never
+ // started) — not a step the script failed at after the process was gone.
await writeFile(join(repo, 'update.sh'), '#!/bin/sh\nexit 1\n');
await writeFile(join(repo, 'update.ps1'), 'exit 1\n');
- mock.executeUpdate.mockResolvedValue({ success: false, failedStep: 'npm-install', errorMessage: 'Update failed at step "npm-install" (exit code 1)' });
+ mock.startPortosSelfUpdate.mockRejectedValue(new Error('1 CoS agent is running'));
await expect(updateApp({
id: 'portos-default',
@@ -169,15 +181,16 @@ describe('managed app updates', () => {
type: 'express',
repoPath: repo,
pm2ProcessNames: ['portos-server'],
- }, vi.fn())).rejects.toThrow('Update failed at step "npm-install" (exit code 1)');
+ }, vi.fn())).rejects.toThrow('1 CoS agent is running');
});
- 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.
+ it('propagates the shared launcher\'s "already in progress" refusal', async () => {
+ // The atomic lock now lives in the launcher, shared with
+ // POST /api/update/execute — the two entry points into update.sh must not
+ // launch it concurrently, and this path must not swallow that refusal.
await writeFile(join(repo, 'update.sh'), '#!/bin/sh\nexit 0\n');
await writeFile(join(repo, 'update.ps1'), 'exit 0\n');
- mock.setUpdateInProgress.mockResolvedValue(false);
+ mock.startPortosSelfUpdate.mockRejectedValue(new Error('Update already in progress'));
await expect(updateApp({
id: 'portos-default',
@@ -186,8 +199,6 @@ describe('managed app updates', () => {
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 () => {
@@ -205,7 +216,7 @@ describe('managed app updates', () => {
pm2ProcessNames: ['portos-server'],
}, vi.fn());
- expect(mock.executeUpdate).toHaveBeenCalled();
+ expect(mock.startPortosSelfUpdate).toHaveBeenCalled();
expect(mock.spawn).not.toHaveBeenCalled();
});
@@ -225,7 +236,7 @@ describe('managed app updates', () => {
pm2ProcessNames: ['portos-server'],
}, vi.fn());
- expect(mock.executeUpdate).not.toHaveBeenCalled();
+ expect(mock.startPortosSelfUpdate).not.toHaveBeenCalled();
expect(mock.spawn).toHaveBeenCalled();
expect(mock.restart).toHaveBeenCalledWith('portos-server', undefined);
});
@@ -244,7 +255,7 @@ describe('managed app updates', () => {
pm2ProcessNames: ['example-app'],
}, vi.fn());
- expect(mock.executeUpdate).not.toHaveBeenCalled();
+ expect(mock.startPortosSelfUpdate).not.toHaveBeenCalled();
expect(mock.spawn).toHaveBeenCalled();
expect(mock.restart).toHaveBeenCalledWith('example-app', undefined);
});
@@ -264,7 +275,7 @@ describe('managed app updates', () => {
pm2ProcessNames: ['portos-server'],
}, vi.fn());
- expect(mock.executeUpdate).not.toHaveBeenCalled();
+ expect(mock.startPortosSelfUpdate).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
diff --git a/server/services/portosSelfUpdate.js b/server/services/portosSelfUpdate.js
new file mode 100644
index 0000000000..76f47a0fcf
--- /dev/null
+++ b/server/services/portosSelfUpdate.js
@@ -0,0 +1,214 @@
+/**
+ * The single launcher for PortOS's own update.sh / update.ps1.
+ *
+ * Two surfaces start a PortOS self-update — the Update page
+ * (`POST /api/update/execute`) and App Management's Git tab (the `app:update`
+ * socket handler for the PortOS app record) — and they used to carry two
+ * different implementations of the same lifecycle. The Update page's version
+ * was the correct one, so it is the one that lives here and both callers now
+ * share it:
+ *
+ * 1. Refuse the update (preflight) before touching anything.
+ * 2. Resolve the release tag the run is labelled with.
+ * 3. Take the atomic `updateInProgress` lock, then re-check the guards that
+ * could have gone live during step 1-2's awaits.
+ * 4. Launch `executeUpdate` and RETURN — never await it.
+ *
+ * Step 4 is the whole point. `update.sh` deletes this server's PM2 entries
+ * partway through, so the process that launched it is killed long before the
+ * script reaches its closing `pm2 start`. `executeUpdate`'s double-fork keeps
+ * the SCRIPT alive across that (see `server/lib/detachedSpawn.js`), but nothing
+ * can keep the awaiting caller alive — so a caller that awaits it simply never
+ * runs its own completion code, and any UI waiting on that completion hangs on
+ * "Stopping apps..." forever even though the install came back fine. The
+ * client side of the contract is `usePortosRestartWatch`, which watches the
+ * step stream and the health endpoint rather than a completion event.
+ */
+
+import { ServerError } from '../lib/errorHandler.js';
+import { withStateLock } from './cosState.js';
+import { executeUpdate } from './updateExecutor.js';
+import * as updateChecker from './updateChecker.js';
+import {
+ agentsActiveError,
+ checkPortosUpdatePreflight,
+ countActiveCosAgents,
+ getPersistentMindImageWorkGuard,
+ persistentMindImageWorkError,
+ persistentMindStateUntrustedError,
+} from './updatePreflight.js';
+
+// Well-formed semver release tag (e.g. "v1.27.0" or "v1.27.0-rc.1"). The tag
+// reaches a shell script, so anything option-shaped is refused outright.
+const TAG_PATTERN = /^v\d+\.\d+\.\d+(-[a-zA-Z0-9.]+)?$/;
+
+/**
+ * Which run this is, and therefore what the caller is allowed to launch:
+ *
+ * - `release` — update TO a newer GitHub release. Requires a known release tag.
+ * - `reconcile` — finish a half-updated install (issue #1779): run update.sh
+ * even with no newer release. Gated on the install ACTUALLY
+ * being out of sync, so a cached release tag can't force
+ * update.sh onto an install that has nothing to do.
+ * - `refresh` — run the lifecycle over whatever is on disk NOW. For a caller
+ * that has already advanced the checkout itself: the state a
+ * reconcile's gate looks for is the state that caller just
+ * created, so re-checking it would only ask whether its own
+ * pull happened.
+ *
+ * Refusals only; the tag comes from `resolveTag` below.
+ */
+function assertCanRun(status, mode) {
+ if (mode === 'release' && !status.latestRelease?.tag) {
+ throw new ServerError('No release available to update to', { status: 400, code: 'NO_RELEASE' });
+ }
+ if (mode !== 'reconcile') return;
+ if (!status.installState) {
+ // installState is best-effort (.catch(() => null) in getUpdateStatus); a
+ // transient git/fs hiccup shouldn't read as "already in sync".
+ throw new ServerError('Could not determine install state — try again', { status: 503, code: 'INSTALL_STATE_UNAVAILABLE' });
+ }
+ if (!status.installState.outOfSync) {
+ throw new ServerError('Install is already in sync — nothing to reconcile', { status: 400, code: 'ALREADY_IN_SYNC' });
+ }
+}
+
+/**
+ * The tag this run is labelled with. update.sh pulls the default branch
+ * regardless of it, so outside `release` it is purely what the run is logged
+ * and reported under.
+ */
+function resolveTag(status, mode) {
+ return mode === 'release' ? status.latestRelease.tag : `v${status.currentVersion}`;
+}
+
+/**
+ * Workspaces whose installed deps are stale per installState's receipt check.
+ *
+ * update.sh decides what to reinstall from the commit diff its OWN `git pull`
+ * produced — so when HEAD already advanced before the script ran, that diff is
+ * empty and the stale node_modules survive the update (#1779). Naming the
+ * workspaces here forces a from-scratch reinstall of exactly those. 'root' maps
+ * to update.sh's '.' token.
+ */
+function forceCleanWorkspacesFor(status) {
+ return (status.installState?.staleDeps?.workspaces || [])
+ .filter(w => w.stale)
+ .map(w => (w.name === 'root' ? '.' : w.name));
+}
+
+/**
+ * Refuse, lock, and launch a PortOS self-update. Resolves as soon as the
+ * detached script is running — NOT when the update finishes.
+ *
+ * @param {object} options
+ * @param {object} [options.io] - Socket.IO server for `portos:update:*` frames.
+ * Omit on a caller that renders the run from `onStep` alone — mirroring the
+ * whole stream onto both channels doubles the fan-out for no new reader.
+ * @param {boolean} [options.acknowledgeFork]
+ * @param {boolean} [options.acknowledgePersistentMindImageBackup]
+ * @param {boolean} [options.preflightAlreadyRun] - the caller ran
+ * `checkPortosUpdatePreflight` itself (to refuse BEFORE touching the checkout,
+ * and to report the refusal code its UI offers an acknowledgement for), so
+ * re-running the guards here would re-read the whole CoS state and re-walk
+ * every dep receipt for an answer already given. The post-lock re-check below
+ * is the authoritative one either way.
+ * @param {'release'|'reconcile'|'refresh'} [options.mode]
+ * @param {(step: string, status: string, message: string) => void} [options.onStep]
+ * Extra progress sink, for a caller with its own step stream.
+ * @returns {Promise<{started: true, tag: string}>}
+ */
+export async function startPortosSelfUpdate({
+ io,
+ acknowledgeFork = false,
+ acknowledgePersistentMindImageBackup = false,
+ preflightAlreadyRun = false,
+ mode = 'release',
+ onStep,
+} = {}) {
+ // Never restart PortOS out from under a live CoS agent, in-flight Persistent
+ // Mind image work, or an unacknowledged fork. Fast-fail before the lock so
+ // every mode is covered before doing the work below; the post-lock re-check
+ // closes the window an agent could start in during it. The status is re-read
+ // even when the guards are skipped: a caller that already ran them did so
+ // before advancing the checkout, so its snapshot predates the pull whose
+ // stale workspaces this run has to clean.
+ const status = preflightAlreadyRun
+ ? await updateChecker.getUpdateStatus()
+ : await checkPortosUpdatePreflight({ acknowledgeFork, acknowledgePersistentMindImageBackup });
+
+ assertCanRun(status, mode);
+ const tag = resolveTag(status, mode);
+ if (!TAG_PATTERN.test(tag)) {
+ throw new ServerError('Invalid release tag format', { status: 400, code: 'INVALID_TAG' });
+ }
+
+ // Atomic check-and-set: rejects if already in progress, preventing concurrent
+ // updates. Holding it is also what keeps CoS agent spawns off a process
+ // update.sh is about to `pm2 delete` (#4124) — `subAgentSpawner`,
+ // `agentLifecycle` and `persistentMindSupervisor` all gate on it.
+ const acquired = await updateChecker.setUpdateInProgress(true);
+ if (!acquired) {
+ throw new ServerError('Update already in progress', { status: 409, code: 'UPDATE_IN_PROGRESS' });
+ }
+
+ // Re-check after acquiring the lock: an agent (e.g. a scheduled/autopilot
+ // spawn) may have started live during the awaits above. If so, release the
+ // lock and reject rather than restart out from under it. A spawn that begins
+ // AFTER this, during update.sh itself, is closed from the spawn side by the
+ // lock we just took.
+ const postLock = await countActiveCosAgents();
+ if (postLock > 0) {
+ await updateChecker.setUpdateInProgress(false);
+ throw agentsActiveError(postLock);
+ }
+ const postLockImageCheck = await withStateLock(() => getPersistentMindImageWorkGuard()).catch(async (error) => {
+ await updateChecker.setUpdateInProgress(false);
+ throw error;
+ });
+ if (!postLockImageCheck.trusted || (!postLockImageCheck.safe && !acknowledgePersistentMindImageBackup)) {
+ await updateChecker.setUpdateInProgress(false);
+ if (!postLockImageCheck.trusted) throw persistentMindStateUntrustedError();
+ throw persistentMindImageWorkError(postLockImageCheck);
+ }
+
+ const emit = (step, stepStatus, message) => {
+ if (io) {
+ io.emit('portos:update:step', { step, status: stepStatus, message, timestamp: Date.now() });
+ }
+ onStep?.(step, stepStatus, message);
+ };
+
+ const forceCleanWorkspaces = mode === 'release' ? undefined : forceCleanWorkspacesFor(status);
+
+ // Deliberately not awaited — see the module header. The script writes the
+ // true post-update version to data/update-complete.json, which the server
+ // reads on boot, so `tag` is only the label this launch is reported under.
+ executeUpdate(tag, emit, { forceCleanWorkspaces }).then(result => {
+ // May never fire: update.sh's PM2 delete usually kills this process first.
+ // The client polls /api/system/health instead of relying on it.
+ if (!io) return;
+ if (result.success) {
+ io.emit('portos:update:complete', {
+ success: true,
+ newVersion: result.version || tag.replace(/^v/, ''),
+ versionKnown: !!result.version,
+ });
+ } else {
+ io.emit('portos:update:error', { message: result.errorMessage ?? 'Update failed', step: result.failedStep ?? 'unknown' });
+ }
+ }).catch(async err => {
+ console.error(`❌ Update launch failed for ${tag}: ${err.message}`);
+ io?.emit('portos:update:error', { message: err.message, step: 'unknown' });
+ // A rejection means executeUpdate never reached `recordUpdateResult`, which
+ // is what normally clears the lock on both its resolved outcomes. Without
+ // this release the lock stays set until the 30-minute stale timeout —
+ // wedging every later update at 409 UPDATE_IN_PROGRESS and blocking every
+ // CoS agent spawn in the meantime (issue #6036).
+ await updateChecker.setUpdateInProgress(false).catch(releaseErr => {
+ console.error(`❌ Failed to release update lock after launch failure: ${releaseErr.message}`);
+ });
+ });
+
+ return { started: true, tag };
+}
diff --git a/server/services/portosSelfUpdate.test.js b/server/services/portosSelfUpdate.test.js
new file mode 100644
index 0000000000..4099469715
--- /dev/null
+++ b/server/services/portosSelfUpdate.test.js
@@ -0,0 +1,132 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+// The release and reconcile modes are already driven end-to-end through
+// POST /api/update/execute in routes/update.test.js. This suite covers what
+// only App Management's Git tab reaches: `refresh` mode, which exists because
+// that path pulls the checkout onto its origin default branch BEFORE handing
+// off — and the assumptions both other modes rely on then stop holding.
+vi.mock('./updateChecker.js', () => ({
+ getUpdateStatus: vi.fn(),
+ setUpdateInProgress: vi.fn().mockResolvedValue(true),
+}));
+vi.mock('./updateExecutor.js', () => ({
+ executeUpdate: vi.fn().mockResolvedValue({ success: true, version: '1.26.0' }),
+}));
+const { mockSpawningTasks } = vi.hoisted(() => ({ mockSpawningTasks: new Set() }));
+vi.mock('./agentState.js', () => ({
+ getActiveAgentIds: vi.fn().mockReturnValue([]),
+ spawningTasks: mockSpawningTasks,
+}));
+vi.mock('./cosAgentLifecycle.js', () => ({ filterLiveAgentIds: vi.fn(async (ids) => ids) }));
+vi.mock('./cosState.js', () => ({
+ readPersistentMindStateForSafetyCheck: vi.fn(async () => ({
+ trusted: true,
+ persistentMind: { queuedMessages: [], activeTurn: null },
+ })),
+ withStateLock: vi.fn(async (fn) => fn()),
+}));
+
+import * as updateChecker from './updateChecker.js';
+import { executeUpdate } from './updateExecutor.js';
+import { startPortosSelfUpdate } from './portosSelfUpdate.js';
+
+// An install with nothing pending and no newer release — the state a reconcile
+// refuses outright.
+const inSyncStatus = (overrides = {}) => ({
+ currentVersion: '1.26.0',
+ latestRelease: null,
+ remoteInfo: { isFork: false, hasOrigin: true, fullName: 'atomantic/PortOS' },
+ upstream: { fullName: 'atomantic/PortOS' },
+ forkSyncFresh: false,
+ installState: { outOfSync: false, staleDeps: { stale: false, workspaces: [] } },
+ ...overrides,
+});
+
+describe('startPortosSelfUpdate — refresh mode', () => {
+ const io = { emit: vi.fn() };
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mockSpawningTasks.clear();
+ updateChecker.setUpdateInProgress.mockResolvedValue(true);
+ updateChecker.getUpdateStatus.mockResolvedValue(inSyncStatus());
+ executeUpdate.mockResolvedValue({ success: true, version: '1.26.0' });
+ });
+
+ it('runs on an in-sync install, where a reconcile would refuse', async () => {
+ // The Git tab has already pulled the checkout by the time it hands off, so
+ // gating on "is the install out of sync?" would only be re-asking whether
+ // that pull happened — and getUpdateStatus can still report the pre-pull
+ // snapshot. A refusal here is what would leave the user's explicit "Update
+ // app" doing nothing.
+ await expect(startPortosSelfUpdate({ io, mode: 'reconcile' }))
+ .rejects.toThrow(/already in sync/i);
+
+ const result = await startPortosSelfUpdate({ io, mode: 'refresh' });
+
+ expect(result).toEqual({ started: true, tag: 'v1.26.0' });
+ expect(executeUpdate).toHaveBeenCalledOnce();
+ });
+
+ it('force-cleans the workspaces whose deps are stale, since update.sh sees no commit diff', async () => {
+ // update.sh decides what to reinstall from the diff its OWN `git pull`
+ // produces. The Git tab already advanced HEAD, so that diff is empty and
+ // stale node_modules would survive the update (#1779) unless the workspaces
+ // are named explicitly. 'root' maps to update.sh's '.' token.
+ updateChecker.getUpdateStatus.mockResolvedValue(inSyncStatus({
+ installState: {
+ outOfSync: true,
+ staleDeps: {
+ stale: true,
+ workspaces: [
+ { name: 'root', stale: true },
+ { name: 'client', stale: true },
+ { name: 'server', stale: false },
+ ],
+ },
+ },
+ }));
+
+ await startPortosSelfUpdate({ io, mode: 'refresh' });
+
+ expect(executeUpdate).toHaveBeenCalledWith(
+ 'v1.26.0',
+ expect.any(Function),
+ { forceCleanWorkspaces: ['.', 'client'] },
+ );
+ });
+
+ it('mirrors every step to the caller as well as the portos:update:step bus', async () => {
+ // App Management renders the run in its own `app:update:step` frames, so
+ // the launcher has to feed both sinks — otherwise the Git tab's progress
+ // row stays empty for the whole update.
+ const onStep = vi.fn();
+ executeUpdate.mockImplementation(async (_tag, emit) => {
+ emit('pm2-stop', 'running', 'Stopping PortOS apps...');
+ return { success: true, version: '1.26.0' };
+ });
+
+ await startPortosSelfUpdate({ io, mode: 'refresh', onStep });
+ await vi.waitFor(() => expect(onStep).toHaveBeenCalled());
+
+ expect(onStep).toHaveBeenCalledWith('pm2-stop', 'running', 'Stopping PortOS apps...');
+ expect(io.emit).toHaveBeenCalledWith('portos:update:step', expect.objectContaining({
+ step: 'pm2-stop',
+ status: 'running',
+ }));
+ });
+
+ it('releases the update lock when the launch itself rejects', async () => {
+ // executeUpdate clears the flag through recordUpdateResult on both of its
+ // RESOLVED outcomes; a rejection reports none, and the stuck flag then
+ // wedges every later update and every CoS agent spawn (#6036).
+ executeUpdate.mockRejectedValue(new Error('spawn EACCES'));
+
+ await startPortosSelfUpdate({ io, mode: 'refresh' });
+
+ await vi.waitFor(() => expect(updateChecker.setUpdateInProgress).toHaveBeenCalledWith(false));
+ expect(io.emit).toHaveBeenCalledWith('portos:update:error', expect.objectContaining({
+ message: 'spawn EACCES',
+ }));
+ });
+});
diff --git a/server/services/socket.test.js b/server/services/socket.test.js
index 5810456a97..cbeaa81642 100644
--- a/server/services/socket.test.js
+++ b/server/services/socket.test.js
@@ -785,7 +785,9 @@ describe('socket.js — initSocket', () => {
await socket.handlers['app:update']({ appId: APP.id, syncFork: true });
await flush();
expect(vi.mocked(runAppUpdate)).toHaveBeenCalledTimes(2);
- expect(vi.mocked(runAppUpdate).mock.calls.at(-1)[2]).toEqual({ syncFork: true });
+ expect(vi.mocked(runAppUpdate).mock.calls.at(-1)[2]).toEqual({
+ syncFork: true, acknowledgeFork: false, acknowledgePersistentMindImageBackup: false,
+ });
});
// The HTTP route that used to own these two calls is gone; the socket is the
diff --git a/server/services/updatePreflightParity.test.js b/server/services/updatePreflightParity.test.js
index 27e740897e..3e7a712b48 100644
--- a/server/services/updatePreflightParity.test.js
+++ b/server/services/updatePreflightParity.test.js
@@ -167,7 +167,9 @@ describe('PortOS update preflight parity — route vs. socket', () => {
appUpdaterUpdateApp.mockResolvedValue({ success: true, steps: [] });
const { fireUpdate: fireAckUpdate } = makeSocketHarness();
await fireAckUpdate({ appId: PORTOS_APP_ID, acknowledgeFork: true });
- expect(appUpdaterUpdateApp).toHaveBeenCalledWith(portosApp, expect.any(Function), { syncFork: false });
+ expect(appUpdaterUpdateApp).toHaveBeenCalledWith(portosApp, expect.any(Function), {
+ syncFork: false, acknowledgeFork: true, acknowledgePersistentMindImageBackup: false,
+ });
});
it('a non-PortOS app is never subject to the PortOS preflight', async () => {
diff --git a/server/sockets/apps.js b/server/sockets/apps.js
index 74e3c02368..da484d52b7 100644
--- a/server/sockets/apps.js
+++ b/server/sockets/apps.js
@@ -37,6 +37,11 @@ const beginAppOperation = (io, app, type) => {
return operation;
};
+// A PortOS self-update deliberately leaves its operation registered: the
+// process is about to be replaced, so the map dies with it. A test driving that
+// path has no process boundary, so it needs a way back to an empty set.
+export const __resetAppOperations = () => activeAppOperations.clear();
+
const endAppOperation = (io, appId) => {
if (!activeAppOperations.delete(appId)) return;
io.emit('app:operations:active', activeOperationsPayload());
@@ -93,6 +98,7 @@ export const registerAppHandlers = (socket, io) => {
socket.on('app:update', async (rawData) => {
let operatingAppId = null;
+ let result = null;
try {
const data = validateSocketData(appUpdateSchema, rawData, socket, 'app:update');
if (!data) return;
@@ -143,9 +149,17 @@ export const registerAppHandlers = (socket, io) => {
};
let failure = null;
- const result = await appUpdater.updateApp(app, emit, { syncFork: data.syncFork === true }).catch(err => {
+ result = await appUpdater.updateApp(app, emit, {
+ syncFork: data.syncFork === true,
+ acknowledgeFork: data.acknowledgeFork === true,
+ acknowledgePersistentMindImageBackup: data.acknowledgePersistentMindImageBackup === true,
+ }).catch(err => {
failure = err;
- io.emit('app:update:error', { appId: app.id, message: err.message });
+ // Refusals raised inside the update (the PortOS launcher's post-lock
+ // re-check, say) carry the same acknowledgement codes the pre-check
+ // emits above — the panel's retry buttons key on `code`, so dropping it
+ // here would leave a refusal the user could have acted on inert.
+ io.emit('app:update:error', { appId: app.id, code: err.code || null, message: err.message });
return null;
});
@@ -155,17 +169,24 @@ export const registerAppHandlers = (socket, io) => {
await logAction('update', app.id, app.name, { steps: result?.steps ?? [] }, result?.success === true, failure?.message ?? null);
appsService.notifyAppsChanged('update', app.id);
- if (result) {
+ if (result?.selfUpdateStarted) {
+ // update.sh will `pm2 delete` THIS process partway through, so there is
+ // no completion to report and nothing after the restart to clear the
+ // operation. Leaving it registered (the map dies with the process) is
+ // what keeps the row rendering the script's STEP: frames right up to
+ // the moment the server goes down.
+ console.log(`♻️ PortOS self-update handed off — update.sh will restart this process`);
+ } else if (result) {
io.emit('app:update:complete', { appId: app.id, success: result.success, steps: result.steps });
console.log(`✅ Socket update complete for ${app.name}`);
}
} catch (err) {
const message = err?.message ?? String(err);
console.error(`❌ Socket handler error [app:update]: ${message}`);
- io.emit('app:update:error', { appId: operatingAppId, message });
+ io.emit('app:update:error', { appId: operatingAppId, code: err?.code || null, message });
io.emit('app:update:complete', { appId: operatingAppId, success: false, steps: [] });
} finally {
- if (operatingAppId) endAppOperation(io, operatingAppId);
+ if (operatingAppId && !result?.selfUpdateStarted) endAppOperation(io, operatingAppId);
}
});
diff --git a/server/sockets/apps.test.js b/server/sockets/apps.test.js
index 05aa150f7f..026b01155b 100644
--- a/server/sockets/apps.test.js
+++ b/server/sockets/apps.test.js
@@ -34,7 +34,7 @@ import * as appsService from '../services/apps.js';
import * as appUpdater from '../services/appUpdater.js';
import * as pm2Standardizer from '../services/pm2Standardizer.js';
import { logAction } from '../services/history.js';
-import { registerAppHandlers } from '../sockets/apps.js';
+import { __resetAppOperations, registerAppHandlers } from '../sockets/apps.js';
// Two app records pointing at ONE checkout — the case app id alone can't catch.
const APPS = {
@@ -202,6 +202,63 @@ describe('app socket handlers', () => {
});
});
+ describe('PortOS self-update handoff', () => {
+ it('keeps the operation live and reports no completion once update.sh owns the restart', async () => {
+ // update.sh pm2-deletes THIS process partway through, so appUpdater
+ // returns as soon as the detached script is launched. Reporting the
+ // operation "complete" here would clear the Git tab's progress row while
+ // the script is still running, and clearing the operation would drop the
+ // remaining STEP: frames on the floor — which is the "Stopping PortOS
+ // apps..." freeze this handoff exists to fix.
+ appUpdater.updateApp.mockResolvedValue({
+ success: true,
+ selfUpdateStarted: true,
+ steps: [{ step: 'git-pull', success: true }, { step: 'app-update', success: true }],
+ });
+ const client = connect(bus);
+
+ await client.fire('app:update', { appId: 'app-a' });
+
+ expect(client.events('app:update:complete')).toHaveLength(0);
+ expect(client.events('app:update:error')).toHaveLength(0);
+ // The launch itself succeeded, so the ledger records it rather than
+ // waiting for a completion that will never arrive.
+ expect(logAction).toHaveBeenCalledWith(
+ 'update', 'app-a', 'Example App A',
+ { steps: [{ step: 'git-pull', success: true }, { step: 'app-update', success: true }] },
+ true, null,
+ );
+ expect(client.last('app:operations:active').payload.operations).toMatchObject([
+ { appId: 'app-a', type: 'update' },
+ ]);
+
+ // Nothing ends this operation in production either — the process is
+ // replaced. Without a process boundary the module state would leak into
+ // every later test in the file.
+ __resetAppOperations();
+ });
+
+ it('threads the PortOS preflight acknowledgements into the updater', async () => {
+ // The launcher re-checks the image guard after taking the lock, so an
+ // acknowledgement the user opted into here has to reach it or the retry
+ // refuses again on the very guard they just acknowledged.
+ appUpdater.updateApp.mockResolvedValue({ success: true, steps: [] });
+ const client = connect(bus);
+
+ await client.fire('app:update', {
+ appId: 'app-a',
+ acknowledgeFork: true,
+ acknowledgePersistentMindImageBackup: true,
+ });
+
+ expect(appUpdater.updateApp).toHaveBeenCalledWith(
+ APPS['app-a'],
+ expect.any(Function),
+ { syncFork: false, acknowledgeFork: true, acknowledgePersistentMindImageBackup: true },
+ );
+ });
+ });
+
describe('failure recovery', () => {
it('records a failed update in the ledger, broadcasts the change, and clears the operation', async () => {
appUpdater.updateApp.mockRejectedValue(new Error('git pull failed'));
@@ -209,7 +266,9 @@ describe('app socket handlers', () => {
await client.fire('app:update', { appId: 'app-a' });
- expect(client.last('app:update:error').payload).toEqual({ appId: 'app-a', message: 'git pull failed' });
+ // `code` is always on the envelope — null for a plain failure, set for a
+ // refusal the panel can offer an acknowledgement for.
+ expect(client.last('app:update:error').payload).toEqual({ appId: 'app-a', code: null, message: 'git pull failed' });
// A thrown update still gets a history row rather than vanishing from it.
expect(logAction).toHaveBeenCalledWith('update', 'app-a', 'Example App A', { steps: [] }, false, 'git pull failed');
expect(appsService.notifyAppsChanged).toHaveBeenCalledWith('update', 'app-a');