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: keep managed-app ports out of browser-blocked 6000 and label static servers as UI (#11978)

Adam Eivy69be4482ebaf
diff --git a/docs/API.md b/docs/API.md
index 6d93a24c32..8b05b7fe4e 100644
--- a/docs/API.md
+++ b/docs/API.md
@@ -120,7 +120,7 @@ legacy list for local Apps/Dashboard views.
| POST | `/apps/:id/restart` | Restart app via PM2 |
| GET | `/apps/:id/status` | Get PM2 status |
| GET | `/apps/:id/logs` | Get recent logs |
-| POST | `/apps/:id/refresh-config` | Re-parse ecosystem config |
+| POST | `/apps/:id/refresh-config` | Re-parse ecosystem config; the record's `apiPort`/`uiPort`/`devUiPort` are set to match it, and a port the config no longer declares is cleared |
| POST | `/apps/:id/quality-snapshot` | Rebuild the app's numeric quality snapshot and land canonical schema v2 `.quality.json` through an immediately-merged pull request on `portos/quality-snapshot` (scoped to that one path; the live checkout is not committed). The file is not the peer wire payload (`PORTOS_SCHEMA_VERSIONS.appQuality` stays 1). A v1 file is rewritten when current evidence exists. Answers `{ success, published, path }` plus the commit `hash`, `prUrl`, and `prNumber`, or a `reason` of `no-repo-path` / `not-a-repo` / `no-evidence` / `no-changes` / `no-remote` / `no-default-branch` / `pr-failed` / `unsupported-format` / `invalid-evidence` when nothing was written. `unsupported-format` means a future, unrecognized, malformed, or oversize file was left in place. Not gated on the app's `publishQualitySnapshot` toggle — that toggle only automates the same publish after each audit. Any app's committed `.quality.json` (or a historical `quality-snapshot.json` when `.quality.json` is absent) is read back as a "Release snapshot" quality source, PortOS's own checkout included (`npm run quality:snapshot` is the same publish, run from the release step; `npm run quality:snapshot -- --migrate` converts an old file without reading the database). |
| GET | `/apps/:id/quality-schedule` | The Quality tab's weekly-schedule form: every audit check with its applicability verdict and reason, the repository shapes that verdict came from, the cron expressions already occupied on this app, and the plan the shipped defaults produce. Read-only — no LLM call, no write. |
| POST | `/apps/:id/quality-schedule/preview` | Re-plan for an edited form (selection, per-check delivery mode, checks per day, hour window, claim-drain task and offset). Still read-only; a POST only because the option bag carries a per-check map. |
diff --git a/docs/PORTS.md b/docs/PORTS.md
index aca8c879fb..95ef567a98 100644
--- a/docs/PORTS.md
+++ b/docs/PORTS.md
@@ -125,7 +125,8 @@ module.exports = {
### Port Detection
PortOS automatically detects ports from env vars:
-- `PORT` → labeled as `api` (or `ui` for `-ui`/`-client` processes, `health` for `-browser` processes with CDP)
+- A process's `ports: { ui: N }` object wins when present. The PM2 Standardizer writes one for every process, labeling HTML-serving processes `ui` so the app gets an Open button
+- `PORT` → labeled as `api` (or `ui` for `-ui`/`-client` processes, `health` for `-browser` processes with CDP) when the process has no `ports` object
- `CDP_PORT` → labeled as `cdp`
- `VITE_PORT` → labeled as `ui`
- `--port` in args → labeled as `ui`
@@ -144,8 +145,8 @@ PortOS automatically detects ports from env vars:
|-------|---------|
| 5553-5561 | PortOS core services (includes the `:5553` loopback mirror and the `portos-db` Docker container on `:5561`) |
| 5562-5569 | Reserved for PortOS extensions. Assigned: 5562 whisper, 5563 Eidoverse bridge (on demand), 5564 slotstream (on demand), 5565 Tailcat ingress (on demand), 5566 jev scorer (on demand), 5568 llama-server. Unassigned but still reserved: 5567, 5569 |
-| 5570-5599 | User applications — **put managed apps here** |
-| 6000-6099 | Outside the PortOS band. Used by `GET /api/ports/scan` and `POST /api/ports/allocate` (`server/services/ports.js`), and by the PM2 Standardizer when it reassigns a colliding port (`server/services/pm2Standardizer.js`). Scaffolded apps still get 5570-5599 |
+| 5570-5599 | User applications — **put managed apps here**. `GET /api/ports/scan`, `POST /api/ports/allocate` (`server/services/ports.js`) and the PM2 Standardizer's collision reassignment (`server/services/pm2Standardizer.js`) all allocate from this band, overflowing just past 5599 when it is full |
+| 6000 and other browser-blocked ports | Never allocated. Chrome and Firefox refuse to connect to the WHATWG Fetch "bad ports" (`ERR_UNSAFE_PORT`; 6000 is X11), so a managed app there has no reachable UI. `server/lib/browserUnsafePorts.js` holds the list and every allocator skips it |
> **A collision inside `5553-5569` is silent, not loud.** The natural assumption is
> that a second listener on a taken port fails with `EADDRINUSE`, so an accidental
diff --git a/server/lib/README.md b/server/lib/README.md
index a0b5b14de4..6c77af2d53 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -657,6 +657,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `backupConfig.js` | `resolveBackupConfig(settings.backup)` + `DEFAULT_BACKUP_CRON` — the single declaring module for how a SPARSE backup settings slice resolves (#6632): an omitted `enabled` means enabled, a missing/blank `cronExpression` means midnight (`0 0 * * *`), and `scheduled` additionally requires a `destPath`. Also `resolveRetentionCount(settings.backup)` + `DEFAULT_RETENTION_COUNT`/`MIN_RETENTION_COUNT`/`MAX_RETENTION_COUNT` (#8334): per-source completed-snapshot retention, where an omitted or `null` `retentionCount` means unlimited — a NEW install ships the `30` default on disk via `data.reference/settings.json`, never invented here for an absent value. Read-time resolution only — nothing on disk changes. Shared by `services/backupScheduler.js` (registration + handler eligibility, and the retention count `services/backup.js#runBackup` prunes with) and `routes/settings.js` (the GET projects effective values), so the Settings screen can render what the scheduler will actually do instead of inventing its own defaults. |
| `systemIdle.js` | `summarizeSystemActivity(processingSnapshot)` → `{ idle, activeCount, queuedCount, blockers[] }` + `describeActivityBlockers` — the ONE definition of "is this install doing anything", derived from the `/api/system/processing` snapshot. Queued work counts as active. Rendered by the dashboard's Live activity widget and refused on by the unattended auto-updater, so the two can never disagree about a window in which PortOS may restart itself. Every blocker label is generated prose (a count and a noun); no snapshot content is echoed. |
| `browserConfig.js` | Shared `browserExecutablePath` resolution for managed and owned render browsers, plus custom path helpers for deriving macOS app bundles, detecting configured browser choices, normalizing browser config, and validating Chrome-compatible binary paths. |
+| `browserUnsafePorts.js` | `BROWSER_UNSAFE_PORTS` / `isBrowserUnsafePort(port)` — the WHATWG Fetch "bad ports" browsers refuse (`ERR_UNSAFE_PORT`, incl. X11's 6000). Port allocators (`findAvailablePorts`, `services/ports.js`, the PM2 standardizer) must skip these so a managed app's UI is never unreachable. |
| `condaEnv.js` | Resolves a NAMED conda environment's interpreter: `condaEnvPythonCandidates(envName)` builds the ordered candidate list (`CONDA_PREFIX` — walking up two levels when it points at an `envs/<name>` rather than a root — then `CONDA_ROOT`, `~/miniconda3`, `~/anaconda3`, `~/miniforge3`, `~/mambaforge`, `/opt/conda`), and `resolveCondaEnvPython(envName, { exists })` returns the first that exists or `null`. Separate from `pythonSetup.js` (which probes *venv* layouts and computes candidates from `PATHS` at module load) so a conda lookup pulls in no eager path work. Used by the image-to-3D CUDA lanes, which each own a distinct env (`trellis2`, `pixal3d`) so one lane's pinned deps can't disturb the other's. |
| `cudaCapability.js` | NVIDIA CUDA host probe — the one place that shells to `nvidia-smi`. `detectCudaGpus()` / cached `getCudaCapability()` return `{ available, status, gpus, maxVramGb }` where `status` is three-way: `'available'`, `'absent'` (no driver, or driver present with zero GPUs), or `'unknown'` (nvidia-smi exists but wouldn't answer — `available` is `null`, never `false`, so callers can say "couldn't detect" instead of lying about the hardware). `unknown` is not memoized so a transient driver hiccup retries. `parseNvidiaSmiGpus(stdout)` is the pure CSV parser (a `[N/A]` VRAM column yields `vramGb: null`, not a dropped GPU). Gates the image-to-3D `local-cuda` lane and the Windows FLUX.2 CUDA-torch wheel choice (`pythonSetup.js#hasNvidiaGpu`). `detectCudaComputeCapability()` / cached `getCudaComputeCapability()` are a SEPARATE `nvidia-smi` query (`--query-gpu=name,compute_cap,memory.total`, parsed by `parseNvidiaSmiComputeCaps`) returning `primaryComputeCap` — the arch of the LARGEST card, since a render uses one GPU — for build flags like NATTEN's `NATTEN_CUDA_ARCH` and SGLang provider filtering; kept separate because an older driver rejects `compute_cap` and would fail the whole VRAM query with it. `detectCudaUtilization()` / `getCudaUtilization()` add live per-GPU utilization on a short TTL. |
| `systemCapabilities.js` | Machine-local capability snapshot plus the shared three-state hardware requirement evaluator. Captures coarse platform, architecture, Apple Silicon, memory, CPU, and cached CUDA facts; derives requirements for media models, local-LLM catalog entries, and provider runtimes; hides only known-incompatible choices while preserving `unknown` probe results. |
diff --git a/server/lib/browserUnsafePorts.js b/server/lib/browserUnsafePorts.js
new file mode 100644
index 0000000000..abd73e026d
--- /dev/null
+++ b/server/lib/browserUnsafePorts.js
@@ -0,0 +1,14 @@
+// WHATWG Fetch "bad ports": browsers refuse to connect to these (ERR_UNSAFE_PORT),
+// so a managed app bound to one has a UI nobody can open. Mirrors
+// https://fetch.spec.whatwg.org/#port-blocking (Chrome and Firefox add X11's 6000
+// to the list). Allocators must never hand one out.
+export const BROWSER_UNSAFE_PORTS = Object.freeze(new Set([
+ 1, 7, 9, 11, 13, 15, 17, 19, 20, 21, 22, 23, 25, 37, 42, 43, 53, 69, 77, 79,
+ 87, 95, 101, 102, 103, 104, 109, 110, 111, 113, 115, 117, 119, 123, 135, 137,
+ 139, 143, 161, 179, 389, 427, 465, 512, 513, 514, 515, 526, 530, 531, 532,
+ 540, 548, 554, 556, 563, 587, 601, 636, 989, 990, 993, 995, 1719, 1720, 1723,
+ 2049, 3659, 4045, 4190, 5060, 5061, 6000, 6566, 6665, 6666, 6667, 6668, 6669,
+ 6679, 6697, 10080,
+]));
+
+export const isBrowserUnsafePort = (port) => BROWSER_UNSAFE_PORTS.has(port);
diff --git a/server/lib/index.js b/server/lib/index.js
index 5776f2aa1b..440c7d725b 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -632,6 +632,7 @@ export * from './backupConfig.js';
export * from './backupSnapshotBoundary.js';
export * from './systemIdle.js';
export * from './browserConfig.js';
+export * from './browserUnsafePorts.js';
export * from './buildId.js';
export * from './buildIdentity.js';
export * from './condaEnv.js';
diff --git a/server/lib/platform.js b/server/lib/platform.js
index 793be285d5..7964c054e3 100644
--- a/server/lib/platform.js
+++ b/server/lib/platform.js
@@ -1,5 +1,6 @@
import { exec, execSync } from './childProcess.js';
import { promisify } from 'util';
+import { isBrowserUnsafePort } from './browserUnsafePorts.js';
// Keep promisification lazy so pure platform consumers can be imported from
// tests that intentionally mock only the child-process methods they exercise.
@@ -117,19 +118,22 @@ export async function isPortInUse(port, probeOptions) {
}
/**
- * Find available ports in a range
+ * Find available ports in a range. Never returns a browser-blocked port
+ * (`isBrowserUnsafePort`), since an app on one cannot be opened from the UI.
* @param {number} start Start of range
* @param {number} end End of range
* @param {number} count Number of ports to find
+ * @param {object} [probeOptions] Listener-discovery overrides
+ * @param {number[]} [reservedPorts] Ports held by registered apps that are not listening right now
* @returns {Promise<number[]>} Available ports
*/
-export async function findAvailablePorts(start, end, count = 1, probeOptions) {
+export async function findAvailablePorts(start, end, count = 1, probeOptions, reservedPorts = []) {
if (start > end || count <= 0) return [];
- const usedPorts = new Set(await getListeningPorts(probeOptions));
+ const usedPorts = new Set([...await getListeningPorts(probeOptions), ...reservedPorts]);
const available = [];
for (let port = start; port <= end && available.length < count; port++) {
- if (!usedPorts.has(port)) {
+ if (!usedPorts.has(port) && !isBrowserUnsafePort(port)) {
available.push(port);
}
}
diff --git a/server/lib/platform.test.js b/server/lib/platform.test.js
index 09ee008aed..cc4b1cc923 100644
--- a/server/lib/platform.test.js
+++ b/server/lib/platform.test.js
@@ -74,6 +74,22 @@ describe('platform module', () => {
await expect(findAvailablePorts(6000, 6003, 2, options)).resolves.toEqual([6001, 6003])
})
+ it('never returns a browser-blocked port even when it is free', async () => {
+ const options = {
+ platform: 'linux',
+ exec: vi.fn().mockResolvedValue({ stdout: 'State Header' }),
+ }
+ await expect(findAvailablePorts(5998, 6002, 4, options)).resolves.toEqual([5998, 5999, 6001, 6002])
+ })
+
+ it('skips ports reserved by registered apps', async () => {
+ const options = {
+ platform: 'linux',
+ exec: vi.fn().mockResolvedValue({ stdout: 'State Header' }),
+ }
+ await expect(findAvailablePorts(5570, 5573, 2, options, [5570, 5572])).resolves.toEqual([5571, 5573])
+ })
+
it('should return empty array when range is exhausted', async () => {
// Range of 0 ports
const ports = await findAvailablePorts(49400, 49399, 1, {
diff --git a/server/routes/apps/lifecycle.js b/server/routes/apps/lifecycle.js
index 6907f41498..aa904d143f 100644
--- a/server/routes/apps/lifecycle.js
+++ b/server/routes/apps/lifecycle.js
@@ -338,17 +338,15 @@ router.post('/:id/refresh-config', loadApp, asyncHandler(async (req, res) => {
updates.processes = processes;
updates.pm2ProcessNames = processes.map(p => p.name);
- // Derive ports from parsed process labels (same logic as streamDetection)
- const apiProc = processes.find(p => p.ports?.api);
- if (apiProc) updates.apiPort = apiProc.ports.api;
-
- const uiProc = processes.find(p => p.ports?.ui);
- if (uiProc) updates.uiPort = uiProc.ports.ui;
-
- const devUiProc = processes.find(p => p.ports?.devUi);
- if (devUiProc) updates.devUiPort = devUiProc.ports.devUi;
-
- updates.uiPort = deriveUiPort(updates.uiPort, updates.apiPort, updates.devUiPort || app.devUiPort);
+ // The config is the source of truth: a port it no longer declares is
+ // cleared (null) rather than left behind on the record.
+ const apiPort = processes.find(p => p.ports?.api)?.ports.api ?? null;
+ const devUiPort = processes.find(p => p.ports?.devUi)?.ports.devUi ?? null;
+ const uiPort = processes.find(p => p.ports?.ui)?.ports.ui ?? null;
+
+ updates.apiPort = apiPort;
+ updates.devUiPort = devUiPort;
+ updates.uiPort = deriveUiPort(uiPort, apiPort, devUiPort) ?? null;
}
// Same containment rule as the icon route: a stored path outside the repo
diff --git a/server/routes/apps/lifecycle.test.js b/server/routes/apps/lifecycle.test.js
index 94d570c557..a06c537432 100644
--- a/server/routes/apps/lifecycle.test.js
+++ b/server/routes/apps/lifecycle.test.js
@@ -67,6 +67,7 @@ import * as appsService from '../../services/apps.js';
import * as pm2Service from '../../services/pm2.js';
import * as history from '../../services/history.js';
import * as appUpdater from '../../services/appUpdater.js';
+import { parseEcosystemFromPath } from '../../services/streamingDetect.js';
describe('Apps Lifecycle Routes', () => {
let app;
@@ -578,6 +579,61 @@ describe('Apps Lifecycle Routes', () => {
expect(response.status).toBe(400);
});
});
+
+ describe('POST /api/apps/:id/refresh-config', () => {
+ const staleApp = {
+ id: 'app-001',
+ name: 'Static Site',
+ type: 'express',
+ repoPath: REAL_DIR,
+ buildCommand: 'npm run build',
+ appIconPath: 'icon.svg',
+ apiPort: 6000,
+ uiPort: null,
+ devUiPort: 6001
+ };
+
+ beforeEach(() => {
+ appsService.getAppById.mockResolvedValue(staleApp);
+ appsService.updateApp.mockImplementation(async (id, updates) => ({ ...staleApp, ...updates }));
+ });
+
+ it('clears record ports the config no longer declares', async () => {
+ // The config moved from env PORT (api 6000) to a ui-labeled port.
+ parseEcosystemFromPath.mockResolvedValue({
+ processes: [{ name: 'site', ports: { ui: 5570 } }],
+ pm2Home: null
+ });
+
+ const response = await request(app).post('/api/apps/app-001/refresh-config');
+
+ expect(response.status).toBe(200);
+ expect(appsService.updateApp).toHaveBeenCalledWith('app-001', expect.objectContaining({
+ apiPort: null,
+ uiPort: 5570,
+ devUiPort: null
+ }));
+ expect(response.body.app).toMatchObject({ apiPort: null, uiPort: 5570, devUiPort: null });
+ });
+
+ it('still serves the production UI from the API port when only a dev UI is declared', async () => {
+ parseEcosystemFromPath.mockResolvedValue({
+ processes: [
+ { name: 'site-server', ports: { api: 5570 } },
+ { name: 'site-client', ports: { devUi: 5571 } }
+ ],
+ pm2Home: null
+ });
+
+ await request(app).post('/api/apps/app-001/refresh-config');
+
+ expect(appsService.updateApp).toHaveBeenCalledWith('app-001', expect.objectContaining({
+ apiPort: 5570,
+ uiPort: 5570,
+ devUiPort: 5571
+ }));
+ });
+ });
});
describe('host-control gate on app lifecycle (#8716)', () => {
diff --git a/server/routes/ports.test.js b/server/routes/ports.test.js
new file mode 100644
index 0000000000..bb6b0a1c4f
--- /dev/null
+++ b/server/routes/ports.test.js
@@ -0,0 +1,59 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import express from 'express';
+import { request } from '../lib/testHelper.js';
+import { errorMiddleware } from '../lib/errorHandler.js';
+
+const state = vi.hoisted(() => ({ listening: [], reserved: [] }));
+
+// Feed the real port-discovery parsers: one line per supported platform format,
+// so the assertion holds on darwin (lsof), linux (ss) and win32 (netstat) runners.
+vi.mock('../lib/childProcess.js', async (importOriginal) => ({
+ ...await importOriginal(),
+ exec: vi.fn((_command, ...rest) => {
+ const callback = rest.at(-1);
+ const stdout = state.listening
+ .map((p) => `LISTEN 0 511 0.0.0.0:${p} 0.0.0.0:*\nnode 1 u IPv4 TCP *:${p} (LISTEN)\n TCP 0.0.0.0:${p} 0.0.0.0:0 LISTENING`)
+ .join('\n');
+ callback(null, { stdout });
+ }),
+}));
+vi.mock('../services/apps.js', () => ({
+ getReservedPorts: vi.fn(async () => state.reserved),
+}));
+
+import portsRoutes from './ports.js';
+import { isBrowserUnsafePort } from '../lib/browserUnsafePorts.js';
+
+const range = (from, to) => Array.from({ length: to - from + 1 }, (_, i) => from + i);
+
+describe('POST /api/ports/allocate', () => {
+ let app;
+ beforeEach(() => {
+ state.listening = [];
+ state.reserved = [];
+ app = express();
+ app.use(express.json());
+ app.use('/api/ports', portsRoutes);
+ app.use(errorMiddleware);
+ });
+
+ it('hands out the first free ports of the documented managed band, skipping listeners and reserved ports', async () => {
+ state.listening = [5570, 5571];
+ state.reserved = [5572];
+
+ const res = await request(app).post('/api/ports/allocate').send({ count: 2 });
+
+ expect(res.status).toBe(200);
+ expect(res.body.allocated).toEqual([5573, 5574]);
+ });
+
+ it('overflows past the band without ever returning a browser-blocked port', async () => {
+ state.listening = range(5570, 5599);
+
+ const res = await request(app).post('/api/ports/allocate').send({ count: 3 });
+
+ expect(res.status).toBe(200);
+ expect(res.body.allocated).toEqual([5600, 5601, 5602]);
+ expect(res.body.allocated.some(isBrowserUnsafePort)).toBe(false);
+ });
+});
diff --git a/server/services/pm2Standardizer.analyze.test.js b/server/services/pm2Standardizer.analyze.test.js
new file mode 100644
index 0000000000..cc82437dc0
--- /dev/null
+++ b/server/services/pm2Standardizer.analyze.test.js
@@ -0,0 +1,70 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { mkdtempSync, writeFileSync, rmSync } from 'fs';
+import { tmpdir } from 'os';
+import { join } from 'path';
+
+vi.mock('./providers.js', () => ({
+ getActiveProvider: vi.fn().mockResolvedValue({ id: 'p1', name: 'Test Provider', type: 'cli', enabled: true }),
+ getProviderById: vi.fn(),
+}));
+vi.mock('./promptRunner.js', () => ({ runPromptThroughProvider: vi.fn() }));
+vi.mock('./apps.js', () => ({
+ getReservedPorts: vi.fn().mockResolvedValue([]),
+ getAllApps: vi.fn().mockResolvedValue([]),
+}));
+vi.mock('../lib/platform.js', async (importOriginal) => ({
+ ...await importOriginal(),
+ getListeningPorts: vi.fn().mockResolvedValue([]),
+}));
+
+import { analyzeApp } from './pm2Standardizer.js';
+import { runPromptThroughProvider } from './promptRunner.js';
+import { parseEcosystemConfig } from './streamingDetect.js';
+
+describe('analyzeApp port handling', () => {
+ let repo;
+ beforeEach(() => {
+ repo = mkdtempSync(join(tmpdir(), 'portos-std-'));
+ writeFileSync(join(repo, 'package.json'), JSON.stringify({ name: 'site', scripts: { start: 'node serve.js' } }));
+ return () => rmSync(repo, { recursive: true, force: true });
+ });
+
+ it('moves a browser-blocked port and writes a ui label so a static server gets an Open link', async () => {
+ runPromptThroughProvider.mockResolvedValue({
+ text: JSON.stringify({
+ processes: [{
+ name: 'site', cwd: '.', script: 'serve.js', watch: false,
+ ports: { ui: 6000 },
+ env: { NODE_ENV: 'development', PORT: 6000 },
+ }],
+ strayPorts: [],
+ reasoning: 'static server',
+ }),
+ });
+
+ const result = await analyzeApp(repo);
+
+ expect(result.success).toBe(true);
+ expect(result.proposedChanges.portReassignments).toEqual([{ from: 6000, to: 5570 }]);
+ const [proc] = parseEcosystemConfig(result.proposedChanges.ecosystemContent).processes;
+ expect(proc.ports).toEqual({ ui: 5570 });
+ });
+
+ it('drops a malformed ports map instead of writing it into the ecosystem file', async () => {
+ runPromptThroughProvider.mockResolvedValue({
+ text: JSON.stringify({
+ processes: [{
+ name: 'site', cwd: '.', script: 'serve.js', watch: false,
+ ports: { ui: 'sixty' },
+ env: { NODE_ENV: 'development', PORT: 5580 },
+ }],
+ strayPorts: [],
+ }),
+ });
+
+ const result = await analyzeApp(repo);
+
+ const [proc] = parseEcosystemConfig(result.proposedChanges.ecosystemContent).processes;
+ expect(proc.ports).toEqual({ api: 5580 });
+ });
+});
diff --git a/server/services/pm2Standardizer.js b/server/services/pm2Standardizer.js
index 0e79697449..ebcd48d5d6 100644
--- a/server/services/pm2Standardizer.js
+++ b/server/services/pm2Standardizer.js
@@ -12,6 +12,8 @@ import { PORTOS_APP_ID } from '../lib/appIdentity.js';
import { usesPm2 } from './appProcessTypes.js';
import { isStandardizable } from './streamingDetect.js';
import { getListeningPorts } from '../lib/platform.js';
+import { isBrowserUnsafePort } from '../lib/browserUnsafePorts.js';
+import { DEFAULT_PORT_RANGE_START } from './ports.js';
const execAsync = promisify(exec);
const DEFAULT_PM2_AI_TIMEOUT_MS = 180000;
@@ -27,9 +29,13 @@ export const PORTOS_ECOSYSTEM_MARKER = 'Generated by PortOS PM2 Standardizer';
// 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];
-// Collision reassignments start here, the same 6000–6099 range services/ports.js
-// allocates from. Both sit outside the PortOS 5553–5569 band and the Vite defaults.
-const REASSIGN_FROM = 6000;
+// Collision reassignments start at the managed-app band services/ports.js
+// allocates from (above the PortOS 5553–5569 band, clear of the Vite defaults).
+const REASSIGN_FROM = DEFAULT_PORT_RANGE_START;
+
+// A port the standardizer must never leave an app on, whoever proposed it:
+// already taken on the host, or one browsers refuse to connect to.
+const isOffLimitsPort = (port, taken) => taken.has(port) || isBrowserUnsafePort(port);
/**
* Why an app must not be standardized, or `null` when it may be.
@@ -64,11 +70,21 @@ export function standardizeRefusalFor(app) {
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.
+ * A process's `ports` label map ({ ui: 5570 }) reduced to its positive-integer
+ * entries — the LLM output is untrusted, and `parseEcosystemConfig` only reads
+ * `\w+: digits` pairs back out of the generated file.
+ */
+function declaredPortEntries(proc) {
+ if (!proc.ports || typeof proc.ports !== 'object' || Array.isArray(proc.ports)) return [];
+ return Object.entries(proc.ports).filter(([label, value]) => /^\w+$/.test(label) && Number.isInteger(value) && value > 0);
+}
+
+/**
+ * Collect every numeric port a process references — port-ish env keys, its
+ * declared `ports` labels, plus a `--port N` token in its args string.
*/
function collectPortRefs(proc) {
- const refs = [];
+ const refs = declaredPortEntries(proc).map(([, value]) => value);
if (proc.env && typeof proc.env === 'object') {
for (const [key, value] of Object.entries(proc.env)) {
if (!isPortKey(key)) continue;
@@ -99,6 +115,9 @@ function applyProcPortRemap(proc, procRemap) {
if (procRemap.has(n)) proc.env[key] = procRemap.get(n);
}
}
+ for (const [label, value] of declaredPortEntries(proc)) {
+ if (procRemap.has(value)) proc.ports[label] = procRemap.get(value);
+ }
if (typeof proc.args === 'string') {
proc.args = proc.args.replace(/(--port\s+)(\d+)/g, (full, pre, num) => {
const n = Number(num);
@@ -112,12 +131,12 @@ export function reassignCollidingPorts(processes, takenPorts) {
// Every non-taken port referenced anywhere will be KEPT by some process, so a
// replacement must avoid all of them up front — otherwise a colliding process
- // listed BEFORE the process that owns a valid 6000-range port could be handed
+ // listed BEFORE the process that owns a valid managed-band port could be handed
// that port (LLM output order isn't guaranteed), needlessly moving the owner.
const keptValues = new Set();
for (const proc of processes || []) {
for (const value of collectPortRefs(proc)) {
- if (!taken.has(value)) keptValues.add(value);
+ if (!isOffLimitsPort(value, taken)) keptValues.add(value);
}
}
@@ -127,7 +146,7 @@ export function reassignCollidingPorts(processes, takenPorts) {
const assigned = new Set();
const pickFree = () => {
let p = REASSIGN_FROM;
- while (used.has(p) || assigned.has(p)) p++;
+ while (used.has(p) || assigned.has(p) || isBrowserUnsafePort(p)) p++;
assigned.add(p);
used.add(p);
return p;
@@ -144,7 +163,7 @@ export function reassignCollidingPorts(processes, takenPorts) {
for (const proc of processes || []) {
const procRemap = new Map(); // old -> new, scoped to this process
for (const value of new Set(collectPortRefs(proc))) {
- if (taken.has(value) || claimed.has(value)) {
+ if (isOffLimitsPort(value, taken) || claimed.has(value)) {
const np = pickFree();
procRemap.set(value, np);
reassignments.push([value, np]);
@@ -312,7 +331,7 @@ ${context.viteConfigs.map(f => `#### ${f.name}\n\`\`\`javascript\n${f.content}\n
${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.
+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 5570–5599 range** (never 6000 or any other port browsers refuse to connect to) instead of the framework defaults found in vite.config/.env, even when a config file suggests otherwise.
## PM2 Standard Requirements
@@ -324,6 +343,7 @@ These ports are already listening on this host, reserved by another managed app,
6. **Set cwd** for each process pointing to its directory
7. **Include NODE_ENV** in all env blocks
8. **UI vs Dev UI ports**: When the API server serves the production build of the frontend (Express static files), the production UI port equals the API port. The Vite dev server port is a separate "dev UI" port only used during development. Label Vite dev ports as UI or DEV_UI in the PORTS object (both conventions are acceptable).
+9. **Port labels**: Give every process that listens on a port a \`ports\` object naming what it serves — \`{ "ui": N }\` for a process that serves HTML to a browser (a static file server, Vite, Next, an Express app serving a built frontend), \`{ "api": N }\` for a JSON/API-only server, \`{ "devUi": N }\` for a Vite dev server that sits beside an API process. The same number stays in env \`PORT\`. Without the label PortOS assumes a bare \`PORT\` is an API and the app gets no Open button.
## Output Format
@@ -338,6 +358,7 @@ Return ONLY valid JSON (no markdown wrapper, no explanation) with this structure
"watch": "array of paths to watch or false",
"watchDelay": 1000,
"ignoreWatch": ["node_modules", "data", "*.log"],
+ "ports": { "ui|api|devUi": "number - the same port as env.PORT, labeled by what the process serves" },
"env": {
"NODE_ENV": "development",
"PORT": "number - the port this process uses"
@@ -427,6 +448,11 @@ function generateEcosystemContent(processes, appName) {
config.watch = false;
}
+ const labeledPorts = declaredPortEntries(proc);
+ if (labeledPorts.length > 0) {
+ config.ports = Object.fromEntries(labeledPorts);
+ }
+
config.env = proc.env || { NODE_ENV: 'development' };
return config;
diff --git a/server/services/pm2Standardizer.test.js b/server/services/pm2Standardizer.test.js
index 30269efa52..6c27bcfb9a 100644
--- a/server/services/pm2Standardizer.test.js
+++ b/server/services/pm2Standardizer.test.js
@@ -56,10 +56,10 @@ describe('reassignCollidingPorts', () => {
];
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]]);
+ expect(processes[0].env.PORT).toBe(5570);
+ expect(processes[1].env.VITE_PORT).toBe(5571);
+ expect(processes[1].args).toBe('vite --host --port 5571');
+ expect(reassigned).toEqual([[5173, 5570], [5174, 5571]]);
});
it('keeps the same new value when an old port appears in multiple places of one process', () => {
@@ -67,9 +67,9 @@ describe('reassignCollidingPorts', () => {
{ 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');
+ expect(processes[0].env.PORT).toBe(5570);
+ expect(processes[0].env.VITE_PORT).toBe(5570);
+ expect(processes[0].args).toBe('vite --host --port 5570');
});
it('leaves non-colliding ports untouched', () => {
@@ -86,20 +86,20 @@ describe('reassignCollidingPorts', () => {
];
const reassigned = reassignCollidingPorts(processes, []);
expect(processes[0].env.PORT).toBe(3000); // first keeps the free port
- expect(processes[1].env.PORT).toBe(6000); // duplicate bumped to a distinct one
- expect(reassigned).toEqual([[3000, 6000]]);
+ expect(processes[1].env.PORT).toBe(5570); // duplicate bumped to a distinct one
+ expect(reassigned).toEqual([[3000, 5570]]);
});
it('does not bump a later process off its valid port to satisfy an earlier collision', () => {
// server (listed first) is on a taken port; client already holds a valid
- // 6000. The replacement for server must skip 6000 rather than steal it.
+ // 5570. The replacement for server must skip 5570 rather than steal it.
const processes = [
{ name: 'server', env: { PORT: 5173 } },
- { name: 'client', env: { VITE_PORT: 6000 } }
+ { name: 'client', env: { VITE_PORT: 5570 } }
];
reassignCollidingPorts(processes, [5173]);
- expect(processes[1].env.VITE_PORT).toBe(6000); // untouched
- expect(processes[0].env.PORT).toBe(6001); // skipped 6000
+ expect(processes[1].env.VITE_PORT).toBe(5570); // untouched
+ expect(processes[0].env.PORT).toBe(5571); // skipped 5570
});
it('gives distinct ports to two processes that both reference the same taken port', () => {
@@ -110,38 +110,61 @@ describe('reassignCollidingPorts', () => {
{ name: 'cli', args: 'vite --host --port 5173', env: { VITE_PORT: 5173 } }
];
reassignCollidingPorts(processes, [5173]);
- 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(processes[0].env.PORT).toBe(5570);
+ expect(processes[1].env.VITE_PORT).toBe(5571);
+ expect(processes[1].args).toBe('vite --host --port 5571');
expect(processes[0].env.PORT).not.toBe(processes[1].env.VITE_PORT);
});
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.
+ // server keeps 5570 (free); client's 5173 is taken and must NOT be bumped to 5570.
const processes = [
- { name: 'server', env: { PORT: 6000 } },
+ { name: 'server', env: { PORT: 5570 } },
{ name: 'client', env: { VITE_PORT: 5173 } }
];
reassignCollidingPorts(processes, [5173]);
- expect(processes[0].env.PORT).toBe(6000);
- expect(processes[1].env.VITE_PORT).toBe(6001);
+ expect(processes[0].env.PORT).toBe(5570);
+ expect(processes[1].env.VITE_PORT).toBe(5571);
});
it('skips already-assigned ports when picking a free replacement', () => {
- // 6000 is taken, so the first reassignment lands on 6001, the next on 6002.
+ // 5570 is taken, so the first reassignment lands on 5571, the next on 5572.
const processes = [
{ name: 'a', env: { PORT: 5173 } },
{ name: 'b', env: { PORT: 5174 } }
];
- reassignCollidingPorts(processes, [5173, 5174, 6000]);
+ reassignCollidingPorts(processes, [5173, 5174, 5570]);
+ expect(processes[0].env.PORT).toBe(5571);
+ expect(processes[1].env.PORT).toBe(5572);
+ });
+
+ it('moves a process off a browser-blocked port even when nothing else holds it', () => {
+ const processes = [{ name: 'site', env: { PORT: 6000 } }];
+ const reassigned = reassignCollidingPorts(processes, []);
+ expect(processes[0].env.PORT).toBe(5570);
+ expect(reassigned).toEqual([[6000, 5570]]);
+ });
+
+ it('never picks a browser-blocked replacement when the managed band is exhausted', () => {
+ // 5570–5999 all taken, so the next free candidate is 6000 — which browsers refuse.
+ const taken = [5173];
+ for (let p = 5570; p < 6000; p++) taken.push(p);
+ const processes = [{ name: 'srv', env: { PORT: 5173 } }];
+ reassignCollidingPorts(processes, taken);
expect(processes[0].env.PORT).toBe(6001);
- expect(processes[1].env.PORT).toBe(6002);
+ });
+
+ it('remaps the ports label map together with env.PORT', () => {
+ const processes = [{ name: 'site', ports: { ui: 5173 }, env: { PORT: 5173 } }];
+ reassignCollidingPorts(processes, [5173]);
+ expect(processes[0].ports).toEqual({ ui: 5570 });
+ expect(processes[0].env.PORT).toBe(5570);
});
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.PORT).toBe(5570);
expect(processes[0].env.RETRIES).toBe(5173); // not a port key
});
});
diff --git a/server/services/ports.js b/server/services/ports.js
index 8f3dd1ab2d..b33f8bb506 100644
--- a/server/services/ports.js
+++ b/server/services/ports.js
@@ -1,9 +1,11 @@
import { getListeningPorts, findAvailablePorts } from '../lib/platform.js';
import { getReservedPorts } from './apps.js';
-// Default port range for new apps
-const DEFAULT_PORT_RANGE_START = 6000;
-const DEFAULT_PORT_RANGE_END = 6099;
+// Managed-app band from docs/PORTS.md; 5553-5569 belongs to PortOS itself.
+// Allocation overflows past the end (see allocatePorts) but never below the start.
+export const DEFAULT_PORT_RANGE_START = 5570;
+export const DEFAULT_PORT_RANGE_END = 5599;
+const PORT_OVERFLOW = 100;
/**
* Scan system for used ports and compute available ranges
@@ -22,7 +24,7 @@ export async function scanPorts() {
const freeRanges = computeFreeRanges(allOccupied, DEFAULT_PORT_RANGE_START, DEFAULT_PORT_RANGE_END);
// Find suggested next available ports
- const suggestedPorts = await findAvailablePorts(DEFAULT_PORT_RANGE_START, DEFAULT_PORT_RANGE_END, 2);
+ const suggestedPorts = await findAvailablePorts(DEFAULT_PORT_RANGE_START, DEFAULT_PORT_RANGE_END, 2, undefined, reservedPorts);
return {
usedPorts,
@@ -76,20 +78,16 @@ export async function checkPortsAvailable(ports) {
}
/**
- * Allocate N ports from the available range
+ * Allocate N ports, preferring the managed band and overflowing just past it.
+ * Skips listeners, ports reserved by registered apps, and browser-blocked ports.
*/
export async function allocatePorts(count = 1) {
- const scan = await scanPorts();
-
- if (scan.suggestedPorts.length < count) {
- const needed = count - scan.suggestedPorts.length;
- const additional = await findAvailablePorts(
- DEFAULT_PORT_RANGE_START,
- DEFAULT_PORT_RANGE_END + 100,
- needed
- );
- return [...scan.suggestedPorts, ...additional].slice(0, count);
- }
-
- return scan.suggestedPorts.slice(0, count);
+ const reservedPorts = await getReservedPorts();
+ return findAvailablePorts(
+ DEFAULT_PORT_RANGE_START,
+ DEFAULT_PORT_RANGE_END + PORT_OVERFLOW,
+ count,
+ undefined,
+ reservedPorts
+ );
}