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

fix pm2 port collisions on standardize and persist edited ports to ecosystem.config

[._.]/ Adam Eivy6e7c9f6767b3
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index e0dc35d372..e9f38438d8 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -13,3 +13,5 @@
- **The GitHub Release workflow no longer crashes on a large changelog.** The v2.22.0 release (a ~175KB changelog) failed at the "Create Release" step with `Argument list too long`: the changelog was passed to `softprops/action-gh-release` as the `body:` input, which GitHub materializes as an `INPUT_BODY` environment variable, and a 175KB env var overflows `ARG_MAX` when the action's Node process is exec'd. The body also exceeds GitHub's hard 125,000-character release-note limit (a separate HTTP 422). The workflow now writes the (placeholder-substituted) changelog to a file and feeds it via `body_path:` instead of an env var, and caps it at 120,000 chars on a whole-line boundary — appending a pointer to the full changelog file at the tag when truncated. (`.github/workflows/release.yml`)
- Scheduled-task descriptions in the Automation UI no longer fall back to a raw dasherized label. `claim-work` (the single-source work-tracker router), `code-reviewer-a`/`code-reviewer-b`, and `do-replan` now show real one-line descriptions instead of "claim work" / "code reviewer a", which read as orphaned/legacy tasks. A parity guard test now keeps the description map in sync with the task-type list.
+- PM2 standardization no longer assigns ports that are already in use. The analysis now feeds the AI the set of listening/reserved ports (plus the common Vite defaults 5173/5174) to avoid, and a deterministic post-pass reassigns any port that still collides into the 6000–6099 range — so standardizing an app never lands on a port another app already holds.
+- Editing an app's ports now persists. Port fields are derived from `ecosystem.config.cjs`, so saving only updated PortOS's registry while PM2 kept the old ports and the next config refresh reverted the change. Saving a changed port now rewrites the matching value in the app's `ecosystem.config.cjs` (the source of truth). Restart the app for the new port to take effect.
diff --git a/client/src/components/apps/EditAppDrawer.jsx b/client/src/components/apps/EditAppDrawer.jsx
index 61fbf40028..a3642b3fa7 100644
--- a/client/src/components/apps/EditAppDrawer.jsx
+++ b/client/src/components/apps/EditAppDrawer.jsx
@@ -260,6 +260,9 @@ export default function EditAppDrawer({ app, onClose, onSave }) {
/>
</div>
</div>
+ <p className="text-xs text-gray-500">
+ Saving a changed port rewrites the matching value in this app's <code className="text-gray-400">ecosystem.config.cjs</code> (the source of truth PM2 reads). Restart the app for the new port to take effect.
+ </p>
{app.id !== PORTOS_APP_ID && (
<div className="bg-port-bg/50 border border-port-border rounded-lg p-3 space-y-2">
diff --git a/server/routes/apps.js b/server/routes/apps.js
index 4c89c99732..ad051c9b9f 100644
--- a/server/routes/apps.js
+++ b/server/routes/apps.js
@@ -15,7 +15,7 @@ import { validateRequest, appSchema, appUpdateSchema, sanitizeTaskMetadata, docu
import * as git from '../services/git.js';
import { parseCronToNextRun } from '../services/eventScheduler.js';
import { asyncHandler, ServerError } from '../lib/errorHandler.js';
-import { parseEcosystemFromPath, usesPm2 } from '../services/streamingDetect.js';
+import { parseEcosystemFromPath, usesPm2, writeEcosystemPorts } from '../services/streamingDetect.js';
import { detectAppIcon, getIconContentType, isUsableSvg } from '../services/appIconDetect.js';
import { hasDeployScript } from '../services/appDeployer.js';
import { checkScripts, installScripts, XCODE_SCRIPT_NAMES } from '../services/xcodeScripts.js';
@@ -373,12 +373,43 @@ router.post('/', asyncHandler(async (req, res, next) => {
// PUT /api/apps/:id - Update app
router.put('/:id', asyncHandler(async (req, res, next) => {
const data = validateRequest(appUpdateSchema, req.body);
+
+ // 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'];
+ 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)) {
+ 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]);
+ }
+ }
+ 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;
+ });
+ if (result?.changed) {
+ console.log(`🔧 Updated ${result.file} ports for ${app.name}: ${remap.map(([o, n]) => `${o}→${n}`).join(', ')} (restart the app to apply)`);
+ }
+ }
+ }
+
res.json(app);
}));
diff --git a/server/routes/apps.test.js b/server/routes/apps.test.js
index 5aeb5759ed..fac9ecef3b 100644
--- a/server/routes/apps.test.js
+++ b/server/routes/apps.test.js
@@ -35,6 +35,7 @@ vi.mock('../services/history.js', () => ({
vi.mock('../services/streamingDetect.js', () => ({
parseEcosystemFromPath: vi.fn(),
+ writeEcosystemPorts: vi.fn().mockResolvedValue({ file: 'ecosystem.config.cjs', changed: true }),
usesPm2: vi.fn((type) => !new Set(['ios-native', 'macos-native', 'xcode', 'swift']).has(type)),
NON_PM2_TYPES: new Set(['ios-native', 'macos-native', 'xcode', 'swift'])
}));
@@ -256,6 +257,33 @@ describe('Apps Routes', () => {
expect(response.status).toBe(404);
});
+
+ it('writes changed ports back to the ecosystem config (source of truth)', async () => {
+ // 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);
+ appsService.updateApp.mockResolvedValue({ ...mockApp, apiPort: 6000, uiPort: 6001 });
+
+ const response = await request(app)
+ .put('/api/apps/app-001')
+ .send({ apiPort: 6000, uiPort: 6001 });
+
+ expect(response.status).toBe(200);
+ expect(streamingDetect.writeEcosystemPorts).toHaveBeenCalledWith(
+ process.cwd(),
+ expect.arrayContaining([[5173, 6000], [5174, 6001]])
+ );
+ });
+
+ it('does not write to the ecosystem config when no port changed', async () => {
+ const mockApp = { id: 'app-001', name: 'App', type: 'node', repoPath: process.cwd(), apiPort: 5173 };
+ appsService.getAppById.mockResolvedValue(mockApp);
+ appsService.updateApp.mockResolvedValue({ ...mockApp, name: 'Renamed' });
+
+ await request(app).put('/api/apps/app-001').send({ name: 'Renamed' });
+
+ expect(streamingDetect.writeEcosystemPorts).not.toHaveBeenCalled();
+ });
});
describe('DELETE /api/apps/:id', () => {
diff --git a/server/services/pm2Standardizer.js b/server/services/pm2Standardizer.js
index 8743abc9c5..f1835c8e86 100644
--- a/server/services/pm2Standardizer.js
+++ b/server/services/pm2Standardizer.js
@@ -7,10 +7,113 @@ 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 { getListeningPorts } from '../lib/platform.js';
const execAsync = promisify(exec);
const DEFAULT_PM2_AI_TIMEOUT_MS = 180000;
+// Common Vite dev defaults — always avoided, since a developer machine almost
+// always already has something on 5173 (and 5174 is Vite's auto-fallback).
+const VITE_DEFAULT_PORTS = [5173, 5174];
+// New ports are reassigned from here up (PortOS's managed-app convention, see
+// DEFAULT_PORT_RANGE_START in services/ports.js) — clear of PortOS's own
+// 5553–5561 block and the Vite defaults.
+const REASSIGN_FROM = 6000;
+
+const isPortKey = (key) => /(^|_)PORT$/i.test(key);
+
+/**
+ * Collect every numeric port a process references — port-ish env keys plus a
+ * `--port N` token in its args string.
+ */
+function collectPortRefs(proc) {
+ const refs = [];
+ if (proc.env && typeof proc.env === 'object') {
+ for (const [key, value] of Object.entries(proc.env)) {
+ if (!isPortKey(key)) continue;
+ const n = Number(value);
+ if (Number.isInteger(n)) refs.push(n);
+ }
+ }
+ if (typeof proc.args === 'string') {
+ const m = proc.args.match(/--port\s+(\d+)/);
+ if (m) refs.push(Number(m[1]));
+ }
+ return refs;
+}
+
+/**
+ * Deterministically reassign any process port that collides with a taken port
+ * (already-running, reserved by another PortOS app, or a Vite default) or that
+ * duplicates another process in this same config. Mutates `processes` in place
+ * (env port values + `--port` args) and returns the list of `[old, new]`
+ * reassignments. This is the guarantee the LLM prompt can't provide on its own.
+ */
+export function reassignCollidingPorts(processes, takenPorts) {
+ const taken = new Set((takenPorts || []).filter(Number.isInteger));
+
+ // Every port the LLM referenced — a replacement must avoid these too, so a
+ // bumped port can't land on a port another process legitimately kept.
+ const referenced = new Set();
+ for (const proc of processes || []) {
+ for (const value of collectPortRefs(proc)) referenced.add(value);
+ }
+
+ const assigned = new Set();
+ const pickFree = () => {
+ let p = REASSIGN_FROM;
+ while (taken.has(p) || referenced.has(p) || assigned.has(p)) p++;
+ assigned.add(p);
+ return p;
+ };
+
+ // Remap is keyed by old value so every occurrence of a colliding port (env
+ // PORT, VITE_PORT, --port arg) moves together and stays consistent. Two
+ // processes that share an identical non-taken port are left as-is — splitting
+ // a shared value is ambiguous, and that runtime dup is the config's own
+ // choice, not the external collision this guards against.
+ const remap = new Map();
+ for (const value of referenced) {
+ if (taken.has(value)) remap.set(value, pickFree());
+ }
+
+ if (remap.size === 0) return [];
+
+ for (const proc of processes) {
+ if (proc.env && typeof proc.env === 'object') {
+ for (const [key, value] of Object.entries(proc.env)) {
+ if (!isPortKey(key)) continue;
+ const n = Number(value);
+ if (remap.has(n)) proc.env[key] = remap.get(n);
+ }
+ }
+ if (typeof proc.args === 'string') {
+ proc.args = proc.args.replace(/(--port\s+)(\d+)/g, (full, pre, num) => {
+ const n = Number(num);
+ return remap.has(n) ? `${pre}${remap.get(n)}` : full;
+ });
+ }
+ }
+
+ return [...remap.entries()];
+}
+
+/**
+ * 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.
+ */
+async function gatherTakenPorts() {
+ const [reserved, listening] = await Promise.all([
+ getReservedPorts().catch(() => []),
+ getListeningPorts().catch(() => []),
+ ]);
+ return Array.from(new Set([...reserved, ...listening, ...VITE_DEFAULT_PORTS]))
+ .filter(Number.isInteger)
+ .sort((a, b) => a - b);
+}
+
/**
* Gather all config files for standardization analysis
*/
@@ -84,7 +187,7 @@ async function gatherConfigContext(dirPath) {
/**
* Build LLM prompt for PM2 standardization analysis
*/
-function buildStandardizationPrompt(context) {
+function buildStandardizationPrompt(context, takenPorts = []) {
return `# PM2 Standardization Analysis
You are analyzing a Node.js application to generate a standardized PM2 ecosystem configuration.
@@ -114,6 +217,12 @@ ${context.envFiles.map(f => `#### ${f.name}\n\`\`\`\n${f.content}\n\`\`\``).join
${context.viteConfigs.length > 0 ? `### Vite Configs
${context.viteConfigs.map(f => `#### ${f.name}\n\`\`\`javascript\n${f.content}\n\`\`\``).join('\n\n')}` : ''}
+## Ports Already In Use — DO NOT ASSIGN ANY OF THESE
+
+${takenPorts.length > 0 ? takenPorts.join(', ') : '(none detected)'}
+
+These ports are already listening on this host, reserved by another managed app, or are common Vite defaults (5173/5174). Assigning any of them causes a collision. **Pick new ports in the 6000–6099 range** instead of the framework defaults found in vite.config/.env, even when a config file suggests otherwise.
+
## PM2 Standard Requirements
1. **All ports MUST be in ecosystem.config.cjs env blocks** - Never in .env or vite.config
@@ -295,9 +404,10 @@ export async function analyzeApp(repoPath, providerId = null) {
return { success: false, error: 'AI provider is disabled' };
}
- // Gather context
+ // Gather context + the set of ports we must steer the LLM away from
const context = await gatherConfigContext(repoPath);
- const prompt = buildStandardizationPrompt(context);
+ const takenPorts = await gatherTakenPorts();
+ const prompt = buildStandardizationPrompt(context, takenPorts);
// Execute analysis
const startTime = Date.now();
@@ -310,6 +420,13 @@ export async function analyzeApp(repoPath, providerId = null) {
// Parse response
const analysis = parseAnalysisResponse(response);
+ // Deterministic safety net: even if the LLM ignored the avoid-list, remap any
+ // port that still collides with a taken/duplicate port before generating the file.
+ const portReassignments = reassignCollidingPorts(analysis.processes, takenPorts);
+ if (portReassignments.length > 0) {
+ console.log(`🔧 PM2 standardizer reassigned colliding ports: ${portReassignments.map(([o, n]) => `${o}→${n}`).join(', ')}`);
+ }
+
// Generate ecosystem content
const ecosystemContent = generateEcosystemContent(analysis.processes, context.dirName);
@@ -328,7 +445,8 @@ export async function analyzeApp(repoPath, providerId = null) {
createEcosystem: !context.ecosystemConfig,
ecosystemContent,
processes: analysis.processes,
- strayPorts: analysis.strayPorts || []
+ strayPorts: analysis.strayPorts || [],
+ portReassignments: portReassignments.map(([from, to]) => ({ from, to }))
},
llmAnalysis: {
providerId: provider.id,
diff --git a/server/services/pm2Standardizer.test.js b/server/services/pm2Standardizer.test.js
new file mode 100644
index 0000000000..a8188c32b1
--- /dev/null
+++ b/server/services/pm2Standardizer.test.js
@@ -0,0 +1,76 @@
+import { describe, it, expect } from 'vitest';
+import { reassignCollidingPorts } from './pm2Standardizer.js';
+
+describe('reassignCollidingPorts', () => {
+ it('moves a process off a taken port and rewrites both env.PORT and --port args', () => {
+ // The reported bug: standardizer copied Vite's 5173/5174 even though 5173
+ // was already listening.
+ const processes = [
+ { name: 'app-server', env: { NODE_ENV: 'development', PORT: 5173 } },
+ { name: 'app-client', args: 'vite --host --port 5174', env: { VITE_PORT: 5174 } }
+ ];
+ const reassigned = reassignCollidingPorts(processes, [5173, 5174]);
+
+ expect(processes[0].env.PORT).toBe(6000);
+ expect(processes[1].env.VITE_PORT).toBe(6001);
+ expect(processes[1].args).toBe('vite --host --port 6001');
+ expect(reassigned).toEqual([[5173, 6000], [5174, 6001]]);
+ });
+
+ it('keeps the same new value when an old port appears in multiple places of one process', () => {
+ const processes = [
+ { name: 'client', args: 'vite --host --port 5173', env: { PORT: 5173, VITE_PORT: 5173 } }
+ ];
+ reassignCollidingPorts(processes, [5173]);
+ expect(processes[0].env.PORT).toBe(6000);
+ expect(processes[0].env.VITE_PORT).toBe(6000);
+ expect(processes[0].args).toBe('vite --host --port 6000');
+ });
+
+ it('leaves non-colliding ports untouched', () => {
+ const processes = [{ name: 'srv', env: { PORT: 4321 } }];
+ const reassigned = reassignCollidingPorts(processes, [5173, 5174]);
+ expect(processes[0].env.PORT).toBe(4321);
+ expect(reassigned).toEqual([]);
+ });
+
+ it('leaves an intra-config duplicate of a non-taken port untouched (value-keyed remap cannot split a shared value)', () => {
+ const processes = [
+ { name: 'a', env: { PORT: 3000 } },
+ { name: 'b', env: { PORT: 3000 } }
+ ];
+ const reassigned = reassignCollidingPorts(processes, []);
+ expect(processes[0].env.PORT).toBe(3000);
+ expect(processes[1].env.PORT).toBe(3000);
+ expect(reassigned).toEqual([]);
+ });
+
+ it('never reassigns a colliding port onto a port another process legitimately kept', () => {
+ // server keeps 6000 (free); client's 5173 is taken and must NOT be bumped to 6000.
+ const processes = [
+ { name: 'server', env: { PORT: 6000 } },
+ { name: 'client', env: { VITE_PORT: 5173 } }
+ ];
+ reassignCollidingPorts(processes, [5173]);
+ expect(processes[0].env.PORT).toBe(6000);
+ expect(processes[1].env.VITE_PORT).toBe(6001);
+ });
+
+ it('skips already-assigned ports when picking a free replacement', () => {
+ // 6000 is taken, so the first reassignment lands on 6001, the next on 6002.
+ const processes = [
+ { name: 'a', env: { PORT: 5173 } },
+ { name: 'b', env: { PORT: 5174 } }
+ ];
+ reassignCollidingPorts(processes, [5173, 5174, 6000]);
+ expect(processes[0].env.PORT).toBe(6001);
+ expect(processes[1].env.PORT).toBe(6002);
+ });
+
+ it('only treats *_PORT / PORT env keys as ports', () => {
+ const processes = [{ name: 'a', env: { PORT: 5173, RETRIES: 5173 } }];
+ reassignCollidingPorts(processes, [5173]);
+ expect(processes[0].env.PORT).toBe(6000);
+ expect(processes[0].env.RETRIES).toBe(5173); // not a port key
+ });
+});
diff --git a/server/services/streamingDetect.js b/server/services/streamingDetect.js
index c5fef43b0f..d11c18e4bf 100644
--- a/server/services/streamingDetect.js
+++ b/server/services/streamingDetect.js
@@ -3,7 +3,7 @@ import { existsSync } from 'fs';
import { join, basename } from 'path';
import { homedir } from 'os';
import { execPm2 } from './pm2.js';
-import { safeJSONParse, tryReadFile } from '../lib/fileUtils.js';
+import { safeJSONParse, tryReadFile, atomicWrite } from '../lib/fileUtils.js';
import { detectAppIcon } from './appIconDetect.js';
/** App types that do not use PM2 for process management */
@@ -434,6 +434,114 @@ 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 };
+}
+
+/**
+ * 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.
+ *
+ * `ecosystem.config.cjs` is the source of truth for an app's ports — PortOS
+ * *derives* uiPort/apiPort/devUiPort from it via parseEcosystemConfig. Editing
+ * ports in the UI therefore has to write back here, or PM2 keeps the old ports
+ * and the next config refresh re-derives them and clobbers the edit.
+ *
+ * Replacements are deliberately narrow so unrelated numbers (watch_delay,
+ * timeouts) are never touched:
+ * 1. numeric values inside a `const PORTS = {...}` block (arbitrary keys),
+ * 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.
+ *
+ * @param {string} content
+ * @param {Map<number,number>|Array<[number,number]>} remap
+ * @returns {string}
+ */
+export function rewriteEcosystemPorts(content, remap) {
+ const pairs = (remap instanceof Map ? [...remap.entries()] : remap || [])
+ .map(([o, n]) => [Number(o), Number(n)])
+ .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}`;
+ // 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);
+ pairs.forEach(([oldP], i) => {
+ inner = inner.replace(new RegExp(`(:\\s*)${oldP}\\b`, 'g'), `$1${ph(i)}`);
+ });
+ out = before + inner + after;
+ }
+
+ // 2) `--port <old>` in args strings.
+ pairs.forEach(([oldP], i) => {
+ out = out.replace(new RegExp(`(--port\\s+)${oldP}\\b`, 'g'), `$1${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)}`
+ );
+ });
+
+ // Resolve placeholders → new values.
+ pairs.forEach(([, newP], i) => {
+ out = out.split(ph(i)).join(String(newP));
+ });
+
+ return out;
+}
+
+/**
+ * Persist a port remap to an app's on-disk ecosystem config (`.cjs` preferred,
+ * then `.js`). Returns `{ file, changed }`. No-op (changed:false) when nothing
+ * matched. See rewriteEcosystemPorts for why this is the canonical write path.
+ *
+ * @param {string} repoPath
+ * @param {Map<number,number>|Array<[number,number]>} remap
+ */
+export async function writeEcosystemPorts(repoPath, remap) {
+ for (const name of ['ecosystem.config.cjs', 'ecosystem.config.js']) {
+ const filePath = join(repoPath, name);
+ if (!existsSync(filePath)) continue;
+ const content = await readFile(filePath, 'utf-8');
+ const updated = rewriteEcosystemPorts(content, remap);
+ if (updated !== content) {
+ await atomicWrite(filePath, updated);
+ return { file: name, changed: true };
+ }
+ return { file: name, changed: false };
+ }
+ return { file: null, changed: false };
+}
+
/**
* Stream detection results to a socket as each step completes
*/
diff --git a/server/services/streamingDetect.test.js b/server/services/streamingDetect.test.js
index 26224f8b8e..263dece739 100644
--- a/server/services/streamingDetect.test.js
+++ b/server/services/streamingDetect.test.js
@@ -1,5 +1,5 @@
import { describe, it, expect } from 'vitest';
-import { parseEcosystemConfig } from './streamingDetect.js';
+import { parseEcosystemConfig, rewriteEcosystemPorts } from './streamingDetect.js';
describe('parseEcosystemConfig', () => {
it('captures arbitrary *_PORT env vars and labels them by camelCased stem', () => {
@@ -276,3 +276,61 @@ describe('parseEcosystemConfig', () => {
expect(proc.ports).toEqual({ api: 5590, ui: 5591 });
});
});
+
+describe('rewriteEcosystemPorts', () => {
+ it('rewrites inline env PORT/VITE_PORT and --port args (the standardizer-generated shape)', () => {
+ const content = `module.exports = {
+ apps: [
+ { name: 'app-server', script: 'server.js', env: { NODE_ENV: 'development', PORT: 5173 } },
+ { name: 'app-client', script: 'npx', args: 'vite --host --port 5174', env: { VITE_PORT: 5174 } }
+ ]
+};
+`;
+ const out = rewriteEcosystemPorts(content, [[5173, 6000], [5174, 6001]]);
+ expect(out).toContain('PORT: 6000');
+ expect(out).toContain('--port 6001');
+ expect(out).toContain('VITE_PORT: 6001');
+ expect(out).not.toContain('5173');
+ expect(out).not.toContain('5174');
+ // Re-parsing the rewritten file yields the new ports.
+ const { processes } = parseEcosystemConfig(out);
+ expect(processes.find(p => p.name === 'app-server').ports.api).toBe(6000);
+ });
+
+ 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 } }] };
+`;
+ const out = rewriteEcosystemPorts(content, [[5173, 6000]]);
+ expect(out).toContain('UI: 6000');
+ expect(out).toContain('API: 5555'); // untouched
+ });
+
+ it('does not touch unrelated numbers that merely equal an old port', () => {
+ const content = `module.exports = {
+ apps: [{ name: 'x', script: 's.js', watch_delay: 1000, env: { PORT: 1000 } }]
+};
+`;
+ const out = rewriteEcosystemPorts(content, [[1000, 6000]]);
+ expect(out).toContain('watch_delay: 1000'); // not a port key — preserved
+ expect(out).toContain('PORT: 6000');
+ });
+
+ it('does not chain when a new port equals another old port', () => {
+ const content = `module.exports = { apps: [
+ { name: 'a', script: 's.js', env: { PORT: 6000 } },
+ { name: 'b', script: 's.js', env: { PORT: 6001 } }
+] };
+`;
+ const out = rewriteEcosystemPorts(content, [[6000, 6001], [6001, 6002]]);
+ const { processes } = parseEcosystemConfig(out);
+ expect(processes.find(p => p.name === 'a').ports.api).toBe(6001);
+ expect(processes.find(p => p.name === 'b').ports.api).toBe(6002);
+ });
+
+ 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);
+ expect(rewriteEcosystemPorts(content, [[5173, 5173]])).toBe(content);
+ });
+});