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
feat: capture every *_PORT in ecosystem configs and reserve them
[._.]/ Adam Eivy36f330006894
diff --git a/server/lib/validation.js b/server/lib/validation.jsindex 1ca8c182c1..95d4a37ab0 100644--- a/server/lib/validation.js+++ b/server/lib/validation.js@@ -144,10 +144,13 @@ export const automationScheduleUpdateSchema = automationScheduleSchema.partial()// EXISTING SCHEMAS// =============================================================================-// Process definition schema (for PM2 processes with ports)+// `ports` is an open-ended label→port map so app-specific keys derived from+// *_PORT env vars (coinbaseIpc, geminiIpc, etc.) survive validation alongside+// the well-known labels (api, ui, devUi, cdp, health).export const processSchema = z.object({name: z.string().min(1),port: z.number().int().min(1).max(65535).nullable().optional(),+ ports: z.record(z.number().int().min(1).max(65535)).optional(),description: z.string().optional()});diff --git a/server/services/apps.js b/server/services/apps.jsindex 9b171e3762..69f76d9047 100644--- a/server/services/apps.js+++ b/server/services/apps.js@@ -427,20 +427,38 @@ export async function toggleAllAppTaskTypes(id, enabled) {}/**- * Get reserved ports from all registered apps+ * Reserved ports across every app — top-level uiPort/devUiPort/apiPort/tlsPort+ * plus every value in each process's `ports` map. Walking processes[] is what+ * lets the scaffolder avoid colliding with non-public ports (engine IPC, CDP)+ * that have no top-level field of their own.*/export async function getReservedPorts() {const apps = await getAllApps();const ports = new Set();+ const addPort = (p) => {+ const n = typeof p === 'number' ? p : parseInt(p, 10);+ if (Number.isInteger(n) && n > 0) ports.add(n);+ };+for (const app of apps) {- if (app.uiPort) ports.add(app.uiPort);- if (app.apiPort) ports.add(app.apiPort);+ addPort(app.uiPort);+ addPort(app.devUiPort);+ addPort(app.apiPort);+ addPort(app.tlsPort);+ if (Array.isArray(app.processes)) {+ for (const proc of app.processes) {+ if (proc?.port) addPort(proc.port);+ if (proc?.ports && typeof proc.ports === 'object') {+ for (const value of Object.values(proc.ports)) addPort(value);+ }+ }+ }}// Also reserve PortOS ports- ports.add(PORTS.API);- ports.add(PORTS.UI);+ addPort(PORTS.API);+ addPort(PORTS.UI);return Array.from(ports).sort((a, b) => a - b);}diff --git a/server/services/apps.test.js b/server/services/apps.test.jsnew file mode 100644index 0000000000..a426966253--- /dev/null+++ b/server/services/apps.test.js@@ -0,0 +1,90 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';++vi.mock('fs/promises', () => ({+ writeFile: vi.fn().mockResolvedValue(undefined),+}));++vi.mock('../lib/fileUtils.js', () => ({+ ensureDir: vi.fn().mockResolvedValue(undefined),+ readJSONFile: vi.fn(),+ PATHS: { data: '/mock/data', root: '/mock/root' },+}));++vi.mock('../../lib/tailscale-https.js', () => ({+ hasTailscaleCert: () => false,+}));++vi.mock('../lib/ports.js', () => ({+ PORTS: { API: 5555, API_LOCAL: 5553, UI: 5554 },+}));++vi.mock('./taskSchedule.js', () => ({+ SELF_IMPROVEMENT_TASK_TYPES: [],+}));++import { readJSONFile } from '../lib/fileUtils.js';+import { getReservedPorts, invalidateCache, PORTOS_APP_ID } from './apps.js';++describe('getReservedPorts', () => {+ beforeEach(() => {+ invalidateCache();+ vi.clearAllMocks();+ });++ it('reserves every per-process port (ports map values), not just uiPort/apiPort', async () => {+ // Mirror critical-mass: top-level apiPort/uiPort + engine processes that+ // expose IPC ports via the per-process `ports` map.+ readJSONFile.mockResolvedValue({+ apps: {+ [PORTOS_APP_ID]: { name: 'PortOS', uiPort: 5555, apiPort: 5555, devUiPort: 5554 },+ 'critical-mass': {+ name: 'critical-mass',+ apiPort: 5563,+ uiPort: 5563,+ devUiPort: 5564,+ processes: [+ { name: 'critical-mass', ports: { api: 5563, coinbaseIpc: 5565, geminiIpc: 5566, cryptocomIpc: 5567 } },+ { name: 'critical-mass-coinbase', ports: { exchangeIpc: 5565 } },+ { name: 'critical-mass-gemini', ports: { geminiIpc: 5566 } },+ { name: 'critical-mass-cryptocom', ports: { cryptocomIpc: 5567 } },+ { name: 'critical-mass-ui', ports: { devUi: 5564 } },+ ],+ },+ },+ });++ const reserved = await getReservedPorts();++ // Includes engine IPC ports surfaced only through processes[].ports+ expect(reserved).toContain(5565);+ expect(reserved).toContain(5566);+ expect(reserved).toContain(5567);+ // Top-level port fields still reserved+ expect(reserved).toContain(5563);+ expect(reserved).toContain(5564);+ // PortOS baseline ports always reserved+ expect(reserved).toContain(5555);+ expect(reserved).toContain(5554);+ // De-duplicated and sorted ascending+ expect([...reserved]).toEqual([...new Set(reserved)].sort((a, b) => a - b));+ });++ it('ignores invalid port values in processes[].ports', async () => {+ readJSONFile.mockResolvedValue({+ apps: {+ [PORTOS_APP_ID]: { name: 'PortOS' },+ 'weird-app': {+ name: 'weird',+ processes: [+ { name: 'a', ports: { api: 5570, broken: null, alsoBroken: 'not-a-port', zero: 0 } },+ ],+ },+ },+ });++ const reserved = await getReservedPorts();+ expect(reserved).toContain(5570);+ expect(reserved).not.toContain(0);+ expect(reserved.every(p => Number.isInteger(p) && p > 0)).toBe(true);+ });+});diff --git a/server/services/streamingDetect.js b/server/services/streamingDetect.jsindex 1a1c2b3487..9453ed3c57 100644--- a/server/services/streamingDetect.js+++ b/server/services/streamingDetect.js@@ -214,41 +214,47 @@ export function parseEcosystemConfig(content) {return null;};- // Extract CDP_PORT first (Chrome DevTools Protocol port for browser processes)- // Word boundary ensures we don't match VITE_CDP_PORT- // Capture full expression (up to , or }) to handle process.env.X || fallback- const cdpPortMatch = appBlock.match(/(?:env|env_development|env_production)\s*:\s*\{[^}]*\bCDP_PORT\s*:\s*([^,}\n]+)/);- if (cdpPortMatch) {- const resolved = resolvePortValue(cdpPortMatch[1]);- if (resolved) ports.cdp = resolved;+ // Collect every `<NAME>_PORT` env-var first, label after — so CDP_PORT+ // can influence the smart label chosen for PORT regardless of source order.+ // The `_PORT` suffix requirement avoids matching identifiers like REPORT.+ const envPorts = {};+ const envBlockRegex = /(?:env|env_development|env_production)\s*:\s*\{([^}]*)\}/g;+ let envBlockMatch;+ while ((envBlockMatch = envBlockRegex.exec(appBlock)) !== null) {+ const envContent = envBlockMatch[1];+ const portKeyRegex = /\b(PORT|[A-Z][A-Z0-9_]*_PORT)\b\s*:\s*([^,}\n]+)/g;+ let m;+ while ((m = portKeyRegex.exec(envContent)) !== null) {+ const key = m[1];+ if (envPorts[key] !== undefined) continue;+ const resolved = resolvePortValue(m[2]);+ if (resolved) envPorts[key] = resolved;+ }}- // Extract PORT from env (handles literals, variables, and process.env.X || fallback)- const portMatch = appBlock.match(/(?:env|env_development|env_production)\s*:\s*\{[^}]*\bPORT\s*:\s*([^,}\n]+)/);- if (portMatch) {- const resolved = resolvePortValue(portMatch[1]);- if (resolved) {- // Smart labeling based on process name and context- const isUiProcess = /[-_](ui|client)$/i.test(processName);- const isBrowserProcess = /[-_]browser$/i.test(processName);- const hasCdpPort = ports.cdp !== undefined;-- if (isUiProcess) {- ports.ui = resolved;- } else if (isBrowserProcess && hasCdpPort) {- // Browser processes with CDP_PORT use PORT for health checks- ports.health = resolved;- } else {- ports.api = resolved;- }+ const isUiProcess = /[-_](ui|client)$/i.test(processName);+ const isBrowserProcess = /[-_]browser$/i.test(processName);++ if (envPorts.CDP_PORT !== undefined) ports.cdp = envPorts.CDP_PORT;+ if (envPorts.PORT !== undefined) {+ if (isUiProcess) {+ ports.ui = envPorts.PORT;+ } else if (isBrowserProcess && ports.cdp !== undefined) {+ // Browser processes pair CDP_PORT (DevTools) with PORT (health endpoint).+ ports.health = envPorts.PORT;+ } else {+ ports.api = envPorts.PORT;}}-- // Extract VITE_PORT for Vite processes- const vitePortMatch = appBlock.match(/(?:env|env_development|env_production)\s*:\s*\{[^}]*VITE_PORT\s*:\s*([^,}\n]+)/);- if (vitePortMatch) {- const resolved = resolvePortValue(vitePortMatch[1]);- if (resolved) ports.ui = resolved;+ if (envPorts.VITE_PORT !== undefined) ports.ui = envPorts.VITE_PORT;++ // FOO_BAR_PORT → fooBar, capturing app-specific labels (coinbaseIpc, etc.).+ for (const [key, value] of Object.entries(envPorts)) {+ if (key === 'PORT' || key === 'VITE_PORT' || key === 'CDP_PORT') continue;+ const stem = key.replace(/_?PORT$/, '');+ if (!stem) continue;+ const label = stem.toLowerCase().replace(/_(\w)/g, (_, c) => c.toUpperCase());+ if (ports[label] === undefined) ports[label] = value;}// Also check for --port in argsdiff --git a/server/services/streamingDetect.test.js b/server/services/streamingDetect.test.jsnew file mode 100644index 0000000000..8b43f65fed--- /dev/null+++ b/server/services/streamingDetect.test.js@@ -0,0 +1,152 @@+import { describe, it, expect } from 'vitest';+import { parseEcosystemConfig } from './streamingDetect.js';++describe('parseEcosystemConfig', () => {+ it('captures arbitrary *_PORT env vars and labels them by camelCased stem', () => {+ // Mirror the critical-mass shape: a server process that fans out IPC ports+ // to per-exchange engine processes.+ const content = `+ const PORTS = {+ API: 5563,+ UI: 5564,+ COINBASE_IPC: 5565,+ GEMINI_IPC: 5566,+ CRYPTOCOM_IPC: 5567,+ };++ module.exports = {+ apps: [+ {+ name: 'critical-mass',+ script: 'server.js',+ env: {+ PORT: PORTS.API,+ COINBASE_IPC_PORT: PORTS.COINBASE_IPC,+ GEMINI_IPC_PORT: PORTS.GEMINI_IPC,+ CRYPTOCOM_IPC_PORT: PORTS.CRYPTOCOM_IPC,+ },+ },+ {+ name: 'critical-mass-coinbase',+ script: 'engines/coinbase-engine.js',+ env: {+ EXCHANGE_IPC_PORT: PORTS.COINBASE_IPC,+ },+ },+ {+ name: 'critical-mass-gemini',+ script: 'engines/gemini-engine.js',+ env: {+ GEMINI_IPC_PORT: PORTS.GEMINI_IPC,+ },+ },+ ],+ };+ `;++ const { processes } = parseEcosystemConfig(content);++ const main = processes.find(p => p.name === 'critical-mass');+ expect(main.ports).toEqual({+ api: 5563,+ coinbaseIpc: 5565,+ geminiIpc: 5566,+ cryptocomIpc: 5567,+ });++ const coinbase = processes.find(p => p.name === 'critical-mass-coinbase');+ expect(coinbase.ports).toEqual({ exchangeIpc: 5565 });++ const gemini = processes.find(p => p.name === 'critical-mass-gemini');+ expect(gemini.ports).toEqual({ geminiIpc: 5566 });+ });++ it('preserves smart-labeling for PORT/VITE_PORT/CDP_PORT alongside generic *_PORT capture', () => {+ const content = `+ module.exports = {+ apps: [+ {+ name: 'my-app-server',+ env: {+ PORT: 5570,+ ADMIN_PORT: 5571,+ },+ },+ {+ name: 'my-app-ui',+ env: {+ VITE_PORT: 5572,+ },+ },+ {+ name: 'my-app-browser',+ env: {+ CDP_PORT: 5573,+ PORT: 5574,+ },+ },+ ],+ };+ `;++ const { processes } = parseEcosystemConfig(content);++ const server = processes.find(p => p.name === 'my-app-server');+ expect(server.ports.api).toBe(5570);+ expect(server.ports.admin).toBe(5571);++ const ui = processes.find(p => p.name === 'my-app-ui');+ // Post-processing relabels Vite ports from `ui` → `devUi` whenever a sibling+ // api process exists (the prod UI is served by the API server in that shape).+ expect(ui.ports.devUi).toBe(5572);+ expect(ui.ports.ui).toBeUndefined();++ const browser = processes.find(p => p.name === 'my-app-browser');+ expect(browser.ports.cdp).toBe(5573);+ // Browser process with CDP_PORT routes PORT → health (not api)+ expect(browser.ports.health).toBe(5574);+ expect(browser.ports.api).toBeUndefined();+ });++ it('does not treat identifiers ending in PORT (e.g., REPORT) as ports', () => {+ const content = `+ module.exports = {+ apps: [+ {+ name: 'reporter',+ env: {+ PORT: 5580,+ REPORT_LEVEL: 3,+ MY_REPORT: 'verbose',+ },+ },+ ],+ };+ `;++ const { processes } = parseEcosystemConfig(content);+ const proc = processes.find(p => p.name === 'reporter');+ expect(proc.ports).toEqual({ api: 5580 });+ });++ it('still honors explicit ports: { ... } literal map (does not double-extract from env)', () => {+ const content = `+ module.exports = {+ apps: [+ {+ name: 'explicit-app',+ ports: { api: 5590, ui: 5591 },+ env: {+ PORT: 9999, // should be ignored — explicit ports map wins+ IPC_PORT: 8888,+ },+ },+ ],+ };+ `;++ const { processes } = parseEcosystemConfig(content);+ const proc = processes.find(p => p.name === 'explicit-app');+ expect(proc.ports).toEqual({ api: 5590, ui: 5591 });+ });+});