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(browser): add Browser management page with CDP controls
Adam Eivy7dd433817fdc
diff --git a/.changelog/v0.10.x.md b/.changelog/v0.10.x.mdindex 454a917129..32795efa3d 100644--- a/.changelog/v0.10.x.md+++ b/.changelog/v0.10.x.md@@ -238,6 +238,17 @@ This release introduces a structured changelog documentation system for creating- **Bulk Import API**: `POST /api/digital-twin/social-accounts/bulk` endpoint for programmatic bulk account creation- **Pre-Seeded Accounts**: User's GitHub (atomantic), Instagram (atomantic), Facebook (atomantic), LinkedIn (antic), X (antic), Substack (antic), and Medium (atomantic) accounts pre-configured+### Browser Management Page+- **Browser Page**: New `/browser` page for managing the persistent CDP/Playwright browser process (portos-browser)+- **Status Dashboard**: Real-time status showing connection state, CDP endpoint, open pages, uptime, CPU, memory, PID, and restart count+- **Process Controls**: Launch, stop, and restart the browser process via PM2 with visual feedback+- **CDP Page Listing**: View all open browser pages with titles, URLs, and types+- **Configuration Panel**: Edit CDP port, host, health port, headless mode, and auto-connect settings with persistence to `data/browser-config.json`+- **PM2 Logs Viewer**: View recent browser process logs inline+- **Browser Version Info**: Shows the Chromium version when connected+- **API Endpoints**: Full REST API at `/api/browser` with status, config, launch, stop, restart, health, process, pages, version, and logs endpoints+- **Navigation**: Added to sidebar with Globe icon between Dev Tools and Media+### AI Provider Model Updates- **Claude Opus 4.6**: Added `claude-opus-4-6` model to Claude Code CLI provider as the new default and heavy tier model- **GPT-5.2**: Codex CLI provider uses `gpt-5.2` as default and heavy tier model (5.3 was not yet available)diff --git a/PLAN.md b/PLAN.mdindex 6ba29b16a9..15ccc35bdf 100644--- a/PLAN.md+++ b/PLAN.md@@ -61,6 +61,8 @@ pm2 logs- [x] **M33**: Soul System - Digital twin identity scaffold management. See [Soul System](./docs/features/soul-system.md)- [x] **M34 P1-P2,P4**: Digital Twin - Quantitative personality modeling and confidence scoring. See [Digital Twin](./docs/features/digital-twin.md)- [x] **M35**: Chief of Staff Enhancement - Proactive autonomous agent with hybrid memory, missions, LM Studio, thinking levels. See [CoS Enhancement](./docs/features/cos-enhancement.md)+- [x] **M35.1**: CoS UI - Added Arcane Sigil (3D) avatar style option alongside Cyberpunk 3D+- [x] **M36**: Browser Management - CDP/Playwright browser page with status, controls, config, and logs### Planned@@ -93,6 +95,7 @@ pm2 logs- [Memory System](./docs/features/memory-system.md) - Semantic memory with LLM classification- [Prompt Manager](./docs/features/prompt-manager.md) - Customizable AI prompts- [Soul System](./docs/features/soul-system.md) - Digital twin identity scaffold+- [Browser Management](./docs/features/browser.md) - CDP/Playwright browser management---diff --git a/client/src/App.jsx b/client/src/App.jsxindex b03465b365..152687b1ec 100644--- a/client/src/App.jsx+++ b/client/src/App.jsx@@ -13,6 +13,7 @@ import DigitalTwin from './pages/DigitalTwin';import Agents from './pages/Agents';import Uploads from './pages/Uploads';import Shell from './pages/Shell';+import BrowserPage from './pages/Browser';// Lazy load heavier pages for code splitting// DevTools pages are large (~2300 lines total) so lazy load them@@ -60,6 +61,7 @@ export default function App() {<Route path="media" element={<Media />} /><Route path="uploads" element={<Uploads />} /><Route path="shell" element={<Shell />} />+ <Route path="browser" element={<BrowserPage />} /><Route path="agents" element={<Navigate to="/agents/personalities" replace />} /><Route path="agents/:tab" element={<Agents />} /><Route path="*" element={<Navigate to="/" replace />} />diff --git a/client/src/components/Layout.jsx b/client/src/components/Layout.jsxindex b2188b40b8..6fc8b6228d 100644--- a/client/src/components/Layout.jsx+++ b/client/src/components/Layout.jsx@@ -32,7 +32,8 @@ import {Link2,LineChart,Upload,- SquareTerminal+ SquareTerminal,+ Globe} from 'lucide-react';import packageJson from '../../package.json';import Logo from './Logo';@@ -101,6 +102,7 @@ const navItems = [{ to: '/devtools/usage', label: 'Usage', icon: BarChart3 }]},+ { to: '/browser', label: 'Browser', icon: Globe, single: true },{ to: '/media', label: 'Media', icon: Camera, single: true },{ to: '/uploads', label: 'Uploads', icon: Upload, single: true },{ to: '/shell', label: 'Shell', icon: SquareTerminal, single: true }diff --git a/client/src/pages/Browser.jsx b/client/src/pages/Browser.jsxnew file mode 100644index 0000000000..d0634b445d--- /dev/null+++ b/client/src/pages/Browser.jsx@@ -0,0 +1,485 @@+import { useState, useEffect, useCallback } from 'react';+import {+ Globe, Play, Square, RefreshCw, Settings, Activity,+ Monitor, Wifi, WifiOff, Clock, Cpu, MemoryStick,+ ExternalLink, FileText, ChevronDown, ChevronRight+} from 'lucide-react';+import {+ getBrowserStatus, getBrowserConfig, updateBrowserConfig,+ launchBrowser, stopBrowser, restartBrowser,+ getBrowserPages, getBrowserLogs+} from '../services/api';+import toast from 'react-hot-toast';++const POLL_INTERVAL = 5000;++function formatBytes(bytes) {+ if (!bytes) return '0 B';+ const units = ['B', 'KB', 'MB', 'GB'];+ let i = 0;+ let val = bytes;+ while (val >= 1024 && i < units.length - 1) {+ val /= 1024;+ i++;+ }+ return `${val.toFixed(1)} ${units[i]}`;+}++function formatUptime(timestamp) {+ if (!timestamp) return '-';+ const ms = Date.now() - timestamp;+ const seconds = Math.floor(ms / 1000);+ if (seconds < 60) return `${seconds}s`;+ const minutes = Math.floor(seconds / 60);+ if (minutes < 60) return `${minutes}m ${seconds % 60}s`;+ const hours = Math.floor(minutes / 60);+ if (hours < 24) return `${hours}h ${minutes % 60}m`;+ const days = Math.floor(hours / 24);+ return `${days}d ${hours % 24}h`;+}++export default function BrowserPage() {+ const [status, setStatus] = useState(null);+ const [loading, setLoading] = useState(true);+ const [actionLoading, setActionLoading] = useState(null);+ const [showConfig, setShowConfig] = useState(false);+ const [showLogs, setShowLogs] = useState(false);+ const [showPages, setShowPages] = useState(true);+ const [logs, setLogs] = useState('');+ const [config, setConfig] = useState(null);+ const [configDraft, setConfigDraft] = useState(null);++ const fetchStatus = useCallback(async () => {+ const data = await getBrowserStatus().catch(() => null);+ if (data) {+ setStatus(data);+ setLoading(false);+ }+ }, []);++ const fetchLogs = useCallback(async () => {+ const data = await getBrowserLogs(100).catch(() => null);+ if (data) {+ const combined = [data.stdout, data.stderr].filter(Boolean).join('\n');+ setLogs(combined || '(no logs)');+ }+ }, []);++ // Initial load+ useEffect(() => {+ fetchStatus();+ }, [fetchStatus]);++ // Poll for status updates+ useEffect(() => {+ const interval = setInterval(fetchStatus, POLL_INTERVAL);+ return () => clearInterval(interval);+ }, [fetchStatus]);++ // Load config when settings panel opens+ useEffect(() => {+ if (showConfig && !config) {+ getBrowserConfig().then(c => {+ setConfig(c);+ setConfigDraft(c);+ }).catch(() => {});+ }+ }, [showConfig, config]);++ // Load logs when panel opens+ useEffect(() => {+ if (showLogs) fetchLogs();+ }, [showLogs, fetchLogs]);++ const handleAction = useCallback(async (action, fn) => {+ setActionLoading(action);+ const result = await fn().catch(err => {+ toast.error(`Failed to ${action}: ${err.message}`);+ return null;+ });+ if (result) {+ toast.success(`Browser ${action} successful`);+ // Refresh full status after action+ await fetchStatus();+ }+ setActionLoading(null);+ }, [fetchStatus]);++ const handleSaveConfig = useCallback(async () => {+ if (!configDraft) return;+ const saved = await updateBrowserConfig(configDraft).catch(err => {+ toast.error(`Failed to save config: ${err.message}`);+ return null;+ });+ if (saved) {+ setConfig(saved);+ setConfigDraft(saved);+ toast.success('Browser config saved');+ }+ }, [configDraft]);++ const isRunning = status?.process?.status === 'online';+ const isConnected = status?.connected;++ return (+ <div>+ {/* Header */}+ <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4 mb-6">+ <div>+ <h2 className="text-2xl font-bold text-white flex items-center gap-2">+ <Globe size={28} className="text-port-accent" />+ Browser+ </h2>+ <p className="text-gray-500">Manage the authenticated CDP/Playwright browser</p>+ </div>+ <div className="flex items-center gap-2 flex-wrap">+ <button+ onClick={() => setShowConfig(s => !s)}+ className={`flex items-center gap-2 px-3 py-1.5 text-sm rounded-lg transition-colors ${+ showConfig+ ? 'bg-port-accent text-white'+ : 'bg-port-card border border-port-border text-gray-400 hover:text-white hover:border-port-accent/50'+ }`}+ >+ <Settings size={16} />+ <span className="hidden sm:inline">Config</span>+ </button>+ <button+ onClick={() => { setShowLogs(s => !s); }}+ className={`flex items-center gap-2 px-3 py-1.5 text-sm rounded-lg transition-colors ${+ showLogs+ ? 'bg-port-accent text-white'+ : 'bg-port-card border border-port-border text-gray-400 hover:text-white hover:border-port-accent/50'+ }`}+ >+ <FileText size={16} />+ <span className="hidden sm:inline">Logs</span>+ </button>+ <button+ onClick={fetchStatus}+ disabled={loading}+ className="flex items-center gap-2 px-3 py-1.5 text-sm rounded-lg bg-port-card border border-port-border text-gray-400 hover:text-white hover:border-port-accent/50 transition-colors disabled:opacity-50"+ >+ <RefreshCw size={16} className={loading ? 'animate-spin' : ''} />+ <span className="hidden sm:inline">Refresh</span>+ </button>+ </div>+ </div>++ {/* Config panel */}+ {showConfig && configDraft && (+ <div className="mb-6 p-4 bg-port-card border border-port-border rounded-xl">+ <h3 className="text-lg font-semibold text-white mb-4">Browser Configuration</h3>+ <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">+ <div>+ <label className="block text-sm text-gray-400 mb-1">CDP Port</label>+ <input+ type="number"+ value={configDraft.cdpPort}+ onChange={e => setConfigDraft(d => ({ ...d, cdpPort: parseInt(e.target.value, 10) || 5556 }))}+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm focus:outline-none focus:border-port-accent"+ />+ </div>+ <div>+ <label className="block text-sm text-gray-400 mb-1">CDP Host</label>+ <input+ type="text"+ value={configDraft.cdpHost}+ onChange={e => setConfigDraft(d => ({ ...d, cdpHost: e.target.value }))}+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm focus:outline-none focus:border-port-accent"+ />+ </div>+ <div>+ <label className="block text-sm text-gray-400 mb-1">Health Port</label>+ <input+ type="number"+ value={configDraft.healthPort}+ onChange={e => setConfigDraft(d => ({ ...d, healthPort: parseInt(e.target.value, 10) || 5557 }))}+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm focus:outline-none focus:border-port-accent"+ />+ </div>+ <div className="flex items-center gap-2">+ <input+ type="checkbox"+ id="headless"+ checked={configDraft.headless}+ onChange={e => setConfigDraft(d => ({ ...d, headless: e.target.checked }))}+ className="w-4 h-4 rounded border-port-border bg-port-bg text-port-accent focus:ring-port-accent"+ />+ <label htmlFor="headless" className="text-sm text-gray-400">Headless mode</label>+ </div>+ <div className="flex items-center gap-2">+ <input+ type="checkbox"+ id="autoConnect"+ checked={configDraft.autoConnect}+ onChange={e => setConfigDraft(d => ({ ...d, autoConnect: e.target.checked }))}+ className="w-4 h-4 rounded border-port-border bg-port-bg text-port-accent focus:ring-port-accent"+ />+ <label htmlFor="autoConnect" className="text-sm text-gray-400">Auto-connect on startup</label>+ </div>+ </div>+ <div className="mt-4 flex justify-end">+ <button+ onClick={handleSaveConfig}+ className="px-4 py-2 bg-port-accent text-white rounded-lg text-sm font-medium hover:bg-port-accent/80 transition-colors"+ >+ Save Config+ </button>+ </div>+ </div>+ )}++ {/* Logs panel */}+ {showLogs && (+ <div className="mb-6 bg-port-card border border-port-border rounded-xl overflow-hidden">+ <div className="flex items-center justify-between p-3 border-b border-port-border">+ <h3 className="text-sm font-semibold text-white">Recent Logs</h3>+ <button+ onClick={fetchLogs}+ className="text-xs text-gray-400 hover:text-white transition-colors"+ >+ <RefreshCw size={14} />+ </button>+ </div>+ <pre className="p-3 text-xs text-gray-400 font-mono overflow-auto max-h-64 whitespace-pre-wrap">+ {logs || 'Loading...'}+ </pre>+ </div>+ )}++ {/* Main grid */}+ <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">+ {/* Status + Controls */}+ <div className="lg:col-span-2 space-y-6">+ {/* Status card */}+ <div className="bg-port-card border border-port-border rounded-xl p-5">+ <div className="flex items-center justify-between mb-4">+ <h3 className="text-lg font-semibold text-white flex items-center gap-2">+ <Activity size={20} className="text-port-accent" />+ Browser Status+ </h3>+ <div className={`flex items-center gap-2 px-3 py-1 rounded-full text-sm font-medium ${+ isConnected+ ? 'bg-port-success/10 text-port-success'+ : isRunning+ ? 'bg-port-warning/10 text-port-warning'+ : 'bg-port-error/10 text-port-error'+ }`}>+ {isConnected ? <Wifi size={14} /> : <WifiOff size={14} />}+ {isConnected ? 'Connected' : isRunning ? 'Running (not connected)' : 'Stopped'}+ </div>+ </div>++ <div className="grid grid-cols-2 sm:grid-cols-4 gap-4">+ <div className="bg-port-bg rounded-lg p-3">+ <div className="text-xs text-gray-500 mb-1">Process</div>+ <div className={`text-sm font-medium ${+ isRunning ? 'text-port-success' : 'text-port-error'+ }`}>+ {status?.process?.status || 'unknown'}+ </div>+ </div>+ <div className="bg-port-bg rounded-lg p-3">+ <div className="text-xs text-gray-500 mb-1">CDP Endpoint</div>+ <div className="text-sm font-medium text-white truncate" title={status?.cdpEndpoint}>+ {status?.cdpEndpoint || '-'}+ </div>+ </div>+ <div className="bg-port-bg rounded-lg p-3">+ <div className="text-xs text-gray-500 mb-1">Open Pages</div>+ <div className="text-sm font-medium text-white">+ {status?.pageCount ?? '-'}+ </div>+ </div>+ <div className="bg-port-bg rounded-lg p-3">+ <div className="text-xs text-gray-500 mb-1">Uptime</div>+ <div className="text-sm font-medium text-white flex items-center gap-1">+ <Clock size={12} />+ {formatUptime(status?.process?.uptime)}+ </div>+ </div>+ </div>++ {/* Process details row */}+ {status?.process?.exists && (+ <div className="grid grid-cols-2 sm:grid-cols-4 gap-4 mt-3">+ <div className="bg-port-bg rounded-lg p-3">+ <div className="text-xs text-gray-500 mb-1 flex items-center gap-1"><Cpu size={10} /> CPU</div>+ <div className="text-sm font-medium text-white">{status.process.cpu ?? 0}%</div>+ </div>+ <div className="bg-port-bg rounded-lg p-3">+ <div className="text-xs text-gray-500 mb-1 flex items-center gap-1"><MemoryStick size={10} /> Memory</div>+ <div className="text-sm font-medium text-white">{formatBytes(status.process.memory)}</div>+ </div>+ <div className="bg-port-bg rounded-lg p-3">+ <div className="text-xs text-gray-500 mb-1">PID</div>+ <div className="text-sm font-medium text-white">{status.process.pid ?? '-'}</div>+ </div>+ <div className="bg-port-bg rounded-lg p-3">+ <div className="text-xs text-gray-500 mb-1">Restarts</div>+ <div className="text-sm font-medium text-white">{status.process.restarts ?? 0}</div>+ </div>+ </div>+ )}++ {/* Version info */}+ {status?.version && (+ <div className="mt-3 bg-port-bg rounded-lg p-3">+ <div className="text-xs text-gray-500 mb-1">Browser Version</div>+ <div className="text-sm text-white">+ {status.version.Browser || status.version['User-Agent'] || 'Unknown'}+ </div>+ </div>+ )}+ </div>++ {/* Controls */}+ <div className="bg-port-card border border-port-border rounded-xl p-5">+ <h3 className="text-lg font-semibold text-white mb-4">Controls</h3>+ <div className="flex flex-wrap gap-3">+ {!isRunning ? (+ <button+ onClick={() => handleAction('launch', launchBrowser)}+ disabled={actionLoading !== null}+ className="flex items-center gap-2 px-5 py-2.5 bg-port-success text-white rounded-lg font-medium hover:bg-port-success/80 transition-colors disabled:opacity-50 min-h-[40px]"+ >+ {actionLoading === 'launch'+ ? <RefreshCw size={18} className="animate-spin" />+ : <Play size={18} />+ }+ Launch Browser+ </button>+ ) : (+ <>+ <button+ onClick={() => handleAction('stop', stopBrowser)}+ disabled={actionLoading !== null}+ className="flex items-center gap-2 px-5 py-2.5 bg-port-error text-white rounded-lg font-medium hover:bg-port-error/80 transition-colors disabled:opacity-50 min-h-[40px]"+ >+ {actionLoading === 'stop'+ ? <RefreshCw size={18} className="animate-spin" />+ : <Square size={18} />+ }+ Stop+ </button>+ <button+ onClick={() => handleAction('restart', restartBrowser)}+ disabled={actionLoading !== null}+ className="flex items-center gap-2 px-5 py-2.5 bg-port-warning text-white rounded-lg font-medium hover:bg-port-warning/80 transition-colors disabled:opacity-50 min-h-[40px]"+ >+ {actionLoading === 'restart'+ ? <RefreshCw size={18} className="animate-spin" />+ : <RefreshCw size={18} />+ }+ Restart+ </button>+ </>+ )}+ </div>+ </div>++ {/* Open Pages */}+ <div className="bg-port-card border border-port-border rounded-xl overflow-hidden">+ <button+ onClick={() => setShowPages(s => !s)}+ className="w-full flex items-center justify-between p-4 text-left hover:bg-port-border/30 transition-colors"+ >+ <h3 className="text-lg font-semibold text-white flex items-center gap-2">+ <Monitor size={20} className="text-port-accent" />+ Open Pages+ {status?.pages?.length > 0 && (+ <span className="ml-2 px-2 py-0.5 text-xs rounded-full bg-port-accent/20 text-port-accent">+ {status.pages.length}+ </span>+ )}+ </h3>+ {showPages ? <ChevronDown size={18} className="text-gray-400" /> : <ChevronRight size={18} className="text-gray-400" />}+ </button>+ {showPages && (+ <div className="border-t border-port-border">+ {!status?.pages || status.pages.length === 0 ? (+ <div className="p-4 text-sm text-gray-500">+ {isConnected ? 'No pages open' : 'Browser not connected'}+ </div>+ ) : (+ <div className="divide-y divide-port-border">+ {status.pages.map(page => (+ <div key={page.id} className="p-3 hover:bg-port-border/20 transition-colors">+ <div className="flex items-start justify-between gap-2">+ <div className="min-w-0">+ <div className="text-sm font-medium text-white truncate">+ {page.title}+ </div>+ <div className="text-xs text-gray-500 truncate mt-0.5">+ {page.url}+ </div>+ </div>+ <span className="text-[10px] px-1.5 py-0.5 rounded bg-port-border text-gray-400 flex-shrink-0">+ {page.type}+ </span>+ </div>+ </div>+ ))}+ </div>+ )}+ </div>+ )}+ </div>+ </div>++ {/* Sidebar */}+ <div className="space-y-4">+ {/* Quick Status */}+ <div className="bg-port-card border border-port-border rounded-xl p-4">+ <h3 className="font-semibold text-white mb-4">Connection Info</h3>+ <div className="space-y-3">+ <div className="flex items-center justify-between">+ <span className="text-gray-400 text-sm">CDP Port</span>+ <span className="text-sm font-mono text-white">{status?.config?.cdpPort || '-'}</span>+ </div>+ <div className="flex items-center justify-between">+ <span className="text-gray-400 text-sm">Health Port</span>+ <span className="text-sm font-mono text-white">{status?.config?.healthPort || '-'}</span>+ </div>+ <div className="flex items-center justify-between">+ <span className="text-gray-400 text-sm">Headless</span>+ <span className={`text-sm font-medium ${status?.config?.headless ? 'text-port-success' : 'text-port-warning'}`}>+ {status?.config?.headless ? 'Yes' : 'No'}+ </span>+ </div>+ <div className="flex items-center justify-between">+ <span className="text-gray-400 text-sm">Auto-connect</span>+ <span className={`text-sm font-medium ${status?.config?.autoConnect ? 'text-port-success' : 'text-gray-500'}`}>+ {status?.config?.autoConnect ? 'Yes' : 'No'}+ </span>+ </div>+ </div>+ </div>++ {/* CDP Endpoint card */}+ <div className="bg-port-card border border-port-border rounded-xl p-4">+ <h3 className="font-semibold text-white mb-3">CDP Endpoint</h3>+ <div className="bg-port-bg rounded-lg p-3 font-mono text-xs text-port-accent break-all">+ {status?.cdpEndpoint || `ws://127.0.0.1:5556`}+ </div>+ <p className="text-xs text-gray-500 mt-2">+ Use this endpoint to connect Playwright or other CDP clients to the running browser instance.+ </p>+ </div>++ {/* Instructions */}+ <div className="bg-port-card border border-port-border rounded-xl p-4">+ <h3 className="font-semibold text-white mb-3">Usage</h3>+ <ul className="space-y-2 text-sm text-gray-400">+ <li>1. Launch the browser using the controls</li>+ <li>2. Browser runs as a PM2 process (portos-browser)</li>+ <li>3. Connect via CDP endpoint for automation</li>+ <li>4. Sessions persist across restarts</li>+ </ul>+ </div>+ </div>+ </div>+ </div>+ );+}diff --git a/data.sample/browser-config.json b/data.sample/browser-config.jsonnew file mode 100644index 0000000000..61cd66d851--- /dev/null+++ b/data.sample/browser-config.json@@ -0,0 +1,8 @@+{+ "cdpPort": 5556,+ "cdpHost": "127.0.0.1",+ "healthPort": 5557,+ "autoConnect": true,+ "headless": true,+ "userDataDir": ""+}diff --git a/docs/features/browser.md b/docs/features/browser.mdnew file mode 100644index 0000000000..10996d69d0--- /dev/null+++ b/docs/features/browser.md@@ -0,0 +1,78 @@+# Browser Management++Manage the persistent CDP/Playwright browser instance used by PortOS for web automation, authenticated scraping, and CoS agent tasks.++## Architecture++The browser runs as a separate PM2 process (`portos-browser`) that launches a Chromium instance with Chrome DevTools Protocol (CDP) enabled. The PortOS server communicates with it via HTTP health checks and the CDP debug endpoint.++```+PortOS Server (5554)+ ├── /api/browser routes → browserService.js+ │ ├── Health check → portos-browser health endpoint (5557)+ │ ├── CDP pages → CDP debug endpoint (5556)+ │ └── PM2 commands → pm2 start/stop/restart portos-browser+ └── Browser Page UI → /browser+ └── Polls /api/browser for real-time status++portos-browser (PM2 process)+ ├── Chromium with --remote-debugging-port=5556+ └── Health server on port 5557+```++## Ports++| Port | Purpose |+|------|---------|+| 5556 | Chrome DevTools Protocol (CDP) |+| 5557 | Browser health check endpoint |++## API Endpoints++| Method | Path | Description |+|--------|------|-------------|+| GET | `/api/browser` | Full combined status |+| GET | `/api/browser/config` | Get browser configuration |+| PUT | `/api/browser/config` | Update browser configuration |+| POST | `/api/browser/launch` | Start browser via PM2 |+| POST | `/api/browser/stop` | Stop browser via PM2 |+| POST | `/api/browser/restart` | Restart browser via PM2 |+| GET | `/api/browser/health` | Quick health check |+| GET | `/api/browser/process` | PM2 process details |+| GET | `/api/browser/pages` | List open CDP pages |+| GET | `/api/browser/version` | CDP version info |+| GET | `/api/browser/logs` | Recent PM2 logs |++## Configuration++Stored in `data/browser-config.json`:++```json+{+ "cdpPort": 5556,+ "cdpHost": "127.0.0.1",+ "healthPort": 5557,+ "autoConnect": true,+ "headless": true,+ "userDataDir": ""+}+```++## Usage++1. Navigate to `/browser` in the PortOS UI+2. Click **Launch Browser** to start the CDP browser process+3. The status dashboard shows real-time connection state, open pages, and process metrics+4. Use the **Config** panel to adjust CDP ports, headless mode, etc.+5. Connect external Playwright scripts to the CDP endpoint shown on the page++## Connecting External Scripts++```javascript+import { chromium } from 'playwright';++const browser = await chromium.connectOverCDP('ws://127.0.0.1:5556');+const context = browser.contexts()[0];+const page = await context.newPage();+await page.goto('https://example.com');+```diff --git a/server/routes/browser.js b/server/routes/browser.jsnew file mode 100644index 0000000000..424f92f012--- /dev/null+++ b/server/routes/browser.js@@ -0,0 +1,91 @@+import express from 'express';+import { z } from 'zod';+import * as browserService from '../services/browserService.js';++const router = express.Router();++// Validation schemas+const updateConfigSchema = z.object({+ cdpPort: z.number().int().min(1024).max(65535).optional(),+ cdpHost: z.string().optional(),+ healthPort: z.number().int().min(1024).max(65535).optional(),+ autoConnect: z.boolean().optional(),+ headless: z.boolean().optional(),+ userDataDir: z.string().optional()+});++// GET /api/browser - Full browser status+router.get('/', async (req, res) => {+ const status = await browserService.getFullStatus();+ res.json(status);+});++// GET /api/browser/config - Get browser config+router.get('/config', async (req, res) => {+ const config = await browserService.getConfig();+ res.json(config);+});++// PUT /api/browser/config - Update browser config+router.put('/config', async (req, res) => {+ const updates = updateConfigSchema.parse(req.body);+ const config = await browserService.updateConfig(updates);+ res.json(config);+});++// POST /api/browser/launch - Start the browser process+router.post('/launch', async (req, res) => {+ console.log('🌐 Browser launch requested');+ const status = await browserService.launchBrowser();+ res.json(status);+});++// POST /api/browser/stop - Stop the browser process+router.post('/stop', async (req, res) => {+ console.log('🛑 Browser stop requested');+ const status = await browserService.stopBrowser();+ res.json(status);+});++// POST /api/browser/restart - Restart the browser process+router.post('/restart', async (req, res) => {+ console.log('🔄 Browser restart requested');+ const status = await browserService.restartBrowser();+ res.json(status);+});++// GET /api/browser/health - Quick health check+router.get('/health', async (req, res) => {+ const health = await browserService.getHealthStatus();+ res.json(health);+});++// GET /api/browser/process - PM2 process status+router.get('/process', async (req, res) => {+ const process = await browserService.getProcessStatus();+ res.json(process);+});++// GET /api/browser/pages - List open CDP pages+router.get('/pages', async (req, res) => {+ const pages = await browserService.getOpenPages();+ res.json(pages);+});++// GET /api/browser/version - CDP version info+router.get('/version', async (req, res) => {+ const version = await browserService.getCdpVersion();+ if (!version) {+ return res.status(503).json({ error: 'Browser not reachable' });+ }+ res.json(version);+});++// GET /api/browser/logs - Recent PM2 logs+router.get('/logs', async (req, res) => {+ const lines = parseInt(req.query.lines || '50', 10);+ const logs = await browserService.getRecentLogs(lines);+ res.json(logs);+});++export default router;diff --git a/server/services/browserService.js b/server/services/browserService.jsnew file mode 100644index 0000000000..6d5730932c--- /dev/null+++ b/server/services/browserService.js@@ -0,0 +1,225 @@+/**+ * Browser Service - manages the portos-browser CDP instance+ * Communicates with the portos-browser process (port 5557 health, port 5556 CDP)+ * Stores config in data/browser-config.json+ */++import { readFile, writeFile, mkdir } from 'fs/promises';+import { join, dirname } from 'path';+import { fileURLToPath } from 'url';+import { EventEmitter } from 'events';++const __filename = fileURLToPath(import.meta.url);+const __dirname = dirname(__filename);+const DATA_DIR = join(__dirname, '..', '..', 'data');+const CONFIG_FILE = join(DATA_DIR, 'browser-config.json');++export const browserEvents = new EventEmitter();++const DEFAULT_CONFIG = {+ cdpPort: 5556,+ cdpHost: '127.0.0.1',+ healthPort: 5557,+ autoConnect: true,+ headless: true,+ userDataDir: ''+};++let cachedConfig = null;++// ---------- Config persistence ----------++export async function loadConfig() {+ if (cachedConfig) return cachedConfig;+ const raw = await readFile(CONFIG_FILE, 'utf-8').catch(() => null);+ cachedConfig = raw ? { ...DEFAULT_CONFIG, ...JSON.parse(raw) } : { ...DEFAULT_CONFIG };+ return cachedConfig;+}++export async function saveConfig(config) {+ await mkdir(DATA_DIR, { recursive: true });+ cachedConfig = { ...DEFAULT_CONFIG, ...config };+ await writeFile(CONFIG_FILE, JSON.stringify(cachedConfig, null, 2));+ browserEvents.emit('config:changed', cachedConfig);+ return cachedConfig;+}++export async function getConfig() {+ return loadConfig();+}++export async function updateConfig(updates) {+ const current = await loadConfig();+ return saveConfig({ ...current, ...updates });+}++// ---------- Status / Health ----------++export async function getHealthStatus() {+ const config = await loadConfig();+ const healthUrl = `http://127.0.0.1:${config.healthPort}/health`;++ const controller = new AbortController();+ const timeout = setTimeout(() => controller.abort(), 3000);++ const response = await fetch(healthUrl, { signal: controller.signal }).catch(() => null);+ clearTimeout(timeout);++ if (!response || !response.ok) {+ return {+ connected: false,+ processRunning: false,+ cdpPort: config.cdpPort,+ cdpHost: config.cdpHost,+ healthPort: config.healthPort,+ cdpEndpoint: `ws://${config.cdpHost}:${config.cdpPort}`,+ error: response ? `Health check returned ${response.status}` : 'Health check unreachable'+ };+ }++ const data = await response.json();+ return {+ connected: data.status === 'healthy',+ processRunning: true,+ cdpPort: data.cdpPort || config.cdpPort,+ cdpHost: data.cdpHost || config.cdpHost,+ healthPort: config.healthPort,+ cdpEndpoint: data.cdpEndpoint || `ws://${config.cdpHost}:${config.cdpPort}`,+ status: data.status+ };+}++// ---------- PM2 process management ----------++async function pm2Action(action) {+ const { execFile } = await import('child_process');+ const { promisify } = await import('util');+ const execFileAsync = promisify(execFile);++ console.log(`🌐 Browser PM2 ${action}: portos-browser`);+ const { stdout } = await execFileAsync('pm2', [action, 'portos-browser']);+ console.log(`✅ Browser PM2 ${action} complete`);++ // Give PM2 a moment to settle+ await new Promise(resolve => setTimeout(resolve, 1500));++ const status = await getHealthStatus();+ browserEvents.emit('status:changed', status);+ return status;+}++export async function launchBrowser() {+ return pm2Action('start');+}++export async function stopBrowser() {+ return pm2Action('stop');+}++export async function restartBrowser() {+ return pm2Action('restart');+}++// ---------- PM2 status (process-level) ----------++export async function getProcessStatus() {+ const { execFile } = await import('child_process');+ const { promisify } = await import('util');+ const execFileAsync = promisify(execFile);++ const { stdout } = await execFileAsync('pm2', ['jlist']);+ const processes = JSON.parse(stdout);+ const browserProc = processes.find(p => p.name === 'portos-browser');++ if (!browserProc) {+ return { exists: false, status: 'not_found', pm2_id: null };+ }++ return {+ exists: true,+ status: browserProc.pm2_env?.status || 'unknown',+ pm2_id: browserProc.pm_id,+ pid: browserProc.pid,+ memory: browserProc.monit?.memory || 0,+ cpu: browserProc.monit?.cpu || 0,+ uptime: browserProc.pm2_env?.pm_uptime || null,+ restarts: browserProc.pm2_env?.restart_time || 0,+ unstableRestarts: browserProc.pm2_env?.unstable_restarts || 0+ };+}++// ---------- Logs ----------++export async function getRecentLogs(lines = 50) {+ const { execFile } = await import('child_process');+ const { promisify } = await import('util');+ const execFileAsync = promisify(execFile);++ const { stdout, stderr } = await execFileAsync('pm2', ['logs', 'portos-browser', '--nostream', '--lines', String(lines)], {+ timeout: 5000+ }).catch(() => ({ stdout: '', stderr: '' }));++ return { stdout: stdout || '', stderr: stderr || '' };+}++// ---------- CDP page listing (connects to the debug endpoint) ----------++export async function getOpenPages() {+ const config = await loadConfig();+ const listUrl = `http://${config.cdpHost}:${config.cdpPort}/json/list`;++ const controller = new AbortController();+ const timeout = setTimeout(() => controller.abort(), 3000);++ const response = await fetch(listUrl, { signal: controller.signal }).catch(() => null);+ clearTimeout(timeout);++ if (!response || !response.ok) {+ return [];+ }++ const pages = await response.json();+ return pages.map(p => ({+ id: p.id,+ title: p.title || '(untitled)',+ url: p.url,+ type: p.type+ }));+}++// ---------- CDP version info ----------++export async function getCdpVersion() {+ const config = await loadConfig();+ const versionUrl = `http://${config.cdpHost}:${config.cdpPort}/json/version`;++ const controller = new AbortController();+ const timeout = setTimeout(() => controller.abort(), 3000);++ const response = await fetch(versionUrl, { signal: controller.signal }).catch(() => null);+ clearTimeout(timeout);++ if (!response || !response.ok) return null;+ return response.json();+}++// ---------- Full combined status ----------++export async function getFullStatus() {+ const [health, process, pages, version, config] = await Promise.all([+ getHealthStatus(),+ getProcessStatus(),+ getOpenPages().catch(() => []),+ getCdpVersion().catch(() => null),+ getConfig()+ ]);++ return {+ ...health,+ process,+ pages,+ pageCount: pages.length,+ version,+ config+ };+}