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): don't 422 non-port edits on derived-port apps; skip comments in rewrite
[._.]/ Adam Eivy79e3b743a610
diff --git a/server/routes/apps.js b/server/routes/apps.jsindex 2fa0cb2326..e91dd1e591 100644--- a/server/routes/apps.js+++ b/server/routes/apps.js@@ -398,15 +398,22 @@ router.put('/:id', asyncHandler(async (req, res, next) => {const v = existing[key];if (Number.isInteger(v)) valueCounts.set(v, (valueCounts.get(v) || 0) + 1);}- // A port the user actually changed (valid new value, differs from current).- const changedKeys = PORT_KEYS.filter(key => Number.isInteger(data[key]) && data[key] !== existing[key]);+ // A port the user actually changed. Require a STORED integer old value:+ // EditAppModal submits every field (even on a rename), and for an app whose+ // top-level port isn't stored in apps.json (derived from processes) the+ // submitted value is just the echoed derived display value — comparing it+ // against an undefined registry value would misread an unchanged field as a+ // change and wrongly reject the edit. Without a stored old value there's+ // also no literal to diff/rewrite, so such fields are left to a config edit.+ const changedKeys = PORT_KEYS.filter(key =>+ Number.isInteger(existing[key]) && Number.isInteger(data[key]) && data[key] !== existing[key]);const remap = [];const unpersistable = [];for (const key of changedKeys) {- const oldPort = existing[key];- // No old literal to find (derived/absent), or value shared with another- // field (can't disambiguate by value) → can't write it to the config.- if (!Number.isInteger(oldPort) || valueCounts.get(oldPort) > 1) {+ const oldPort = existing[key]; // guaranteed integer by the filter above+ // Value shared with another field (can't disambiguate by value) → can't+ // safely write it to the config without clobbering the other field.+ if (valueCounts.get(oldPort) > 1) {unpersistable.push(key);continue;}diff --git a/server/routes/apps.test.js b/server/routes/apps.test.jsindex 2b36d02bd3..5459fea8a8 100644--- a/server/routes/apps.test.js+++ b/server/routes/apps.test.js@@ -299,6 +299,22 @@ describe('Apps Routes', () => {expect(appsService.updateApp).not.toHaveBeenCalled();});+ it('does not reject a non-port edit on an app whose top-level ports are not stored (derived)', async () => {+ // apps.json has no apiPort/uiPort (derived from processes); a rename+ // submits the echoed display values. Those must not read as port changes.+ const mockApp = { id: 'app-001', name: 'App', type: 'node', repoPath: process.cwd() };+ appsService.getAppById.mockResolvedValue(mockApp);+ appsService.updateApp.mockResolvedValue({ ...mockApp, name: 'Renamed' });++ const response = await request(app)+ .put('/api/apps/app-001')+ .send({ name: 'Renamed', apiPort: 5555, uiPort: 5556 });++ expect(response.status).toBe(200);+ expect(streamingDetect.writeEcosystemPorts).not.toHaveBeenCalled();+ expect(appsService.updateApp).toHaveBeenCalled();+ });+it('rejects (422) when the port literal is not found in the config (changed:false)', async () => {const mockApp = { id: 'app-001', name: 'App', type: 'node', repoPath: process.cwd(), apiPort: 5173 };appsService.getAppById.mockResolvedValue(mockApp);diff --git a/server/services/streamingDetect.js b/server/services/streamingDetect.jsindex a9ed95f8ba..2dc2ce9cd2 100644--- a/server/services/streamingDetect.js+++ b/server/services/streamingDetect.js@@ -482,6 +482,46 @@ function findValuePortRegions(content) {return regions;}+/**+ * Byte ranges `[start, end)` covered by line comments and block comments,+ * skipping comment markers that appear inside string/template literals. Used to+ * keep the port rewrite from matching (and falsely "succeeding" on) a port that+ * only appears in a comment.+ */+function commentRanges(content) {+ const ranges = [];+ let i = 0;+ const n = content.length;+ let inString = false;+ let stringChar = null;+ while (i < n) {+ const c = content[i];+ const nx = i + 1 < n ? content[i + 1] : '';+ if (inString) {+ if (c === '\\') { i += 2; continue; }+ if (c === stringChar) inString = false;+ i++;+ continue;+ }+ if (c === '"' || c === "'" || c === '`') { inString = true; stringChar = c; i++; continue; }+ if (c === '/' && nx === '/') {+ const start = i; i += 2;+ while (i < n && content[i] !== '\n') i++;+ ranges.push([start, i]);+ continue;+ }+ if (c === '/' && nx === '*') {+ const start = i; i += 2;+ while (i < n && !(content[i] === '*' && content[i + 1] === '/')) i++;+ i += 2;+ ranges.push([start, Math.min(i, n)]);+ continue;+ }+ i++;+ }+ return ranges;+}+/*** Rewrite port literals in an ecosystem.config content string per a remap of* old → new port numbers. Pure (no I/O) so it's unit-testable.@@ -518,6 +558,19 @@ export function rewriteEcosystemPorts(content, remap) {// Port-ish env keys: PORT, FOO_PORT, VITE_PORT (and quoted variants), plus `port:`.const KEY = `(?:[A-Za-z][A-Za-z0-9_]*_PORT|PORT|port)`;+ // Replace `re` everywhere EXCEPT inside comments — `re` must have its port+ // number as the last capture group so we know where the digits start. A port+ // value living only in a comment (`// PORT: 5173`) must NOT count as a rewrite,+ // or writeEcosystemPorts would report changed:true while the executable config+ // is untouched, recreating the apps.json-vs-PM2 mismatch this prevents.+ const replaceOutsideComments = (str, re, phI) => {+ const ranges = commentRanges(str);+ return str.replace(re, (full, prefix, offset) => {+ const numStart = offset + prefix.length;+ return ranges.some(([s, e]) => numStart >= s && numStart < e) ? full : `${prefix}${phI}`;+ });+ };+let out = content;// 1) Within `const PORTS = {...}` and each per-app `ports: {...}` object,@@ -528,32 +581,26 @@ export function rewriteEcosystemPorts(content, remap) {for (const region of regions) {let inner = out.slice(region.start, region.end + 1);pairs.forEach(([oldP], i) => {- inner = inner.replace(new RegExp(`(:\\s*)${oldP}\\b`, 'g'), `$1${ph(i)}`);+ inner = replaceOutsideComments(inner, new RegExp(`(:\\s*)${oldP}\\b`, 'g'), ph(i));});out = out.slice(0, region.start) + inner + out.slice(region.end + 1);}// 2) `--port <old>` in args strings.pairs.forEach(([oldP], i) => {- out = out.replace(new RegExp(`(--port\\s+)${oldP}\\b`, 'g'), `$1${ph(i)}`);+ out = replaceOutsideComments(out, new RegExp(`(--port\\s+)${oldP}\\b`, 'g'), ph(i));});// 3) Port-ish key assignments anywhere (env blocks, ports objects).pairs.forEach(([oldP], i) => {- out = out.replace(- new RegExp(`(['"\`]?\\b${KEY}\\b['"\`]?\\s*:\\s*)${oldP}\\b`, 'g'),- `$1${ph(i)}`- );+ out = replaceOutsideComments(out, new RegExp(`(['"\`]?\\b${KEY}\\b['"\`]?\\s*:\\s*)${oldP}\\b`, 'g'), ph(i));});// 4) Top-level port constants — `const API_PORT = 5555` / `let CDP_PORT = …`.// parseEcosystemConfig derives ports from these (a `\w*PORT\w*` name `=`// number), so an edit that skipped them would revert on the next refresh.pairs.forEach(([oldP], i) => {- out = out.replace(- new RegExp(`((?:const|let|var)\\s+\\w*PORT\\w*\\s*=\\s*)${oldP}\\b`, 'g'),- `$1${ph(i)}`- );+ out = replaceOutsideComments(out, new RegExp(`((?:const|let|var)\\s+\\w*PORT\\w*\\s*=\\s*)${oldP}\\b`, 'g'), ph(i));});// 5) Fallback-expression defaults — `PORT: process.env.PORT || 4420`.@@ -562,10 +609,7 @@ export function rewriteEcosystemPorts(content, remap) {// so match the port-ish key, then any same-value expression up to `||`.// `[^,}\n]*?` keeps the match inside one value (no comma/brace/newline).pairs.forEach(([oldP], i) => {- out = out.replace(- new RegExp(`(['"\`]?\\b${KEY}\\b['"\`]?\\s*:\\s*[^,}\\n]*?\\|\\|\\s*['"]?)${oldP}\\b`, 'g'),- `$1${ph(i)}`- );+ out = replaceOutsideComments(out, new RegExp(`(['"\`]?\\b${KEY}\\b['"\`]?\\s*:\\s*[^,}\\n]*?\\|\\|\\s*['"]?)${oldP}\\b`, 'g'), ph(i));});// Resolve placeholders → new values.diff --git a/server/services/streamingDetect.test.js b/server/services/streamingDetect.test.jsindex ed17168389..0279641ded 100644--- a/server/services/streamingDetect.test.js+++ b/server/services/streamingDetect.test.js@@ -377,6 +377,24 @@ module.exports = { apps: [{ name: 'x', script: 's.js', env: { PORT: API_PORT, CDexpect(parseEcosystemConfig(out).processes[0].ports.api).toBe(6000);});+ it('does not rewrite a port that appears only in a comment (no false success)', () => {+ // The executable port is 4000; 5173 lives only in a comment. Rewriting+ // 5173 must change nothing — else writeEcosystemPorts would report success+ // while the real config still serves 4000.+ const content = `module.exports = { apps: [{ name: 'x', script: 's.js', env: { /* legacy PORT: 5173 */ PORT: 4000 } }] };+// historical default PORT: 5173+`;+ const out = rewriteEcosystemPorts(content, [[5173, 6000]]);+ expect(out).toBe(content); // unchanged+ });++ it('rewrites the executable port but leaves a same-valued trailing comment alone', () => {+ const content = `module.exports = { apps: [{ name: 'x', script: 's.js', env: { PORT: 5173 } }] }; // default was 5173\n`;+ const out = rewriteEcosystemPorts(content, [[5173, 6000]]);+ expect(parseEcosystemConfig(out).processes[0].ports.api).toBe(6000);+ expect(out).toContain('// default was 5173'); // comment untouched+ });+it('is a no-op when remap is empty or only contains identity pairs', () => {const content = `module.exports = { apps: [{ name: 'x', script: 's.js', env: { PORT: 5173 } }] };`;expect(rewriteEcosystemPorts(content, [])).toBe(content);