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: add persistent browser service and port allocation standard
Adam Eivy2ddb89c7f56e
diff --git a/.browser.template/package.json b/.browser.template/package.jsonnew file mode 100644index 0000000000..277ddf687a--- /dev/null+++ b/.browser.template/package.json@@ -0,0 +1,13 @@+{+ "name": "portos-browser",+ "version": "1.0.0",+ "private": true,+ "description": "Persistent browser for PortOS CoS and sub-agents",+ "type": "module",+ "scripts": {+ "start": "node server.js"+ },+ "dependencies": {+ "playwright": "^1.49.0"+ }+}diff --git a/.browser.template/server.js b/.browser.template/server.jsnew file mode 100644index 0000000000..609da4a032--- /dev/null+++ b/.browser.template/server.js@@ -0,0 +1,84 @@+import { chromium } from 'playwright';+import { createServer } from 'http';++const CDP_PORT = parseInt(process.env.CDP_PORT || '5556', 10);+const HEALTH_PORT = parseInt(process.env.PORT || '5557', 10);++let browser = null;++async function launchBrowser() {+ console.log(`🌐 Launching persistent Chromium browser with CDP on port ${CDP_PORT}`);++ browser = await chromium.launch({+ headless: true,+ args: [+ `--remote-debugging-port=${CDP_PORT}`,+ '--remote-debugging-address=0.0.0.0',+ '--no-first-run',+ '--no-default-browser-check',+ '--disable-background-networking',+ '--disable-sync',+ '--disable-translate',+ '--disable-extensions',+ '--disable-infobars',+ '--disable-notifications'+ ]+ });++ browser.on('disconnected', () => {+ console.log('⚠️ Browser disconnected, restarting...');+ setTimeout(launchBrowser, 1000);+ });++ console.log(`✅ Browser launched, CDP available at ws://0.0.0.0:${CDP_PORT}`);+ return browser;+}++// Simple health check server+const healthServer = createServer((req, res) => {+ if (req.url === '/health') {+ const status = browser && browser.isConnected() ? 'healthy' : 'unhealthy';+ res.writeHead(browser && browser.isConnected() ? 200 : 503, { 'Content-Type': 'application/json' });+ res.end(JSON.stringify({+ status,+ cdpPort: CDP_PORT,+ cdpEndpoint: `ws://0.0.0.0:${CDP_PORT}`+ }));+ } else if (req.url === '/') {+ res.writeHead(200, { 'Content-Type': 'application/json' });+ res.end(JSON.stringify({+ service: 'portos-browser',+ cdpPort: CDP_PORT,+ healthPort: HEALTH_PORT,+ endpoints: {+ health: '/health',+ cdp: `ws://0.0.0.0:${CDP_PORT}`+ }+ }));+ } else {+ res.writeHead(404);+ res.end('Not Found');+ }+});++async function shutdown() {+ console.log('🛑 Shutting down browser...');+ if (browser) {+ await browser.close();+ }+ healthServer.close();+ process.exit(0);+}++process.on('SIGTERM', shutdown);+process.on('SIGINT', shutdown);++async function main() {+ await launchBrowser();++ healthServer.listen(HEALTH_PORT, '0.0.0.0', () => {+ console.log(`📡 Health check server listening on port ${HEALTH_PORT}`);+ });+}++main();diff --git a/.gitignore b/.gitignoreindex dab5dc55f8..19c1a23f56 100644--- a/.gitignore+++ b/.gitignore@@ -31,4 +31,8 @@ Thumbs.db# PM2.pm2/+# Playwright.playwright-mcp++# Persistent browser for CoS/agents+.browser/diff --git a/CLAUDE.md b/CLAUDE.mdindex daffe15b29..d7363f2967 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -24,6 +24,16 @@ pm2 logsPortOS is a monorepo with Express.js server (port 5554) and React/Vite client (port 5555). PM2 manages app lifecycles. Data persists to JSON files in `./data/`.+### Port Allocation++PortOS uses ports 5554-5560. Define all ports in `ecosystem.config.cjs` using the `ports` object:++```javascript+ports: { api: 5554, health: 5555 } // labeled ports for documentation+```++See `docs/PORTS.md` for the full port allocation guide.+### Server (`server/`)- **Routes**: HTTP handlers with Zod validation- **Services**: Business logic, PM2/file/Socket.IO operationsdiff --git a/README.md b/README.mdindex cf6b9aa693..5dd5d513b6 100644--- a/README.md+++ b/README.md@@ -40,12 +40,9 @@ Auto-detect project configuration from your codebase — ports, start commands,git clone https://github.com/atomantic/PortOS.gitcd PortOS-# Install dependencies+# Install dependencies (also sets up data/ and .browser/ directories)npm run install:all-# Copy sample data (first time only)-cp -r data.sample data-# Start with PM2 (recommended)pm2 start ecosystem.config.cjs@@ -127,6 +124,7 @@ Configure AI providers for the runner:## Documentation- [Contributing Guide](./docs/CONTRIBUTING.md) — Development setup and code guidelines+- [Port Allocation](./docs/PORTS.md) — Port conventions and allocation guide- [Versioning & Releases](./docs/VERSIONING.md) — Version format and release process- [Implementation Plan](./PLAN.md) — Detailed feature roadmap and API referencediff --git a/client/src/pages/Apps.jsx b/client/src/pages/Apps.jsxindex ae7f81b9af..ef139581c0 100644--- a/client/src/pages/Apps.jsx+++ b/client/src/pages/Apps.jsx@@ -171,10 +171,16 @@ export default function Apps() {{/* Show process names with ports - filter to only this app's processes */}{(app.pm2ProcessNames || []).map((procName, i) => {const procInfo = app.processes?.find(p => p.name === procName);- const port = procInfo?.port;+ const ports = procInfo?.ports || {};+ const portEntries = Object.entries(ports);+ const portDisplay = portEntries.length > 1+ ? portEntries.map(([label, port]) => `${label}:${port}`).join(',')+ : portEntries.length === 1+ ? `:${portEntries[0][1]}`+ : '';return (<span key={i}>- {procName}{port ? <span className="text-cyan-500">:{port}</span> : ''}+ {procName}<span className="text-cyan-500">{portDisplay}</span>{i < (app.pm2ProcessNames?.length || 0) - 1 ? ',' : ''}</span>);@@ -329,8 +335,12 @@ export default function Apps() {proc.status === 'stopped' ? 'bg-gray-500' : 'bg-port-error'}`} /><span className="text-sm text-white font-mono">{proc.name}</span>- {processConfig?.port && (- <span className="text-xs text-cyan-400 font-mono">:{processConfig.port}</span>+ {processConfig?.ports && Object.keys(processConfig.ports).length > 0 && (+ <span className="text-xs text-cyan-400 font-mono">+ {Object.entries(processConfig.ports).length > 1+ ? Object.entries(processConfig.ports).map(([label, port]) => `${label}:${port}`).join(',')+ : `:${Object.values(processConfig.ports)[0]}`}+ </span>)}<span className="text-xs text-gray-500">{proc.status}</span>{proc.cpu !== undefined && (diff --git a/docs/PORTS.md b/docs/PORTS.mdnew file mode 100644index 0000000000..a64483db99--- /dev/null+++ b/docs/PORTS.md@@ -0,0 +1,94 @@+# Port Allocation Guide++PortOS uses a contiguous port allocation scheme to make it easy to understand which ports are in use and which are available.++## Port Allocation Standard++### Convention++1. **Contiguous Ranges**: Each app should use a contiguous block of ports+2. **Labeled Ports**: Use the `ports` object in `ecosystem.config.cjs` to define all ports with descriptive labels+3. **No Gaps**: Avoid leaving gaps between port allocations within an app++### Port Labels++Common port labels:+- `api` - REST API server+- `ui` - Web UI / frontend+- `cdp` - Chrome DevTools Protocol+- `health` - Health check endpoint+- `ws` - WebSocket server++## PortOS Port Allocations++| Port | Process | Label | Description |+|------|---------|-------|-------------|+| 5554 | portos-server | api | Main API server |+| 5555 | portos-client | ui | Vite dev server (React UI) |+| 5556 | portos-browser | cdp | Chrome DevTools Protocol |+| 5557 | portos-browser | health | Browser health check API |+| 5558 | (reserved) | - | Reserved for future PortOS use |+| 5559 | portos-autofixer | api | Autofixer daemon API |+| 5560 | portos-autofixer-ui | ui | Autofixer web UI |++## Defining Ports in ecosystem.config.cjs++Use the `ports` object to define all ports used by a process:++```javascript+{+ name: 'my-app',+ script: 'server.js',+ // PortOS convention: define all ports used by this process+ ports: {+ api: 5570, // REST API+ health: 5571 // Health check endpoint+ },+ env: {+ PORT: 5570,+ HEALTH_PORT: 5571+ }+}+```++### Multiple Ports Example++For processes that expose multiple ports (like the browser with CDP and health):++```javascript+{+ name: 'portos-browser',+ script: '.browser/server.js',+ ports: { cdp: 5556, health: 5557 },+ env: {+ CDP_PORT: 5556,+ PORT: 5557+ }+}+```++## Guidelines for New Apps++1. **Check Available Ports**: Use PortOS apps list to see which ports are in use+2. **Pick a Contiguous Range**: Choose a starting port and allocate contiguously+3. **Document in ports object**: Always define the `ports` object in ecosystem.config+4. **Avoid Common Ports**: Stay away from well-known ports (80, 443, 3000, 8080, etc.)++## Recommended Port Ranges++| Range | Purpose |+|-------|---------|+| 5554-5560 | PortOS core services |+| 5561-5569 | Reserved for PortOS extensions |+| 5570-5599 | User applications |++## Viewing Port Usage++The PortOS apps list shows all ports for each process:+- Single port: `process-name:5554`+- Multiple ports: `process-name (cdp:5556,health:5557)`++Use the API to get detailed port information:+```bash+curl http://localhost:5554/api/apps | jq '.[].processes'+```diff --git a/ecosystem.config.cjs b/ecosystem.config.cjsindex 9e33292817..0ded62fefd 100644--- a/ecosystem.config.cjs+++ b/ecosystem.config.cjs@@ -5,6 +5,8 @@ module.exports = {script: 'server/index.js',cwd: __dirname,interpreter: 'node',+ // PortOS convention: define all ports used by this process+ ports: { api: 5554 },env: {NODE_ENV: 'development',PORT: 5554,@@ -18,6 +20,7 @@ module.exports = {script: 'node_modules/.bin/vite',cwd: `${__dirname}/client`,args: '--host 0.0.0.0 --port 5555',+ ports: { ui: 5555 },env: {NODE_ENV: 'development'},@@ -28,6 +31,7 @@ module.exports = {script: 'autofixer/server.js',cwd: __dirname,interpreter: 'node',+ ports: { api: 5559 },env: {NODE_ENV: 'development',PORT: 5559@@ -43,6 +47,7 @@ module.exports = {script: 'autofixer/ui.js',cwd: __dirname,interpreter: 'node',+ ports: { ui: 5560 },env: {NODE_ENV: 'development',PORT: 5560@@ -52,6 +57,23 @@ module.exports = {max_restarts: 10,min_uptime: '10s',restart_delay: 5000+ },+ {+ name: 'portos-browser',+ script: '.browser/server.js',+ cwd: __dirname,+ interpreter: 'node',+ ports: { cdp: 5556, health: 5557 },+ env: {+ NODE_ENV: 'development',+ CDP_PORT: 5556,+ PORT: 5557+ },+ watch: false,+ autorestart: true,+ max_restarts: 10,+ min_uptime: '10s',+ restart_delay: 5000}]};diff --git a/package.json b/package.jsonindex 561e1562c1..1fe74aef95 100644--- a/package.json+++ b/package.json@@ -10,7 +10,10 @@"dev:client": "cd client && npm run dev","build": "cd client && npm run build","start": "cd server && npm start",- "install:all": "npm install && cd client && npm install && cd ../server && npm install",+ "install:all": "npm install && cd client && npm install && cd ../server && npm install && cd .. && npm run setup",+ "setup": "node scripts/setup-data.js && node scripts/setup-browser.js",+ "setup:data": "node scripts/setup-data.js",+ "setup:browser": "node scripts/setup-browser.js","test": "cd server && npm test"},"devDependencies": {diff --git a/scripts/setup-browser.js b/scripts/setup-browser.jsnew file mode 100644index 0000000000..94a9aeee9c--- /dev/null+++ b/scripts/setup-browser.js@@ -0,0 +1,28 @@+#!/usr/bin/env node+import { existsSync, mkdirSync, cpSync } from 'fs';+import { execSync } from 'child_process';+import { dirname, join } from 'path';+import { fileURLToPath } from 'url';++const __dirname = dirname(fileURLToPath(import.meta.url));+const rootDir = join(__dirname, '..');+const browserDir = join(rootDir, '.browser');+const templateDir = join(rootDir, '.browser.template');++console.log('🌐 Setting up .browser directory...');++if (!existsSync(browserDir)) {+ console.log('📁 Creating .browser directory from template...');+ mkdirSync(browserDir, { recursive: true });+ cpSync(templateDir, browserDir, { recursive: true });++ console.log('📦 Installing browser dependencies...');+ execSync('npm install', { cwd: browserDir, stdio: 'inherit' });++ console.log('🎭 Installing Playwright browsers...');+ execSync('npx playwright install chromium', { cwd: browserDir, stdio: 'inherit' });++ console.log('✅ .browser directory setup complete');+} else {+ console.log('✅ .browser directory already exists, skipping setup');+}diff --git a/scripts/setup-data.js b/scripts/setup-data.jsnew file mode 100644index 0000000000..127f920d95--- /dev/null+++ b/scripts/setup-data.js@@ -0,0 +1,39 @@+#!/usr/bin/env node+import { existsSync, mkdirSync, cpSync, readdirSync, statSync } from 'fs';+import { dirname, join } from 'path';+import { fileURLToPath } from 'url';++const __dirname = dirname(fileURLToPath(import.meta.url));+const rootDir = join(__dirname, '..');+const dataDir = join(rootDir, 'data');+const sampleDir = join(rootDir, 'data.sample');++console.log('📁 Setting up data directory...');++if (!existsSync(dataDir)) {+ console.log('📁 Creating data directory from data.sample...');+ mkdirSync(dataDir, { recursive: true });+ cpSync(sampleDir, dataDir, { recursive: true });+ console.log('✅ Data directory created');+} else {+ // Ensure all subdirectories exist without overwriting existing files+ const ensureSubdirs = (srcDir, destDir) => {+ const items = readdirSync(srcDir);+ for (const item of items) {+ const srcPath = join(srcDir, item);+ const destPath = join(destDir, item);+ const stat = statSync(srcPath);++ if (stat.isDirectory()) {+ if (!existsSync(destPath)) {+ console.log(`📁 Creating missing directory: ${item}`);+ mkdirSync(destPath, { recursive: true });+ }+ ensureSubdirs(srcPath, destPath);+ }+ }+ };++ ensureSubdirs(sampleDir, dataDir);+ console.log('✅ Data directory already exists, ensured subdirectories');+}diff --git a/server/services/streamingDetect.js b/server/services/streamingDetect.jsindex 2f3eba77f6..bad3f21420 100644--- a/server/services/streamingDetect.js+++ b/server/services/streamingDetect.js@@ -92,44 +92,60 @@ export function parseEcosystemConfig(content) {const appBlock = content.substring(startPos, endPos + 1);- // Extract port from env.PORT or env_development.PORT- let port = null;- const portMatch = appBlock.match(/(?:env|env_development|env_production)\s*:\s*\{[^}]*\bPORT\s*:\s*(\d+)/);- if (portMatch) {- port = parseInt(portMatch[1]);+ // Extract ports - first try the PortOS standard 'ports' object+ let ports = {};++ // Look for ports: { label: port, ... } object (PortOS standard)+ const portsObjMatch = appBlock.match(/\bports\s*:\s*\{([^}]+)\}/);+ if (portsObjMatch) {+ const portsContent = portsObjMatch[1];+ const portEntries = portsContent.matchAll(/(\w+)\s*:\s*(\d+)/g);+ for (const entry of portEntries) {+ ports[entry[1]] = parseInt(entry[2]);+ }}- // Check for CDP_PORT (Chrome DevTools Protocol port for browser processes)- if (!port) {- // First try numeric value+ // Fall back to legacy parsing if no ports object found+ if (Object.keys(ports).length === 0) {+ // Extract PORT from env+ const portMatch = appBlock.match(/(?:env|env_development|env_production)\s*:\s*\{[^}]*\bPORT\s*:\s*(\d+)/);+ if (portMatch) {+ ports.api = parseInt(portMatch[1]);+ }++ // Extract CDP_PORT (Chrome DevTools Protocol port for browser processes)const cdpPortMatch = appBlock.match(/(?:env|env_development|env_production)\s*:\s*\{[^}]*CDP_PORT\s*:\s*(\d+)/);if (cdpPortMatch) {- port = parseInt(cdpPortMatch[1]);+ ports.cdp = parseInt(cdpPortMatch[1]);} else {// Check for variable reference (CDP_PORT: CDP_PORT)const cdpVarMatch = appBlock.match(/CDP_PORT\s*:\s*(\w+)/);if (cdpVarMatch && portConstants[cdpVarMatch[1]]) {- port = portConstants[cdpVarMatch[1]];+ ports.cdp = portConstants[cdpVarMatch[1]];}}- }- // Also check for --port in args- if (!port) {- const argsPortMatch = appBlock.match(/args\s*:\s*['"][^'"]*--port\s+(\d+)/);- if (argsPortMatch) {- port = parseInt(argsPortMatch[1]);+ // Also check for --port in args+ if (Object.keys(ports).length === 0) {+ const argsPortMatch = appBlock.match(/args\s*:\s*['"][^'"]*--port\s+(\d+)/);+ if (argsPortMatch) {+ ports.ui = parseInt(argsPortMatch[1]);+ }}- }- // Check for port: XXXX directly (some configs use this)- if (!port) {- const directPortMatch = appBlock.match(/\bport\s*:\s*(\d+)/);- if (directPortMatch) {- port = parseInt(directPortMatch[1]);+ // Check for port: XXXX directly (some configs use this)+ if (Object.keys(ports).length === 0) {+ const directPortMatch = appBlock.match(/\bport\s*:\s*(\d+)/);+ if (directPortMatch) {+ ports.api = parseInt(directPortMatch[1]);+ }}}+ // Primary port is the first one found (for backwards compatibility)+ const portValues = Object.values(ports);+ const port = portValues.length > 0 ? portValues[0] : null;+// Extract cwd for processes that might have external config fileslet cwd = null;const cwdMatch = appBlock.match(/cwd\s*:\s*['"]([^'"]+)['"]/);@@ -140,7 +156,7 @@ export function parseEcosystemConfig(content) {// Check if this process uses vite (need to check vite.config in cwd)const usesVite = /\bvite\b/i.test(appBlock);- processes.push({ name: processName, port, cwd, usesVite });+ processes.push({ name: processName, port, ports, cwd, usesVite });lastIndex = endPos;}