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

fix: address round 7 review — NaN guards, stale update recovery, polling guard

Adam Eivyfc6bfe0453b2
diff --git a/client/src/components/apps/tabs/UpdateTab.jsx b/client/src/components/apps/tabs/UpdateTab.jsx
index d35b503be4..af45b2a105 100644
--- a/client/src/components/apps/tabs/UpdateTab.jsx
+++ b/client/src/components/apps/tabs/UpdateTab.jsx
@@ -61,7 +61,7 @@ export default function UpdateTab() {
});
// 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') {
+ if ((step === 'restarting' || step === 'restart') && targetVersionRef.current) {
setUpdating(false);
setPolling(true);
toast.loading('PortOS is restarting...', { id: 'portos-update-restart', duration: Infinity });
diff --git a/server/index.js b/server/index.js
index e033fa3878..cbb297a629 100644
--- a/server/index.js
+++ b/server/index.js
@@ -65,7 +65,7 @@ import './services/subAgentSpawner.js'; // Initialize CoS agent spawner
import * as automationScheduler from './services/automationScheduler.js';
import * as agentActionExecutor from './services/agentActionExecutor.js';
import { startBackupScheduler } from './services/backupScheduler.js';
-import { startUpdateScheduler, recordUpdateResult } from './services/updateChecker.js';
+import { startUpdateScheduler, recordUpdateResult, clearStaleUpdateInProgress } from './services/updateChecker.js';
import { startBrainScheduler } from './services/brainScheduler.js';
import { recoverStuckClassifications } from './services/brain.js';
import { initBridge as initBrainMemoryBridge } from './services/brainMemoryBridge.js';
@@ -297,6 +297,9 @@ readFile(updateMarkerPath, 'utf-8').then(raw => {
});
});
+// Clear stale updateInProgress if the server was killed mid-update
+clearStaleUpdateInProgress().catch(err => console.error(`❌ Stale update recovery failed: ${err.message}`));
+
// Start periodic update checker (checks GitHub releases every 30 min)
startUpdateScheduler();
diff --git a/server/routes/meatspace.js b/server/routes/meatspace.js
index 87f62ab04c..48d4ca425a 100644
--- a/server/routes/meatspace.js
+++ b/server/routes/meatspace.js
@@ -182,6 +182,9 @@ router.post('/alcohol/custom-drinks', asyncHandler(async (req, res) => {
*/
router.put('/alcohol/custom-drinks/:index', asyncHandler(async (req, res) => {
const index = parseInt(req.params.index, 10);
+ if (!Number.isInteger(index)) {
+ throw new ServerError('Invalid index', { status: 400, code: 'INVALID_INDEX' });
+ }
const data = validateRequest(customDrinkUpdateSchema, req.body);
const drink = await alcoholService.updateCustomDrink(index, data);
if (!drink) {
@@ -196,6 +199,9 @@ router.put('/alcohol/custom-drinks/:index', asyncHandler(async (req, res) => {
*/
router.delete('/alcohol/custom-drinks/:index', asyncHandler(async (req, res) => {
const index = parseInt(req.params.index, 10);
+ if (!Number.isInteger(index)) {
+ throw new ServerError('Invalid index', { status: 400, code: 'INVALID_INDEX' });
+ }
const removed = await alcoholService.removeCustomDrink(index);
if (!removed) {
throw new ServerError('Custom drink not found', { status: 404, code: 'NOT_FOUND' });
diff --git a/server/services/meatspaceAlcohol.js b/server/services/meatspaceAlcohol.js
index 6bfb42c236..2de0381007 100644
--- a/server/services/meatspaceAlcohol.js
+++ b/server/services/meatspaceAlcohol.js
@@ -295,6 +295,7 @@ export async function addCustomDrink({ name, oz, abv }) {
}
export async function updateCustomDrink(index, updates) {
+ if (!Number.isInteger(index)) return null;
const data = await loadCustomDrinks();
if (index < 0 || index >= data.drinks.length) return null;
const drink = data.drinks[index];
@@ -307,6 +308,7 @@ export async function updateCustomDrink(index, updates) {
}
export async function removeCustomDrink(index) {
+ if (!Number.isInteger(index)) return null;
const data = await loadCustomDrinks();
if (index < 0 || index >= data.drinks.length) return null;
const removed = data.drinks.splice(index, 1)[0];
@@ -316,6 +318,7 @@ export async function removeCustomDrink(index) {
}
export async function reorderCustomDrinks(fromIndex, toIndex) {
+ if (!Number.isInteger(fromIndex) || !Number.isInteger(toIndex)) return null;
const data = await loadCustomDrinks();
if (fromIndex < 0 || fromIndex >= data.drinks.length) return null;
if (toIndex < 0 || toIndex >= data.drinks.length) return null;
diff --git a/server/services/updateChecker.js b/server/services/updateChecker.js
index 0e7bda0b58..6583f25b17 100644
--- a/server/services/updateChecker.js
+++ b/server/services/updateChecker.js
@@ -164,6 +164,7 @@ export async function setUpdateInProgress(inProgress) {
return withLock(async () => {
const state = await loadState();
state.updateInProgress = inProgress;
+ state.updateStartedAt = inProgress ? new Date().toISOString() : null;
await saveState(state);
});
}
@@ -175,11 +176,47 @@ export async function recordUpdateResult(result) {
return withLock(async () => {
const state = await loadState();
state.updateInProgress = false;
+ state.updateStartedAt = null;
state.lastUpdateResult = result;
await saveState(state);
});
}
+const STALE_UPDATE_TIMEOUT_MS = 30 * 60 * 1000; // 30 minutes
+
+/**
+ * Clear stale updateInProgress flag on boot.
+ * If the server was killed mid-update (before recordUpdateResult ran),
+ * updateInProgress stays true and blocks future updates indefinitely.
+ * This detects that condition via updateStartedAt age and clears it.
+ */
+export async function clearStaleUpdateInProgress() {
+ return withLock(async () => {
+ const state = await loadState();
+ if (!state.updateInProgress) return false;
+
+ const startedAt = state.updateStartedAt ? new Date(state.updateStartedAt).getTime() : 0;
+ const ageMs = Date.now() - startedAt;
+
+ // If no timestamp or older than timeout, treat as stale
+ if (!state.updateStartedAt || ageMs > STALE_UPDATE_TIMEOUT_MS) {
+ console.log(`🧹 Clearing stale updateInProgress (started ${state.updateStartedAt ?? 'unknown'}, age ${Math.round(ageMs / 60000)}min)`);
+ state.updateInProgress = false;
+ state.updateStartedAt = null;
+ state.lastUpdateResult = {
+ version: state.latestRelease?.version ?? 'unknown',
+ success: false,
+ completedAt: new Date().toISOString(),
+ log: 'Cleared stale update lock on boot — server was likely killed mid-update'
+ };
+ await saveState(state);
+ return true;
+ }
+
+ return false;
+ });
+}
+
/**
* Start the periodic update checker.
*/
diff --git a/server/services/updateChecker.test.js b/server/services/updateChecker.test.js
index c853fecd24..187e0c6b6d 100644
--- a/server/services/updateChecker.test.js
+++ b/server/services/updateChecker.test.js
@@ -32,6 +32,7 @@ import {
ignoreVersion,
clearIgnored,
checkForUpdate,
+ clearStaleUpdateInProgress,
updateEvents
} from './updateChecker.js';
@@ -325,3 +326,81 @@ describe('checkForUpdate', () => {
expect(result.latestRelease.version).toBe('2.0.0');
});
});
+
+describe('clearStaleUpdateInProgress', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ writeFile.mockResolvedValue(undefined);
+ ensureDir.mockResolvedValue(undefined);
+ });
+
+ it('should return false when updateInProgress is false', async () => {
+ readJSONFile.mockResolvedValue({
+ lastCheck: null,
+ latestRelease: null,
+ ignoredVersions: [],
+ updateInProgress: false,
+ updateStartedAt: null,
+ lastUpdateResult: null
+ });
+
+ const cleared = await clearStaleUpdateInProgress();
+ expect(cleared).toBe(false);
+ expect(writeFile).not.toHaveBeenCalled();
+ });
+
+ it('should clear stale updateInProgress when updateStartedAt is older than 30 minutes', async () => {
+ const staleTime = new Date(Date.now() - 60 * 60 * 1000).toISOString(); // 1 hour ago
+ readJSONFile.mockResolvedValue({
+ lastCheck: null,
+ latestRelease: { version: '1.28.0' },
+ ignoredVersions: [],
+ updateInProgress: true,
+ updateStartedAt: staleTime,
+ lastUpdateResult: null
+ });
+
+ const cleared = await clearStaleUpdateInProgress();
+ expect(cleared).toBe(true);
+ expect(writeFile).toHaveBeenCalled();
+ const saved = JSON.parse(writeFile.mock.calls[0][1]);
+ expect(saved.updateInProgress).toBe(false);
+ expect(saved.updateStartedAt).toBeNull();
+ expect(saved.lastUpdateResult.success).toBe(false);
+ expect(saved.lastUpdateResult.version).toBe('1.28.0');
+ });
+
+ it('should clear updateInProgress when updateStartedAt is missing', async () => {
+ readJSONFile.mockResolvedValue({
+ lastCheck: null,
+ latestRelease: null,
+ ignoredVersions: [],
+ updateInProgress: true,
+ updateStartedAt: null,
+ lastUpdateResult: null
+ });
+
+ const cleared = await clearStaleUpdateInProgress();
+ expect(cleared).toBe(true);
+ expect(writeFile).toHaveBeenCalled();
+ const saved = JSON.parse(writeFile.mock.calls[0][1]);
+ expect(saved.updateInProgress).toBe(false);
+ expect(saved.lastUpdateResult.version).toBe('unknown');
+ });
+
+ it('should not clear updateInProgress when update is recent (< 30 min)', async () => {
+ const recentTime = new Date(Date.now() - 5 * 60 * 1000).toISOString(); // 5 minutes ago
+ readJSONFile.mockResolvedValue({
+ lastCheck: null,
+ latestRelease: { version: '1.28.0' },
+ ignoredVersions: [],
+ updateInProgress: true,
+ updateStartedAt: recentTime,
+ lastUpdateResult: null
+ });
+
+ const cleared = await clearStaleUpdateInProgress();
+ expect(cleared).toBe(false);
+ expect(writeFile).not.toHaveBeenCalled();
+ });
+});