Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: apply update preflight guards to App Management's socket update path (#5984)
Adam Eivy425544ec79d1
diff --git a/client/src/components/apps/tabs/RepositorySourcePanel.jsx b/client/src/components/apps/tabs/RepositorySourcePanel.jsxindex 5737f34761..aa79f738dd 100644--- a/client/src/components/apps/tabs/RepositorySourcePanel.jsx+++ b/client/src/components/apps/tabs/RepositorySourcePanel.jsx@@ -171,6 +171,7 @@ export default function RepositorySourcePanel({ appId, appName, onUpdated, refreisOperating,operationType,error: operationError,+ errorCode: operationErrorCode,completed: operationCompleted,startUpdate,} = useAppOperation({ appId, onComplete: handleOperationComplete });@@ -240,6 +241,16 @@ export default function RepositorySourcePanel({ appId, appName, onUpdated, refrestartUpdate(appId, appName, { syncFork: intent?.syncFork === true });};+ // Retry a refused PortOS self-update with the acknowledgement its refusal+ // code named (server/services/updatePreflight.js). The refusal happened+ // before any operation actually started, so — unlike a real update+ // failure — it's safe to clear the "reload before trying again" latch and+ // let the user retry immediately (#5984).+ const handleAcknowledgeAndRetry = (ackOptions) => {+ setUpdateRequested(false);+ startUpdate(appId, appName, ackOptions);+ };+return (<div className="rounded-xl border border-port-accent/30 bg-port-card p-4 sm:p-5"><div className="flex flex-wrap items-start justify-between gap-3">@@ -272,6 +283,28 @@ export default function RepositorySourcePanel({ appId, appName, onUpdated, refrecompleted={operationCompleted}completedMessage={operationType === 'update' ? 'Reload this page before starting another update.' : undefined}/>+ {/* Refusals PortOS's shared update preflight raises (server/services/updatePreflight.js)+ carry an explicit acknowledgement the user can opt into and retry with. */}+ {operationErrorCode === 'FORK_SYNC_REQUIRED' && (+ <button+ onClick={() => handleAcknowledgeAndRetry({ acknowledgeFork: true })}+ disabled={isOperating || syncingFork}+ className="mt-2 flex min-h-[40px] items-center gap-1.5 rounded-lg border border-port-border px-3 py-2 text-sm text-gray-300 hover:border-port-accent hover:text-white disabled:opacity-50"+ >+ <Download size={15} />+ Update from fork as-is+ </button>+ )}+ {operationErrorCode === 'PERSISTENT_MIND_IMAGES_IN_FLIGHT' && (+ <button+ onClick={() => handleAcknowledgeAndRetry({ acknowledgePersistentMindImageBackup: true })}+ disabled={isOperating || syncingFork}+ className="mt-2 flex min-h-[40px] items-center gap-1.5 rounded-lg border border-port-border px-3 py-2 text-sm text-gray-300 hover:border-port-accent hover:text-white disabled:opacity-50"+ >+ <Download size={15} />+ Update anyway (back up first)+ </button>+ )}</div>)}diff --git a/client/src/components/apps/tabs/RepositorySourcePanel.test.jsx b/client/src/components/apps/tabs/RepositorySourcePanel.test.jsxindex 97ebc8b670..3d4f43a948 100644--- a/client/src/components/apps/tabs/RepositorySourcePanel.test.jsx+++ b/client/src/components/apps/tabs/RepositorySourcePanel.test.jsx@@ -276,6 +276,54 @@ describe('managed app repository sources', () => {expect(screen.getByText('Remote freshness is unknown; a managed update can retry the source checkouts.')).toBeInTheDocument();});+ it('offers to update from a fork as-is after a FORK_SYNC_REQUIRED refusal', async () => {+ useAppOperation.mockReturnValue({+ steps: [], isOperating: false, operationType: 'update',+ error: 'Running from a fork (alice/PortOS). Sync your fork first, or acknowledge.',+ errorCode: 'FORK_SYNC_REQUIRED', completed: false,+ startUpdate: vi.fn(),+ });+ render(<RepositorySourcePanel appId="portos-default" appName="PortOS" />);++ const retryButton = await screen.findByRole('button', { name: 'Update from fork as-is' });+ fireEvent.click(retryButton);++ expect(useAppOperation.mock.results[0].value.startUpdate).toHaveBeenCalledWith(+ 'portos-default', 'PortOS', { acknowledgeFork: true },+ );+ });++ it('offers to update anyway after a PERSISTENT_MIND_IMAGES_IN_FLIGHT refusal', async () => {+ useAppOperation.mockReturnValue({+ steps: [], isOperating: false, operationType: 'update',+ error: 'Persistent Mind has 1 queued image message.',+ errorCode: 'PERSISTENT_MIND_IMAGES_IN_FLIGHT', completed: false,+ startUpdate: vi.fn(),+ });+ render(<RepositorySourcePanel appId="portos-default" appName="PortOS" />);++ const retryButton = await screen.findByRole('button', { name: 'Update anyway (back up first)' });+ fireEvent.click(retryButton);++ expect(useAppOperation.mock.results[0].value.startUpdate).toHaveBeenCalledWith(+ 'portos-default', 'PortOS', { acknowledgePersistentMindImageBackup: true },+ );+ });++ it('does not offer an acknowledgement retry for a refusal with no acknowledgement (AGENTS_ACTIVE)', async () => {+ useAppOperation.mockReturnValue({+ steps: [], isOperating: false, operationType: 'update',+ error: '1 CoS agent is running — updating would restart PortOS and sever it.',+ errorCode: 'AGENTS_ACTIVE', completed: false,+ startUpdate: vi.fn(),+ });+ render(<RepositorySourcePanel appId="portos-default" appName="PortOS" />);++ await screen.findByText(/CoS agent is running/);+ expect(screen.queryByRole('button', { name: 'Update from fork as-is' })).not.toBeInTheDocument();+ expect(screen.queryByRole('button', { name: 'Update anyway (back up first)' })).not.toBeInTheDocument();+ });+it('does not mislabel an undiscovered repository topology as a custom origin', async () => {const status = canonicalStatus();status.updateAvailable = false;diff --git a/client/src/hooks/useAppOperation.js b/client/src/hooks/useAppOperation.jsindex 37fc94aa58..5779d371bf 100644--- a/client/src/hooks/useAppOperation.js+++ b/client/src/hooks/useAppOperation.js@@ -80,6 +80,7 @@ export function useAppOperation({ onComplete, appId: scopeAppId } = {}) {type: op.type,steps: op.steps?.length ? op.steps : (current?.steps || []),error: null,+ errorCode: null,completed: false};}@@ -106,7 +107,7 @@ export function useAppOperation({ onComplete, appId: scopeAppId } = {}) {socket.emit('app:operations:list');return;}- patch(data, current => ({ ...current, error: data?.message || 'Operation failed' }));+ patch(data, current => ({ ...current, error: data?.message || 'Operation failed', errorCode: data?.code || null }));};const onDone = (data) => {@@ -158,7 +159,7 @@ export function useAppOperation({ onComplete, appId: scopeAppId } = {}) {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, completed: false } }));+ setOperations(prev => ({ ...prev, [appId]: { appId, appName, type, steps: [], error: null, errorCode: null, completed: false } }));socket.emit(type === 'update' ? 'app:update' : 'app:standardize', { appId, ...options });}, []);@@ -176,6 +177,7 @@ export function useAppOperation({ onComplete, appId: scopeAppId } = {}) {isOperating: list.some(isLive),steps: primary?.steps || [],error: primary?.error ?? null,+ errorCode: primary?.errorCode ?? null,completed: primary?.completed ?? false,operatingAppId: primary?.appId ?? null,operatingAppName: primary?.appName ?? null,diff --git a/server/lib/socketValidation.js b/server/lib/socketValidation.jsindex 09518d455b..02339114d7 100644--- a/server/lib/socketValidation.js+++ b/server/lib/socketValidation.js@@ -81,10 +81,15 @@ export const shellAttachSchema = z.object({// shell:stop — session IDexport const shellStopSchema = shellSessionIdSchema;-// app:update — app ID for pull/install/restart cycle+// app:update — app ID for pull/install/restart cycle. `acknowledgeFork` and+// `acknowledgePersistentMindImageBackup` are only consulted for the PortOS app+// record — they mirror POST /api/update/execute's executeSchema so App+// Management can supply the same preflight acknowledgements (#5984).export const appUpdateSchema = z.object({appId: z.string().min(1, 'appId is required'),- syncFork: z.boolean().optional()+ syncFork: z.boolean().optional(),+ acknowledgeFork: z.boolean().optional(),+ acknowledgePersistentMindImageBackup: z.boolean().optional()});// app:standardize — app ID for PM2 standardization.diff --git a/server/lib/socketValidation.test.js b/server/lib/socketValidation.test.jsindex bdb5f28f8a..9f9cdaf139 100644--- a/server/lib/socketValidation.test.js+++ b/server/lib/socketValidation.test.js@@ -172,6 +172,18 @@ describe('socketValidation schemas', () => {expect(appStandardizeSchema.safeParse({}).success).toBe(false);});+ it('appUpdateSchema accepts the PortOS preflight acknowledgements (#5984)', () => {+ const result = appUpdateSchema.safeParse({+ appId: 'foo',+ acknowledgeFork: true,+ acknowledgePersistentMindImageBackup: true,+ });+ expect(result.success).toBe(true);+ expect(result.data.acknowledgeFork).toBe(true);+ expect(result.data.acknowledgePersistentMindImageBackup).toBe(true);+ expect(appUpdateSchema.safeParse({ appId: 'foo', acknowledgeFork: 'yes' }).success).toBe(false);+ });+it('appDeploySchema defaults flags to an empty array', () => {const result = appDeploySchema.safeParse({ appId: 'foo' });expect(result.success).toBe(true);diff --git a/server/routes/update.js b/server/routes/update.jsindex b2af17ed89..78f5dfec37 100644--- a/server/routes/update.js+++ b/server/routes/update.js@@ -3,81 +3,20 @@ import { z } from 'zod';import { asyncHandler, ServerError } from '../lib/errorHandler.js';import { validateRequest } from '../lib/validation.js';import { UPSTREAM_FULL_NAME } from '../lib/gitRemote.js';-import { persistentMindImageWorkGuard } from '../lib/persistentMind.js';import * as updateChecker from '../services/updateChecker.js';import { executeUpdate } from '../services/updateExecutor.js';-import { getActiveAgentIds, spawningTasks } from '../services/agentState.js';-import { readPersistentMindStateForSafetyCheck, withStateLock } from '../services/cosState.js';-import { filterLiveAgentIds } from '../services/cosAgentLifecycle.js';+import { withStateLock } from '../services/cosState.js';+import {+ countActiveCosAgents,+ agentsActiveError,+ getPersistentMindImageWorkGuard,+ persistentMindImageWorkError,+ persistentMindStateUntrustedError,+ checkPortosUpdatePreflight,+} from '../services/updatePreflight.js';const router = Router();-// Count CoS agents a PortOS restart (update.sh → pm2 restart) would disrupt:-// live processes (direct + runner spawns) PLUS any task mid-spawn. During a-// spawn the task sits in `spawningTasks` while its child process is created and-// only THEN registered in the process maps (`withSpawnDedupGuard` holds the set-// across the whole launch) — so an agent that has already spawned a process but-// not yet registered it is invisible to getActiveAgentIds() alone. Summing both-// includes every distinct in-flight task in the count (a live agent plus two-// spawning tasks reads as 3, not 1). It can transiently over-report by 1 during-// the sub-second overlap where a single launching agent sits in BOTH sets, but-// the guard only needs `> 0` and the count is a near-exact upper bound shown in-// an advisory notice — an occasional +1 mid-launch is preferable to dropping-// the spawning tasks entirely.-//-// This still can't close the window where a NEW spawn begins AFTER a caller-// reads this but before update.sh's pm2 restart. The route's post-lock re-check-// below narrows it; fully closing it needs every CoS spawn engine to consult-// updateInProgress (tracked in #4124) — the orphan reaper bounds the residual.-//-// The map ids are filtered through PortOS's own durable records first-// (`filterLiveAgentIds`). Neither map is self-cleaning, and `syncRunnerAgents`-// adopts whatever the CoS Runner still advertises — so a TUI the runner failed-// to kill stayed "active" until the next PortOS restart, permanently blocking-// the one action that would have cleared it. A restart cannot sever a run this-// process has already finalized, so a finalized id must not gate the update.-async function countActiveCosAgents() {- const live = await filterLiveAgentIds(getActiveAgentIds());- return live.length + spawningTasks.size;-}--// The 409 the update flow raises when a restart would sever a live/spawning-// agent — shared by the fast-fail pre-check and the post-lock re-check.-function agentsActiveError(n) {- return new ServerError(- `${n} CoS agent${n === 1 ? ' is' : 's are'} running — updating would restart PortOS and ` +- `sever ${n === 1 ? 'it' : 'them'}. Pause or wait for the agent${n === 1 ? '' : 's'} to finish, then update.`,- { status: 409, code: 'AGENTS_ACTIVE' }- );-}--const persistentMindImageWorkError = (guard) => {- const work = [- guard.queuedImageMessages > 0- ? `${guard.queuedImageMessages} queued image message${guard.queuedImageMessages === 1 ? '' : 's'}`- : null,- guard.activeImageMessage ? 'one active image turn' : null,- ].filter(Boolean).join(' and ');- return new ServerError(- `Persistent Mind has ${work}. Drain the image-bearing work, or create a backup and retry ` +- 'with acknowledgePersistentMindImageBackup: true. Older source readers cannot preserve image references.',- { status: 409, code: 'PERSISTENT_MIND_IMAGES_IN_FLIGHT' },- );-};--async function getPersistentMindImageWorkGuard() {- const snapshot = await readPersistentMindStateForSafetyCheck();- if (!snapshot.trusted) {- return { safe: false, trusted: false, queuedImageMessages: 0, activeImageMessage: false };- }- return persistentMindImageWorkGuard(snapshot.persistentMind);-}--const persistentMindStateUntrustedError = () => new ServerError(- 'Persistent Mind state could not be validated. Restore data/cos/state.json from backup before updating.',- { status: 409, code: 'PERSISTENT_MIND_STATE_UNTRUSTED' },-);-const ignoreSchema = z.object({version: z.string().min(1, 'version is required')});@@ -189,23 +128,17 @@ 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. 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).- // countActiveCosAgents() reflects exactly what a restart would kill (see its- // definition above). 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 closes the window an agent- // could start in during that work.- const preCheck = await countActiveCosAgents();- if (preCheck > 0) throw agentsActiveError(preCheck);- const preImageCheck = await getPersistentMindImageWorkGuard();- if (!preImageCheck.trusted) throw persistentMindStateUntrustedError();- if (!preImageCheck.safe && !acknowledgePersistentMindImageBackup) {- throw persistentMindImageWorkError(preImageCheck);- }-- const status = await updateChecker.getUpdateStatus();+ // 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.@@ -238,23 +171,6 @@ router.post('/execute', asyncHandler(async (req, res) => {throw new ServerError('Invalid release tag format', { status: 400, code: 'INVALID_TAG' });}- // Fork gate: update.sh pulls from origin, so running from an unsynced fork- // would silently no-op (or pull a stale version). Require either a recent- // fork sync of the upstream branch or an explicit acknowledgement that the- // user knows they're updating from their own origin.- const remote = status.remoteInfo;- if (remote?.isFork && !acknowledgeFork) {- // Reuse the freshness boolean the service already computed so the route- // and `status.forkSyncFresh` agree by construction (no duplicate math).- if (!status.forkSyncFresh) {- throw new ServerError(- `Running from a fork (${remote.fullName}). Sync your fork from ${status.upstream.fullName} ` +- `first, or re-submit with acknowledgeFork: true to update from your fork's origin as-is.`,- { status: 412, code: 'FORK_SYNC_REQUIRED' }- );- }- }-// Atomic check-and-set: rejects if already in progress, preventing concurrent updatesconst acquired = await updateChecker.setUpdateInProgress(true);if (!acquired) {diff --git a/server/services/updatePreflight.js b/server/services/updatePreflight.jsnew file mode 100644index 0000000000..dbf3499143--- /dev/null+++ b/server/services/updatePreflight.js@@ -0,0 +1,121 @@+import { ServerError } from '../lib/errorHandler.js';+import { persistentMindImageWorkGuard } from '../lib/persistentMind.js';+import { getActiveAgentIds, spawningTasks } from './agentState.js';+import { readPersistentMindStateForSafetyCheck } from './cosState.js';+import { filterLiveAgentIds } from './cosAgentLifecycle.js';+import * as updateChecker from './updateChecker.js';++// Shared refusal logic for the PortOS self-update path, called from both+// POST /api/update/execute (server/routes/update.js) and the app:update+// socket handler for the PortOS app record (server/sockets/apps.js) — the+// route previously ran these checks alone, leaving App Management's socket+// path free to restart PortOS out from under a live CoS agent (#5984).++// Count CoS agents a PortOS restart (update.sh → pm2 restart) would disrupt:+// live processes (direct + runner spawns) PLUS any task mid-spawn. During a+// spawn the task sits in `spawningTasks` while its child process is created and+// only THEN registered in the process maps (`withSpawnDedupGuard` holds the set+// across the whole launch) — so an agent that has already spawned a process but+// not yet registered it is invisible to getActiveAgentIds() alone. Summing both+// includes every distinct in-flight task in the count (a live agent plus two+// spawning tasks reads as 3, not 1). It can transiently over-report by 1 during+// the sub-second overlap where a single launching agent sits in BOTH sets, but+// the guard only needs `> 0` and the count is a near-exact upper bound shown in+// an advisory notice — an occasional +1 mid-launch is preferable to dropping+// the spawning tasks entirely.+//+// This still can't close the window where a NEW spawn begins AFTER a caller+// reads this but before update.sh's pm2 restart. The route's post-lock re-check+// narrows it further; fully closing it needs every CoS spawn engine to consult+// updateInProgress (tracked in #4124) — the orphan reaper bounds the residual.+//+// The map ids are filtered through PortOS's own durable records first+// (`filterLiveAgentIds`). Neither map is self-cleaning, and `syncRunnerAgents`+// adopts whatever the CoS Runner still advertises — so a TUI the runner failed+// to kill stayed "active" until the next PortOS restart, permanently blocking+// the one action that would have cleared it. A restart cannot sever a run this+// process has already finalized, so a finalized id must not gate the update.+export async function countActiveCosAgents() {+ const live = await filterLiveAgentIds(getActiveAgentIds());+ return live.length + spawningTasks.size;+}++// The 409 the update flow raises when a restart would sever a live/spawning+// agent — shared by the fast-fail pre-check and the post-lock re-check.+export function agentsActiveError(n) {+ return new ServerError(+ `${n} CoS agent${n === 1 ? ' is' : 's are'} running — updating would restart PortOS and ` ++ `sever ${n === 1 ? 'it' : 'them'}. Pause or wait for the agent${n === 1 ? '' : 's'} to finish, then update.`,+ { status: 409, code: 'AGENTS_ACTIVE' }+ );+}++export function persistentMindImageWorkError(guard) {+ const work = [+ guard.queuedImageMessages > 0+ ? `${guard.queuedImageMessages} queued image message${guard.queuedImageMessages === 1 ? '' : 's'}`+ : null,+ guard.activeImageMessage ? 'one active image turn' : null,+ ].filter(Boolean).join(' and ');+ return new ServerError(+ `Persistent Mind has ${work}. Drain the image-bearing work, or create a backup and retry ` ++ 'with acknowledgePersistentMindImageBackup: true. Older source readers cannot preserve image references.',+ { status: 409, code: 'PERSISTENT_MIND_IMAGES_IN_FLIGHT' },+ );+}++export async function getPersistentMindImageWorkGuard() {+ const snapshot = await readPersistentMindStateForSafetyCheck();+ if (!snapshot.trusted) {+ return { safe: false, trusted: false, queuedImageMessages: 0, activeImageMessage: false };+ }+ return persistentMindImageWorkGuard(snapshot.persistentMind);+}++export const persistentMindStateUntrustedError = () => new ServerError(+ 'Persistent Mind state could not be validated. Restore data/cos/state.json from backup before updating.',+ { status: 409, code: 'PERSISTENT_MIND_STATE_UNTRUSTED' },+);++export function forkSyncRequiredError(remote, status) {+ return new ServerError(+ `Running from a fork (${remote.fullName}). Sync your fork from ${status.upstream.fullName} ` ++ `first, or re-submit with acknowledgeFork: true to update from your fork's origin as-is.`,+ { status: 412, code: 'FORK_SYNC_REQUIRED' }+ );+}++/**+ * One-shot preflight for a PortOS self-update: refuses when a live CoS agent+ * would be severed, when Persistent Mind has unacknowledged image-bearing work,+ * or when running from a fork that hasn't been acknowledged/synced recently.+ * Throws a ServerError (409/412) to refuse; otherwise resolves with the+ * getUpdateStatus() snapshot so a caller that also needs it (the route's tag+ * resolution) isn't forced to fetch it twice.+ *+ * This covers exactly the PRE-lock checks `POST /api/update/execute` ran+ * before #5984 — the route still runs its own post-lock re-check (agents ++ * image guard, under `withStateLock`) separately, since that recheck's timing+ * is specific to the atomic `setUpdateInProgress` window around update.sh.+ */+export async function checkPortosUpdatePreflight({+ acknowledgeFork = false,+ acknowledgePersistentMindImageBackup = false,+} = {}) {+ const activeCosAgents = await countActiveCosAgents();+ if (activeCosAgents > 0) throw agentsActiveError(activeCosAgents);++ const imageCheck = await getPersistentMindImageWorkGuard();+ if (!imageCheck.trusted) throw persistentMindStateUntrustedError();+ if (!imageCheck.safe && !acknowledgePersistentMindImageBackup) {+ throw persistentMindImageWorkError(imageCheck);+ }++ const status = await updateChecker.getUpdateStatus();+ const remote = status.remoteInfo;+ if (remote?.isFork && !acknowledgeFork && !status.forkSyncFresh) {+ throw forkSyncRequiredError(remote, status);+ }++ return status;+}diff --git a/server/services/updatePreflightParity.test.js b/server/services/updatePreflightParity.test.jsnew file mode 100644index 0000000000..27e740897e--- /dev/null+++ b/server/services/updatePreflightParity.test.js@@ -0,0 +1,185 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import express from 'express';+import { request } from '../lib/testHelper.js';+import { errorMiddleware } from '../lib/errorHandler.js';+import { PORTOS_APP_ID } from '../lib/appIdentity.js';++// Both POST /api/update/execute (server/routes/update.js) and the app:update+// socket handler for the PortOS app (server/sockets/apps.js) now route their+// refusal logic through the same checkPortosUpdatePreflight() (issue #5984).+// This suite proves that sharing: it drives BOTH entry points from identical+// mocked agent/persistent-mind/fork state and asserts they refuse with the+// same code and message, rather than re-covering every guard permutation+// already exercised per-route in update.test.js.+vi.mock('../services/updateChecker.js', () => ({+ getUpdateStatus: vi.fn(),+ setUpdateInProgress: vi.fn().mockResolvedValue(true),+}));+vi.mock('../services/updateExecutor.js', () => ({+ executeUpdate: vi.fn().mockResolvedValue({ success: true, version: '1.26.0' }),+}));+const { mockSpawningTasks } = vi.hoisted(() => ({ mockSpawningTasks: new Set() }));+vi.mock('../services/agentState.js', () => ({+ getActiveAgentIds: vi.fn().mockReturnValue([]),+ spawningTasks: mockSpawningTasks,+}));+vi.mock('../services/cosAgentLifecycle.js', () => ({+ filterLiveAgentIds: vi.fn(async (ids) => ids),+}));+const { mockCosState } = vi.hoisted(() => ({+ mockCosState: { persistentMind: { queuedMessages: [], activeTurn: null } },+}));+vi.mock('../services/cosState.js', () => ({+ readPersistentMindStateForSafetyCheck: vi.fn(async () => ({+ trusted: true,+ persistentMind: mockCosState.persistentMind,+ })),+ withStateLock: vi.fn(async (fn) => fn()),+}));++const portosApp = { id: PORTOS_APP_ID, name: 'PortOS', repoPath: '/repo' };+vi.mock('../services/apps.js', () => ({+ getAppById: vi.fn(async () => portosApp),+ notifyAppsChanged: vi.fn(),+}));+vi.mock('../services/history.js', () => ({ logAction: vi.fn() }));+vi.mock('../services/appUpdater.js', () => ({ updateApp: vi.fn() }));+vi.mock('../services/appDeployer.js', () => ({ runDeployFlow: vi.fn() }));+vi.mock('../services/pm2Standardizer.js', () => ({}));+vi.mock('../services/streamingDetect.js', () => ({ streamDetection: vi.fn() }));++import * as updateChecker from '../services/updateChecker.js';+import { executeUpdate } from '../services/updateExecutor.js';+import { getActiveAgentIds } from '../services/agentState.js';+import { readPersistentMindStateForSafetyCheck } from '../services/cosState.js';+import { updateApp as appUpdaterUpdateApp } from '../services/appUpdater.js';+import updateRoutes from '../routes/update.js';+import { registerAppHandlers } from '../sockets/apps.js';++const makeRouteApp = () => {+ const app = express();+ app.use(express.json());+ app.use('/api/update', updateRoutes);+ app.use(errorMiddleware);+ return app;+};++// Minimal fake socket/io: records emit() calls and lets the test fire the+// registered 'app:update' handler directly.+const makeSocketHarness = () => {+ const handlers = new Map();+ const emitted = [];+ const socket = {+ on: (event, fn) => { handlers.set(event, fn); },+ emit: (event, payload) => { emitted.push({ event, payload }); },+ };+ const io = { emit: (event, payload) => { emitted.push({ event, payload }); } };+ registerAppHandlers(socket, io);+ return {+ fireUpdate: (payload) => handlers.get('app:update')(payload),+ emitted,+ };+};++// A baseline in-sync, non-fork status with a cached release — mirrors+// update.test.js's baseStatus so both suites describe the same "healthy"+// server state.+const baseStatus = (overrides = {}) => ({+ currentVersion: '1.26.0',+ latestRelease: { tag: 'v1.27.0', version: '1.27.0' },+ remoteInfo: { isFork: false, hasOrigin: true, fullName: 'atomantic/PortOS' },+ upstream: { fullName: 'atomantic/PortOS' },+ forkSyncFresh: false,+ installState: { outOfSync: false },+ ...overrides+});++describe('PortOS update preflight parity — route vs. socket', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mockSpawningTasks.clear();+ updateChecker.setUpdateInProgress.mockResolvedValue(true);+ updateChecker.getUpdateStatus.mockResolvedValue(baseStatus());+ executeUpdate.mockResolvedValue({ success: true, version: '1.26.0' });+ getActiveAgentIds.mockReturnValue([]);+ mockCosState.persistentMind = { queuedMessages: [], activeTurn: null };+ readPersistentMindStateForSafetyCheck.mockImplementation(async () => ({+ trusted: true,+ persistentMind: mockCosState.persistentMind,+ }));+ });++ it('refuses identically when a CoS agent is live', async () => {+ getActiveAgentIds.mockReturnValue(['agent-1']);++ const routeRes = await request(makeRouteApp()).post('/api/update/execute').send({});+ expect(routeRes.status).toBe(409);+ expect(routeRes.body.code).toBe('AGENTS_ACTIVE');++ const { fireUpdate, emitted } = makeSocketHarness();+ await fireUpdate({ appId: PORTOS_APP_ID });+ const errorEvent = emitted.find((e) => e.event === 'app:update:error');+ expect(errorEvent).toBeTruthy();+ expect(errorEvent.payload.code).toBe('AGENTS_ACTIVE');+ expect(errorEvent.payload.message).toBe(routeRes.body.error);+ expect(appUpdaterUpdateApp).not.toHaveBeenCalled();+ });++ it('refuses identically when Persistent Mind has unacknowledged queued image work', async () => {+ mockCosState.persistentMind = {+ queuedMessages: [{ id: 'message-example', images: [{ attachmentId: 'attachment-example' }] }],+ activeTurn: null,+ };++ const routeRes = await request(makeRouteApp()).post('/api/update/execute').send({});+ expect(routeRes.status).toBe(409);+ expect(routeRes.body.code).toBe('PERSISTENT_MIND_IMAGES_IN_FLIGHT');++ const { fireUpdate, emitted } = makeSocketHarness();+ await fireUpdate({ appId: PORTOS_APP_ID });+ const errorEvent = emitted.find((e) => e.event === 'app:update:error');+ expect(errorEvent.payload.code).toBe('PERSISTENT_MIND_IMAGES_IN_FLIGHT');+ expect(errorEvent.payload.message).toBe(routeRes.body.error);+ expect(appUpdaterUpdateApp).not.toHaveBeenCalled();+ });++ it('refuses identically when running from an unsynced fork, and both honor acknowledgeFork', async () => {+ updateChecker.getUpdateStatus.mockResolvedValue(baseStatus({+ remoteInfo: { isFork: true, hasOrigin: true, fullName: 'alice/PortOS' },+ forkSyncFresh: false,+ }));++ const routeRes = await request(makeRouteApp()).post('/api/update/execute').send({});+ expect(routeRes.status).toBe(412);+ expect(routeRes.body.code).toBe('FORK_SYNC_REQUIRED');++ const { fireUpdate, emitted } = makeSocketHarness();+ await fireUpdate({ appId: PORTOS_APP_ID });+ const errorEvent = emitted.find((e) => e.event === 'app:update:error');+ expect(errorEvent.payload.code).toBe('FORK_SYNC_REQUIRED');+ expect(errorEvent.payload.message).toBe(routeRes.body.error);+ expect(appUpdaterUpdateApp).not.toHaveBeenCalled();++ // Both honor the acknowledgement and proceed.+ const ackRouteRes = await request(makeRouteApp()).post('/api/update/execute').send({ acknowledgeFork: true });+ expect(ackRouteRes.status).toBe(200);++ 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 });+ });++ it('a non-PortOS app is never subject to the PortOS preflight', async () => {+ const { getAppById } = await import('../services/apps.js');+ getAppById.mockResolvedValueOnce({ id: 'some-other-app', name: 'Other App', repoPath: '/other' });+ getActiveAgentIds.mockReturnValue(['agent-1']); // would refuse a PortOS update+ appUpdaterUpdateApp.mockResolvedValue({ success: true, steps: [] });++ const { fireUpdate, emitted } = makeSocketHarness();+ await fireUpdate({ appId: 'some-other-app' });++ expect(emitted.find((e) => e.event === 'app:update:error')).toBeUndefined();+ expect(appUpdaterUpdateApp).toHaveBeenCalled();+ });+});diff --git a/server/sockets/apps.js b/server/sockets/apps.jsindex 2648f0ab46..74e3c02368 100644--- a/server/sockets/apps.js+++ b/server/sockets/apps.js@@ -4,6 +4,8 @@ import * as appsService from '../services/apps.js';import { logAction } from '../services/history.js';import * as appUpdater from '../services/appUpdater.js';import * as appDeployer from '../services/appDeployer.js';+import { checkPortosUpdatePreflight } from '../services/updatePreflight.js';+import { PORTOS_APP_ID } from '../lib/appIdentity.js';import {appDeploySchema,appStandardizeSchema,@@ -111,6 +113,26 @@ export const registerAppHandlers = (socket, io) => {return;}+ // PortOS is itself a managed app, and updating it restarts the whole+ // install — apply the same refusals POST /api/update/execute enforces+ // (a live CoS agent, in-flight Persistent Mind image work, an+ // unacknowledged fork) so App Management can't restart out from under+ // them just because it dispatches through this socket instead (#5984).+ // Emitted directly (not thrown) so only this error event fires — letting+ // it fall to the outer catch below would also fire app:update:complete+ // with success:false, which overwrites this message with a generic one+ // client-side (useAppOperation's onDone patch).+ if (app.id === PORTOS_APP_ID) {+ const refusal = await checkPortosUpdatePreflight({+ acknowledgeFork: data.acknowledgeFork === true,+ acknowledgePersistentMindImageBackup: data.acknowledgePersistentMindImageBackup === true,+ }).then(() => null, (err) => err);+ if (refusal) {+ socket.emit('app:update:error', { appId: app.id, code: refusal.code, message: refusal.message });+ return;+ }+ }+console.log(`⬇️ Socket update started for ${app.name}`);const operation = beginAppOperation(io, app, 'update');operatingAppId = app.id;