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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
address review (codex): normalize served-by-API uiPort instead of 422ing the common edit path
Adam Eivy08d106c98aac
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex c9762f9da9..d3cd1a09bb 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. 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.+- 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, and an explicit `ports: { ui: N, devUi: N }` map with matching values is split correctly (only the edited key changes). 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 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. For an app whose prod UI is **served by the API** (no separate UI port), the UI port can't be set on its own — it always follows the API port: the stored UI port is normalized to track the API port on every save (so it never freezes at a stale value), and you change it by changing the API port.diff --git a/server/routes/apps.js b/server/routes/apps.jsindex 17ea7eece5..5d4d4e2c25 100644--- a/server/routes/apps.js+++ b/server/routes/apps.js@@ -509,22 +509,21 @@ router.put('/:id', asyncHandler(async (req, res, next) => {const changedKeys = PORT_KEYS.filter(key =>Number.isInteger(currentPort[key]) && Number.isInteger(data[key]) && data[key] !== currentPort[key]);- // Derived-uiPort guard. When an app has an API process plus a Vite dev UI- // but no literal `ports.ui`, the prod UI is served by the API and the- // displayed `uiPort` is *derived* (= apiPort). There's no independent ui- // literal to rewrite, so a uiPort edit can't persist on its own. Compare the- // submitted uiPort against the NEW derived value — i.e. the API port AFTER- // this same request's apiPort change (if any), so a valid combined save like- // `apiPort: 6000→7000, uiPort: 7000` (UI still following the API) is accepted- // rather than rejected against the stale old value. Only a uiPort that- // diverges from the new API port is a genuine independent change → 422 (the- // user must change the API port instead). The modal echoes the derived value- // on every save; that echo is stripped below so it's never stored explicitly.+ // Served-by-API detection. When an app has an API process plus a Vite dev+ // UI but no literal `ports.ui`, the prod UI is served by the API server, so+ // the `uiPort` is *derived* (= apiPort) and CANNOT be set independently —+ // there's no separate UI port literal in the config to rewrite. The edit+ // drawer always submits every port field and never syncs the UI field to a+ // changed API field, so an API-only edit arrives as `{ apiPort: <new>,+ // uiPort: <old derived> }`. We can't distinguish that stale echo from a+ // deliberate (impossible) independent UI change, so the only coherent+ // behavior is to IGNORE the submitted uiPort entirely and pin the stored+ // value to the derived port (= the post-edit API port). That tracks the API+ // port on every save, never reverts, and never spuriously 422s the common+ // API-edit path. The user changes this UI port by changing the API port.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);- const derivedUiChangeRejected =- uiIsDerived && Number.isInteger(data.uiPort) && data.uiPort !== derivedUiPort;const remap = [];const targetedEdits = []; // shared-value keys: rewritten by process + labelfor (const key of changedKeys) {@@ -539,25 +538,13 @@ router.put('/:id', asyncHandler(async (req, res, next) => {remap.push([oldPort, data[key]]);}- // Reject a derived-uiPort change before touching the config (it has no- // literal to write — the user must change the API port). Doing this first- // keeps the rejected request from persisting any OTHER port edit in the- // same PUT.- if (derivedUiChangeRejected) {- throw new ServerError(- `Cannot change ${existing.name}'s UI port directly — its prod UI is served by the API server, so the UI port follows the API port. Change the API port instead.`,- { status: 422, code: 'PORT_NOT_PERSISTABLE' }- );- }-- // Served-by-API apps have NO explicit uiPort in the config — it's derived- // from apiPort on read. Pin the stored uiPort to the NEW derived value so it- // tracks the (possibly just-changed) API port. Deleting it from this partial- // update is NOT enough: updateApp merges omitted fields over the existing- // record, so a stale explicit `uiPort` left by an earlier refresh would- // survive (truthy) and block re-derivation — after API 6000→7000 the GET- // path would keep returning the old 6000. Writing the derived value- // overwrites any stale stored port and self-corrects on every API change.+ // Pin the stored uiPort to the derived value for served-by-API apps (see+ // above). This both overwrites the drawer's echoed/stale UI field and keeps+ // the stored value tracking apiPort — deleting `data.uiPort` would NOT be+ // enough, since updateApp merges omitted fields over the existing record, so+ // a stale explicit `uiPort` from an earlier refresh would survive (truthy)+ // and block re-derivation (after API 6000→7000 the GET path would keep+ // returning 6000). Writing the derived value self-corrects on every save.// (uiIsDerived is computed from the parsed CONFIG, not apps.json, so it's// true even when apps.json already holds a stale explicit value.)if (uiIsDerived) {diff --git a/server/routes/apps.test.js b/server/routes/apps.test.jsindex b17ee160d1..1aa8bc742b 100644--- a/server/routes/apps.test.js+++ b/server/routes/apps.test.js@@ -356,22 +356,31 @@ describe('Apps Routes', () => {expect(appsService.updateApp).not.toHaveBeenCalled();});- it('rejects (422) a change to a derived uiPort (prod UI served by the API, no literal ui port)', async () => {+ it('ignores a submitted uiPort on a derived (served-by-API) app and pins it to the derived value', async () => {// App has an API process + Vite dev UI but no literal ports.ui, so the- // displayed uiPort is derived (= apiPort). Changing it can't persist —- // the user must change the API port instead → 422, config untouched.+ // displayed uiPort is derived (= apiPort). The drawer submits all fields+ // and never syncs the UI field to a changed API field, so a stale/echoed+ // or even hand-typed uiPort can't be distinguished from a deliberate+ // (impossible) independent UI change. The route ignores the submitted+ // value: no config write for the UI port, no 422, and the stored uiPort is+ // pinned to the derived value so it keeps tracking the API port.const mockApp = { id: 'app-001', name: 'App', type: 'node', repoPath: process.cwd(), apiPort: 6000, uiPort: 6000, devUiPort: 5556 };appsService.getAppById.mockResolvedValue(mockApp);// Parser yields api + devUi only; ui is derived from api (served-by-API).streamingDetect.parseEcosystemFromPath.mockResolvedValue({processes: [{ name: 'srv', ports: { api: 6000, devUi: 5556 } }]});+ appsService.updateApp.mockResolvedValue({ ...mockApp });const response = await request(app).put('/api/apps/app-001').send({ uiPort: 7000 });- expect(response.status).toBe(422);+ expect(response.status).toBe(200);+ // No API port change → no config rewrite for the (ignored) UI port.expect(streamingDetect.writeEcosystemPortEdits).not.toHaveBeenCalled();- expect(appsService.updateApp).not.toHaveBeenCalled();+ // Stored uiPort pinned to the derived value (= unchanged apiPort 6000),+ // NOT the submitted 7000.+ const updateArg = appsService.updateApp.mock.calls[0][1];+ expect(updateArg.uiPort).toBe(6000);});it('strips the echoed derived uiPort so it is never persisted as an explicit field', async () => {@@ -428,23 +437,33 @@ describe('Apps Routes', () => {expect(updateArg.apiPort).toBe(7000);});- it('rejects (422) a served-by-API uiPort that diverges from the new API port', async () => {- // apiPort→7000 but uiPort sent as 6000: the user is asking for a UI port- // that does NOT follow the API port, which a served-by-API app can't do.- // Compared against the NEW derived value (7000), 6000 diverges → 422.+ it('accepts the common API-only edit (drawer echoes the stale derived uiPort) and pins uiPort to the new API port', async () => {+ // The drawer submits all fields and does NOT sync the UI field when the+ // API field changes, so a normal API-only edit arrives as+ // { apiPort: 7000, uiPort: 6000 (old derived) }. That stale echo must NOT+ // 422 — the API port persists via the value-keyed rewrite and the stored+ // uiPort is pinned to the NEW derived value (7000), not the echoed 6000.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({processes: [{ name: 'srv', ports: { api: 6000, devUi: 5556 } }]});+ appsService.updateApp.mockResolvedValue({ ...mockApp, apiPort: 7000, uiPort: 7000 });const response = await request(app).put('/api/apps/app-001').send({ apiPort: 7000, uiPort: 6000 });- expect(response.status).toBe(422);- expect(streamingDetect.writeEcosystemPortEdits).not.toHaveBeenCalled();- expect(appsService.updateApp).not.toHaveBeenCalled();+ expect(response.status).toBe(200);+ // API port persisted; the stale echoed UI port is ignored, not remapped.+ expect(streamingDetect.writeEcosystemPortEdits).toHaveBeenCalledWith(+ process.cwd(),+ [[6000, 7000]],+ []+ );+ const updateArg = appsService.updateApp.mock.calls[0][1];+ expect(updateArg.uiPort).toBe(7000); // pinned to NEW derived value, not echoed 6000+ expect(updateArg.apiPort).toBe(7000);});it('does not reject a non-port edit on an app whose top-level ports are not stored (derived)', async () => {