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

address review (codex): skip commented PORTS blocks; diff port edits against parsed config

[._.]/ Adam Eivy976591653d14
diff --git a/server/routes/apps.js b/server/routes/apps.js
index e91dd1e591..e9e3d74f31 100644
--- a/server/routes/apps.js
+++ b/server/routes/apps.js
@@ -389,28 +389,40 @@ router.put('/:id', asyncHandler(async (req, res, next) => {
// 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)) {
+ // Diff the submitted ports against the ACTUAL config values (not apps.json,
+ // whose top-level fields may be stale or absent for derived ports). This
+ // is the single source of truth for both "did it change" and "what's the
+ // old literal to rewrite": EditAppModal submits every field even on a
+ // rename, so a value equal to the config's current port is a no-op echo,
+ // and a value that differs is a genuine edit to persist.
+ const { processes: cfgProcs } = await parseEcosystemFromPath(existing.repoPath);
+ const LABEL_BY_KEY = { apiPort: 'api', uiPort: 'ui', devUiPort: 'devUi' };
+ const currentPort = {};
+ for (const proc of cfgProcs || []) {
+ for (const [key, label] of Object.entries(LABEL_BY_KEY)) {
+ if (currentPort[key] === undefined && Number.isInteger(proc.ports?.[label])) {
+ currentPort[key] = proc.ports[label];
+ }
+ }
+ }
// 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. Such a change is unpersistable by value alone.
const valueCounts = new Map();
for (const key of PORT_KEYS) {
- const v = existing[key];
+ const v = currentPort[key];
if (Number.isInteger(v)) valueCounts.set(v, (valueCounts.get(v) || 0) + 1);
}
- // 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.
+ // A port is "changed" when the submitted value differs from the config's
+ // current value for that label. A field the config doesn't define has no
+ // literal to rewrite, so it isn't treated as a config edit here.
const changedKeys = PORT_KEYS.filter(key =>
- Number.isInteger(existing[key]) && Number.isInteger(data[key]) && data[key] !== existing[key]);
+ Number.isInteger(currentPort[key]) && Number.isInteger(data[key]) && data[key] !== currentPort[key]);
const remap = [];
const unpersistable = [];
for (const key of changedKeys) {
- const oldPort = existing[key]; // guaranteed integer by the filter above
+ const oldPort = currentPort[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) {
diff --git a/server/routes/apps.test.js b/server/routes/apps.test.js
index 5459fea8a8..4d103a611a 100644
--- a/server/routes/apps.test.js
+++ b/server/routes/apps.test.js
@@ -262,6 +262,7 @@ describe('Apps Routes', () => {
// repoPath must exist on disk so the pathExists guard passes.
const mockApp = { id: 'app-001', name: 'App', type: 'node', repoPath: process.cwd(), apiPort: 5173, uiPort: 5174 };
appsService.getAppById.mockResolvedValue(mockApp);
+ streamingDetect.parseEcosystemFromPath.mockResolvedValue({ processes: [{ name: 'a', ports: { api: 5173, ui: 5174 } }] });
appsService.updateApp.mockResolvedValue({ ...mockApp, apiPort: 6000, uiPort: 6001 });
const response = await request(app)
@@ -291,6 +292,7 @@ describe('Apps Routes', () => {
// rather than persist a registry value PM2 will contradict.
const mockApp = { id: 'app-001', name: 'App', type: 'node', repoPath: process.cwd(), apiPort: 6000, uiPort: 6000 };
appsService.getAppById.mockResolvedValue(mockApp);
+ streamingDetect.parseEcosystemFromPath.mockResolvedValue({ processes: [{ name: 'a', ports: { api: 6000, ui: 6000 } }] });
const response = await request(app).put('/api/apps/app-001').send({ uiPort: 7000 });
@@ -304,6 +306,8 @@ describe('Apps Routes', () => {
// 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);
+ // Config currently serves these derived ports; the modal echoes them back.
+ streamingDetect.parseEcosystemFromPath.mockResolvedValue({ processes: [{ name: 'a', ports: { api: 5555, ui: 5556 } }] });
appsService.updateApp.mockResolvedValue({ ...mockApp, name: 'Renamed' });
const response = await request(app)
@@ -318,6 +322,7 @@ describe('Apps Routes', () => {
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);
+ streamingDetect.parseEcosystemFromPath.mockResolvedValue({ processes: [{ name: 'a', ports: { api: 5173 } }] });
streamingDetect.writeEcosystemPorts.mockResolvedValueOnce({ file: 'ecosystem.config.cjs', changed: false });
const response = await request(app).put('/api/apps/app-001').send({ apiPort: 6000 });
@@ -329,6 +334,7 @@ describe('Apps Routes', () => {
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.parseEcosystemFromPath.mockResolvedValue({ processes: [{ name: 'a', ports: { api: 5173 } }] });
streamingDetect.writeEcosystemPorts.mockRejectedValueOnce(new Error('EACCES'));
const response = await request(app).put('/api/apps/app-001').send({ apiPort: 6000 });
diff --git a/server/services/streamingDetect.js b/server/services/streamingDetect.js
index 2dc2ce9cd2..09432f2304 100644
--- a/server/services/streamingDetect.js
+++ b/server/services/streamingDetect.js
@@ -443,38 +443,30 @@ export async function parseEcosystemFromPath(dirPath) {
return { processes: [], pm2Home: null };
}
-/**
- * Locate the `const PORTS = { ... }` literal in an ecosystem config and return
- * its `{ start, end }` byte offsets (inclusive of the opening/closing braces),
- * or null when there's no PORTS object. Brace-counted so nested objects
- * (`{ server: { api: 5555 } }`) are captured whole.
- */
-function findPortsBlock(content) {
- const m = content.match(/(?:const|let|var)\s+PORTS\s*=\s*\{/);
- if (!m) return null;
- const start = m.index + m[0].length - 1; // index of the opening '{'
- // Reuse the parser's brace matcher — it correctly ignores braces inside
- // strings/comments/`${...}`, which a bare depth counter would miscount.
- const end = findMatchingBrace(content, start);
- return end < 0 ? null : { start, end };
-}
-
/**
* Brace-matched `{ start, end }` regions whose numeric values are rewritten
- * by VALUE regardless of key name: the `const PORTS = {...}` block AND every
+ * by VALUE regardless of key name: every `const PORTS = {...}` block AND every
* per-app `ports: { api: N, ui: N }` object. parseEcosystemConfig reads the
* per-app `ports:` object FIRST when deriving uiPort/apiPort/devUiPort, so a
* rewrite that skipped it would let the edit silently revert on the next
* config refresh — the exact bug the write-back exists to prevent.
+ *
+ * Commented-out matches are skipped: rewriting a port inside a commented
+ * `const PORTS = {...}` would make writeEcosystemPorts report success while the
+ * executable config is untouched (the per-region slice starts at the `{`, so
+ * the region's own comment scan can no longer see the leading `//`/`/*`).
*/
function findValuePortRegions(content) {
+ const comments = commentRanges(content);
+ const inComment = (pos) => comments.some(([s, e]) => pos >= s && pos < e);
const regions = [];
- const portsConst = findPortsBlock(content);
- if (portsConst) regions.push(portsConst);
- // Lowercase, case-sensitive `ports:` — won't match `const PORTS` or `reports:`.
- const re = /\bports\s*:\s*\{/g;
+ // `const PORTS = {` (uppercase, any declarator) OR a lowercase `ports: {`
+ // object value — the latter is case-sensitive so it won't match `const PORTS`
+ // or `reports:`.
+ const re = /(?:(?:const|let|var)\s+PORTS\s*=\s*|\bports\s*:\s*)\{/g;
let m;
while ((m = re.exec(content)) !== null) {
+ if (inComment(m.index)) continue;
const open = m.index + m[0].length - 1;
const end = findMatchingBrace(content, open);
if (end >= 0) regions.push({ start: open, end });
diff --git a/server/services/streamingDetect.test.js b/server/services/streamingDetect.test.js
index 0279641ded..e54996aa4d 100644
--- a/server/services/streamingDetect.test.js
+++ b/server/services/streamingDetect.test.js
@@ -395,6 +395,15 @@ module.exports = { apps: [{ name: 'x', script: 's.js', env: { PORT: API_PORT, CD
expect(out).toContain('// default was 5173'); // comment untouched
});
+ it('does not rewrite a port inside a commented-out PORTS block', () => {
+ const content = `/* legacy: const PORTS = { API: 5173 } */
+const PORTS = { API: 4000 };
+module.exports = { apps: [{ name: 'x', script: 's.js', env: { PORT: PORTS.API } }] };
+`;
+ const out = rewriteEcosystemPorts(content, [[5173, 6000]]);
+ expect(out).toBe(content); // the only 5173 is in a 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);