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: attribute ecosystem port labels to the owning app, not the first process that declares one (#7357)

[._.]/ Adam Eivy858a8d03c813
diff --git a/server/lib/README.md b/server/lib/README.md
index 887ef1d235..5363f10026 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -529,6 +529,7 @@ pm` default, `NPM_CONFIG_PREFIX`, nvm/Volta) installed `codex` successfully and
| `db/` | Boot DDL for the PostgreSQL schema, split per domain (#2832). `db/schema/index.js` re-exports each module's statement array and composes the two ordered lists `ensureSchemaImpl()` runs on every boot (`buildUpgradeDdl()` then `buildCatalogDdl()`). **Statement order is load-bearing** — append inside the domain module and leave the composer order alone. See `db/schema/README.md` for the module catalog. |
| `pgTimestamp.js` | `mirrorTimestamp(value, fallback)` — coerce a hand-editable timestamp into a value Postgres TIMESTAMPTZ always accepts (or fall back), guarding boot-time binds against `Date.parse` rollover + out-of-range years. |
| `pgTools.js` | `pg_dump` binary resolution shared by the backup snapshot path and the native↔Docker export path: `resolvePgDumpBinary(serverMajor)` (PORTOS_PGDUMP override → version-aware auto-select → bare `pg_dump`), plus the lower-level `pickPgDump` / `discoverPgDumpCandidates` / `resolvePgDump`. Picks the closest installed `pg_dump` whose major is ≥ the running server's. |
+| `ecosystemProcessPorts.js` | Attributes a parsed PM2 ecosystem config's port labels to the app that OWNS them (#7357): `processSurface(name)` (a process name minus one trailing role suffix, so `portos-server`/`portos-ui` share surface `portos` while `portos-autofixer-ui` does not), `attributeProcessPorts(processes, app)` (`api`/`ui`/`devUi` resolved from the app's own surface first, then from any carrier not provably a sibling surface, and left undefined when none — which is what lets the served-by-API `uiPort` derivation take over), and `findCrossProcessPortCollision(processes, edits)` (the pre-write guard: a port another process in the same config already holds). Shared by `services/appPortConfig.js` (write-back) and `services/appListEnrichment.js` (read/derive) so a displayed port and a rewritten port can never disagree about whose it is. |
| `ports.js` | Canonical `PORTS` object (mirroring `ecosystem.config.cjs`, pinned by `ports.test.js`), `DEFAULT_PEER_PORT`, and `resolvePostgresPort(pgMode)`. A pure leaf: `client/src/lib/ports.js` re-exports it, so nothing here may read `process.env` at module scope — the env-derived origins live in `portosUrls.js`. |
| `portosUrls.js` | `PORTOS_UI_URL` / `PORTOS_API_URL` — the origins PortOS interpolates into prompts and links, resolved from `PORTOS_*` / `PORT` at module load. Split out of `ports.js` so that module stays free of module-scope `process.env` reads and can be re-exported to the client. |
| `platform.js` | Platform/OS detection helpers — listening-port probes plus `isAppleSilicon()` (arm64 darwin; gates MLX model features, detect at the route boundary). |
diff --git a/server/lib/ecosystemProcessPorts.js b/server/lib/ecosystemProcessPorts.js
new file mode 100644
index 0000000000..0c2a34de5f
--- /dev/null
+++ b/server/lib/ecosystemProcessPorts.js
@@ -0,0 +1,201 @@
+/**
+ * Attribute an ecosystem config's parsed port labels to the app that owns them.
+ *
+ * A PM2 ecosystem config routinely describes SEVERAL product surfaces: PortOS's
+ * own config declares `portos-server`/`portos-ui` (the app) alongside
+ * `portos-autofixer`/`portos-autofixer-ui` and `portos-browser` (sibling
+ * daemons). "First process carrying the label wins" silently mis-attributes a
+ * sibling's port to the app — issue #7357: the ONLY `ports.ui` in PortOS's
+ * config belongs to `portos-autofixer-ui` (5560), so saving the PortOS app
+ * record resolved `uiPort` to 5560, defeated the served-by-API derivation, and
+ * rewrote `AUTOFIXER_UI` to the API server's own 5555.
+ *
+ * The rule here is *positive attribution with a conservative fallback*:
+ *
+ * 1. Prefer a process on the app's own SURFACE — the process name with a
+ * trailing role suffix (`-server`, `-ui`, …) stripped. `portos-server` and
+ * `portos-ui` share surface `portos`; `portos-autofixer-ui` does not.
+ * 2. Otherwise accept the first process carrying the label UNLESS it is
+ * provably a sibling surface — its surface differs from the app's AND at
+ * least one other process in the config shares that surface, which is what
+ * makes it a distinct multi-process product surface rather than an
+ * unconventionally-named process of this app.
+ *
+ * Step 2 is what keeps an app whose processes are named `backend`/`frontend`
+ * working exactly as before: `frontend` is not on `backend`'s surface, but
+ * nothing else in the config claims surface `frontend`, so its `ui` port is
+ * still the app's. A label with no attributable process resolves to `undefined`,
+ * which is the signal callers use to fall back to derivation (a served-by-API
+ * app's `uiPort` = its `apiPort`).
+ *
+ * Pure and import-free: both the write-back path (`services/appPortConfig.js`)
+ * and the read/derive path (`services/appListEnrichment.js`) share it so a
+ * displayed port and a rewritten port can never disagree about whose it is.
+ */
+
+/**
+ * Role suffixes a process name carries to mark WHICH part of one surface it is.
+ * Stripping them collapses `portos-server` and `portos-ui` onto surface
+ * `portos` while leaving `portos-autofixer` (no role suffix) as its own.
+ */
+/** A declared port value: a positive integer (0 / null / a string is not a port). */
+const isPort = (value) => Number.isInteger(value) && value > 0;
+
+const ROLE_SUFFIXES = ['server', 'api', 'backend', 'ui', 'client', 'web', 'frontend'];
+
+/**
+ * The product surface a PM2 process belongs to: its name minus one trailing
+ * role suffix. Only a suffix preceded by `-`/`_` and leaving a non-empty stem is
+ * stripped, so a bare `ui` process stays `ui` rather than collapsing to ''.
+ */
+export function processSurface(name) {
+ if (typeof name !== 'string' || name.length === 0) return '';
+ for (const suffix of ROLE_SUFFIXES) {
+ const match = name.match(new RegExp(`^(.+)[-_]${suffix}$`, 'i'));
+ if (match) return match[1];
+ }
+ return name;
+}
+
+/**
+ * The process whose surface defines the app. Prefers a name the app record
+ * already claims as its own (`processes[]`/`pm2ProcessNames[]`, in order) and
+ * that the config actually declares — the record is the only place that knows
+ * which of several surfaces in one config is the app. Falls back to the first
+ * process carrying an `api` port (the historical primary), then the first
+ * process at all.
+ *
+ * The owned-name list is used for ORDER only, never as a membership filter: a
+ * record lists every PM2 process it supervises, siblings included (PortOS's own
+ * record claims `portos-autofixer-ui`), so filtering by it would re-admit the
+ * very process this module exists to exclude.
+ */
+function resolvePrimaryProcess(processes, ownedNames) {
+ for (const name of ownedNames || []) {
+ const match = processes.find(proc => proc?.name === name);
+ if (match) return match;
+ }
+ return processes.find(proc => isPort(proc?.ports?.api)) || processes[0] || null;
+}
+
+/** Process names the app record claims, in declaration order. */
+function ownedProcessNames(app) {
+ const names = [];
+ for (const proc of Array.isArray(app?.processes) ? app.processes : []) {
+ if (typeof proc?.name === 'string') names.push(proc.name);
+ }
+ for (const name of Array.isArray(app?.pm2ProcessNames) ? app.pm2ProcessNames : []) {
+ if (typeof name === 'string') names.push(name);
+ }
+ return names;
+}
+
+/**
+ * Resolve `api`/`ui`/`devUi` ports from a parsed process list, attributing each
+ * label to the app that owns it rather than to whichever process declares it
+ * first.
+ *
+ * @param {Array<{name?: string, ports?: Record<string, number>}>} processes
+ * parsed ecosystem processes (or an app record's `processes[]` — same shape)
+ * @param {object} [app] the app record, consulted only for which process names
+ * it owns; omit it and the primary falls back to the first `api` process
+ * @returns {{ ports: Record<string, number|undefined>, processNames: Record<string, string|undefined> }}
+ * `ports[label]` is undefined when no process can be attributed the label;
+ * `processNames[label]` names the process the value came from (what a targeted
+ * config rewrite must aim at).
+ */
+export function attributeProcessPorts(processes, app) {
+ const procs = (processes || []).filter(proc => proc && typeof proc === 'object');
+ const ports = {};
+ const processNames = {};
+ if (procs.length === 0) return { ports, processNames };
+
+ const primary = resolvePrimaryProcess(procs, ownedProcessNames(app));
+ const appSurface = processSurface(primary?.name);
+
+ // Surfaces with two or more processes of their own are distinct product
+ // surfaces in this config — that is the evidence needed to IGNORE one of their
+ // labels rather than mis-attribute it to the app.
+ const surfaceCounts = new Map();
+ for (const proc of procs) {
+ const surface = processSurface(proc.name);
+ surfaceCounts.set(surface, (surfaceCounts.get(surface) || 0) + 1);
+ }
+
+ for (const label of ['api', 'ui', 'devUi']) {
+ const carriers = procs.filter(proc => isPort(proc.ports?.[label]));
+ const owned = carriers.find(proc => processSurface(proc.name) === appSurface);
+ // No process on the app's own surface declares this label: accept the first
+ // carrier that is not provably a sibling surface (step 2 above).
+ const attributed = owned
+ || carriers.find(proc => (surfaceCounts.get(processSurface(proc.name)) || 0) < 2);
+ if (!attributed) continue;
+ ports[label] = attributed.ports[label];
+ processNames[label] = attributed.name;
+ }
+
+ return { ports, processNames };
+}
+
+/**
+ * Cross-process port collisions a set of edits would introduce.
+ *
+ * A port the config already gives to ANOTHER process must never be written into
+ * this one: issue #7357 rewrote `AUTOFIXER_UI` to 5555 while `portos-server`
+ * held 5555, producing a correct-looking config that collides the moment PM2
+ * restarts. Every label in every process's `ports` map counts as a claim — a
+ * sibling's `cdp`/`health`/loopback-mirror port is just as taken as its `api`.
+ *
+ * Only CROSS-process collisions are reported. Two labels on one process sharing
+ * a value is the legitimate served-by-API shape (`ports: { api: N, ui: N }`),
+ * and edits that merely reproduce it must still go through.
+ *
+ * @param {Array<{name?: string, ports?: Record<string, number>}>} processes
+ * @param {Array<{processName: string, label: string, newPort: number}>} edits
+ * @returns {{ processName: string, label: string, newPort: number, heldBy: string, heldLabel: string }|null}
+ * the first collision found, or null when every edit is free of one
+ */
+export function findCrossProcessPortCollision(processes, edits) {
+ const procs = (processes || []).filter(proc => proc && typeof proc === 'object');
+ // Post-edit view: an edited label vacates its old value, so an edit that moves
+ // a port out of the way cannot collide with the value it just released.
+ const claims = [];
+ for (const proc of procs) {
+ for (const [label, port] of Object.entries(proc.ports || {})) {
+ if (!isPort(port)) continue;
+ const edit = (edits || []).find(e => e?.processName === proc.name && e?.label === label);
+ claims.push({ processName: proc.name, label, port: edit ? edit.newPort : port });
+ }
+ }
+
+ for (const edit of edits || []) {
+ if (!edit || !isPort(edit.newPort)) continue;
+ const held = claims.find(claim => claim.processName !== edit.processName && claim.port === edit.newPort);
+ if (held) {
+ return {
+ processName: edit.processName,
+ label: edit.label,
+ newPort: edit.newPort,
+ heldBy: held.processName,
+ heldLabel: held.label,
+ };
+ }
+ }
+ return null;
+}
+
+/**
+ * Derive `uiPort` from `apiPort` when an app has a dev UI but no dedicated prod
+ * UI port — the prod UI is then served by the API server, so the two are the
+ * same port and the UI port cannot be set independently.
+ *
+ * Lives beside the attribution rules because it is the other half of the same
+ * decision: `attributeProcessPorts` deciding a label has no owning process is
+ * precisely what hands control to this derivation. Keeping it here also stops
+ * the port write-back path from importing a service graph for one pure
+ * function; `services/appListEnrichment.js` re-exports it for its callers.
+ */
+export function deriveUiPort(uiPort, apiPort, devUiPort) {
+ if (!uiPort && apiPort && devUiPort) return apiPort;
+ return uiPort;
+}
diff --git a/server/lib/importScoping.test.js b/server/lib/importScoping.test.js
index fcdf1706ca..32955a2d6c 100644
--- a/server/lib/importScoping.test.js
+++ b/server/lib/importScoping.test.js
@@ -606,7 +606,18 @@ describe('deferred imports stay deferred (#6156)', () => {
// `modelPinAudit.js` gaining `reviewerConfig.js` / `goalFidelity.js` cost
// nothing — `routes/providers.js` already reaches both through
// `lib/validation.js`.
-const MAX_STATIC_INSTANTIATIONS = 104668;
+// Fixing the sibling-process port mis-attribution (#7357) measures +37, all of
+// it a new boundary test file plus one dependency-free leaf. The attribution
+// rules live in `lib/ecosystemProcessPorts.js`, which imports nothing, so the
+// ~13 existing closures that reach the two services now sharing it each gain one
+// node. `services/appPortConfig.test.js` has to go through the real filesystem
+// (the regression is "the config file must come back byte-identical", which the
+// route suite's mocked writer cannot observe), so it pays its own closure. That
+// closure is 24 rather than 83 because the same change moved `deriveUiPort` —
+// three pure lines the write-back path was importing the whole 81-module
+// `services/appListEnrichment.js` for — down into that leaf, which
+// re-exports it for its existing callers.
+const MAX_STATIC_INSTANTIATIONS = 104705;
const SKIP_DIRS = new Set(['node_modules', 'coverage', 'dist', 'data']);
diff --git a/server/lib/index.js b/server/lib/index.js
index 6f0c7031d0..54e22e4afd 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -636,3 +636,4 @@ export * from './auditQuality.js';
export * from './mindToolRecipes.js';
export * from './deckTemplates.js';
export * from './deckValidation.js';
+export * from './ecosystemProcessPorts.js';
diff --git a/server/routes/apps/crud.js b/server/routes/apps/crud.js
index d35814c285..db606f576c 100644
--- a/server/routes/apps/crud.js
+++ b/server/routes/apps/crud.js
@@ -172,7 +172,7 @@ router.put('/:id', asyncHandler(async (req, res, next) => {
// 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)) {
- const { persistFailed, uiPortOverride } = await applyEcosystemPortEdits(existing, data);
+ const { persistFailed, uiPortOverride, portCollision } = await applyEcosystemPortEdits(existing, data);
// Pin the stored uiPort to the derived value for served-by-API apps. This
// both overwrites the drawer's echoed/stale UI field and keeps the stored
@@ -184,6 +184,16 @@ router.put('/:id', asyncHandler(async (req, res, next) => {
data.uiPort = uiPortOverride;
}
+ // Collision gate: the edit would give one process a port another process in
+ // the same ecosystem config already holds. Nothing was written; reject so the
+ // user fixes the conflict rather than discovering it as a failed PM2 restart.
+ if (portCollision) {
+ throw new ServerError(
+ `Port ${portCollision.newPort} is already used by the ${portCollision.heldBy} process (${portCollision.heldLabel}) in ${existing.name}'s ecosystem config — pick a port no other process claims.`,
+ { status: 422, code: 'PORT_COLLISION' }
+ );
+ }
+
// 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).
diff --git a/server/services/appListEnrichment.js b/server/services/appListEnrichment.js
index 0822b05951..302261cb55 100644
--- a/server/services/appListEnrichment.js
+++ b/server/services/appListEnrichment.js
@@ -8,8 +8,9 @@
* derivation. The route just fetches the apps and responds — this module is
* the single home for the enrichment logic.
*
- * The pure port/status derivation helpers (`deriveUiPort`, `deriveAppPorts`,
- * `computeOverallStatus`) live here too and are re-exported from
+ * The pure port/status derivation helpers (`deriveAppPorts`,
+ * `computeOverallStatus`, and `deriveUiPort` re-exported from
+ * `lib/ecosystemProcessPorts.js`) live here too and are re-exported from
* `routes/apps/shared.js` so the detail (`GET /:id`) and lifecycle routes keep
* a single shared implementation without importing a service from a route.
*/
@@ -19,15 +20,12 @@ import { listProcessesStrict } from './pm2.js';
import { hasDeployScript } from './appDeployer.js';
import { checkScripts } from './xcodeScripts.js';
import { pathExists } from '../lib/fileUtils.js';
+import { attributeProcessPorts, deriveUiPort } from '../lib/ecosystemProcessPorts.js';
-/**
- * Derive uiPort from apiPort when app has dev UI but no dedicated prod UI port
- * (prod UI is served by the API server in these cases).
- */
-export function deriveUiPort(uiPort, apiPort, devUiPort) {
- if (!uiPort && apiPort && devUiPort) return apiPort;
- return uiPort;
-}
+// The served-by-API derivation itself lives in the pure lib leaf beside the
+// port-attribution rules (its two halves are one decision); re-exported here so
+// routes/apps/shared.js and every existing deep import keep resolving it.
+export { deriveUiPort };
/**
* Derive uiPort/apiPort/devUiPort from an app's process list when not
@@ -38,18 +36,14 @@ export function deriveUiPort(uiPort, apiPort, devUiPort) {
export function deriveAppPorts(app, processes) {
let { uiPort, apiPort, devUiPort } = app;
const procs = processes || [];
- if (!uiPort && procs.length) {
- const uiProc = procs.find(p => p.ports?.ui);
- if (uiProc) uiPort = uiProc.ports.ui;
- }
- if (!apiPort && procs.length) {
- const apiProc = procs.find(p => p.ports?.api);
- if (apiProc) apiPort = apiProc.ports.api;
- }
- if (!devUiPort && procs.length) {
- const devUiProc = procs.find(p => p.ports?.devUi);
- if (devUiProc) devUiPort = devUiProc.ports.devUi;
- }
+ // Attribute each label to a process that belongs to THIS app (#7357) — the
+ // same rule the write-back path uses, so a displayed port and a rewritten port
+ // can never disagree about whose it is. A sibling surface's `ports.ui` (e.g.
+ // `portos-autofixer-ui` in PortOS's own config) is not the app's UI port.
+ const { ports } = attributeProcessPorts(procs, app);
+ if (!uiPort) uiPort = ports.ui;
+ if (!apiPort) apiPort = ports.api;
+ if (!devUiPort) devUiPort = ports.devUi;
uiPort = deriveUiPort(uiPort, apiPort, devUiPort);
return { uiPort, apiPort, devUiPort };
}
diff --git a/server/services/appPortConfig.js b/server/services/appPortConfig.js
index ca1a23b35f..ab91840d7f 100644
--- a/server/services/appPortConfig.js
+++ b/server/services/appPortConfig.js
@@ -10,16 +10,19 @@
* still owns the precondition guard (`usesPm2` + path exists) and the HTTP
* error/response mapping.
*
- * Returns `{ persistFailed, uiPortOverride, changedKeys }`:
+ * Returns `{ persistFailed, uiPortOverride, changedKeys, portCollision }`:
* - persistFailed — true when the user changed a port we could NOT write to
* the source-of-truth config (caller should reject 422).
* - uiPortOverride — the derived uiPort to pin for served-by-API apps
* (undefined when the app's ui port is a real literal).
* - changedKeys — port keys that differed from the config (for context).
+ * - portCollision — set when an edit would hand one process a port ANOTHER
+ * process in the same config already holds (caller rejects
+ * 422); nothing is written in that case.
*/
import { parseEcosystemFromPath, writeEcosystemPortEdits } from './streamingDetect.js';
-import { deriveUiPort } from './appListEnrichment.js';
+import { attributeProcessPorts, deriveUiPort, findCrossProcessPortCollision } from '../lib/ecosystemProcessPorts.js';
const PORT_KEYS = ['apiPort', 'uiPort', 'devUiPort'];
const LABEL_BY_KEY = { apiPort: 'api', uiPort: 'ui', devUiPort: 'devUi' };
@@ -37,15 +40,18 @@ export async function applyEcosystemPortEdits(existing, data) {
// 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);
+ // Attribute each label to the process that belongs to THIS app, not to
+ // whichever process declares the label first (#7357): one ecosystem config
+ // routinely describes several product surfaces, and a sibling daemon's
+ // `ports.ui` is not the app's UI port. A label with no attributable process
+ // stays undefined, which is what lets the served-by-API derivation below take
+ // over instead of the config edit landing on the sibling's literal.
+ const { ports: attributedPorts, processNames: procNameByLabel } = attributeProcessPorts(cfgProcs, existing);
const currentPort = {};
const procNameByKey = {}; // which process block owns each label (for targeted rewrites)
- 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];
- procNameByKey[key] = proc.name;
- }
- }
+ for (const [key, label] of Object.entries(LABEL_BY_KEY)) {
+ currentPort[key] = attributedPorts[label];
+ procNameByKey[key] = procNameByLabel[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
@@ -78,6 +84,21 @@ export async function applyEcosystemPortEdits(existing, data) {
const effectiveApiPort = Number.isInteger(data.apiPort) ? data.apiPort : currentPort.apiPort;
const derivedUiPort = deriveUiPort(undefined, effectiveApiPort, currentPort.devUiPort);
const uiIsDerived = currentPort.uiPort === undefined && Number.isInteger(derivedUiPort);
+ // Collision guard (#7357): never hand one process a port ANOTHER process in
+ // the same config already holds. Whatever the rewrite path — value-keyed or
+ // targeted — the result would be a correct-looking config that collides the
+ // moment PM2 restarts, so this runs BEFORE any write and rejects instead.
+ // Every edit is described by process + label here, including the value-keyed
+ // ones (which name a process for attribution but rewrite by value).
+ const portCollision = findCrossProcessPortCollision(cfgProcs, changedKeys.map(key => ({
+ processName: procNameByKey[key],
+ label: LABEL_BY_KEY[key],
+ newPort: data[key],
+ })));
+ if (portCollision) {
+ return { persistFailed: false, uiPortOverride: uiIsDerived ? derivedUiPort : undefined, changedKeys, portCollision };
+ }
+
const remap = [];
const targetedEdits = []; // shared-value keys: rewritten by process + label
for (const key of changedKeys) {
@@ -122,5 +143,6 @@ export async function applyEcosystemPortEdits(existing, data) {
persistFailed,
uiPortOverride: uiIsDerived ? derivedUiPort : undefined,
changedKeys,
+ portCollision: null,
};
}
diff --git a/server/services/appPortConfig.test.js b/server/services/appPortConfig.test.js
new file mode 100644
index 0000000000..5b47cf9059
--- /dev/null
+++ b/server/services/appPortConfig.test.js
@@ -0,0 +1,151 @@
+/**
+ * Port write-back fidelity against a REAL multi-process ecosystem config.
+ *
+ * These go through the filesystem deliberately: issue #7357 was a mis-attributed
+ * label that produced a successful-looking write into a SIBLING process's port
+ * literal, and the route suite mocks `writeEcosystemPortEdits` away, so nothing
+ * above this layer can observe what actually landed on disk. The assertion that
+ * uniquely catches the regression is "the config file is byte-identical".
+ */
+
+import { describe, it, expect, beforeEach, afterEach } from 'vitest';
+import { mkdtemp, rm, readFile, writeFile } from 'fs/promises';
+import { tmpdir } from 'os';
+import { join } from 'path';
+import { applyEcosystemPortEdits } from './appPortConfig.js';
+
+/**
+ * The shape PortOS's own config has: a served-by-API primary (`PORT` env, no
+ * `ports.ui` literal), a Vite dev UI, and a SIBLING daemon pair whose `-ui`
+ * process is the only `ports.ui` in the whole file. Names are placeholders; the
+ * structure is what reproduces #7357.
+ */
+const SIBLING_UI_CONFIG = `const PORTS = {
+ API: 6000, // Example API server
+ UI: 6001, // Vite dev server
+ HELPER: 6002, // Helper daemon API
+ HELPER_UI: 6003, // Helper daemon UI
+};
+
+module.exports = {
+ apps: [
+ { name: 'example-server', script: 'server/index.js', env: { PORT: PORTS.API } },
+ { name: 'example-ui', script: 'npm', args: 'run dev', env: { VITE_PORT: PORTS.UI } },
+ { name: 'example-helper', script: 'helper/index.js', env: { PORT: PORTS.HELPER } },
+ { name: 'example-helper-ui', script: 'helper/ui.js', env: { PORT: PORTS.HELPER_UI } }
+ ]
+};
+`;
+
+/** Two-process app with unconventional names — neither shares a surface. */
+const UNCONVENTIONAL_CONFIG = `const PORTS = {
+ API: 7000,
+ WEBAPP: 7001,
+};
+
+module.exports = {
+ apps: [
+ { name: 'backend', script: 'server/index.js', env: { PORT: PORTS.API } },
+ { name: 'frontend', script: 'web/index.js', env: { UI_PORT: PORTS.WEBAPP } }
+ ]
+};
+`;
+
+describe('applyEcosystemPortEdits', () => {
+ let repoPath;
+
+ beforeEach(async () => {
+ repoPath = await mkdtemp(join(tmpdir(), 'portos-appPortConfig-'));
+ });
+
+ afterEach(async () => {
+ await rm(repoPath, { recursive: true, force: true });
+ });
+
+ const writeConfig = async (content) => {
+ await writeFile(join(repoPath, 'ecosystem.config.cjs'), content, 'utf-8');
+ return content;
+ };
+
+ const readConfig = () => readFile(join(repoPath, 'ecosystem.config.cjs'), 'utf-8');
+
+ it('leaves a sibling process\'s UI port untouched when the drawer echoes the derived uiPort', async () => {
+ // #7357: `example-helper-ui` owns the only `ports.ui` in the file, so the
+ // old first-carrier-wins resolution read uiPort as 6003, defeated the
+ // served-by-API derivation, and rewrote HELPER_UI to the API server's 6000.
+ const before = await writeConfig(SIBLING_UI_CONFIG);
+ const existing = {
+ id: 'example',
+ name: 'Example',
+ repoPath,
+ type: 'node',
+ processes: [{ name: 'example-server' }, { name: 'example-ui' }, { name: 'example-helper' }, { name: 'example-helper-ui' }],
+ };
+
+ // Exactly what EditAppModal submits on ANY save of this record (a rename,
+ // an archive toggle): every port field, echoing the stored derived uiPort.
+ const result = await applyEcosystemPortEdits(existing, { apiPort: 6000, uiPort: 6000, devUiPort: 6001 });
+
+ expect(await readConfig()).toBe(before);
+ expect(result.changedKeys).toEqual([]);
+ // uiPort is derived (served-by-API), so it is pinned to the API port.
+ expect(result.uiPortOverride).toBe(6000);
+ expect(result.persistFailed).toBe(false);
+ });
+
+ it('rejects an edit that would take a port another process already holds, writing nothing', async () => {
+ const before = await writeConfig(SIBLING_UI_CONFIG);
+ const existing = {
+ id: 'example',
+ name: 'Example',
+ repoPath,
+ type: 'node',
+ processes: [{ name: 'example-server' }, { name: 'example-ui' }],
+ };
+
+ // 6002 belongs to `example-helper`. Writing it into the dev UI port would
+ // produce a correct-looking config that collides at the next PM2 restart.
+ const result = await applyEcosystemPortEdits(existing, { apiPort: 6000, uiPort: 6000, devUiPort: 6002 });
+
+ expect(await readConfig()).toBe(before);
+ expect(result.portCollision).toMatchObject({ newPort: 6002, heldBy: 'example-helper' });
+ });
+
+ it('still persists a genuine port change that collides with nothing', async () => {
+ // The bypass probe for the two guards above: a normal edit must still write,
+ // or both assertions would be satisfied by a service that never writes.
+ await writeConfig(SIBLING_UI_CONFIG);
+ const existing = {
+ id: 'example',
+ name: 'Example',
+ repoPath,
+ type: 'node',
+ processes: [{ name: 'example-server' }, { name: 'example-ui' }],
+ };
+
+ const result = await applyEcosystemPortEdits(existing, { apiPort: 6010, uiPort: 6000, devUiPort: 6001 });
+
+ const after = await readConfig();
+ expect(result.changedKeys).toEqual(['apiPort']);
+ expect(result.persistFailed).toBe(false);
+ expect(after).toContain('API: 6010,');
+ // …and only the API port moved.
+ expect(after).toContain('HELPER_UI: 6003,');
+ expect(after).toContain('UI: 6001,');
+ });
+
+ it('still attributes a UI port to a process that shares no naming convention with the primary', async () => {
+ // `frontend` is not on `backend`'s surface, but nothing else in the config
+ // claims surface `frontend` — so it is this app's UI, not a sibling's, and a
+ // real edit to it must still persist.
+ await writeConfig(UNCONVENTIONAL_CONFIG);
+ const existing = { id: 'example', name: 'Example', repoPath, type: 'node', processes: [{ name: 'backend' }, { name: 'frontend' }] };
+
+ const result = await applyEcosystemPortEdits(existing, { apiPort: 7000, uiPort: 7010 });
+
+ expect(result.changedKeys).toEqual(['uiPort']);
+ // Not treated as derived — the app has a real UI port literal.
+ expect(result.uiPortOverride).toBeUndefined();
+ expect(await readConfig()).toContain('WEBAPP: 7010,');
+ });
+});