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 (claude): rewrite per-app ports:{} objects, exempt own ports on re-standardize

[._.]/ Adam Eivy6269d1bc0ab2
diff --git a/server/routes/apps.js b/server/routes/apps.js
index ad051c9b9f..140b8a8ffb 100644
--- a/server/routes/apps.js
+++ b/server/routes/apps.js
@@ -376,8 +376,10 @@ router.put('/:id', asyncHandler(async (req, res, next) => {
// Only port edits need the canonical-config write-back below; snapshot the
// pre-update ports just for those so ordinary updates (rename, archive,
- // jira/datadog) don't pay the extra read + fs stat.
- const PORT_KEYS = ['apiPort', 'uiPort', 'devUiPort', 'tlsPort'];
+ // jira/datadog) don't pay the extra read + fs stat. tlsPort is omitted: it's
+ // synthetic (derived from cert presence / upgradeAppTls), never a literal in
+ // ecosystem.config.cjs, so there's nothing to rewrite for it.
+ 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);
diff --git a/server/services/pm2Standardizer.js b/server/services/pm2Standardizer.js
index f1835c8e86..06e706781c 100644
--- a/server/services/pm2Standardizer.js
+++ b/server/services/pm2Standardizer.js
@@ -7,7 +7,7 @@ import { getActiveProvider, getProviderById } from './providers.js';
import { spawn } from 'child_process';
import { safeJSONParse, tryReadFile } from '../lib/fileUtils.js';
import { runPromptThroughProvider } from '../lib/promptRunner.js';
-import { getReservedPorts } from './apps.js';
+import { getReservedPorts, getAllApps } from './apps.js';
import { getListeningPorts } from '../lib/platform.js';
const execAsync = promisify(exec);
@@ -99,18 +99,42 @@ export function reassignCollidingPorts(processes, takenPorts) {
return [...remap.entries()];
}
+/**
+ * Collect every port a registered app already holds — top-level fields plus
+ * each process's `ports` map — mirroring getReservedPorts' per-app walk. Used
+ * to exempt the app being re-standardized from its own "taken" set.
+ */
+function ownPortsOf(app) {
+ const ports = [];
+ if (!app) return ports;
+ for (const p of [app.uiPort, app.devUiPort, app.apiPort, app.tlsPort]) ports.push(p);
+ if (Array.isArray(app.processes)) {
+ for (const proc of app.processes) {
+ if (proc?.port) ports.push(proc.port);
+ if (proc?.ports && typeof proc.ports === 'object') {
+ for (const value of Object.values(proc.ports)) ports.push(value);
+ }
+ }
+ }
+ return ports.filter(Number.isInteger);
+}
+
/**
* Ports that must not be assigned to a freshly standardized app: everything
* currently listening on the host, every port already reserved by another
- * PortOS-managed app, and the common Vite defaults.
+ * PortOS-managed app, and the common Vite defaults — minus `excludePorts`, the
+ * ports the app being standardized already owns (so re-standardizing keeps its
+ * own valid ports instead of treating them as collisions and bumping them).
*/
-async function gatherTakenPorts() {
+async function gatherTakenPorts(excludePorts = []) {
const [reserved, listening] = await Promise.all([
getReservedPorts().catch(() => []),
getListeningPorts().catch(() => []),
]);
+ const own = new Set(excludePorts.filter(Number.isInteger));
return Array.from(new Set([...reserved, ...listening, ...VITE_DEFAULT_PORTS]))
.filter(Number.isInteger)
+ .filter((p) => !own.has(p))
.sort((a, b) => a - b);
}
@@ -404,9 +428,12 @@ export async function analyzeApp(repoPath, providerId = null) {
return { success: false, error: 'AI provider is disabled' };
}
- // Gather context + the set of ports we must steer the LLM away from
+ // Gather context + the set of ports we must steer the LLM away from. Exempt
+ // the app's own current ports (matched by repoPath) so re-standardizing a
+ // registered app doesn't treat its valid ports as collisions and bump them.
const context = await gatherConfigContext(repoPath);
- const takenPorts = await gatherTakenPorts();
+ const ownApp = (await getAllApps().catch(() => [])).find((a) => a.repoPath === repoPath);
+ const takenPorts = await gatherTakenPorts(ownPortsOf(ownApp));
const prompt = buildStandardizationPrompt(context, takenPorts);
// Execute analysis
diff --git a/server/services/streamingDetect.js b/server/services/streamingDetect.js
index d11c18e4bf..ec25180be2 100644
--- a/server/services/streamingDetect.js
+++ b/server/services/streamingDetect.js
@@ -450,6 +450,29 @@ function findPortsBlock(content) {
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
+ * 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.
+ */
+function findValuePortRegions(content) {
+ 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;
+ let m;
+ while ((m = re.exec(content)) !== null) {
+ const open = m.index + m[0].length - 1;
+ const end = findMatchingBrace(content, open);
+ if (end >= 0) regions.push({ start: open, end });
+ }
+ return regions;
+}
+
/**
* 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.
@@ -461,12 +484,14 @@ function findPortsBlock(content) {
*
* Replacements are deliberately narrow so unrelated numbers (watch_delay,
* timeouts) are never touched:
- * 1. numeric values inside a `const PORTS = {...}` block (arbitrary keys),
+ * 1. numeric values inside a `const PORTS = {...}` block AND each per-app
+ * `ports: {...}` object (arbitrary keys — matched by value),
* 2. `--port <n>` tokens in args strings,
* 3. port-ish env keys (`PORT`, `*_PORT`, `VITE_PORT`) and `port:`.
*
* Each old value is first swapped to a unique placeholder, then placeholders
* resolve to new values — so a remap like 6000→6001, 6001→6002 can't chain.
+ * Placeholders are NUL-wrapped so index 1's token can't prefix-match index 10's.
*
* @param {string} content
* @param {Map<number,number>|Array<[number,number]>} remap
@@ -478,24 +503,23 @@ export function rewriteEcosystemPorts(content, remap) {
.filter(([o, n]) => Number.isInteger(o) && Number.isInteger(n) && o > 0 && n > 0 && o !== n);
if (pairs.length === 0) return content;
- const ph = (i) => `PORT_REMAP_${i}`;
+ const ph = (i) => `PORT_REMAP_${i}_`;
// 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)`;
let out = content;
- // 1) Within `const PORTS = {...}`, swap any `: <old>` value (keys there are
- // arbitrary — API, UI, WEB, …). Operate on the isolated block so the same
- // pattern outside the block isn't over-matched.
- const block = findPortsBlock(out);
- if (block) {
- const before = out.slice(0, block.start);
- let inner = out.slice(block.start, block.end + 1);
- const after = out.slice(block.end + 1);
+ // 1) Within `const PORTS = {...}` and each per-app `ports: {...}` object,
+ // swap any `: <old>` value (keys there are arbitrary — API, UI, api, ui).
+ // Process regions back-to-front so each splice's offsets stay valid for
+ // the earlier (lower-index) regions still to be rewritten.
+ const regions = findValuePortRegions(out).sort((a, b) => b.start - a.start);
+ 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)}`);
});
- out = before + inner + after;
+ out = out.slice(0, region.start) + inner + out.slice(region.end + 1);
}
// 2) `--port <old>` in args strings.
diff --git a/server/services/streamingDetect.test.js b/server/services/streamingDetect.test.js
index 263dece739..f9bbb53fc6 100644
--- a/server/services/streamingDetect.test.js
+++ b/server/services/streamingDetect.test.js
@@ -297,6 +297,21 @@ describe('rewriteEcosystemPorts', () => {
expect(processes.find(p => p.name === 'app-server').ports.api).toBe(6000);
});
+ it('rewrites a per-app ports: {...} object — the parser\'s PRIMARY derivation source', () => {
+ // parseEcosystemConfig reads the literal `ports:` object before env, so a
+ // rewrite that skipped it would let the edit revert on the next refresh.
+ const content = `module.exports = { apps: [
+ { name: 'app-server', script: 's.js', ports: { api: 5555, ui: 5173 }, env: { PORT: 5555 } }
+] };
+`;
+ const out = rewriteEcosystemPorts(content, [[5555, 6000], [5173, 6001]]);
+ const { processes } = parseEcosystemConfig(out);
+ expect(processes[0].ports.api).toBe(6000);
+ expect(processes[0].ports.ui).toBe(6001);
+ expect(out).not.toContain('5555');
+ expect(out).not.toContain('5173');
+ });
+
it('rewrites values inside a const PORTS = {...} block regardless of key name', () => {
const content = `const PORTS = { API: 5555, UI: 5173 };
module.exports = { apps: [{ name: 'x', script: 's.js', env: { PORT: PORTS.API, VITE_PORT: PORTS.UI } }] };
@@ -328,6 +343,15 @@ module.exports = { apps: [{ name: 'x', script: 's.js', env: { PORT: PORTS.API, V
expect(processes.find(p => p.name === 'b').ports.api).toBe(6002);
});
+ it('resolves 11+ remap pairs without placeholder prefix collision (index 1 vs 10)', () => {
+ const pairs = Array.from({ length: 11 }, (_, k) => [7000 + k, 8000 + k]);
+ const content = pairs.map(([o]) => `PORT: ${o}`).join('\n');
+ const out = rewriteEcosystemPorts(content, pairs);
+ for (const [, newP] of pairs) expect(out).toContain(`PORT: ${newP}`);
+ expect(out).not.toMatch(/PORT_REMAP/);
+ for (const [oldP] of pairs) expect(out).not.toContain(`PORT: ${oldP}`);
+ });
+
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);