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): write config before registry, skip ambiguous shared-port rewrites
[._.]/ Adam Eivybda695305bd5
diff --git a/server/routes/apps.js b/server/routes/apps.jsindex 140b8a8ffb..e82cdcc4d1 100644--- a/server/routes/apps.js+++ b/server/routes/apps.js@@ -382,36 +382,49 @@ router.put('/:id', asyncHandler(async (req, res, next) => {const PORT_KEYS = ['apiPort', 'uiPort', 'devUiPort'];const hasPortUpdate = PORT_KEYS.some(key => key in data);const existing = hasPortUpdate ? await appsService.getAppById(req.params.id) : null;- const app = await appsService.updateApp(req.params.id, data);-- if (!app) {- throw new ServerError('App not found', { status: 404, code: 'NOT_FOUND' });- }- // Port fields in apps.json are *derived* from ecosystem.config.cjs by- // parseEcosystemConfig. Persisting an edit only to apps.json leaves PM2 on- // the old ports and lets the next config refresh clobber the change — so- // write the new ports back to the canonical config file too.- if (existing && usesPm2(app.type) && await pathExists(app.repoPath)) {+ // Port fields in apps.json are *derived* from ecosystem.config.cjs (the+ // source of truth PM2 reads). Persist the change to the canonical config+ // FIRST, before the derived registry: an unreadable/unwritable config then+ // surfaces as a failed request instead of a 200 that leaves apps.json and+ // PM2 disagreeing (the write throws and bubbles to the error middleware).+ if (existing && usesPm2(existing.type) && await pathExists(existing.repoPath)) {+ // Count current values so a value-keyed rewrite never fires on a number+ // shared by another port field (e.g. uiPort derived from apiPort, both+ // 6000) — that would rewrite every occurrence and clobber the field the+ // user didn't touch.+ const valueCounts = new Map();+ for (const key of PORT_KEYS) {+ const v = existing[key];+ if (Number.isInteger(v)) valueCounts.set(v, (valueCounts.get(v) || 0) + 1);+ }const remap = [];for (const key of PORT_KEYS) {const oldPort = existing[key];- const newPort = app[key];- if (Number.isInteger(oldPort) && Number.isInteger(newPort) && oldPort !== newPort) {- remap.push([oldPort, newPort]);+ const newPort = data[key];+ if (!Number.isInteger(oldPort) || !Number.isInteger(newPort) || oldPort === newPort) continue;+ if (valueCounts.get(oldPort) > 1) {+ console.warn(`⚠️ Skipped ecosystem rewrite of ${key} for ${existing.name}: ${oldPort} is shared by another port — can't disambiguate by value`);+ continue;}+ remap.push([oldPort, newPort]);}if (remap.length > 0) {- const result = await writeEcosystemPorts(app.repoPath, remap).catch((err) => {- console.error(`❌ Failed to write ports to ecosystem config for ${app.name}: ${err.message}`);- return null;- });+ const result = await writeEcosystemPorts(existing.repoPath, remap);if (result?.changed) {- console.log(`🔧 Updated ${result.file} ports for ${app.name}: ${remap.map(([o, n]) => `${o}→${n}`).join(', ')} (restart the app to apply)`);+ console.log(`🔧 Updated ${result.file} ports for ${existing.name}: ${remap.map(([o, n]) => `${o}→${n}`).join(', ')} (restart the app to apply)`);+ } else {+ console.warn(`⚠️ Port edit for ${existing.name} found no matching literal in ecosystem config — registry updated, but restart/refresh won't pick up the new port`);}}}+ const app = await appsService.updateApp(req.params.id, data);++ if (!app) {+ throw new ServerError('App not found', { status: 404, code: 'NOT_FOUND' });+ }+res.json(app);}));diff --git a/server/routes/apps.test.js b/server/routes/apps.test.jsindex fac9ecef3b..a9b19a0cc8 100644--- a/server/routes/apps.test.js+++ b/server/routes/apps.test.js@@ -284,6 +284,31 @@ describe('Apps Routes', () => {expect(streamingDetect.writeEcosystemPorts).not.toHaveBeenCalled();});++ it('skips the rewrite when the changed port shares its value with another port field', async () => {+ // uiPort derived from apiPort — both 6000. Changing only uiPort must NOT+ // value-rewrite every 6000 (which would clobber the unchanged apiPort).+ const mockApp = { id: 'app-001', name: 'App', type: 'node', repoPath: process.cwd(), apiPort: 6000, uiPort: 6000 };+ appsService.getAppById.mockResolvedValue(mockApp);+ appsService.updateApp.mockResolvedValue({ ...mockApp, uiPort: 7000 });++ const response = await request(app).put('/api/apps/app-001').send({ uiPort: 7000 });++ expect(response.status).toBe(200);+ expect(streamingDetect.writeEcosystemPorts).not.toHaveBeenCalled();+ });++ it('fails the request (and does not update the registry) when the config write throws', async () => {+ const mockApp = { id: 'app-001', name: 'App', type: 'node', repoPath: process.cwd(), apiPort: 5173 };+ appsService.getAppById.mockResolvedValue(mockApp);+ streamingDetect.writeEcosystemPorts.mockRejectedValueOnce(new Error('EACCES'));++ const response = await request(app).put('/api/apps/app-001').send({ apiPort: 6000 });++ expect(response.status).toBeGreaterThanOrEqual(500);+ // Registry write must not happen after a failed canonical-config write.+ expect(appsService.updateApp).not.toHaveBeenCalled();+ });});describe('DELETE /api/apps/:id', () => {