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
hold the self-update launcher's return until the script is actually spawned
[._.]/ Adam Eivy3114ad1f54ba
diff --git a/client/src/hooks/usePortosRestartWatch.js b/client/src/hooks/usePortosRestartWatch.jsindex b9a35b5d02..b754be3849 100644--- a/client/src/hooks/usePortosRestartWatch.js+++ b/client/src/hooks/usePortosRestartWatch.js@@ -45,7 +45,7 @@ const TOAST_ID = 'portos-update-restart';* @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}}+ * @returns {{polling: boolean, captureBaseline: (currentVersion?: string|null) => Promise<void>, arm: (opts?: {healthDown?: boolean}) => void}}*/export function usePortosRestartWatch({ enabled = true, active = false, onRestart, onFailure } = {}) {const [polling, setPolling] = useState(false);@@ -75,12 +75,20 @@ export function usePortosRestartWatch({ enabled = true, active = false, onRestar// 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(() => {+ // `healthDown` carries an already-CONFIRMED down observation into the poll.+ // The disconnect path proves the server is unreachable before it arms, and on+ // a same-version reconcile with no baseline (a page that adopted an update it+ // did not start) that proof is the only restart evidence there is. Today the+ // poll re-establishes it anyway, because `useAutoRefetch` fires once+ // immediately on enable while the server is still down — but that makes this+ // hook's correctness depend on another hook's `immediate` default. Carrying+ // the observation forward costs nothing and severs that link.+ const arm = useCallback(({ healthDown = false } = {}) => {if (pollingRef.current) return;activeRef.current = false;pollingRef.current = true;attemptsRef.current = 0;- healthWentDownRef.current = false;+ healthWentDownRef.current = healthDown;setPolling(true);toast.loading('PortOS is restarting...', { id: TOAST_ID, duration: Infinity });callbacksRef.current.onRestart?.();@@ -126,7 +134,7 @@ export function usePortosRestartWatch({ enabled = true, active = false, onRestar// 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();+ if (!ok && activeRef.current && mountedRef.current) arm({ healthDown: true });}, DISCONNECT_CONFIRM_MS);};diff --git a/server/routes/update.test.js b/server/routes/update.test.jsindex 008b7a2ac3..38eed0cea4 100644--- a/server/routes/update.test.js+++ b/server/routes/update.test.js@@ -130,7 +130,7 @@ describe('POST /api/update/execute — reconcile gating (issue #1779)', () => {expect(res.status).toBe(200);expect(res.body).toEqual({ started: true, tag: 'v1.26.0' });// Only the stale workspaces, with 'root' mapped to update.sh's '.' token.- expect(executeUpdate).toHaveBeenCalledWith('v1.26.0', expect.any(Function), { forceCleanWorkspaces: ['.', 'server'] });+ expect(executeUpdate).toHaveBeenCalledWith('v1.26.0', expect.any(Function), expect.objectContaining({ forceCleanWorkspaces: ['.', 'server'] }));});it('reconcile with no stale deps (build/migration staleness) forces no clean', async () => {@@ -139,7 +139,7 @@ describe('POST /api/update/execute — reconcile gating (issue #1779)', () => {}));const res = await request(makeApp()).post('/api/update/execute').send({ reconcile: true });expect(res.status).toBe(200);- expect(executeUpdate).toHaveBeenCalledWith('v1.26.0', expect.any(Function), { forceCleanWorkspaces: [] });+ expect(executeUpdate).toHaveBeenCalledWith('v1.26.0', expect.any(Function), expect.objectContaining({ forceCleanWorkspaces: [] }));});it('reconcile runs even with NO cached release (out of sync)', async () => {@@ -175,7 +175,7 @@ describe('POST /api/update/execute — reconcile gating (issue #1779)', () => {const res = await request(makeApp()).post('/api/update/execute').send({});expect(res.status).toBe(200);expect(res.body.tag).toBe('v1.27.0');- expect(executeUpdate).toHaveBeenCalledWith('v1.27.0', expect.any(Function), { forceCleanWorkspaces: undefined });+ expect(executeUpdate).toHaveBeenCalledWith('v1.27.0', expect.any(Function), expect.objectContaining({ forceCleanWorkspaces: undefined }));});});@@ -388,12 +388,16 @@ describe('POST /api/update/execute — lock handling and socket progress', () =>// Regression for issue #6036: executeUpdate rejecting (e.g. spawnDetached// throwing before any child listener is attached) skips recordUpdateResult,- // so the route is the only place left that can release the lock. Leaving it- // set wedges every later update at 409 and blocks all CoS agent spawns.+ // so the launcher is the only place left that can release the lock. Leaving+ // it set wedges every later update at 409 and blocks all CoS agent spawns.it('releases the update lock and emits an error when executeUpdate rejects', async () => {executeUpdate.mockRejectedValue(new Error('spawn EACCES'));const res = await request(makeApp()).post('/api/update/execute').send({});- expect(res.status).toBe(200);+ // NOT 200: the rejection happens during the LAUNCH, before any script is+ // running, so the caller is told the update never started rather than being+ // handed `started: true` for a restart that is not coming.+ expect(res.status).toBeGreaterThanOrEqual(400);+ expect(res.body.started).toBeUndefined();await vi.waitFor(() => {expect(updateChecker.setUpdateInProgress).toHaveBeenCalledWith(false);});diff --git a/server/services/portosSelfUpdate.js b/server/services/portosSelfUpdate.jsindex 76f47a0fcf..b120b3d625 100644--- a/server/services/portosSelfUpdate.js+++ b/server/services/portosSelfUpdate.js@@ -181,10 +181,26 @@ export async function startPortosSelfUpdate({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 => {+ // `executeUpdate` is two phases behind one promise: a LAUNCH (the+ // still-running guard, then the double-fork spawn) that can refuse or throw,+ // and then the script's whole lifetime. Only the second is fire-and-forget.+ // Reporting `started: true` for a script that never spawned is what would+ // leave a caller waiting for a restart that is not coming — and on the App+ // Management path it also leaves the operation registered forever, since that+ // handler deliberately skips its cleanup for a real handoff, so every later+ // update is then refused as a duplicate. So hold the return until the spawn.+ let launchedFlag = false;+ let markLaunched;+ const launched = new Promise((resolve) => {+ markLaunched = () => { launchedFlag = true; resolve(); };+ });++ // 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.+ const run = executeUpdate(tag, emit, { forceCleanWorkspaces, onLaunched: markLaunched });++ run.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;@@ -210,5 +226,22 @@ export async function startPortosSelfUpdate({});});+ // Settling before the launch signal means the LAUNCH failed: the+ // still-running guard refused (a resolved `success: false`) or the spawn threw+ // (a rejection). Both are the caller's to report. After the signal this+ // resolves regardless — a script that fails later is the fire-and-forget+ // handler's business, and re-throwing it here would be an unhandled rejection+ // (fatal on Node >= 15) because the race below has already settled.+ const launchFailure = run.then(+ (result) => {+ if (!launchedFlag && !result.success) {+ throw new ServerError(result.errorMessage || 'PortOS update failed to launch',+ { status: 409, code: 'UPDATE_LAUNCH_FAILED' });+ }+ },+ (err) => { if (!launchedFlag) throw err; },+ );+ await Promise.race([launched, launchFailure]);+return { started: true, tag };}diff --git a/server/services/portosSelfUpdate.test.js b/server/services/portosSelfUpdate.test.jsindex 4099469715..3e2211a732 100644--- a/server/services/portosSelfUpdate.test.js+++ b/server/services/portosSelfUpdate.test.js@@ -50,7 +50,13 @@ describe('startPortosSelfUpdate — refresh mode', () => {mockSpawningTasks.clear();updateChecker.setUpdateInProgress.mockResolvedValue(true);updateChecker.getUpdateStatus.mockResolvedValue(inSyncStatus());- executeUpdate.mockResolvedValue({ success: true, version: '1.26.0' });+ // Signal the launch the way the real executeUpdate does — the launcher holds+ // its return until the spawn, so a mock that never signals is a mock of a+ // launch that never happened.+ executeUpdate.mockImplementation(async (_tag, _emit, opts) => {+ opts?.onLaunched?.();+ return { success: true, version: '1.26.0' };+ });});it('runs on an in-sync install, where a reconcile would refuse', async () => {@@ -92,7 +98,7 @@ describe('startPortosSelfUpdate — refresh mode', () => {expect(executeUpdate).toHaveBeenCalledWith('v1.26.0',expect.any(Function),- { forceCleanWorkspaces: ['.', 'client'] },+ expect.objectContaining({ forceCleanWorkspaces: ['.', 'client'] }),);});@@ -101,7 +107,8 @@ describe('startPortosSelfUpdate — refresh mode', () => {// 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) => {+ executeUpdate.mockImplementation(async (_tag, emit, opts) => {+ opts?.onLaunched?.();emit('pm2-stop', 'running', 'Stopping PortOS apps...');return { success: true, version: '1.26.0' };});@@ -116,13 +123,57 @@ describe('startPortosSelfUpdate — refresh mode', () => {}));});+ it('refuses rather than reporting a start when a prior script is still running', async () => {+ // executeUpdate's still-running guard RESOLVES `success: false` without ever+ // spawning. Returning `started: true` for that leaves App Management's+ // operation registered forever (its handler skips cleanup on a real+ // handoff), so every later update is refused as a duplicate while the UI+ // waits for a restart that is not coming.+ executeUpdate.mockResolvedValue({+ success: false, failedStep: 'starting',+ errorMessage: 'A previous update script is still running',+ });++ await expect(startPortosSelfUpdate({ io, mode: 'refresh' }))+ .rejects.toThrow(/still running/i);+ });++ it('reports a launch that threw, instead of claiming the script started', async () => {+ executeUpdate.mockRejectedValue(new Error('spawn EACCES'));++ await expect(startPortosSelfUpdate({ io, mode: 'refresh' }))+ .rejects.toThrow('spawn EACCES');+ });++ it('resolves once the script is spawned, without waiting for it to finish', async () => {+ // The whole point: update.sh outlives this process, so the launcher must+ // return at the spawn. A promise that only settles when the script is done+ // would never resolve here — the pm2 delete kills the awaiting process.+ let finish;+ executeUpdate.mockImplementation((_tag, _emit, { onLaunched }) => {+ onLaunched();+ return new Promise((resolve) => { finish = resolve; });+ });++ await expect(startPortosSelfUpdate({ io, mode: 'refresh' }))+ .resolves.toEqual({ started: true, tag: 'v1.26.0' });+ expect(finish).toBeTypeOf('function');+ // A LATER failure is the fire-and-forget handler's business, not a rejection+ // out of a call that already returned — re-throwing it would be an unhandled+ // rejection, which is fatal on Node >= 15.+ finish({ success: false, failedStep: 'build', errorMessage: 'build failed' });+ await vi.waitFor(() => expect(io.emit).toHaveBeenCalledWith(+ 'portos:update:error', expect.objectContaining({ step: 'build' }),+ ));+ });+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 startPortosSelfUpdate({ io, mode: 'refresh' }).catch(() => {});await vi.waitFor(() => expect(updateChecker.setUpdateInProgress).toHaveBeenCalledWith(false));expect(io.emit).toHaveBeenCalledWith('portos:update:error', expect.objectContaining({diff --git a/server/services/updateExecutor.js b/server/services/updateExecutor.jsindex 4f9bae0c37..d47af06948 100644--- a/server/services/updateExecutor.js+++ b/server/services/updateExecutor.js@@ -32,13 +32,17 @@ const UPDATE_PS1 = join(PATHS.root, 'update.ps1');** @param {string} tag - The release tag that triggered the update (for logging)* @param {function} emit - Callback (step, status, message) for progress+ * @param {object} [options]+ * @param {string[]} [options.forceCleanWorkspaces] - workspaces to reinstall from scratch+ * @param {function} [options.onLaunched] - called once the script is spawned, before+ * the returned promise starts tracking its lifetime* @returns {Promise<{success: boolean, version?: string, failedStep?: string, errorMessage?: string}>}*/// Workspaces update.sh / update.ps1 know how to clean-reinstall — the env// passthrough is allowlisted to these so nothing arbitrary reaches the scripts.const CLEANABLE_WORKSPACES = new Set(['.', 'client', 'server', 'autofixer']);-export async function executeUpdate(tag, emit, { forceCleanWorkspaces } = {}) {+export async function executeUpdate(tag, emit, { forceCleanWorkspaces, onLaunched } = {}) {const isWindows = process.platform === 'win32';const cmd = isWindows ? 'powershell' : 'bash';const args = isWindows@@ -101,6 +105,13 @@ export async function executeUpdate(tag, emit, { forceCleanWorkspaces } = {}) {controlDir});+ // The script is running from here on. Everything ABOVE can still refuse (a+ // prior update script is still alive) or throw (spawn error); nothing below+ // can — the returned promise then tracks the script's whole lifetime. A+ // caller that must tell "the launch failed" from "the update failed" waits on+ // this signal rather than on the promise. See `portosSelfUpdate`'s launch gate.+ onLaunched?.();+return new Promise((resolve) => {let lastStep = 'starting';