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
address review (codex + claude): tighten reconcile gating and restart detection
[._.]/ Adam Eivy4e8e7d6a7978
diff --git a/client/src/components/apps/tabs/UpdateTab.jsx b/client/src/components/apps/tabs/UpdateTab.jsxindex b1b4d55f52..c07224e41a 100644--- a/client/src/components/apps/tabs/UpdateTab.jsx+++ b/client/src/components/apps/tabs/UpdateTab.jsx@@ -42,6 +42,11 @@ export default function UpdateTab() {const attemptsRef = useRef(0);const targetVersionRef = useRef(null);const preUpdateVersionRef = useRef(null);+ // 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);const fetchStatus = useCallback(async () => {const data = await api.getUpdateStatus().catch(() => null);@@ -110,18 +115,37 @@ export default function UpdateTab() {// `enabled: polling` gate handles teardown automatically when polling flips// off; attemptsRef resets on every fresh polling cycle.useEffect(() => {- if (polling) attemptsRef.current = 0;+ if (polling) {+ attemptsRef.current = 0;+ healthWentDownRef.current = false;+ }}, [polling]);const pollHealth = useCallback(async () => {attemptsRef.current += 1;const ok = await api.checkHealth().catch(() => null);const preUpdateVersion = preUpdateVersionRef.current;- if (ok?.version && (ok.version === targetVersionRef.current || (preUpdateVersion && ok.version !== preUpdateVersion))) {+ 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 (healthWentDownRef.current && ok.version) {+ // Came back up after a confirmed down→up dip at the same version — a+ // reconcile (no release bump). The restart succeeded; reload to pick up+ // the freshly built client.+ setPolling(false);+ toast.success('Install reconciled — reloading', { id: 'portos-update-restart' });+ setTimeout(() => window.location.reload(), 1000);+ return;}if (attemptsRef.current >= 30) {setPolling(false);diff --git a/server/routes/update.js b/server/routes/update.jsindex bc5df938a9..ffe5873545 100644--- a/server/routes/update.js+++ b/server/routes/update.js@@ -111,19 +111,30 @@ router.post('/execute', asyncHandler(async (req, res) => {const { acknowledgeFork, reconcile } = validateRequest(executeSchema, req.body || {});const status = await updateChecker.getUpdateStatus();- // Normal path requires a known release tag to update TO. A reconcile request- // (issue #1779) instead runs update.sh to finish a bare `git pull` even with- // no newer release — so when no release tag is known, synthesize one from the- // current version purely for logging (update.sh pulls main regardless of tag).- // Guard reconcile on the install actually being out of sync so it can't be- // used to force an unnecessary restart.- let tag = status.latestRelease?.tag;- if (!tag) {- if (reconcile && status.installState?.outOfSync) {- tag = `v${status.currentVersion}`;- } else {+ // 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 injectiondiff --git a/server/routes/update.test.js b/server/routes/update.test.jsnew file mode 100644index 0000000000..f332ae8560--- /dev/null+++ b/server/routes/update.test.js@@ -0,0 +1,111 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import express from 'express';+import { request } from '../lib/testHelper.js';+import { errorMiddleware } from '../lib/errorHandler.js';++// Mock the services the execute route depends on. executeUpdate is fire-and-+// forget in the route (not awaited), so a resolved stub is enough.+vi.mock('../services/updateChecker.js', () => ({+ getUpdateStatus: vi.fn(),+ checkForUpdate: vi.fn(),+ ignoreVersion: vi.fn(),+ clearIgnored: vi.fn(),+ clearStaleUpdateInProgress: vi.fn().mockResolvedValue(false),+ getRemoteInfo: vi.fn(),+ syncFork: vi.fn(),+ setUpdateInProgress: vi.fn().mockResolvedValue(true)+}));+vi.mock('../services/updateExecutor.js', () => ({+ executeUpdate: vi.fn().mockResolvedValue({ success: true, version: '1.26.0' })+}));++import * as updateChecker from '../services/updateChecker.js';+import { executeUpdate } from '../services/updateExecutor.js';+import updateRoutes from './update.js';++const makeApp = () => {+ const app = express();+ app.use(express.json());+ app.use('/api/update', updateRoutes);+ app.use(errorMiddleware);+ return app;+};++// A baseline in-sync, non-fork status with a cached release.+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('POST /api/update/execute — reconcile gating (issue #1779)', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ updateChecker.setUpdateInProgress.mockResolvedValue(true);+ executeUpdate.mockResolvedValue({ success: true, version: '1.26.0' });+ });++ it('rejects reconcile when the install is already in sync (even with a cached release)', async () => {+ updateChecker.getUpdateStatus.mockResolvedValue(baseStatus({ installState: { outOfSync: false } }));+ const res = await request(makeApp()).post('/api/update/execute').send({ reconcile: true });+ expect(res.status).toBe(400);+ expect(res.body.code).toBe('ALREADY_IN_SYNC');+ expect(executeUpdate).not.toHaveBeenCalled();+ });++ it('rejects reconcile when install state could not be determined (null)', async () => {+ updateChecker.getUpdateStatus.mockResolvedValue(baseStatus({ installState: null }));+ const res = await request(makeApp()).post('/api/update/execute').send({ reconcile: true });+ expect(res.status).toBe(503);+ expect(res.body.code).toBe('INSTALL_STATE_UNAVAILABLE');+ expect(executeUpdate).not.toHaveBeenCalled();+ });++ it('runs the reconcile when out of sync, targeting the current version', async () => {+ updateChecker.getUpdateStatus.mockResolvedValue(baseStatus({ installState: { outOfSync: true } }));+ const res = await request(makeApp()).post('/api/update/execute').send({ reconcile: true });+ expect(res.status).toBe(200);+ expect(res.body).toEqual({ started: true, tag: 'v1.26.0' });+ expect(executeUpdate).toHaveBeenCalledWith('v1.26.0', expect.any(Function));+ });++ it('reconcile runs even with NO cached release (out of sync)', async () => {+ updateChecker.getUpdateStatus.mockResolvedValue(+ baseStatus({ latestRelease: null, installState: { outOfSync: true } })+ );+ const res = await request(makeApp()).post('/api/update/execute').send({ reconcile: true });+ expect(res.status).toBe(200);+ expect(res.body.tag).toBe('v1.26.0');+ });++ it('still applies the fork gate to a reconcile (unsynced fork → 412)', async () => {+ updateChecker.getUpdateStatus.mockResolvedValue(baseStatus({+ installState: { outOfSync: true },+ remoteInfo: { isFork: true, hasOrigin: true, fullName: 'alice/PortOS' },+ forkSyncFresh: false+ }));+ const res = await request(makeApp()).post('/api/update/execute').send({ reconcile: true });+ expect(res.status).toBe(412);+ expect(res.body.code).toBe('FORK_SYNC_REQUIRED');+ expect(executeUpdate).not.toHaveBeenCalled();+ });++ it('a non-reconcile update still requires a cached release tag', async () => {+ updateChecker.getUpdateStatus.mockResolvedValue(baseStatus({ latestRelease: null }));+ const res = await request(makeApp()).post('/api/update/execute').send({});+ expect(res.status).toBe(400);+ expect(res.body.code).toBe('NO_RELEASE');+ });++ it('a normal update uses the cached release tag', async () => {+ updateChecker.getUpdateStatus.mockResolvedValue(baseStatus());+ 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));+ });+});diff --git a/server/services/installState.js b/server/services/installState.jsindex a196f20844..2fd11521d9 100644--- a/server/services/installState.js+++ b/server/services/installState.js@@ -44,6 +44,14 @@ const DEP_WORKSPACES = ['.', 'client', 'server', 'autofixer'];// Directories never worth walking for client-source freshness.const WALK_SKIP_DIRS = new Set(['node_modules', 'dist', '.git']);+// The tracked lockfile and npm's receipt (node_modules/.package-lock.json) are+// written by the SAME `npm install`, milliseconds apart, in an order npm does+// not guarantee. Only treat the lockfile as "newer" when it leads the receipt+// by more than this slack — so install-time jitter never produces a permanent+// false "out of sync", while a real pulled-but-uninstalled lock (minutes/hours+// ahead) still trips. A genuine stale lock is never this close.+const LOCKFILE_NEWER_SLACK_MS = 60 * 1000;+/*** Capture the commit the process is running. Idempotent — only the first* successful read sticks, so a later on-disk `git pull` (which we WANT to@@ -147,7 +155,7 @@ async function detectStaleDeps(rootDir, { statMtime = statMtimeMs } = {}) {} else if (manifestMtime > receiptMtime) {stale = true;reason = 'manifest-newer';- } else if (lockMtime != null && lockMtime > receiptMtime) {+ } else if (lockMtime != null && lockMtime - receiptMtime > LOCKFILE_NEWER_SLACK_MS) {stale = true;reason = 'lockfile-newer';}diff --git a/server/services/installState.test.js b/server/services/installState.test.jsindex 3661bb4c65..6fae42d65b 100644--- a/server/services/installState.test.js+++ b/server/services/installState.test.js@@ -101,12 +101,12 @@ describe('getInstallState — stale deps', () => {expect(state.staleDeps.workspaces.every(w => w.reason === 'not-installed')).toBe(true);});- it('flags a workspace whose lockfile is newer than the receipt', async () => {+ it('flags a workspace whose lockfile is newer than the receipt beyond the jitter slack', async () => {const state = await getInstallState(syncedOpts({statMtime: makeStat({'package.json': 100,'.package-lock.json': 200,- 'package-lock.json': 300, // lockfile newer than receipt+ 'package-lock.json': 200 + 120000, // lockfile clearly newer (2 min) → real stale'client/dist/index.html': 500})}));@@ -114,6 +114,20 @@ describe('getInstallState — stale deps', () => {expect(state.staleDeps.workspaces.some(w => w.reason === 'lockfile-newer')).toBe(true);});+ it('does NOT flag lockfile-newer for same-install write jitter (lock barely ahead of receipt)', async () => {+ // The tracked lock and npm's receipt are written by the same `npm install`+ // ms apart; a small lead must never trip a permanent false "out of sync".+ const state = await getInstallState(syncedOpts({+ statMtime: makeStat({+ 'package.json': 100,+ '.package-lock.json': 200,+ 'package-lock.json': 220, // 20ms ahead — within slack+ 'client/dist/index.html': 500+ })+ }));+ expect(state.staleDeps.stale).toBe(false);+ });+it('skips workspaces with no package.json (absent in this install)', async () => {const state = await getInstallState(syncedOpts({statMtime: makeStat({