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

claim the app-operation lock synchronously so two self-updates cannot both run (#6638)

[._.]/ Adam Eivy3380096420d8
diff --git a/server/sockets/apps.js b/server/sockets/apps.js
index da484d52b7..dc662b9dbf 100644
--- a/server/sockets/apps.js
+++ b/server/sockets/apps.js
@@ -20,21 +20,40 @@ import {
// the re-entrancy guard and the resumable progress buffer.
const activeAppOperations = new Map();
+// One operation occupies several keys, so collapse them back to one row.
// repoPath stays server-side: the client only needs to name and render the run.
const activeOperationsPayload = () => ({
- operations: [...activeAppOperations.values()].map(({ repoPath: _repoPath, ...op }) => op)
+ operations: [...new Set(activeAppOperations.values())].map(({ repoPath: _repoPath, ...op }) => op)
});
// Two app records may point at the same checkout, so the app id alone doesn't
-// identify the resource being mutated.
-const findConflictingOperation = (app) => activeAppOperations.get(app.id)
- || (app.repoPath ? [...activeAppOperations.values()].find(op => op.repoPath === app.repoPath) : undefined);
+// identify the resource being mutated — an operation is registered under every
+// key that names the resource it is mutating.
+const operationKeys = (app) => (app.repoPath && app.repoPath !== app.id ? [app.id, app.repoPath] : [app.id]);
+
+const findConflictingOperation = (app) => operationKeys(app)
+ .map(key => activeAppOperations.get(key))
+ .find(Boolean);
+
+// Refuse rather than overwrite: a caller that reaches the registry without
+// going through claimAppOperation must not be able to silently clobber a live
+// run out of the map and orphan its step buffer.
+const setOperationKey = (key, operation) => {
+ if (activeAppOperations.has(key)) throw new Error(`App operation already in flight for ${key}`);
+ activeAppOperations.set(key, operation);
+};
-const beginAppOperation = (io, app, type) => {
+// Claim the resource for this run. The conflict check and the registry write
+// are one synchronous step — an await between them is what let two overlapping
+// dispatches both pass the check, both run, and then delete each other's
+// record (#6638). Callers must claim BEFORE any further await.
+const claimAppOperation = (io, app, type) => {
+ const inFlight = findConflictingOperation(app);
+ if (inFlight) return { ok: false, inFlight };
const operation = { appId: app.id, appName: app.name, type, steps: [], startedAt: Date.now(), repoPath: app.repoPath };
- activeAppOperations.set(app.id, operation);
+ for (const key of operationKeys(app)) setOperationKey(key, operation);
io.emit('app:operations:active', activeOperationsPayload());
- return operation;
+ return { ok: true, operation };
};
// A PortOS self-update deliberately leaves its operation registered: the
@@ -42,8 +61,14 @@ const beginAppOperation = (io, app, type) => {
// path has no process boundary, so it needs a way back to an empty set.
export const __resetAppOperations = () => activeAppOperations.clear();
+// Clear every key this operation holds, and only the keys pointing at THIS
+// operation — a run that already finished must not evict a live sibling.
const endAppOperation = (io, appId) => {
- if (!activeAppOperations.delete(appId)) return;
+ const operation = activeAppOperations.get(appId);
+ if (!operation) return;
+ for (const [key, op] of activeAppOperations) {
+ if (op === operation) activeAppOperations.delete(key);
+ }
io.emit('app:operations:active', activeOperationsPayload());
};
@@ -109,15 +134,20 @@ export const registerAppHandlers = (socket, io) => {
return;
}
- const inFlight = findConflictingOperation(app);
- if (inFlight) {
+ // Claimed here, immediately after the app record resolves and BEFORE the
+ // preflight await below — the claim has to cover every await that
+ // precedes the actual update, or two dispatches land inside the gap.
+ const claim = claimAppOperation(io, app, 'update');
+ if (!claim.ok) {
socket.emit('app:update:error', {
appId: app.id,
duplicate: true,
- message: `An ${inFlight.type} is already running for ${inFlight.appName}`
+ message: `An ${claim.inFlight.type} is already running for ${claim.inFlight.appName}`
});
return;
}
+ const operation = claim.operation;
+ operatingAppId = app.id;
// PortOS is itself a managed app, and updating it restarts the whole
// install — apply the same refusals POST /api/update/execute enforces
@@ -134,14 +164,14 @@ export const registerAppHandlers = (socket, io) => {
acknowledgePersistentMindImageBackup: data.acknowledgePersistentMindImageBackup === true,
}).then(() => null, (err) => err);
if (refusal) {
+ endAppOperation(io, app.id);
+ operatingAppId = null;
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;
const emit = (step, status, message) => {
const frame = { appId: app.id, step, status, message, timestamp: Date.now() };
recordOperationStep(operation, frame);
@@ -208,19 +238,19 @@ export const registerAppHandlers = (socket, io) => {
return;
}
- const inFlight = findConflictingOperation(app);
- if (inFlight) {
+ const claim = claimAppOperation(io, app, 'standardize');
+ if (!claim.ok) {
socket.emit('app:standardize:error', {
appId: app.id,
duplicate: true,
- message: `An ${inFlight.type} is already running for ${inFlight.appName}`
+ message: `An ${claim.inFlight.type} is already running for ${claim.inFlight.appName}`
});
return;
}
+ const operation = claim.operation;
+ operatingAppId = app.id;
console.log(`🔧 Socket standardize started for ${app.name}`);
- const operation = beginAppOperation(io, app, 'standardize');
- operatingAppId = app.id;
const emit = (step, status, message) => {
const frame = { appId: app.id, step, status, message, timestamp: Date.now() };
recordOperationStep(operation, frame);
diff --git a/server/sockets/apps.test.js b/server/sockets/apps.test.js
index 026b01155b..bb07bb64d7 100644
--- a/server/sockets/apps.test.js
+++ b/server/sockets/apps.test.js
@@ -34,6 +34,8 @@ 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 { checkPortosUpdatePreflight } from '../services/updatePreflight.js';
+import { PORTOS_APP_ID } from '../lib/appIdentity.js';
import { __resetAppOperations, registerAppHandlers } from '../sockets/apps.js';
// Two app records pointing at ONE checkout — the case app id alone can't catch.
@@ -41,6 +43,9 @@ const APPS = {
'app-a': { id: 'app-a', name: 'Example App A', repoPath: '/repos/shared', type: 'node' },
'app-b': { id: 'app-b', name: 'Example App B', repoPath: '/repos/shared', type: 'node' },
'app-c': { id: 'app-c', name: 'Example App C', repoPath: '/repos/other', type: 'node' },
+ // PortOS itself: the one update path with an await (the preflight) between
+ // resolving the app record and starting the run.
+ [PORTOS_APP_ID]: { id: PORTOS_APP_ID, name: 'PortOS', repoPath: '/repos/portos', type: 'node' },
};
const deferred = () => {
@@ -102,6 +107,9 @@ describe('app socket handlers', () => {
beforeEach(() => {
vi.clearAllMocks();
+ // activeAppOperations is module state: a test that fails mid-run would
+ // otherwise leave the guard armed and cascade into every later test.
+ __resetAppOperations();
bus = makeBus();
appsService.getAppById.mockImplementation(async (id) => APPS[id] ?? null);
});
@@ -149,6 +157,64 @@ describe('app socket handlers', () => {
await settled;
});
+ it("refuses a second self-update dispatched inside the preflight window", async () => {
+ // app:update awaits the PortOS preflight between resolving the app record
+ // and starting the run. The claim has to be taken synchronously with the
+ // conflict check and ahead of that await — otherwise both dispatches pass
+ // the guard, two update.sh runs rewrite one checkout, and the first to
+ // finish deletes the survivor from the registry (#6638).
+ const preflight = deferred();
+ checkPortosUpdatePreflight.mockImplementation(async () => { await preflight.promise; });
+ const gate = deferred();
+ appUpdater.updateApp.mockImplementation(async () => gate.promise);
+
+ const first = connect(bus);
+ const second = connect(bus);
+ const firstRun = first.fire("app:update", { appId: PORTOS_APP_ID });
+ const secondRun = second.fire("app:update", { appId: PORTOS_APP_ID });
+
+ // Both handlers are now parked in the preflight — the exact window the
+ // claim used to sit behind. Releasing it lets them race.
+ preflight.resolve();
+ await new Promise((resolve) => setTimeout(resolve, 0));
+
+ expect(appUpdater.updateApp).toHaveBeenCalledTimes(1);
+ const refusals = [...first.events("app:update:error"), ...second.events("app:update:error")];
+ expect(refusals).toHaveLength(1);
+ expect(refusals[0].payload).toMatchObject({ appId: PORTOS_APP_ID, duplicate: true });
+
+ // The survivor is still the only registered run while it is in flight.
+ expect(first.last("app:operations:active").payload.operations)
+ .toMatchObject([{ appId: PORTOS_APP_ID, type: "update" }]);
+
+ gate.resolve({ success: true, steps: [] });
+ await Promise.all([firstRun, secondRun]);
+ expect(first.last("app:operations:active").payload.operations).toEqual([]);
+ });
+
+ it("clears every key a finished operation held without evicting a concurrent run", async () => {
+ // app-a holds two keys: its own id and the /repos/shared checkout.
+ const shared = await startParkedUpdate(bus, "app-a");
+ const unrelated = await startParkedUpdate(bus, "app-c");
+
+ shared.release();
+ await shared.settled;
+
+ // A finished run must not take its neighbour out of the registry with it.
+ expect(unrelated.client.last("app:operations:active").payload.operations)
+ .toMatchObject([{ appId: "app-c", type: "update" }]);
+
+ // ...and it has to release the repoPath key too, or the shared checkout
+ // stays blocked forever by an operation that already ended.
+ const reuse = connect(bus);
+ appUpdater.updateApp.mockResolvedValueOnce({ success: true, steps: [] });
+ await reuse.fire("app:update", { appId: "app-b" });
+ expect(reuse.events("app:update:error")).toHaveLength(0);
+
+ unrelated.release();
+ await unrelated.settled;
+ });
+
it('refuses a standardize while an update is running on the same checkout', async () => {
const { settled, release } = await startParkedUpdate(bus, 'app-a');