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): write mixed port edits atomically in one pass

Adam Eivyec00ba4b93e0
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 785522f84d..c9762f9da9 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -22,4 +22,4 @@
- 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.
-- Editing a **shared or derived** port now persists too. When two port fields resolve to the same literal (e.g. the prod UI is served by the API, so `uiPort === apiPort`), the value-keyed rewrite couldn't tell them apart and the edit returned a 422. The PUT route now falls back to a **per-process-label-targeted** rewrite: it locates the specific process block in `ecosystem.config.cjs` and rewrites only the touched label's port (`api`/`ui`/`devUi`), leaving the sibling field — and any same-valued unrelated number — untouched. Edits to ports that live only under a process's `env`/`args` (no top-level field) persist as well. The 422 is now reserved for the genuinely unpersistable case (the literal isn't in the touched process block — e.g. it lives in a shared `const PORTS = {…}` referenced via `ports: PORTS.server`, or is computed entirely at runtime), so a shared-value edit never falsely reports success while the displayed port silently reverts.
+- Editing a **shared or derived** port now persists too. When two port fields resolve to the same literal (e.g. the prod UI is served by the API, so `uiPort === apiPort`), the value-keyed rewrite couldn't tell them apart and the edit returned a 422. The PUT route now falls back to a **per-process-label-targeted** rewrite: it locates the specific process block in `ecosystem.config.cjs` and rewrites only the touched label's port (`api`/`ui`/`devUi`), leaving the sibling field — and any same-valued unrelated number — untouched. Edits to ports that live only under a process's `env`/`args` (no top-level field) persist as well. A save that mixes a distinct port and a shared port is written **atomically** — both rewrites are computed in memory and the config file is written once, only when every edit is persistable — so a request that's rejected (422) never leaves the config half-changed. The 422 is now reserved for the genuinely unpersistable case (the literal isn't in the touched process block — e.g. it lives in a shared `const PORTS = {…}` referenced via `ports: PORTS.server`, or is computed entirely at runtime), so a shared-value edit never falsely reports success while the displayed port silently reverts.
diff --git a/server/routes/apps.js b/server/routes/apps.js
index ebefc5049f..fb0802808b 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, writeEcosystemPorts, writeEcosystemPortsByProcess } from '../services/streamingDetect.js';
+import { parseEcosystemFromPath, usesPm2, writeEcosystemPortEdits } from '../services/streamingDetect.js';
import { checkViteHost, findViteConfig, rewriteAllowedHosts } from '../lib/viteAllowedHosts.js';
import { detectAppIcon, getIconContentType, isUsableSvg } from '../services/appIconDetect.js';
import { hasDeployScript } from '../services/appDeployer.js';
@@ -522,27 +522,31 @@ router.put('/:id', asyncHandler(async (req, res, next) => {
remap.push([oldPort, data[key]]);
}
- const result = remap.length > 0 ? await writeEcosystemPorts(existing.repoPath, remap) : { changed: false };
+ // Persist the value-keyed remap (distinct ports) and the targeted edits
+ // (shared-value ports) in ONE atomic write. Doing them as two separate
+ // writes would let the value-keyed pass land on disk before a later
+ // unpersistable targeted edit forces the 422 below — leaving config
+ // partially changed for a rejected request. writeEcosystemPortEdits
+ // computes both rewrites in memory and writes only when nothing is
+ // unpersistable.
+ const result = changedKeys.length > 0
+ ? await writeEcosystemPortEdits(existing.repoPath, remap, targetedEdits)
+ : { changed: false, remapApplied: false, applied: [], unapplied: [] };
if (result.changed) {
- console.log(`🔧 Updated ${result.file} ports for ${existing.name}: ${remap.map(([o, n]) => `${o}→${n}`).join(', ')} (restart the app to apply)`);
- }
-
- // Shared-value edits: rewrite the specific process block + label. Runs after
- // the value-keyed pass so both touch the freshest on-disk content.
- const targeted = targetedEdits.length > 0
- ? await writeEcosystemPortsByProcess(existing.repoPath, targetedEdits)
- : { changed: false, unapplied: [] };
- if (targeted.changed) {
- console.log(`🔧 Updated ${targeted.file} ports for ${existing.name}: ${targetedEdits.map(e => `${e.label} ${e.oldPort}→${e.newPort}`).join(', ')} (restart the app to apply)`);
+ const remapMsg = result.remapApplied ? remap.map(([o, n]) => `${o}→${n}`).join(', ') : '';
+ const tgtMsg = targetedEdits.map(e => `${e.label} ${e.oldPort}→${e.newPort}`).join(', ');
+ console.log(`🔧 Updated ${result.file} ports for ${existing.name}: ${[remapMsg, tgtMsg].filter(Boolean).join(', ')} (restart the app to apply)`);
}
// Honesty gate: if the user changed a port we could NOT write to the
// source-of-truth config, reject the whole update rather than persist a
// registry value PM2 will contradict (and the next refresh will revert).
- // `!result.changed` catches value-keyed remap pairs whose literal wasn't
- // found; `targeted.unapplied` catches process/label edits that didn't match.
- const valueKeyedFailed = remap.length > 0 && !result.changed;
- const targetedFailed = (targeted.unapplied || []).length > 0;
+ // `remap.length && !remapApplied` catches value-keyed pairs whose literal
+ // wasn't found; `unapplied` catches process/label edits that didn't match.
+ // On any unpersistable targeted edit the writer persists nothing, so this
+ // reject leaves the config untouched.
+ const valueKeyedFailed = remap.length > 0 && !result.remapApplied;
+ const targetedFailed = (result.unapplied || []).length > 0;
if (changedKeys.length > 0 && (valueKeyedFailed || targetedFailed)) {
throw new ServerError(
`Could not persist port change to ${existing.name}'s ecosystem config — the port is derived from process config or is not a literal value. Edit the ecosystem.config.cjs directly to change this port.`,
diff --git a/server/routes/apps.test.js b/server/routes/apps.test.js
index 54da62ca14..09565fa0f3 100644
--- a/server/routes/apps.test.js
+++ b/server/routes/apps.test.js
@@ -35,8 +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 }),
- writeEcosystemPortsByProcess: vi.fn().mockResolvedValue({ file: 'ecosystem.config.cjs', changed: true, applied: [], unapplied: [] }),
+ writeEcosystemPortEdits: vi.fn().mockResolvedValue({ file: 'ecosystem.config.cjs', changed: true, remapApplied: true, applied: [], unapplied: [] }),
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'])
}));
@@ -274,9 +273,10 @@ describe('Apps Routes', () => {
.send({ apiPort: 6000, uiPort: 6001 });
expect(response.status).toBe(200);
- expect(streamingDetect.writeEcosystemPorts).toHaveBeenCalledWith(
+ expect(streamingDetect.writeEcosystemPortEdits).toHaveBeenCalledWith(
process.cwd(),
- expect.arrayContaining([[5173, 6000], [5174, 6001]])
+ expect.arrayContaining([[5173, 6000], [5174, 6001]]),
+ []
);
});
@@ -287,13 +287,13 @@ describe('Apps Routes', () => {
await request(app).put('/api/apps/app-001').send({ name: 'Renamed' });
- expect(streamingDetect.writeEcosystemPorts).not.toHaveBeenCalled();
+ expect(streamingDetect.writeEcosystemPortEdits).not.toHaveBeenCalled();
});
it('persists a shared-value port change via the per-process-targeted rewrite', async () => {
// uiPort and apiPort both 6000 in the same process block. A value-keyed
- // rewrite can't split them, so the route targets the specific process +
- // label (ui) instead — the edit now persists rather than 422.
+ // rewrite can't split them, so the route routes it to the targeted edits
+ // (process + label) instead — the edit now persists rather than 422.
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: 'srv', ports: { api: 6000, ui: 6000 } }] });
@@ -302,20 +302,19 @@ describe('Apps Routes', () => {
const response = await request(app).put('/api/apps/app-001').send({ uiPort: 7000 });
expect(response.status).toBe(200);
- // Value-keyed writer skipped (shared value); targeted writer used instead.
- expect(streamingDetect.writeEcosystemPorts).not.toHaveBeenCalled();
- expect(streamingDetect.writeEcosystemPortsByProcess).toHaveBeenCalledWith(
+ // Empty value-keyed remap (shared value), one targeted edit.
+ expect(streamingDetect.writeEcosystemPortEdits).toHaveBeenCalledWith(
process.cwd(),
+ [],
[{ processName: 'srv', label: 'ui', oldPort: 6000, newPort: 7000 }]
);
expect(appsService.updateApp).toHaveBeenCalled();
});
it('persists a request mixing a distinct port (value-keyed) and a shared port (targeted) in one PUT', async () => {
- // devUiPort is distinct (5556) so it goes through the value-keyed rewrite;
+ // devUiPort is distinct (5556) so it goes through the value-keyed remap;
// apiPort/uiPort share 6000 so the uiPort edit goes through the targeted
- // rewrite. Both writers run, the edit succeeds, and neither pass clobbers
- // the other (their old-value sets are disjoint).
+ // edits. Both are handed to the single atomic writer in one call.
const mockApp = { id: 'app-001', name: 'App', type: 'node', repoPath: process.cwd(), apiPort: 6000, uiPort: 6000, devUiPort: 5556 };
appsService.getAppById.mockResolvedValue(mockApp);
streamingDetect.parseEcosystemFromPath.mockResolvedValue({
@@ -331,13 +330,10 @@ describe('Apps Routes', () => {
.send({ uiPort: 7000, devUiPort: 7001 });
expect(response.status).toBe(200);
- // devUiPort (distinct) → value-keyed; uiPort (shared with api) → targeted.
- expect(streamingDetect.writeEcosystemPorts).toHaveBeenCalledWith(
- process.cwd(),
- [[5556, 7001]]
- );
- expect(streamingDetect.writeEcosystemPortsByProcess).toHaveBeenCalledWith(
+ // One atomic write: devUiPort (distinct) in remap; uiPort (shared) targeted.
+ expect(streamingDetect.writeEcosystemPortEdits).toHaveBeenCalledWith(
process.cwd(),
+ [[5556, 7001]],
[{ processName: 'srv', label: 'ui', oldPort: 6000, newPort: 7000 }]
);
expect(appsService.updateApp).toHaveBeenCalled();
@@ -345,12 +341,12 @@ describe('Apps Routes', () => {
it('rejects (422) a shared-value port change the targeted rewrite cannot apply', async () => {
// Shared value, but the targeted rewrite finds no matching literal to
- // change (e.g. derived from a const the block doesn't contain) → 422.
+ // change (e.g. derived from a const outside the block) → unapplied → 422.
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: 'srv', ports: { api: 6000, ui: 6000 } }] });
- streamingDetect.writeEcosystemPortsByProcess.mockResolvedValueOnce({
- file: 'ecosystem.config.cjs', changed: false, applied: [],
+ streamingDetect.writeEcosystemPortEdits.mockResolvedValueOnce({
+ file: 'ecosystem.config.cjs', changed: false, remapApplied: false, applied: [],
unapplied: [{ processName: 'srv', label: 'ui', oldPort: 6000, newPort: 7000 }]
});
@@ -374,7 +370,7 @@ describe('Apps Routes', () => {
.send({ name: 'Renamed', apiPort: 5555, uiPort: 5556 });
expect(response.status).toBe(200);
- expect(streamingDetect.writeEcosystemPorts).not.toHaveBeenCalled();
+ expect(streamingDetect.writeEcosystemPortEdits).not.toHaveBeenCalled();
expect(appsService.updateApp).toHaveBeenCalled();
});
@@ -382,7 +378,7 @@ describe('Apps Routes', () => {
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 });
+ streamingDetect.writeEcosystemPortEdits.mockResolvedValueOnce({ file: 'ecosystem.config.cjs', changed: false, remapApplied: false, applied: [], unapplied: [] });
const response = await request(app).put('/api/apps/app-001').send({ apiPort: 6000 });
@@ -394,7 +390,7 @@ describe('Apps Routes', () => {
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'));
+ streamingDetect.writeEcosystemPortEdits.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 292fe49ef6..88aa56212d 100644
--- a/server/services/streamingDetect.js
+++ b/server/services/streamingDetect.js
@@ -845,6 +845,63 @@ export async function writeEcosystemPortsByProcess(repoPath, edits) {
return { file: null, changed: false, applied: [], unapplied: edits || [] };
}
+/**
+ * Persist a mixed port edit — a value-keyed `remap` (distinct ports) AND a set
+ * of per-process-label-targeted `edits` (shared-value ports) — to an app's
+ * ecosystem config in ONE atomic write.
+ *
+ * Both rewrites are computed in memory against the same file content, then the
+ * file is written exactly once. This is the only way to keep a mixed edit
+ * all-or-nothing: writing the value-keyed pass and the targeted pass as two
+ * separate `atomicWrite`s lets the first land on disk before the second reports
+ * an unpersistable edit — so a request the caller then 422s would still have
+ * partially changed the config. Here, if ANY targeted edit is unapplied, the
+ * file is left untouched and the whole result is reported as not-persisted, so
+ * the caller's reject path never leaves a partial write behind.
+ *
+ * Returns `{ file, changed, remapApplied, applied, unapplied }`:
+ * - `remapApplied` — true when the value-keyed remap matched a literal
+ * - `applied`/`unapplied` — the targeted edits that did / didn't rewrite
+ *
+ * @param {string} repoPath
+ * @param {Array<[number,number]>} remap
+ * @param {Array<{processName:string,label:string,oldPort:number,newPort:number}>} edits
+ */
+export async function writeEcosystemPortEdits(repoPath, remap, edits) {
+ const hasRemap = (remap || []).length > 0;
+ const hasEdits = (edits || []).length > 0;
+ if (!hasRemap && !hasEdits) return { file: null, changed: false, remapApplied: false, applied: [], unapplied: [] };
+
+ for (const name of ECOSYSTEM_CONFIG_FILENAMES) {
+ const filePath = join(repoPath, name);
+ if (!existsSync(filePath)) continue;
+ const content = await readFile(filePath, 'utf-8');
+
+ // Value-keyed pass first, then targeted — both against the in-memory result
+ // so the single write reflects both. The two passes operate on disjoint
+ // literals (distinct values vs shared values), so ordering can't clobber.
+ const afterRemap = hasRemap ? rewriteEcosystemPorts(content, remap) : content;
+ const { content: afterTargeted, applied, unapplied } = hasEdits
+ ? rewriteEcosystemPortsByProcess(afterRemap, edits)
+ : { content: afterRemap, applied: [], unapplied: [] };
+
+ const remapApplied = afterRemap !== content;
+
+ // Any unpersistable targeted edit ⇒ the caller rejects the whole request,
+ // so persist NOTHING (not even the value-keyed pass that did match).
+ if (unapplied.length > 0) {
+ return { file: name, changed: false, remapApplied: false, applied: [], unapplied };
+ }
+
+ if (afterTargeted !== content) {
+ await atomicWrite(filePath, afterTargeted);
+ return { file: name, changed: true, remapApplied, applied, unapplied };
+ }
+ return { file: name, changed: false, remapApplied, applied, unapplied };
+ }
+ return { file: null, changed: false, remapApplied: false, applied: [], unapplied: edits || [] };
+}
+
/**
* 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 513ce168a2..4e3af0c1c7 100644
--- a/server/services/streamingDetect.test.js
+++ b/server/services/streamingDetect.test.js
@@ -2,7 +2,7 @@ import { describe, it, expect, afterEach } from 'vitest';
import { mkdtempSync, writeFileSync, readFileSync, rmSync } from 'fs';
import { tmpdir } from 'os';
import { join } from 'path';
-import { parseEcosystemConfig, rewriteEcosystemPorts, rewriteEcosystemPortsByProcess, writeEcosystemPorts, writeEcosystemPortsByProcess } from './streamingDetect.js';
+import { parseEcosystemConfig, rewriteEcosystemPorts, rewriteEcosystemPortsByProcess, writeEcosystemPorts, writeEcosystemPortsByProcess, writeEcosystemPortEdits } from './streamingDetect.js';
describe('parseEcosystemConfig', () => {
it('captures arbitrary *_PORT env vars and labels them by camelCased stem', () => {
@@ -680,3 +680,64 @@ module.exports = { apps: [
expect(readFileSync(join(dir, 'ecosystem.config.cjs'), 'utf-8')).toBe(original);
});
});
+
+describe('writeEcosystemPortEdits (combined value-keyed + targeted, atomic)', () => {
+ let dir;
+ afterEach(() => { if (dir) rmSync(dir, { recursive: true, force: true }); dir = null; });
+
+ it('persists a distinct (value-keyed) and a shared (targeted) edit in one write', async () => {
+ dir = mkdtempSync(join(tmpdir(), 'eco-edits-'));
+ writeFileSync(join(dir, 'ecosystem.config.cjs'), `module.exports = { apps: [
+ { name: 'srv', script: 's.js', ports: { api: 6000, ui: 6000 } },
+ { name: 'srv-ui', script: 'npx', args: 'vite --host --port 5556', env: { VITE_PORT: 5556 } }
+] };
+`);
+ const result = await writeEcosystemPortEdits(
+ dir,
+ [[5556, 7001]],
+ [{ processName: 'srv', label: 'ui', oldPort: 6000, newPort: 7000 }]
+ );
+ expect(result.changed).toBe(true);
+ expect(result.remapApplied).toBe(true);
+ expect(result.unapplied).toHaveLength(0);
+ const out = readFileSync(join(dir, 'ecosystem.config.cjs'), 'utf-8');
+ expect(out).toContain('ui: 7000'); // targeted
+ expect(out).toContain('VITE_PORT: 7001'); // value-keyed
+ expect(out).toContain('api: 6000'); // sibling untouched
+ });
+
+ it('persists NOTHING (not even the value-keyed pass) when a targeted edit is unapplied', async () => {
+ // The atomicity bug: the value-keyed remap (devUiPort 5556→7001) is
+ // rewritable, but the shared uiPort lives in an external PORTS.server const
+ // the targeted pass can't reach → unapplied → the route 422s. The
+ // value-keyed change must NOT have already hit disk.
+ dir = mkdtempSync(join(tmpdir(), 'eco-edits-'));
+ const original = `const PORTS = { server: { api: 6000, ui: 6000 } };
+module.exports = { apps: [
+ { name: 'srv', script: 's.js', ports: PORTS.server, env: { PORT: 6000 } },
+ { name: 'srv-ui', script: 'npx', args: 'vite --host --port 5556', env: { VITE_PORT: 5556 } }
+] };
+`;
+ writeFileSync(join(dir, 'ecosystem.config.cjs'), original);
+ const result = await writeEcosystemPortEdits(
+ dir,
+ [[5556, 7001]], // distinct, rewritable
+ [{ processName: 'srv', label: 'ui', oldPort: 6000, newPort: 7000 }] // shared, in external const → unapplied
+ );
+ expect(result.changed).toBe(false);
+ expect(result.remapApplied).toBe(false); // reported as not-persisted
+ expect(result.unapplied.length).toBeGreaterThan(0);
+ // Critical: the file is byte-for-byte unchanged — the value-keyed devUiPort
+ // edit did NOT land on disk despite being individually rewritable.
+ expect(readFileSync(join(dir, 'ecosystem.config.cjs'), 'utf-8')).toBe(original);
+ });
+
+ it('is a no-op when both remap and edits are empty', async () => {
+ dir = mkdtempSync(join(tmpdir(), 'eco-edits-'));
+ const original = `module.exports = { apps: [{ name: 'x', script: 's.js', env: { PORT: 6000 } }] };\n`;
+ writeFileSync(join(dir, 'ecosystem.config.cjs'), original);
+ const result = await writeEcosystemPortEdits(dir, [], []);
+ expect(result.changed).toBe(false);
+ expect(readFileSync(join(dir, 'ecosystem.config.cjs'), 'utf-8')).toBe(original);
+ });
+});