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

v0.2.0 - Complete feature set with AI detection

Adam Eivy156887584f28
diff --git a/PLAN.md b/PLAN.md
index 7561b5f2e0..f9eceb46f8 100644
--- a/PLAN.md
+++ b/PLAN.md
@@ -29,16 +29,75 @@ pm2 logs
- [x] M0: Bootstrap (ports, basic UI shell)
- [x] M1: App registry + grid
- [x] M2: PM2 integration (start/stop/restart/status)
-- [ ] M3: Log viewer (streaming)
-- [ ] M4: Create new app wizard
-- [ ] M5: Dev tools (history, command runner)
-- [ ] M6: AI providers + headless executor
+- [x] M3: Log viewer (Socket.IO streaming)
+- [x] M4: App wizard (register existing + create new)
+- [x] M5: AI providers + headless executor
+- [x] M6: Dev tools (history, command runner)
-### API Endpoints
+---
+
+## M4: App Wizard (Detailed)
+
+The wizard supports two modes:
+
+### Mode 1: Register Existing App
+For apps already running on the system (any path, any user):
+
+**Steps:**
+1. **Basic Info**: Name, description, icon
+2. **Location**: Repo path (file picker or manual entry)
+3. **Ports**: UI port, API port (can auto-detect from running processes)
+4. **Process Config**:
+ - Start command(s)
+ - PM2 process name(s)
+ - Env file location
+5. **Confirm & Register**
+
+**Features:**
+- Detect running processes on specified ports
+- Validate repo path exists
+- Optional: import existing PM2 process into registry
+- No scaffolding, no git operations
+
+### Mode 2: Create New App
+Scaffold a new project from template:
+
+**Steps:**
+1. **Basic Info**: Name, description
+2. **Template**: Select template (vite+express, node-server, static)
+3. **Location**: Parent directory for new repo
+4. **Ports**: Allocate from available range
+5. **Git Setup**:
+ - Initialize git
+ - Create GitHub repo (optional, via `gh` CLI)
+6. **Confirm & Create**
+
+**Actions on create:**
+- Copy template files
+- Configure .env with ports
+- Run `npm install`
+- Initialize git + first commit
+- Create GitHub repo (if selected)
+- Generate PM2 ecosystem config
+- Register in PortOS
+- Start with PM2
+
+### API Endpoints (M4)
+| Route | Description |
+|-------|-------------|
+| POST /api/apps | Register existing app |
+| POST /api/scaffold | Create new app from template |
+| GET /api/templates | List available templates |
+| POST /api/detect/ports | Detect process on port |
+| POST /api/detect/repo | Validate repo path, detect type |
+
+---
+
+### All API Endpoints
| Route | Description |
|-------|-------------|
| GET /api/health | Health check |
-| GET/POST /api/apps | List/create apps |
+| GET/POST /api/apps | List/register apps |
| GET/PUT/DELETE /api/apps/:id | App CRUD |
| POST /api/apps/:id/start | Start via PM2 |
| POST /api/apps/:id/stop | Stop via PM2 |
@@ -46,3 +105,30 @@ pm2 logs
| GET /api/apps/:id/status | PM2 status |
| GET /api/apps/:id/logs | Get logs |
| GET /api/ports/scan | Scan ports |
+| GET /api/logs/processes | List PM2 processes |
+| GET /api/logs/:name | Get logs (static) |
+| Socket.IO logs:subscribe | Stream logs (WebSocket) |
+| POST /api/scaffold | Create new app |
+| GET /api/templates | List templates |
+| POST /api/detect/ports | Detect process on port |
+| POST /api/detect/repo | Validate repo path |
+| GET /api/providers | List AI providers |
+| POST /api/providers | Add provider |
+| PUT /api/providers/:id | Update provider |
+| DELETE /api/providers/:id | Delete provider |
+| POST /api/providers/:id/test | Test provider connectivity |
+| PUT /api/providers/active | Set active provider |
+| GET /api/runs | List run history |
+| POST /api/runs | Execute new run |
+| GET /api/runs/:id | Get run details |
+| GET /api/runs/:id/output | Get run output |
+| POST /api/runs/:id/stop | Stop active run |
+| DELETE /api/runs/:id | Delete run |
+| GET /api/history | List action history |
+| GET /api/history/stats | Get history statistics |
+| DELETE /api/history | Clear history |
+| POST /api/commands/execute | Execute shell command |
+| POST /api/commands/:id/stop | Stop running command |
+| GET /api/commands/allowed | List allowed commands |
+| GET /api/commands/processes | List PM2 processes |
+| POST /api/detect/ai | AI-powered app detection |
diff --git a/client/package-lock.json b/client/package-lock.json
index 396c9f3bee..cbf4471cc4 100644
--- a/client/package-lock.json
+++ b/client/package-lock.json
@@ -10,7 +10,8 @@
"dependencies": {
"react": "^18.3.1",
"react-dom": "^18.3.1",
- "react-router-dom": "^7.1.1"
+ "react-router-dom": "^7.1.1",
+ "socket.io-client": "^4.8.3"
},
"devDependencies": {
"@vitejs/plugin-react": "^4.3.4",
@@ -1161,6 +1162,12 @@
"win32"
]
},
+ "node_modules/@socket.io/component-emitter": {
+ "version": "3.1.2",
+ "resolved": "https://registry.npmjs.org/@socket.io/component-emitter/-/component-emitter-3.1.2.tgz",
+ "integrity": "sha512-9BCxFwvbGg/RsZK9tjXd8s4UcwR0MWeFQ1XEKIQVVvAGJyINdrqKMcTRyLoK8Rse1GjzLV9cwjWV1olXRWEXVA==",
+ "license": "MIT"
+ },
"node_modules/@types/babel__core": {
"version": "7.20.5",
"resolved": "https://registry.npmjs.org/@types/babel__core/-/babel__core-7.20.5.tgz",
@@ -1486,7 +1493,6 @@
"version": "4.4.3",
"resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",
"integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==",
- "dev": true,
"license": "MIT",
"dependencies": {
"ms": "^2.1.3"
@@ -1521,6 +1527,28 @@
"dev": true,
"license": "ISC"
},
+ "node_modules/engine.io-client": {
+ "version": "6.6.4",
+ "resolved": "https://registry.npmjs.org/engine.io-client/-/engine.io-client-6.6.4.tgz",
+ "integrity": "sha512-+kjUJnZGwzewFDw951CDWcwj35vMNf2fcj7xQWOctq1F2i1jkDdVvdFG9kM/BEChymCH36KgjnW0NsL58JYRxw==",
+ "license": "MIT",
+ "dependencies": {
+ "@socket.io/component-emitter": "~3.1.0",
+ "debug": "~4.4.1",
+ "engine.io-parser": "~5.2.1",
+ "ws": "~8.18.3",
+ "xmlhttprequest-ssl": "~2.1.1"
+ }
+ },
+ "node_modules/engine.io-parser": {
+ "version": "5.2.3",
+ "resolved": "https://registry.npmjs.org/engine.io-parser/-/engine.io-parser-5.2.3.tgz",
+ "integrity": "sha512-HqD3yTBfnBxIrbnM1DoD6Pcq8NECnh8d4As1Qgh0z5Gg3jRRIqijury0CL3ghu/edArpUYiYqQiDUQBIs4np3Q==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=10.0.0"
+ }
+ },
"node_modules/esbuild": {
"version": "0.25.12",
"resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.25.12.tgz",
@@ -1876,7 +1904,6 @@
"version": "2.1.3",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
"integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
- "dev": true,
"license": "MIT"
},
"node_modules/mz": {
@@ -2400,6 +2427,34 @@
"integrity": "sha512-oeM1lpU/UvhTxw+g3cIfxXHyJRc/uidd3yK1P242gzHds0udQBYzs3y8j4gCCW+ZJ7ad0yctld8RYO+bdurlvw==",
"license": "MIT"
},
+ "node_modules/socket.io-client": {
+ "version": "4.8.3",
+ "resolved": "https://registry.npmjs.org/socket.io-client/-/socket.io-client-4.8.3.tgz",
+ "integrity": "sha512-uP0bpjWrjQmUt5DTHq9RuoCBdFJF10cdX9X+a368j/Ft0wmaVgxlrjvK3kjvgCODOMMOz9lcaRzxmso0bTWZ/g==",
+ "license": "MIT",
+ "dependencies": {
+ "@socket.io/component-emitter": "~3.1.0",
+ "debug": "~4.4.1",
+ "engine.io-client": "~6.6.1",
+ "socket.io-parser": "~4.2.4"
+ },
+ "engines": {
+ "node": ">=10.0.0"
+ }
+ },
+ "node_modules/socket.io-parser": {
+ "version": "4.2.5",
+ "resolved": "https://registry.npmjs.org/socket.io-parser/-/socket.io-parser-4.2.5.tgz",
+ "integrity": "sha512-bPMmpy/5WWKHea5Y/jYAP6k74A+hvmRCQaJuJB6I/ML5JZq/KfNieUVo/3Mh7SAqn7TyFdIo6wqYHInG1MU1bQ==",
+ "license": "MIT",
+ "dependencies": {
+ "@socket.io/component-emitter": "~3.1.0",
+ "debug": "~4.4.1"
+ },
+ "engines": {
+ "node": ">=10.0.0"
+ }
+ },
"node_modules/source-map-js": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz",
@@ -2722,6 +2777,35 @@
"url": "https://github.com/sponsors/jonschlinkert"
}
},
+ "node_modules/ws": {
+ "version": "8.18.3",
+ "resolved": "https://registry.npmjs.org/ws/-/ws-8.18.3.tgz",
+ "integrity": "sha512-PEIGCY5tSlUt50cqyMXfCzX+oOPqN0vuGqWzbcJ2xvnkzkq46oOpz7dQaTDBdfICb4N14+GARUDw2XV2N4tvzg==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=10.0.0"
+ },
+ "peerDependencies": {
+ "bufferutil": "^4.0.1",
+ "utf-8-validate": ">=5.0.2"
+ },
+ "peerDependenciesMeta": {
+ "bufferutil": {
+ "optional": true
+ },
+ "utf-8-validate": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/xmlhttprequest-ssl": {
+ "version": "2.1.2",
+ "resolved": "https://registry.npmjs.org/xmlhttprequest-ssl/-/xmlhttprequest-ssl-2.1.2.tgz",
+ "integrity": "sha512-TEU+nJVUUnA4CYJFLvK5X9AOeH4KvDvhIfm0vV1GaQRtchnG0hgK5p8hw/xjv8cunWYCsiPCSDzObPyhEwq3KQ==",
+ "engines": {
+ "node": ">=0.4.0"
+ }
+ },
"node_modules/yallist": {
"version": "3.1.1",
"resolved": "https://registry.npmjs.org/yallist/-/yallist-3.1.1.tgz",
diff --git a/client/package.json b/client/package.json
index e8ae9139a0..9ee9eb8e1a 100644
--- a/client/package.json
+++ b/client/package.json
@@ -4,14 +4,15 @@
"private": true,
"type": "module",
"scripts": {
- "dev": "vite --host 127.0.0.1 --port 5555",
+ "dev": "vite --host 0.0.0.0 --port 5555",
"build": "vite build",
"preview": "vite preview"
},
"dependencies": {
"react": "^18.3.1",
"react-dom": "^18.3.1",
- "react-router-dom": "^7.1.1"
+ "react-router-dom": "^7.1.1",
+ "socket.io-client": "^4.8.3"
},
"devDependencies": {
"@vitejs/plugin-react": "^4.3.4",
diff --git a/client/src/App.jsx b/client/src/App.jsx
index 14c45c5455..80d46aee41 100644
--- a/client/src/App.jsx
+++ b/client/src/App.jsx
@@ -2,6 +2,10 @@ import { Routes, Route, Navigate } from 'react-router-dom';
import Layout from './components/Layout';
import Dashboard from './pages/Dashboard';
import Apps from './pages/Apps';
+import Logs from './pages/Logs';
+import CreateApp from './pages/CreateApp';
+import AIProviders from './pages/AIProviders';
+import DevTools from './pages/DevTools';
export default function App() {
return (
@@ -9,23 +13,12 @@ export default function App() {
<Route path="/" element={<Layout />}>
<Route index element={<Dashboard />} />
<Route path="apps" element={<Apps />} />
- <Route path="logs" element={<ComingSoon title="Logs" />} />
- <Route path="devtools" element={<ComingSoon title="Dev Tools" />} />
- <Route path="ai" element={<ComingSoon title="AI Providers" />} />
- <Route path="create" element={<ComingSoon title="Create App" />} />
+ <Route path="logs" element={<Logs />} />
+ <Route path="devtools" element={<DevTools />} />
+ <Route path="ai" element={<AIProviders />} />
+ <Route path="create" element={<CreateApp />} />
<Route path="*" element={<Navigate to="/" replace />} />
</Route>
</Routes>
);
}
-
-function ComingSoon({ title }) {
- return (
- <div className="flex items-center justify-center h-64">
- <div className="text-center">
- <h2 className="text-2xl font-bold text-gray-400 mb-2">{title}</h2>
- <p className="text-gray-500">Coming in next milestone</p>
- </div>
- </div>
- );
-}
diff --git a/client/src/components/AppTile.jsx b/client/src/components/AppTile.jsx
index 35aed58b5a..ccbc98c912 100644
--- a/client/src/components/AppTile.jsx
+++ b/client/src/components/AppTile.jsx
@@ -2,8 +2,20 @@ import { useState } from 'react';
import StatusBadge from './StatusBadge';
import * as api from '../services/api';
+// Construct app URL using current hostname (works with Tailscale)
+function getAppUrl(app) {
+ if (app.uiUrl) return app.uiUrl;
+ if (app.uiPort) {
+ const protocol = window.location.protocol;
+ const hostname = window.location.hostname;
+ return `${protocol}//${hostname}:${app.uiPort}`;
+ }
+ return null;
+}
+
export default function AppTile({ app, onUpdate }) {
const [loading, setLoading] = useState(null);
+ const appUrl = getAppUrl(app);
const handleAction = async (action) => {
setLoading(action);
@@ -59,9 +71,9 @@ export default function AppTile({ app, onUpdate }) {
{/* Actions */}
<div className="flex flex-wrap gap-2">
{/* Open UI */}
- {app.uiUrl && isOnline && (
+ {appUrl && isOnline && (
<a
- href={app.uiUrl}
+ href={appUrl}
target="_blank"
rel="noopener noreferrer"
className="px-3 py-1.5 text-sm rounded-lg bg-port-accent hover:bg-port-accent/80 text-white transition-colors"
diff --git a/client/src/components/Layout.jsx b/client/src/components/Layout.jsx
index 982ecec0d0..3dc3a333af 100644
--- a/client/src/components/Layout.jsx
+++ b/client/src/components/Layout.jsx
@@ -1,3 +1,4 @@
+import { useState, useEffect } from 'react';
import { Outlet, NavLink } from 'react-router-dom';
const navItems = [
@@ -9,51 +10,122 @@ const navItems = [
{ to: '/create', label: 'Create App', icon: '➕' }
];
+const SIDEBAR_KEY = 'portos-sidebar-collapsed';
+
export default function Layout() {
+ const [collapsed, setCollapsed] = useState(() => {
+ const saved = localStorage.getItem(SIDEBAR_KEY);
+ return saved === 'true';
+ });
+ const [mobileOpen, setMobileOpen] = useState(false);
+
+ useEffect(() => {
+ localStorage.setItem(SIDEBAR_KEY, String(collapsed));
+ }, [collapsed]);
+
+ // Close mobile menu on route change
+ useEffect(() => {
+ setMobileOpen(false);
+ }, []);
+
return (
- <div className="min-h-screen bg-port-bg">
- {/* Header */}
- <header className="border-b border-port-border bg-port-card">
- <div className="max-w-7xl mx-auto px-4 py-4 flex items-center justify-between">
- <div className="flex items-center gap-3">
- <span className="text-2xl">🚀</span>
- <h1 className="text-xl font-bold text-white">Port OS</h1>
- </div>
- <div className="text-sm text-gray-500">
- Local Dev Portal
- </div>
+ <div className="min-h-screen bg-port-bg flex">
+ {/* Mobile overlay */}
+ {mobileOpen && (
+ <div
+ className="fixed inset-0 bg-black/50 z-40 lg:hidden"
+ onClick={() => setMobileOpen(false)}
+ />
+ )}
+
+ {/* Sidebar */}
+ <aside
+ className={`
+ fixed lg:static inset-y-0 left-0 z-50
+ flex flex-col bg-port-card border-r border-port-border
+ transition-all duration-300 ease-in-out
+ ${mobileOpen ? 'translate-x-0' : '-translate-x-full lg:translate-x-0'}
+ ${collapsed ? 'lg:w-16' : 'lg:w-56'}
+ w-56
+ `}
+ >
+ {/* Logo */}
+ <div className={`flex items-center gap-3 p-4 border-b border-port-border ${collapsed ? 'lg:justify-center' : ''}`}>
+ <span className="text-2xl flex-shrink-0">🚀</span>
+ <h1 className={`text-lg font-bold text-white whitespace-nowrap transition-opacity ${collapsed ? 'lg:hidden' : ''}`}>
+ Port OS
+ </h1>
</div>
- </header>
-
- {/* Navigation */}
- <nav className="border-b border-port-border bg-port-card/50">
- <div className="max-w-7xl mx-auto px-4">
- <div className="flex gap-1 overflow-x-auto py-2">
- {navItems.map(({ to, label, icon }) => (
- <NavLink
- key={to}
- to={to}
- end={to === '/'}
- className={({ isActive }) =>
- `flex items-center gap-2 px-4 py-2 rounded-lg text-sm font-medium transition-colors whitespace-nowrap ${
- isActive
- ? 'bg-port-accent text-white'
- : 'text-gray-400 hover:text-white hover:bg-port-border'
- }`
- }
- >
- <span>{icon}</span>
- <span>{label}</span>
- </NavLink>
- ))}
+
+ {/* Nav items */}
+ <nav className="flex-1 py-4 overflow-y-auto">
+ {navItems.map(({ to, label, icon }) => (
+ <NavLink
+ key={to}
+ to={to}
+ end={to === '/'}
+ onClick={() => setMobileOpen(false)}
+ className={({ isActive }) =>
+ `flex items-center gap-3 mx-2 px-3 py-2.5 rounded-lg text-sm font-medium transition-colors
+ ${collapsed ? 'lg:justify-center lg:px-2' : ''}
+ ${isActive
+ ? 'bg-port-accent text-white'
+ : 'text-gray-400 hover:text-white hover:bg-port-border'
+ }`
+ }
+ title={collapsed ? label : undefined}
+ >
+ <span className="text-lg flex-shrink-0">{icon}</span>
+ <span className={`whitespace-nowrap transition-opacity ${collapsed ? 'lg:hidden' : ''}`}>
+ {label}
+ </span>
+ </NavLink>
+ ))}
+ </nav>
+
+ {/* Collapse toggle - desktop only */}
+ <button
+ onClick={() => setCollapsed(!collapsed)}
+ className="hidden lg:flex items-center justify-center p-4 border-t border-port-border text-gray-500 hover:text-white hover:bg-port-border transition-colors"
+ title={collapsed ? 'Expand sidebar' : 'Collapse sidebar'}
+ >
+ <svg
+ className={`w-5 h-5 transition-transform ${collapsed ? 'rotate-180' : ''}`}
+ fill="none"
+ stroke="currentColor"
+ viewBox="0 0 24 24"
+ >
+ <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M11 19l-7-7 7-7m8 14l-7-7 7-7" />
+ </svg>
+ </button>
+ </aside>
+
+ {/* Main area */}
+ <div className="flex-1 flex flex-col min-w-0">
+ {/* Mobile header */}
+ <header className="lg:hidden flex items-center justify-between p-4 border-b border-port-border bg-port-card">
+ <button
+ onClick={() => setMobileOpen(true)}
+ className="p-2 -ml-2 text-gray-400 hover:text-white"
+ >
+ <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
+ <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 6h16M4 12h16M4 18h16" />
+ </svg>
+ </button>
+ <div className="flex items-center gap-2">
+ <span className="text-xl">🚀</span>
+ <span className="font-bold text-white">Port OS</span>
</div>
- </div>
- </nav>
+ <div className="w-10" /> {/* Spacer for centering */}
+ </header>
- {/* Main content */}
- <main className="max-w-7xl mx-auto px-4 py-6">
- <Outlet />
- </main>
+ {/* Main content */}
+ <main className="flex-1 p-4 md:p-6 overflow-auto">
+ <div className="max-w-7xl mx-auto">
+ <Outlet />
+ </div>
+ </main>
+ </div>
</div>
);
}
diff --git a/client/src/components/LogViewer.jsx b/client/src/components/LogViewer.jsx
new file mode 100644
index 0000000000..5f09cad5a6
--- /dev/null
+++ b/client/src/components/LogViewer.jsx
@@ -0,0 +1,60 @@
+import { useEffect, useRef } from 'react';
+
+export default function LogViewer({ logs, autoScroll = true, maxHeight = '500px' }) {
+ const containerRef = useRef(null);
+ const shouldScrollRef = useRef(true);
+
+ useEffect(() => {
+ if (autoScroll && shouldScrollRef.current && containerRef.current) {
+ containerRef.current.scrollTop = containerRef.current.scrollHeight;
+ }
+ }, [logs, autoScroll]);
+
+ const handleScroll = () => {
+ if (!containerRef.current) return;
+ const { scrollTop, scrollHeight, clientHeight } = containerRef.current;
+ // Auto-scroll if user is near bottom (within 50px)
+ shouldScrollRef.current = scrollHeight - scrollTop - clientHeight < 50;
+ };
+
+ const getLineClass = (type) => {
+ switch (type) {
+ case 'stderr':
+ return 'text-port-warning';
+ case 'connected':
+ return 'text-port-success';
+ case 'error':
+ return 'text-port-error';
+ default:
+ return 'text-gray-300';
+ }
+ };
+
+ return (
+ <div
+ ref={containerRef}
+ onScroll={handleScroll}
+ className="bg-port-bg border border-port-border rounded-lg overflow-auto font-mono text-sm"
+ style={{ maxHeight }}
+ >
+ {logs.length === 0 ? (
+ <div className="p-4 text-gray-500 text-center">
+ No logs available. Select a process and click "Start Streaming" to begin.
+ </div>
+ ) : (
+ <div className="p-3 space-y-0.5">
+ {logs.map((log, index) => (
+ <div key={index} className={`${getLineClass(log.type)} break-all`}>
+ {log.timestamp && (
+ <span className="text-gray-600 mr-2">
+ {new Date(log.timestamp).toLocaleTimeString()}
+ </span>
+ )}
+ <span>{log.line || log.message || JSON.stringify(log)}</span>
+ </div>
+ ))}
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/client/src/pages/AIProviders.jsx b/client/src/pages/AIProviders.jsx
new file mode 100644
index 0000000000..acf0f167ac
--- /dev/null
+++ b/client/src/pages/AIProviders.jsx
@@ -0,0 +1,537 @@
+import { useState, useEffect } from 'react';
+import * as api from '../services/api';
+import socket from '../services/socket';
+
+export default function AIProviders() {
+ const [providers, setProviders] = useState([]);
+ const [activeProviderId, setActiveProviderId] = useState(null);
+ const [loading, setLoading] = useState(true);
+ const [showForm, setShowForm] = useState(false);
+ const [editingProvider, setEditingProvider] = useState(null);
+ const [testResults, setTestResults] = useState({});
+ const [runs, setRuns] = useState([]);
+ const [showRunPanel, setShowRunPanel] = useState(false);
+ const [runPrompt, setRunPrompt] = useState('');
+ const [selectedWorkspace, setSelectedWorkspace] = useState('');
+ const [apps, setApps] = useState([]);
+ const [activeRun, setActiveRun] = useState(null);
+ const [runOutput, setRunOutput] = useState('');
+
+ useEffect(() => {
+ loadData();
+ }, []);
+
+ useEffect(() => {
+ if (!activeRun) return;
+
+ const handleData = (data) => {
+ setRunOutput(prev => prev + data);
+ };
+
+ const handleComplete = (metadata) => {
+ setActiveRun(null);
+ loadRuns();
+ };
+
+ socket.on(`run:${activeRun}:data`, handleData);
+ socket.on(`run:${activeRun}:complete`, handleComplete);
+
+ return () => {
+ socket.off(`run:${activeRun}:data`, handleData);
+ socket.off(`run:${activeRun}:complete`, handleComplete);
+ };
+ }, [activeRun]);
+
+ const loadData = async () => {
+ setLoading(true);
+ const [providersData, appsData, runsData] = await Promise.all([
+ api.getProviders().catch(() => ({ providers: [], activeProvider: null })),
+ api.getApps().catch(() => []),
+ api.getRuns(20).catch(() => ({ runs: [] }))
+ ]);
+ setProviders(providersData.providers || []);
+ setActiveProviderId(providersData.activeProvider);
+ setApps(appsData);
+ setRuns(runsData.runs || []);
+ setLoading(false);
+ };
+
+ const loadRuns = async () => {
+ const runsData = await api.getRuns(20).catch(() => ({ runs: [] }));
+ setRuns(runsData.runs || []);
+ };
+
+ const handleSetActive = async (id) => {
+ await api.setActiveProvider(id);
+ setActiveProviderId(id);
+ };
+
+ const handleTest = async (id) => {
+ setTestResults(prev => ({ ...prev, [id]: { testing: true } }));
+ const result = await api.testProvider(id).catch(err => ({ success: false, error: err.message }));
+ setTestResults(prev => ({ ...prev, [id]: result }));
+ };
+
+ const handleDelete = async (id) => {
+ await api.deleteProvider(id);
+ loadData();
+ };
+
+ const handleToggleEnabled = async (provider) => {
+ await api.updateProvider(provider.id, { enabled: !provider.enabled });
+ loadData();
+ };
+
+ const handleRefreshModels = async (id) => {
+ await api.refreshProviderModels(id);
+ loadData();
+ };
+
+ const handleExecuteRun = async () => {
+ if (!runPrompt.trim() || !activeProviderId) return;
+
+ setRunOutput('');
+ const workspace = apps.find(a => a.id === selectedWorkspace);
+
+ const result = await api.createRun({
+ providerId: activeProviderId,
+ prompt: runPrompt,
+ workspacePath: workspace?.repoPath,
+ workspaceName: workspace?.name
+ }).catch(err => ({ error: err.message }));
+
+ if (result.error) {
+ setRunOutput(`Error: ${result.error}`);
+ return;
+ }
+
+ setActiveRun(result.runId);
+ };
+
+ const handleStopRun = async () => {
+ if (activeRun) {
+ await api.stopRun(activeRun);
+ setActiveRun(null);
+ }
+ };
+
+ if (loading) {
+ return (
+ <div className="flex items-center justify-center h-64">
+ <div className="text-gray-400">Loading providers...</div>
+ </div>
+ );
+ }
+
+ return (
+ <div className="space-y-6">
+ <div className="flex items-center justify-between">
+ <h1 className="text-2xl font-bold text-white">AI Providers</h1>
+ <div className="flex gap-2">
+ <button
+ onClick={() => setShowRunPanel(!showRunPanel)}
+ className="px-4 py-2 bg-port-accent hover:bg-port-accent/80 text-white rounded-lg transition-colors"
+ >
+ {showRunPanel ? 'Hide Runner' : 'Run Prompt'}
+ </button>
+ <button
+ onClick={() => { setEditingProvider(null); setShowForm(true); }}
+ className="px-4 py-2 bg-port-border hover:bg-port-border/80 text-white rounded-lg transition-colors"
+ >
+ Add Provider
+ </button>
+ </div>
+ </div>
+
+ {/* Run Panel */}
+ {showRunPanel && (
+ <div className="bg-port-card border border-port-border rounded-xl p-4 space-y-4">
+ <div className="flex items-center gap-4">
+ <select
+ value={activeProviderId || ''}
+ onChange={(e) => handleSetActive(e.target.value)}
+ className="px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white"
+ >
+ <option value="">Select Provider</option>
+ {providers.filter(p => p.enabled).map(p => (
+ <option key={p.id} value={p.id}>{p.name}</option>
+ ))}
+ </select>
+
+ <select
+ value={selectedWorkspace}
+ onChange={(e) => setSelectedWorkspace(e.target.value)}
+ className="px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white"
+ >
+ <option value="">No workspace</option>
+ {apps.map(app => (
+ <option key={app.id} value={app.id}>{app.name}</option>
+ ))}
+ </select>
+ </div>
+
+ <textarea
+ value={runPrompt}
+ onChange={(e) => setRunPrompt(e.target.value)}
+ placeholder="Enter your prompt..."
+ rows={3}
+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white resize-none focus:border-port-accent focus:outline-none"
+ />
+
+ <div className="flex justify-between items-center">
+ <button
+ onClick={handleExecuteRun}
+ disabled={!runPrompt.trim() || !activeProviderId || activeRun}
+ className="px-6 py-2 bg-port-success hover:bg-port-success/80 text-white rounded-lg transition-colors disabled:opacity-50"
+ >
+ {activeRun ? 'Running...' : 'Execute'}
+ </button>
+
+ {activeRun && (
+ <button
+ onClick={handleStopRun}
+ className="px-4 py-2 bg-port-error hover:bg-port-error/80 text-white rounded-lg transition-colors"
+ >
+ Stop
+ </button>
+ )}
+ </div>
+
+ {runOutput && (
+ <div className="bg-port-bg border border-port-border rounded-lg p-3 max-h-64 overflow-auto">
+ <pre className="text-sm text-gray-300 font-mono whitespace-pre-wrap">{runOutput}</pre>
+ </div>
+ )}
+ </div>
+ )}
+
+ {/* Provider List */}
+ <div className="grid gap-4">
+ {providers.map(provider => (
+ <div
+ key={provider.id}
+ className={`bg-port-card border rounded-xl p-4 ${
+ provider.id === activeProviderId ? 'border-port-accent' : 'border-port-border'
+ }`}
+ >
+ <div className="flex items-start justify-between">
+ <div className="flex-1">
+ <div className="flex items-center gap-3">
+ <h3 className="text-lg font-semibold text-white">{provider.name}</h3>
+ <span className={`text-xs px-2 py-0.5 rounded ${
+ provider.type === 'cli' ? 'bg-blue-500/20 text-blue-400' : 'bg-purple-500/20 text-purple-400'
+ }`}>
+ {provider.type.toUpperCase()}
+ </span>
+ {provider.id === activeProviderId && (
+ <span className="text-xs px-2 py-0.5 rounded bg-port-accent/20 text-port-accent">
+ ACTIVE
+ </span>
+ )}
+ {!provider.enabled && (
+ <span className="text-xs px-2 py-0.5 rounded bg-gray-500/20 text-gray-400">
+ DISABLED
+ </span>
+ )}
+ </div>
+
+ <div className="mt-2 text-sm text-gray-400 space-y-1">
+ {provider.type === 'cli' && (
+ <p>Command: <code className="text-gray-300">{provider.command} {provider.args?.join(' ')}</code></p>
+ )}
+ {provider.type === 'api' && (
+ <p>Endpoint: <code className="text-gray-300">{provider.endpoint}</code></p>
+ )}
+ {provider.models?.length > 0 && (
+ <p>Models: {provider.models.slice(0, 3).join(', ')}{provider.models.length > 3 ? ` +${provider.models.length - 3}` : ''}</p>
+ )}
+ {provider.defaultModel && (
+ <p>Default: <code className="text-gray-300">{provider.defaultModel}</code></p>
+ )}
+ </div>
+
+ {testResults[provider.id] && !testResults[provider.id].testing && (
+ <div className={`mt-2 text-sm ${testResults[provider.id].success ? 'text-port-success' : 'text-port-error'}`}>
+ {testResults[provider.id].success
+ ? `✓ Available${testResults[provider.id].version ? ` (${testResults[provider.id].version})` : ''}`
+ : `✗ ${testResults[provider.id].error}`
+ }
+ </div>
+ )}
+ </div>
+
+ <div className="flex items-center gap-2">
+ <button
+ onClick={() => handleTest(provider.id)}
+ disabled={testResults[provider.id]?.testing}
+ className="px-3 py-1 text-sm bg-port-border hover:bg-port-border/80 text-white rounded transition-colors disabled:opacity-50"
+ >
+ {testResults[provider.id]?.testing ? 'Testing...' : 'Test'}
+ </button>
+
+ {provider.type === 'api' && (
+ <button
+ onClick={() => handleRefreshModels(provider.id)}
+ className="px-3 py-1 text-sm bg-port-border hover:bg-port-border/80 text-white rounded transition-colors"
+ title="Refresh models from API"
+ >
+ Refresh
+ </button>
+ )}
+
+ <button
+ onClick={() => handleToggleEnabled(provider)}
+ className={`px-3 py-1 text-sm rounded transition-colors ${
+ provider.enabled
+ ? 'bg-port-warning/20 text-port-warning hover:bg-port-warning/30'
+ : 'bg-port-success/20 text-port-success hover:bg-port-success/30'
+ }`}
+ >
+ {provider.enabled ? 'Disable' : 'Enable'}
+ </button>
+
+ {provider.id !== activeProviderId && provider.enabled && (
+ <button
+ onClick={() => handleSetActive(provider.id)}
+ className="px-3 py-1 text-sm bg-port-accent/20 text-port-accent hover:bg-port-accent/30 rounded transition-colors"
+ >
+ Set Active
+ </button>
+ )}
+
+ <button
+ onClick={() => { setEditingProvider(provider); setShowForm(true); }}
+ className="px-3 py-1 text-sm bg-port-border hover:bg-port-border/80 text-white rounded transition-colors"
+ >
+ Edit
+ </button>
+
+ <button
+ onClick={() => handleDelete(provider.id)}
+ className="px-3 py-1 text-sm bg-port-error/20 text-port-error hover:bg-port-error/30 rounded transition-colors"
+ >
+ Delete
+ </button>
+ </div>
+ </div>
+ </div>
+ ))}
+
+ {providers.length === 0 && (
+ <div className="text-center py-12 text-gray-500">
+ No providers configured. Add a provider to get started.
+ </div>
+ )}
+ </div>
+
+ {/* Recent Runs */}
+ {runs.length > 0 && (
+ <div className="mt-8">
+ <h2 className="text-xl font-bold text-white mb-4">Recent Runs</h2>
+ <div className="space-y-2">
+ {runs.map(run => (
+ <div
+ key={run.id}
+ className="bg-port-card border border-port-border rounded-lg p-3 flex items-center justify-between"
+ >
+ <div className="flex items-center gap-4">
+ <span className={`w-2 h-2 rounded-full ${
+ run.success === true ? 'bg-port-success' :
+ run.success === false ? 'bg-port-error' :
+ 'bg-port-warning animate-pulse'
+ }`} />
+ <div>
+ <p className="text-sm text-white">{run.prompt}</p>
+ <p className="text-xs text-gray-500">
+ {run.providerName} • {run.workspaceName || 'No workspace'} • {new Date(run.startTime).toLocaleString()}
+ </p>
+ </div>
+ </div>
+ <div className="text-sm text-gray-400">
+ {run.duration ? `${(run.duration / 1000).toFixed(1)}s` : 'Running...'}
+ </div>
+ </div>
+ ))}
+ </div>
+ </div>
+ )}
+
+ {/* Provider Form Modal */}
+ {showForm && (
+ <ProviderForm
+ provider={editingProvider}
+ onClose={() => { setShowForm(false); setEditingProvider(null); }}
+ onSave={() => { setShowForm(false); setEditingProvider(null); loadData(); }}
+ />
+ )}
+ </div>
+ );
+}
+
+function ProviderForm({ provider, onClose, onSave }) {
+ const [formData, setFormData] = useState({
+ name: provider?.name || '',
+ type: provider?.type || 'cli',
+ command: provider?.command || '',
+ args: provider?.args?.join(' ') || '',
+ endpoint: provider?.endpoint || '',
+ apiKey: provider?.apiKey || '',
+ defaultModel: provider?.defaultModel || '',
+ timeout: provider?.timeout || 300000,
+ enabled: provider?.enabled !== false
+ });
+
+ const handleSubmit = async (e) => {
+ e.preventDefault();
+
+ const data = {
+ ...formData,
+ args: formData.args ? formData.args.split(' ').filter(Boolean) : [],
+ timeout: parseInt(formData.timeout)
+ };
+
+ if (provider) {
+ await api.updateProvider(provider.id, data);
+ } else {
+ await api.createProvider(data);
+ }
+
+ onSave();
+ };
+
+ return (
+ <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
+ <div className="bg-port-card border border-port-border rounded-xl p-6 w-full max-w-lg">
+ <h2 className="text-xl font-bold text-white mb-4">
+ {provider ? 'Edit Provider' : 'Add Provider'}
+ </h2>
+
+ <form onSubmit={handleSubmit} className="space-y-4">
+ <div>
+ <label className="block text-sm text-gray-400 mb-1">Name *</label>
+ <input
+ type="text"
+ value={formData.name}
+ onChange={(e) => setFormData(prev => ({ ...prev, name: e.target.value }))}
+ required
+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white focus:border-port-accent focus:outline-none"
+ />
+ </div>
+
+ <div>
+ <label className="block text-sm text-gray-400 mb-1">Type *</label>
+ <select
+ value={formData.type}
+ onChange={(e) => setFormData(prev => ({ ...prev, type: e.target.value }))}
+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white focus:border-port-accent focus:outline-none"
+ >
+ <option value="cli">CLI</option>
+ <option value="api">API</option>
+ </select>
+ </div>
+
+ {formData.type === 'cli' && (
+ <>
+ <div>
+ <label className="block text-sm text-gray-400 mb-1">Command *</label>
+ <input
+ type="text"
+ value={formData.command}
+ onChange={(e) => setFormData(prev => ({ ...prev, command: e.target.value }))}
+ placeholder="claude"
+ required={formData.type === 'cli'}
+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white focus:border-port-accent focus:outline-none"
+ />
+ </div>
+
+ <div>
+ <label className="block text-sm text-gray-400 mb-1">Arguments (space-separated)</label>
+ <input
+ type="text"
+ value={formData.args}
+ onChange={(e) => setFormData(prev => ({ ...prev, args: e.target.value }))}
+ placeholder="--print -p"
+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white focus:border-port-accent focus:outline-none"
+ />
+ </div>
+ </>
+ )}
+
+ {formData.type === 'api' && (
+ <>
+ <div>
+ <label className="block text-sm text-gray-400 mb-1">Endpoint *</label>
+ <input
+ type="url"
+ value={formData.endpoint}
+ onChange={(e) => setFormData(prev => ({ ...prev, endpoint: e.target.value }))}
+ placeholder="http://localhost:1234/v1"
+ required={formData.type === 'api'}
+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white focus:border-port-accent focus:outline-none"
+ />
+ </div>
+
+ <div>
+ <label className="block text-sm text-gray-400 mb-1">API Key</label>
+ <input
+ type="password"
+ value={formData.apiKey}
+ onChange={(e) => setFormData(prev => ({ ...prev, apiKey: e.target.value }))}
+ placeholder="Optional"
+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white focus:border-port-accent focus:outline-none"
+ />
+ </div>
+ </>
+ )}
+
+ <div>
+ <label className="block text-sm text-gray-400 mb-1">Default Model</label>
+ <input
+ type="text"
+ value={formData.defaultModel}
+ onChange={(e) => setFormData(prev => ({ ...prev, defaultModel: e.target.value }))}
+ placeholder="claude-sonnet-4-20250514"
+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white focus:border-port-accent focus:outline-none"
+ />
+ </div>
+
+ <div>
+ <label className="block text-sm text-gray-400 mb-1">Timeout (ms)</label>
+ <input
+ type="number"
+ value={formData.timeout}
+ onChange={(e) => setFormData(prev => ({ ...prev, timeout: e.target.value }))}
+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white focus:border-port-accent focus:outline-none"
+ />
+ </div>
+
+ <label className="flex items-center gap-2">
+ <input
+ type="checkbox"
+ checked={formData.enabled}
+ onChange={(e) => setFormData(prev => ({ ...prev, enabled: e.target.checked }))}
+ className="w-4 h-4 rounded border-port-border bg-port-bg"
+ />
+ <span className="text-sm text-gray-400">Enabled</span>
+ </label>
+
+ <div className="flex justify-end gap-3 pt-4">
+ <button
+ type="button"
+ onClick={onClose}
+ className="px-4 py-2 text-gray-400 hover:text-white"
+ >
+ Cancel
+ </button>
+ <button
+ type="submit"
+ className="px-6 py-2 bg-port-accent hover:bg-port-accent/80 text-white rounded-lg transition-colors"
+ >
+ {provider ? 'Save' : 'Create'}
+ </button>
+ </div>
+ </form>
+ </div>
+ </div>
+ );
+}
diff --git a/client/src/pages/Apps.jsx b/client/src/pages/Apps.jsx
index d338c254b7..4c2985c9a8 100644
--- a/client/src/pages/Apps.jsx
+++ b/client/src/pages/Apps.jsx
@@ -1,28 +1,12 @@
import { useState, useEffect } from 'react';
+import { Link } from 'react-router-dom';
import StatusBadge from '../components/StatusBadge';
import * as api from '../services/api';
export default function Apps() {
const [apps, setApps] = useState([]);
const [loading, setLoading] = useState(true);
- const [showForm, setShowForm] = useState(false);
const [editingApp, setEditingApp] = useState(null);
- const [formData, setFormData] = useState(getEmptyForm());
- const [error, setError] = useState(null);
- const [saving, setSaving] = useState(false);
-
- function getEmptyForm() {
- return {
- name: '',
- repoPath: '',
- type: 'vite+express',
- uiPort: '',
- apiPort: '',
- startCommands: 'npm run dev',
- pm2ProcessNames: '',
- editorCommand: 'code .'
- };
- }
const fetchApps = async () => {
const data = await api.getApps().catch(() => []);
@@ -34,71 +18,12 @@ export default function Apps() {
fetchApps();
}, []);
- const handleSubmit = async (e) => {
- e.preventDefault();
- setError(null);
- setSaving(true);
-
- const data = {
- name: formData.name,
- repoPath: formData.repoPath,
- type: formData.type,
- uiPort: formData.uiPort ? parseInt(formData.uiPort) : undefined,
- apiPort: formData.apiPort ? parseInt(formData.apiPort) : undefined,
- startCommands: formData.startCommands.split('\n').filter(Boolean),
- pm2ProcessNames: formData.pm2ProcessNames
- ? formData.pm2ProcessNames.split(',').map(s => s.trim()).filter(Boolean)
- : undefined,
- editorCommand: formData.editorCommand || undefined
- };
-
- if (editingApp) {
- await api.updateApp(editingApp.id, data).catch(err => {
- setError(err.message);
- throw err;
- });
- } else {
- await api.createApp(data).catch(err => {
- setError(err.message);
- throw err;
- });
- }
-
- setSaving(false);
- setShowForm(false);
- setEditingApp(null);
- setFormData(getEmptyForm());
- fetchApps();
- };
-
- const handleEdit = (app) => {
- setEditingApp(app);
- setFormData({
- name: app.name,
- repoPath: app.repoPath,
- type: app.type,
- uiPort: app.uiPort || '',
- apiPort: app.apiPort || '',
- startCommands: (app.startCommands || []).join('\n'),
- pm2ProcessNames: (app.pm2ProcessNames || []).join(', '),
- editorCommand: app.editorCommand || 'code .'
- });
- setShowForm(true);
- };
-
const handleDelete = async (app) => {
- if (!confirm(`Delete "${app.name}"?`)) return;
+ if (!confirm(`Delete "${app.name}"? This only removes it from PortOS, not the actual files.`)) return;
await api.deleteApp(app.id);
fetchApps();
};
- const handleCancel = () => {
- setShowForm(false);
- setEditingApp(null);
- setFormData(getEmptyForm());
- setError(null);
- };
-
if (loading) {
return (
<div className="flex items-center justify-center h-64">
@@ -115,153 +40,26 @@ export default function Apps() {
<h2 className="text-2xl font-bold text-white">Apps</h2>
<p className="text-gray-500">Manage registered applications</p>
</div>
- {!showForm && (
- <button
- onClick={() => setShowForm(true)}
- className="px-4 py-2 bg-port-accent hover:bg-port-accent/80 text-white rounded-lg transition-colors"
- >
- + Register App
- </button>
- )}
+ <Link
+ to="/create"
+ className="px-4 py-2 bg-port-accent hover:bg-port-accent/80 text-white rounded-lg transition-colors"
+ >
+ + Add App
+ </Link>
</div>
- {/* Form */}
- {showForm && (
- <div className="bg-port-card border border-port-border rounded-xl p-6 mb-6">
- <h3 className="text-lg font-semibold text-white mb-4">
- {editingApp ? 'Edit App' : 'Register New App'}
- </h3>
-
- {error && (
- <div className="mb-4 p-3 bg-port-error/20 border border-port-error rounded-lg text-port-error text-sm">
- {error}
- </div>
- )}
-
- <form onSubmit={handleSubmit} className="space-y-4">
- <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
- <div>
- <label className="block text-sm text-gray-400 mb-1">Name *</label>
- <input
- type="text"
- value={formData.name}
- onChange={e => setFormData({ ...formData, name: e.target.value })}
- className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white focus:border-port-accent focus:outline-none"
- required
- />
- </div>
-
- <div>
- <label className="block text-sm text-gray-400 mb-1">Type *</label>
- <select
- value={formData.type}
- onChange={e => setFormData({ ...formData, type: e.target.value })}
- className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white focus:border-port-accent focus:outline-none"
- >
- <option value="vite+express">Vite + Express</option>
- <option value="single-node-server">Single Node Server</option>
- <option value="static">Static</option>
- </select>
- </div>
- </div>
-
- <div>
- <label className="block text-sm text-gray-400 mb-1">Repository Path *</label>
- <input
- type="text"
- value={formData.repoPath}
- onChange={e => setFormData({ ...formData, repoPath: e.target.value })}
- className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white focus:border-port-accent focus:outline-none"
- placeholder="/Users/you/projects/my-app"
- required
- />
- </div>
-
- <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
- <div>
- <label className="block text-sm text-gray-400 mb-1">UI Port</label>
- <input
- type="number"
- value={formData.uiPort}
- onChange={e => setFormData({ ...formData, uiPort: e.target.value })}
- className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white focus:border-port-accent focus:outline-none"
- placeholder="3000"
- />
- </div>
-
- <div>
- <label className="block text-sm text-gray-400 mb-1">API Port</label>
- <input
- type="number"
- value={formData.apiPort}
- onChange={e => setFormData({ ...formData, apiPort: e.target.value })}
- className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white focus:border-port-accent focus:outline-none"
- placeholder="3001"
- />
- </div>
- </div>
-
- <div>
- <label className="block text-sm text-gray-400 mb-1">
- Start Commands (one per line)
- </label>
- <textarea
- value={formData.startCommands}
- onChange={e => setFormData({ ...formData, startCommands: e.target.value })}
- className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white focus:border-port-accent focus:outline-none font-mono text-sm"
- rows={2}
- placeholder="npm run dev"
- />
- </div>
-
- <div>
- <label className="block text-sm text-gray-400 mb-1">
- PM2 Process Names (comma-separated)
- </label>
- <input
- type="text"
- value={formData.pm2ProcessNames}
- onChange={e => setFormData({ ...formData, pm2ProcessNames: e.target.value })}
- className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white focus:border-port-accent focus:outline-none"
- placeholder="my-app-ui, my-app-api"
- />
- </div>
-
- <div>
- <label className="block text-sm text-gray-400 mb-1">Editor Command</label>
- <input
- type="text"
- value={formData.editorCommand}
- onChange={e => setFormData({ ...formData, editorCommand: e.target.value })}
- className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white focus:border-port-accent focus:outline-none"
- placeholder="code ."
- />
- </div>
-
- <div className="flex gap-3 pt-2">
- <button
- type="submit"
- disabled={saving}
- className="px-4 py-2 bg-port-accent hover:bg-port-accent/80 text-white rounded-lg transition-colors disabled:opacity-50"
- >
- {saving ? 'Saving...' : editingApp ? 'Save Changes' : 'Register App'}
- </button>
- <button
- type="button"
- onClick={handleCancel}
- className="px-4 py-2 bg-port-border hover:bg-port-border/80 text-gray-300 rounded-lg transition-colors"
- >
- Cancel
- </button>
- </div>
- </form>
- </div>
- )}
-
{/* Table */}
{apps.length === 0 ? (
<div className="bg-port-card border border-port-border rounded-xl p-12 text-center">
- <p className="text-gray-500">No apps registered yet</p>
+ <div className="text-4xl mb-4">📦</div>
+ <h3 className="text-xl font-semibold text-white mb-2">No apps registered</h3>
+ <p className="text-gray-500 mb-6">Add your first app to get started</p>
+ <Link
+ to="/create"
+ className="inline-block px-4 py-2 bg-port-accent hover:bg-port-accent/80 text-white rounded-lg transition-colors"
+ >
+ Add App
+ </Link>
</div>
) : (
<div className="bg-port-card border border-port-border rounded-xl overflow-hidden">
@@ -270,7 +68,7 @@ export default function Apps() {
<thead className="bg-port-border/50">
<tr>
<th className="text-left px-4 py-3 text-sm font-medium text-gray-400">Name</th>
- <th className="text-left px-4 py-3 text-sm font-medium text-gray-400">Type</th>
+ <th className="text-left px-4 py-3 text-sm font-medium text-gray-400">Path</th>
<th className="text-left px-4 py-3 text-sm font-medium text-gray-400">Ports</th>
<th className="text-left px-4 py-3 text-sm font-medium text-gray-400">Status</th>
<th className="text-right px-4 py-3 text-sm font-medium text-gray-400">Actions</th>
@@ -281,18 +79,26 @@ export default function Apps() {
<tr key={app.id} className="hover:bg-port-border/30">
<td className="px-4 py-3">
<div className="font-medium text-white">{app.name}</div>
- <div className="text-xs text-gray-500 truncate max-w-xs">{app.repoPath}</div>
+ <div className="text-xs text-gray-500">
+ {(app.pm2ProcessNames || []).join(', ')}
+ </div>
+ </td>
+ <td className="px-4 py-3">
+ <div className="text-sm text-gray-400 truncate max-w-xs" title={app.repoPath}>
+ {app.repoPath}
+ </div>
</td>
- <td className="px-4 py-3 text-sm text-gray-400">{app.type}</td>
<td className="px-4 py-3 text-sm text-gray-400">
- {[app.uiPort, app.apiPort].filter(Boolean).join(', ') || '-'}
+ {app.uiPort && <span className="mr-2">UI: {app.uiPort}</span>}
+ {app.apiPort && <span>API: {app.apiPort}</span>}
+ {!app.uiPort && !app.apiPort && '-'}
</td>
<td className="px-4 py-3">
<StatusBadge status={app.overallStatus} size="sm" />
</td>
<td className="px-4 py-3 text-right">
<button
- onClick={() => handleEdit(app)}
+ onClick={() => setEditingApp(app)}
className="text-sm text-port-accent hover:text-port-accent/80 mr-3"
>
Edit
@@ -311,6 +117,165 @@ export default function Apps() {
</div>
</div>
)}
+
+ {/* Edit Modal */}
+ {editingApp && (
+ <EditAppModal
+ app={editingApp}
+ onClose={() => setEditingApp(null)}
+ onSave={() => { setEditingApp(null); fetchApps(); }}
+ />
+ )}
+ </div>
+ );
+}
+
+function EditAppModal({ app, onClose, onSave }) {
+ const [formData, setFormData] = useState({
+ name: app.name,
+ repoPath: app.repoPath,
+ uiPort: app.uiPort || '',
+ apiPort: app.apiPort || '',
+ startCommands: (app.startCommands || []).join('\n'),
+ pm2ProcessNames: (app.pm2ProcessNames || []).join(', '),
+ editorCommand: app.editorCommand || 'code .'
+ });
+ const [saving, setSaving] = useState(false);
+ const [error, setError] = useState(null);
+
+ const handleSubmit = async (e) => {
+ e.preventDefault();
+ setError(null);
+ setSaving(true);
+
+ const data = {
+ name: formData.name,
+ repoPath: formData.repoPath,
+ uiPort: formData.uiPort ? parseInt(formData.uiPort) : null,
+ apiPort: formData.apiPort ? parseInt(formData.apiPort) : null,
+ startCommands: formData.startCommands.split('\n').filter(Boolean),
+ pm2ProcessNames: formData.pm2ProcessNames
+ ? formData.pm2ProcessNames.split(',').map(s => s.trim()).filter(Boolean)
+ : undefined,
+ editorCommand: formData.editorCommand || undefined
+ };
+
+ await api.updateApp(app.id, data).catch(err => {
+ setError(err.message);
+ setSaving(false);
+ throw err;
+ });
+
+ setSaving(false);
+ onSave();
+ };
+
+ return (
+ <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
+ <div className="bg-port-card border border-port-border rounded-xl p-6 w-full max-w-lg max-h-[90vh] overflow-auto">
+ <h2 className="text-xl font-bold text-white mb-4">Edit App</h2>
+
+ {error && (
+ <div className="mb-4 p-3 bg-port-error/20 border border-port-error rounded-lg text-port-error text-sm">
+ {error}
+ </div>
+ )}
+
+ <form onSubmit={handleSubmit} className="space-y-4">
+ <div>
+ <label className="block text-sm text-gray-400 mb-1">Name</label>
+ <input
+ type="text"
+ value={formData.name}
+ onChange={e => setFormData({ ...formData, name: e.target.value })}
+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white focus:border-port-accent focus:outline-none"
+ required
+ />
+ </div>
+
+ <div>
+ <label className="block text-sm text-gray-400 mb-1">Repository Path</label>
+ <input
+ type="text"
+ value={formData.repoPath}
+ onChange={e => setFormData({ ...formData, repoPath: e.target.value })}
+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white focus:border-port-accent focus:outline-none"
+ required
+ />
+ </div>
+
+ <div className="grid grid-cols-2 gap-4">
+ <div>
+ <label className="block text-sm text-gray-400 mb-1">UI Port</label>
+ <input
+ type="number"
+ value={formData.uiPort}
+ onChange={e => setFormData({ ...formData, uiPort: e.target.value })}
+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white focus:border-port-accent focus:outline-none"
+ placeholder="3000"
+ />
+ </div>
+
+ <div>
+ <label className="block text-sm text-gray-400 mb-1">API Port</label>
+ <input
+ type="number"
+ value={formData.apiPort}
+ onChange={e => setFormData({ ...formData, apiPort: e.target.value })}
+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white focus:border-port-accent focus:outline-none"
+ placeholder="3001"
+ />
+ </div>
+ </div>
+
+ <div>
+ <label className="block text-sm text-gray-400 mb-1">Start Commands (one per line)</label>
+ <textarea
+ value={formData.startCommands}
+ onChange={e => setFormData({ ...formData, startCommands: e.target.value })}
+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white focus:border-port-accent focus:outline-none font-mono text-sm"
+ rows={2}
+ />
+ </div>
+
+ <div>
+ <label className="block text-sm text-gray-400 mb-1">PM2 Process Names (comma-separated)</label>
+ <input
+ type="text"
+ value={formData.pm2ProcessNames}
+ onChange={e => setFormData({ ...formData, pm2ProcessNames: e.target.value })}
+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white focus:border-port-accent focus:outline-none"
+ />
+ </div>
+
+ <div>
+ <label className="block text-sm text-gray-400 mb-1">Editor Command</label>
+ <input
+ type="text"
+ value={formData.editorCommand}
+ onChange={e => setFormData({ ...formData, editorCommand: e.target.value })}
+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white focus:border-port-accent focus:outline-none"
+ />
+ </div>
+
+ <div className="flex justify-end gap-3 pt-4">
+ <button
+ type="button"
+ onClick={onClose}
+ className="px-4 py-2 text-gray-400 hover:text-white"
+ >
+ Cancel
+ </button>
+ <button
+ type="submit"
+ disabled={saving}
+ className="px-6 py-2 bg-port-accent hover:bg-port-accent/80 text-white rounded-lg transition-colors disabled:opacity-50"
+ >
+ {saving ? 'Saving...' : 'Save Changes'}
+ </button>
+ </div>
+ </form>
+ </div>
</div>
);
}
diff --git a/client/src/pages/CreateApp.jsx b/client/src/pages/CreateApp.jsx
new file mode 100644
index 0000000000..19e4ad350f
--- /dev/null
+++ b/client/src/pages/CreateApp.jsx
@@ -0,0 +1,307 @@
+import { useState, useEffect } from 'react';
+import { useNavigate } from 'react-router-dom';
+import * as api from '../services/api';
+
+export default function CreateApp() {
+ const navigate = useNavigate();
+
+ // Path input
+ const [repoPath, setRepoPath] = useState('');
+ const [pathValid, setPathValid] = useState(null);
+
+ // Detection state
+ const [detecting, setDetecting] = useState(false);
+ const [aiDetecting, setAiDetecting] = useState(false);
+ const [detected, setDetected] = useState(null);
+ const [hasAiProvider, setHasAiProvider] = useState(false);
+
+ // Form fields (populated by detection or manual entry)
+ const [name, setName] = useState('');
+ const [description, setDescription] = useState('');
+ const [uiPort, setUiPort] = useState('');
+ const [apiPort, setApiPort] = useState('');
+ const [startCommands, setStartCommands] = useState('npm run dev');
+ const [pm2Names, setPm2Names] = useState('');
+
+ // Submit state
+ const [submitting, setSubmitting] = useState(false);
+ const [error, setError] = useState(null);
+
+ // Check if AI provider is available
+ useEffect(() => {
+ api.getActiveProvider().then(p => setHasAiProvider(!!p)).catch(() => {});
+ }, []);
+
+ // Validate path on blur
+ const handlePathBlur = async () => {
+ if (!repoPath) {
+ setPathValid(null);
+ return;
+ }
+
+ setDetecting(true);
+ const result = await api.detectRepo(repoPath).catch(() => ({ valid: false }));
+ setPathValid(result.valid);
+ setDetecting(false);
+
+ if (result.valid) {
+ // Apply basic detection
+ if (result.packageJson?.name && !name) {
+ setName(result.packageJson.name);
+ }
+ if (result.startCommands?.length > 0 && startCommands === 'npm run dev') {
+ setStartCommands(result.startCommands.join('\n'));
+ }
+ if (result.detectedPorts?.vite && !uiPort) {
+ setUiPort(String(result.detectedPorts.vite));
+ }
+ if (result.detectedPorts?.main && !apiPort) {
+ setApiPort(String(result.detectedPorts.main));
+ }
+ }
+ };
+
+ // AI-powered detection
+ const handleAiDetect = async () => {
+ if (!repoPath || !pathValid) return;
+
+ setError(null);
+ setAiDetecting(true);
+
+ const result = await api.detectWithAi(repoPath).catch(err => ({
+ success: false,
+ error: err.message
+ }));
+
+ setAiDetecting(false);
+
+ if (!result.success) {
+ setError(result.error || 'AI detection failed');
+ return;
+ }
+
+ setDetected(result);
+
+ // Apply AI-detected values
+ const d = result.detected;
+ if (d.name) setName(d.name);
+ if (d.description) setDescription(d.description);
+ if (d.uiPort) setUiPort(String(d.uiPort));
+ if (d.apiPort) setApiPort(String(d.apiPort));
+ if (d.startCommands?.length > 0) setStartCommands(d.startCommands.join('\n'));
+ if (d.pm2ProcessNames?.length > 0) setPm2Names(d.pm2ProcessNames.join(', '));
+ };
+
+ // Submit form
+ const handleSubmit = async (e) => {
+ e.preventDefault();
+ setError(null);
+ setSubmitting(true);
+
+ const data = {
+ name,
+ repoPath,
+ uiPort: uiPort ? parseInt(uiPort) : null,
+ apiPort: apiPort ? parseInt(apiPort) : null,
+ startCommands: startCommands.split('\n').filter(Boolean),
+ pm2ProcessNames: pm2Names
+ ? pm2Names.split(',').map(s => s.trim()).filter(Boolean)
+ : [name.toLowerCase().replace(/[^a-z0-9]/g, '-')]
+ };
+
+ const result = await api.createApp(data).catch(err => {
+ setError(err.message);
+ return null;
+ });
+
+ setSubmitting(false);
+
+ if (result) {
+ navigate('/apps');
+ }
+ };
+
+ return (
+ <div className="max-w-2xl mx-auto">
+ <div className="mb-6">
+ <h1 className="text-2xl font-bold text-white">Add App</h1>
+ <p className="text-gray-500">Register an existing project with PortOS</p>
+ </div>
+
+ <form onSubmit={handleSubmit} className="space-y-6">
+ {/* Path Input */}
+ <div className="bg-port-card border border-port-border rounded-xl p-6">
+ <label className="block text-sm text-gray-400 mb-2">Project Directory</label>
+ <div className="flex gap-2">
+ <input
+ type="text"
+ value={repoPath}
+ onChange={(e) => { setRepoPath(e.target.value); setPathValid(null); setDetected(null); }}
+ onBlur={handlePathBlur}
+ placeholder="/Users/you/projects/my-app"
+ className="flex-1 px-4 py-3 bg-port-bg border border-port-border rounded-lg text-white focus:border-port-accent focus:outline-none font-mono"
+ />
+ {hasAiProvider && pathValid && (
+ <button
+ type="button"
+ onClick={handleAiDetect}
+ disabled={aiDetecting}
+ className="px-4 py-3 bg-port-accent hover:bg-port-accent/80 text-white rounded-lg transition-colors disabled:opacity-50 whitespace-nowrap"
+ >
+ {aiDetecting ? 'Detecting...' : 'Detect with AI'}
+ </button>
+ )}
+ </div>
+
+ {detecting && (
+ <p className="mt-2 text-sm text-gray-500">Validating path...</p>
+ )}
+
+ {pathValid === false && (
+ <p className="mt-2 text-sm text-port-error">Invalid directory path</p>
+ )}
+
+ {pathValid === true && !detected && (
+ <p className="mt-2 text-sm text-port-success">
+ Valid project directory
+ {hasAiProvider && ' — click "Detect with AI" for smart configuration'}
+ </p>
+ )}
+
+ {detected && (
+ <div className="mt-3 p-3 bg-port-success/10 border border-port-success/30 rounded-lg">
+ <p className="text-sm text-port-success font-medium">
+ AI Detection Complete ({detected.provider})
+ </p>
+ <p className="text-xs text-gray-400 mt-1">
+ {detected.context?.configFiles?.length > 0 && (
+ <>Config files found: {detected.context.configFiles.join(', ')}</>
+ )}
+ </p>
+ </div>
+ )}
+ </div>
+
+ {/* App Details */}
+ {pathValid && (
+ <div className="bg-port-card border border-port-border rounded-xl p-6 space-y-4">
+ <h3 className="text-lg font-semibold text-white mb-4">App Configuration</h3>
+
+ <div>
+ <label className="block text-sm text-gray-400 mb-1">App Name *</label>
+ <input
+ type="text"
+ value={name}
+ onChange={(e) => setName(e.target.value)}
+ placeholder="My Awesome App"
+ required
+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white focus:border-port-accent focus:outline-none"
+ />
+ </div>
+
+ <div>
+ <label className="block text-sm text-gray-400 mb-1">Description</label>
+ <input
+ type="text"
+ value={description}
+ onChange={(e) => setDescription(e.target.value)}
+ placeholder="A brief description of the app"
+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white focus:border-port-accent focus:outline-none"
+ />
+ </div>
+
+ <div className="grid grid-cols-2 gap-4">
+ <div>
+ <label className="block text-sm text-gray-400 mb-1">UI/Frontend Port</label>
+ <input
+ type="number"
+ value={uiPort}
+ onChange={(e) => setUiPort(e.target.value)}
+ placeholder="3000"
+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white focus:border-port-accent focus:outline-none"
+ />
+ </div>
+
+ <div>
+ <label className="block text-sm text-gray-400 mb-1">API/Backend Port</label>
+ <input
+ type="number"
+ value={apiPort}
+ onChange={(e) => setApiPort(e.target.value)}
+ placeholder="3001"
+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white focus:border-port-accent focus:outline-none"
+ />
+ </div>
+ </div>
+
+ <div>
+ <label className="block text-sm text-gray-400 mb-1">Start Commands (one per line)</label>
+ <textarea
+ value={startCommands}
+ onChange={(e) => setStartCommands(e.target.value)}
+ placeholder="npm run dev"
+ rows={2}
+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white focus:border-port-accent focus:outline-none font-mono text-sm"
+ />
+ <p className="text-xs text-gray-500 mt-1">
+ Commands to start your app. Multiple lines = multiple PM2 processes.
+ </p>
+ </div>
+
+ <div>
+ <label className="block text-sm text-gray-400 mb-1">PM2 Process Names (comma-separated)</label>
+ <input
+ type="text"
+ value={pm2Names}
+ onChange={(e) => setPm2Names(e.target.value)}
+ placeholder="my-app-ui, my-app-api"
+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white focus:border-port-accent focus:outline-none"
+ />
+ <p className="text-xs text-gray-500 mt-1">
+ Names for PM2 processes. Leave blank to auto-generate from app name.
+ </p>
+ </div>
+ </div>
+ )}
+
+ {/* Error Display */}
+ {error && (
+ <div className="p-4 bg-port-error/20 border border-port-error rounded-lg text-port-error">
+ {error}
+ </div>
+ )}
+
+ {/* Submit */}
+ {pathValid && (
+ <div className="flex justify-between items-center">
+ <button
+ type="button"
+ onClick={() => navigate(-1)}
+ className="px-4 py-2 text-gray-400 hover:text-white"
+ >
+ Cancel
+ </button>
+ <button
+ type="submit"
+ disabled={!name || submitting}
+ className="px-6 py-3 bg-port-success hover:bg-port-success/80 text-white rounded-lg transition-colors disabled:opacity-50"
+ >
+ {submitting ? 'Registering...' : 'Register App'}
+ </button>
+ </div>
+ )}
+ </form>
+
+ {/* No AI Provider Notice */}
+ {pathValid && !hasAiProvider && (
+ <div className="mt-6 p-4 bg-port-border/50 rounded-lg">
+ <p className="text-sm text-gray-400">
+ <strong className="text-white">Tip:</strong> Configure an AI provider in{' '}
+ <a href="/ai" className="text-port-accent hover:underline">AI Providers</a>{' '}
+ to enable smart auto-detection of app configuration.
+ </p>
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/client/src/pages/Dashboard.jsx b/client/src/pages/Dashboard.jsx
index 95bf265cb8..3247ac8aad 100644
--- a/client/src/pages/Dashboard.jsx
+++ b/client/src/pages/Dashboard.jsx
@@ -67,10 +67,10 @@ export default function Dashboard() {
Register your first app to get started
</p>
<Link
- to="/apps"
+ to="/create"
className="inline-block px-4 py-2 bg-port-accent hover:bg-port-accent/80 text-white rounded-lg transition-colors"
>
- Register App
+ Add App
</Link>
</div>
) : (
diff --git a/client/src/pages/DevTools.jsx b/client/src/pages/DevTools.jsx
new file mode 100644
index 0000000000..7727dcb18d
--- /dev/null
+++ b/client/src/pages/DevTools.jsx
@@ -0,0 +1,430 @@
+import { useState, useEffect, useRef } from 'react';
+import * as api from '../services/api';
+import socket from '../services/socket';
+
+const TABS = [
+ { id: 'history', label: 'History' },
+ { id: 'runner', label: 'Command Runner' },
+ { id: 'processes', label: 'Processes' }
+];
+
+export default function DevTools() {
+ const [activeTab, setActiveTab] = useState('history');
+
+ return (
+ <div className="space-y-6">
+ <div className="flex items-center justify-between">
+ <h1 className="text-2xl font-bold text-white">Dev Tools</h1>
+ </div>
+
+ {/* Tabs */}
+ <div className="flex gap-1 bg-port-card border border-port-border rounded-lg p-1">
+ {TABS.map(tab => (
+ <button
+ key={tab.id}
+ onClick={() => setActiveTab(tab.id)}
+ className={`flex-1 px-4 py-2 rounded-md text-sm font-medium transition-colors ${
+ activeTab === tab.id
+ ? 'bg-port-accent text-white'
+ : 'text-gray-400 hover:text-white hover:bg-port-border/50'
+ }`}
+ >
+ {tab.label}
+ </button>
+ ))}
+ </div>
+
+ {/* Tab Content */}
+ {activeTab === 'history' && <HistoryTab />}
+ {activeTab === 'runner' && <RunnerTab />}
+ {activeTab === 'processes' && <ProcessesTab />}
+ </div>
+ );
+}
+
+function HistoryTab() {
+ const [history, setHistory] = useState([]);
+ const [stats, setStats] = useState(null);
+ const [loading, setLoading] = useState(true);
+ const [filter, setFilter] = useState({ action: '', success: '' });
+ const [actions, setActions] = useState([]);
+
+ useEffect(() => {
+ loadData();
+ }, [filter]);
+
+ const loadData = async () => {
+ setLoading(true);
+ const [historyData, statsData, actionsData] = await Promise.all([
+ api.getHistory({
+ limit: 100,
+ action: filter.action || undefined,
+ success: filter.success !== '' ? filter.success === 'true' : undefined
+ }).catch(() => ({ entries: [] })),
+ api.getHistoryStats().catch(() => null),
+ api.getHistoryActions().catch(() => [])
+ ]);
+ setHistory(historyData.entries || []);
+ setStats(statsData);
+ setActions(actionsData);
+ setLoading(false);
+ };
+
+ const handleClear = async () => {
+ if (confirm('Clear all history?')) {
+ await api.clearHistory();
+ loadData();
+ }
+ };
+
+ const formatTime = (timestamp) => {
+ const date = new Date(timestamp);
+ const now = new Date();
+ const diff = now - date;
+
+ if (diff < 60000) return 'Just now';
+ if (diff < 3600000) return `${Math.floor(diff / 60000)}m ago`;
+ if (diff < 86400000) return `${Math.floor(diff / 3600000)}h ago`;
+ return date.toLocaleDateString();
+ };
+
+ const getActionIcon = (action) => {
+ const icons = {
+ start: '▶️',
+ stop: '⏹️',
+ restart: '🔄',
+ command: '💻',
+ scaffold: '🏗️',
+ 'ai-run': '🤖'
+ };
+ return icons[action] || '📋';
+ };
+
+ if (loading) {
+ return <div className="text-center py-8 text-gray-400">Loading history...</div>;
+ }
+
+ return (
+ <div className="space-y-4">
+ {/* Stats */}
+ {stats && (
+ <div className="grid grid-cols-4 gap-4">
+ <div className="bg-port-card border border-port-border rounded-lg p-4 text-center">
+ <div className="text-2xl font-bold text-white">{stats.total}</div>
+ <div className="text-sm text-gray-400">Total Actions</div>
+ </div>
+ <div className="bg-port-card border border-port-border rounded-lg p-4 text-center">
+ <div className="text-2xl font-bold text-port-success">{stats.successRate}%</div>
+ <div className="text-sm text-gray-400">Success Rate</div>
+ </div>
+ <div className="bg-port-card border border-port-border rounded-lg p-4 text-center">
+ <div className="text-2xl font-bold text-white">{stats.last24h}</div>
+ <div className="text-sm text-gray-400">Last 24h</div>
+ </div>
+ <div className="bg-port-card border border-port-border rounded-lg p-4 text-center">
+ <div className="text-2xl font-bold text-white">{Object.keys(stats.byAction).length}</div>
+ <div className="text-sm text-gray-400">Action Types</div>
+ </div>
+ </div>
+ )}
+
+ {/* Filters */}
+ <div className="flex gap-4 items-center">
+ <select
+ value={filter.action}
+ onChange={(e) => setFilter(prev => ({ ...prev, action: e.target.value }))}
+ className="px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white"
+ >
+ <option value="">All Actions</option>
+ {actions.map(action => (
+ <option key={action} value={action}>{action}</option>
+ ))}
+ </select>
+
+ <select
+ value={filter.success}
+ onChange={(e) => setFilter(prev => ({ ...prev, success: e.target.value }))}
+ className="px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white"
+ >
+ <option value="">All Results</option>
+ <option value="true">Success</option>
+ <option value="false">Failed</option>
+ </select>
+
+ <div className="flex-1" />
+
+ <button
+ onClick={handleClear}
+ className="px-4 py-2 bg-port-error/20 text-port-error hover:bg-port-error/30 rounded-lg transition-colors"
+ >
+ Clear History
+ </button>
+ </div>
+
+ {/* History List */}
+ <div className="bg-port-card border border-port-border rounded-xl overflow-hidden">
+ {history.length === 0 ? (
+ <div className="text-center py-12 text-gray-500">No history entries</div>
+ ) : (
+ <div className="divide-y divide-port-border">
+ {history.map(entry => (
+ <div key={entry.id} className="p-4 hover:bg-port-border/20">
+ <div className="flex items-center gap-4">
+ <span className="text-xl">{getActionIcon(entry.action)}</span>
+ <div className="flex-1">
+ <div className="flex items-center gap-2">
+ <span className="font-medium text-white">{entry.action}</span>
+ {entry.targetName && (
+ <span className="text-gray-400">→ {entry.targetName}</span>
+ )}
+ </div>
+ {entry.details?.command && (
+ <code className="text-xs text-gray-500 font-mono">{entry.details.command}</code>
+ )}
+ </div>
+ <span className={`w-2 h-2 rounded-full ${entry.success ? 'bg-port-success' : 'bg-port-error'}`} />
+ <span className="text-sm text-gray-500">{formatTime(entry.timestamp)}</span>
+ </div>
+ {entry.error && (
+ <div className="mt-2 text-sm text-port-error ml-10">{entry.error}</div>
+ )}
+ </div>
+ ))}
+ </div>
+ )}
+ </div>
+ </div>
+ );
+}
+
+function RunnerTab() {
+ const [command, setCommand] = useState('');
+ const [workspacePath, setWorkspacePath] = useState('');
+ const [output, setOutput] = useState('');
+ const [running, setRunning] = useState(false);
+ const [commandId, setCommandId] = useState(null);
+ const [apps, setApps] = useState([]);
+ const [allowedCommands, setAllowedCommands] = useState([]);
+ const outputRef = useRef(null);
+
+ useEffect(() => {
+ api.getApps().then(setApps).catch(() => []);
+ api.getAllowedCommands().then(setAllowedCommands).catch(() => []);
+ }, []);
+
+ useEffect(() => {
+ if (!commandId) return;
+
+ const handleData = ({ data }) => {
+ setOutput(prev => prev + data);
+ if (outputRef.current) {
+ outputRef.current.scrollTop = outputRef.current.scrollHeight;
+ }
+ };
+
+ const handleComplete = (result) => {
+ setRunning(false);
+ setCommandId(null);
+ setOutput(prev => prev + `\n--- Command finished (exit code: ${result.exitCode}) ---\n`);
+ };
+
+ socket.on(`command:${commandId}:data`, handleData);
+ socket.on(`command:${commandId}:complete`, handleComplete);
+
+ return () => {
+ socket.off(`command:${commandId}:data`, handleData);
+ socket.off(`command:${commandId}:complete`, handleComplete);
+ };
+ }, [commandId]);
+
+ const handleRun = async () => {
+ if (!command.trim()) return;
+
+ setOutput('');
+ setRunning(true);
+
+ const result = await api.executeCommand(command, workspacePath || undefined)
+ .catch(err => ({ error: err.message }));
+
+ if (result.error) {
+ setOutput(`Error: ${result.error}`);
+ setRunning(false);
+ return;
+ }
+
+ setCommandId(result.commandId);
+ };
+
+ const handleStop = async () => {
+ if (commandId) {
+ await api.stopCommand(commandId);
+ setRunning(false);
+ setCommandId(null);
+ }
+ };
+
+ return (
+ <div className="space-y-4">
+ {/* Workspace Selector */}
+ <div className="flex gap-4">
+ <select
+ value={workspacePath}
+ onChange={(e) => setWorkspacePath(e.target.value)}
+ className="px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white"
+ >
+ <option value="">Current directory</option>
+ {apps.map(app => (
+ <option key={app.id} value={app.repoPath}>{app.name} ({app.repoPath})</option>
+ ))}
+ </select>
+ </div>
+
+ {/* Command Input */}
+ <div className="flex gap-2">
+ <input
+ type="text"
+ value={command}
+ onChange={(e) => setCommand(e.target.value)}
+ onKeyDown={(e) => e.key === 'Enter' && !running && handleRun()}
+ placeholder="Enter command (e.g., npm run build)"
+ className="flex-1 px-4 py-3 bg-port-bg border border-port-border rounded-lg text-white font-mono focus:border-port-accent focus:outline-none"
+ />
+ {running ? (
+ <button
+ onClick={handleStop}
+ className="px-6 py-3 bg-port-error hover:bg-port-error/80 text-white rounded-lg transition-colors"
+ >
+ Stop
+ </button>
+ ) : (
+ <button
+ onClick={handleRun}
+ disabled={!command.trim()}
+ className="px-6 py-3 bg-port-success hover:bg-port-success/80 text-white rounded-lg transition-colors disabled:opacity-50"
+ >
+ Run
+ </button>
+ )}
+ </div>
+
+ {/* Allowed Commands Info */}
+ <div className="text-xs text-gray-500">
+ Allowed: {allowedCommands.slice(0, 10).join(', ')}{allowedCommands.length > 10 ? `, +${allowedCommands.length - 10} more` : ''}
+ </div>
+
+ {/* Output */}
+ <div
+ ref={outputRef}
+ className="bg-port-bg border border-port-border rounded-lg p-4 h-96 overflow-auto font-mono text-sm"
+ >
+ {output ? (
+ <pre className="text-gray-300 whitespace-pre-wrap">{output}</pre>
+ ) : (
+ <div className="text-gray-500">Output will appear here...</div>
+ )}
+ </div>
+ </div>
+ );
+}
+
+function ProcessesTab() {
+ const [processes, setProcesses] = useState([]);
+ const [loading, setLoading] = useState(true);
+
+ useEffect(() => {
+ loadProcesses();
+ const interval = setInterval(loadProcesses, 5000);
+ return () => clearInterval(interval);
+ }, []);
+
+ const loadProcesses = async () => {
+ const data = await api.getProcessesList().catch(() => []);
+ setProcesses(data);
+ setLoading(false);
+ };
+
+ const formatMemory = (bytes) => {
+ if (!bytes) return '0 MB';
+ return `${(bytes / 1024 / 1024).toFixed(1)} MB`;
+ };
+
+ const formatUptime = (ms) => {
+ if (!ms) return '-';
+ const hours = Math.floor(ms / 3600000);
+ const mins = Math.floor((ms % 3600000) / 60000);
+ if (hours > 24) {
+ return `${Math.floor(hours / 24)}d ${hours % 24}h`;
+ }
+ return `${hours}h ${mins}m`;
+ };
+
+ const getStatusColor = (status) => {
+ switch (status) {
+ case 'online': return 'bg-port-success';
+ case 'stopped': return 'bg-gray-500';
+ case 'errored': return 'bg-port-error';
+ default: return 'bg-port-warning';
+ }
+ };
+
+ if (loading) {
+ return <div className="text-center py-8 text-gray-400">Loading processes...</div>;
+ }
+
+ return (
+ <div className="space-y-4">
+ <div className="flex justify-between items-center">
+ <p className="text-gray-400">{processes.length} PM2 processes</p>
+ <button
+ onClick={loadProcesses}
+ className="px-4 py-2 bg-port-border hover:bg-port-border/80 text-white rounded-lg transition-colors"
+ >
+ Refresh
+ </button>
+ </div>
+
+ <div className="bg-port-card border border-port-border rounded-xl overflow-hidden">
+ <table className="w-full">
+ <thead className="bg-port-border/50">
+ <tr>
+ <th className="px-4 py-3 text-left text-sm font-medium text-gray-400">Name</th>
+ <th className="px-4 py-3 text-left text-sm font-medium text-gray-400">Status</th>
+ <th className="px-4 py-3 text-left text-sm font-medium text-gray-400">PID</th>
+ <th className="px-4 py-3 text-left text-sm font-medium text-gray-400">CPU</th>
+ <th className="px-4 py-3 text-left text-sm font-medium text-gray-400">Memory</th>
+ <th className="px-4 py-3 text-left text-sm font-medium text-gray-400">Uptime</th>
+ <th className="px-4 py-3 text-left text-sm font-medium text-gray-400">Restarts</th>
+ </tr>
+ </thead>
+ <tbody className="divide-y divide-port-border">
+ {processes.map(proc => (
+ <tr key={proc.pm_id} className="hover:bg-port-border/20">
+ <td className="px-4 py-3">
+ <span className="font-medium text-white">{proc.name}</span>
+ </td>
+ <td className="px-4 py-3">
+ <span className={`inline-flex items-center gap-2 px-2 py-1 rounded text-xs ${getStatusColor(proc.status)} bg-opacity-20`}>
+ <span className={`w-2 h-2 rounded-full ${getStatusColor(proc.status)}`} />
+ {proc.status}
+ </span>
+ </td>
+ <td className="px-4 py-3 text-gray-400 font-mono text-sm">{proc.pid || '-'}</td>
+ <td className="px-4 py-3 text-gray-400">{proc.cpu ? `${proc.cpu}%` : '-'}</td>
+ <td className="px-4 py-3 text-gray-400">{formatMemory(proc.memory)}</td>
+ <td className="px-4 py-3 text-gray-400">{formatUptime(proc.uptime)}</td>
+ <td className="px-4 py-3 text-gray-400">{proc.restarts}</td>
+ </tr>
+ ))}
+ {processes.length === 0 && (
+ <tr>
+ <td colSpan={7} className="px-4 py-12 text-center text-gray-500">
+ No PM2 processes running
+ </td>
+ </tr>
+ )}
+ </tbody>
+ </table>
+ </div>
+ </div>
+ );
+}
diff --git a/client/src/pages/Logs.jsx b/client/src/pages/Logs.jsx
new file mode 100644
index 0000000000..5d6d799855
--- /dev/null
+++ b/client/src/pages/Logs.jsx
@@ -0,0 +1,281 @@
+import { useState, useEffect, useCallback } from 'react';
+import LogViewer from '../components/LogViewer';
+import StatusBadge from '../components/StatusBadge';
+import * as api from '../services/api';
+import socket, { subscribeToLogs } from '../services/socket';
+
+const LINES_OPTIONS = [50, 100, 200, 500, 1000];
+
+export default function Logs() {
+ const [processes, setProcesses] = useState([]);
+ const [selectedProcess, setSelectedProcess] = useState('');
+ const [logs, setLogs] = useState([]);
+ const [streaming, setStreaming] = useState(false);
+ const [lines, setLines] = useState(100);
+ const [loading, setLoading] = useState(true);
+ const [filter, setFilter] = useState('');
+ const [cleanupFn, setCleanupFn] = useState(null);
+ const [connected, setConnected] = useState(socket.connected);
+
+ // Track socket connection status
+ useEffect(() => {
+ const onConnect = () => setConnected(true);
+ const onDisconnect = () => {
+ setConnected(false);
+ setStreaming(false);
+ };
+
+ socket.on('connect', onConnect);
+ socket.on('disconnect', onDisconnect);
+
+ return () => {
+ socket.off('connect', onConnect);
+ socket.off('disconnect', onDisconnect);
+ };
+ }, []);
+
+ // Fetch PM2 processes
+ useEffect(() => {
+ const fetchProcesses = async () => {
+ const procs = await api.getProcesses().catch(() => []);
+ setProcesses(procs);
+ if (procs.length > 0 && !selectedProcess) {
+ setSelectedProcess(procs[0].name);
+ }
+ setLoading(false);
+ };
+ fetchProcesses();
+ const interval = setInterval(fetchProcesses, 10000);
+ return () => clearInterval(interval);
+ }, []);
+
+ // Stop streaming on unmount
+ useEffect(() => {
+ return () => {
+ if (cleanupFn) cleanupFn();
+ };
+ }, [cleanupFn]);
+
+ const fetchLogs = async () => {
+ if (!selectedProcess) return;
+ setLoading(true);
+ const result = await api.getProcessLogs(selectedProcess, lines).catch(() => ({ logs: '' }));
+ const logLines = (result.logs || '').split('\n').filter(Boolean).map(line => ({
+ line,
+ type: 'stdout',
+ timestamp: Date.now()
+ }));
+ setLogs(logLines);
+ setLoading(false);
+ };
+
+ const startStreaming = useCallback(() => {
+ if (!selectedProcess || streaming || !connected) return;
+
+ setLogs([]);
+ setStreaming(true);
+
+ const cleanup = subscribeToLogs(selectedProcess, lines, {
+ onLine: (data) => {
+ setLogs(prev => [...prev, data]);
+ },
+ onSubscribed: (data) => {
+ setLogs(prev => [...prev, {
+ type: 'connected',
+ line: `Connected to ${data.processName}`,
+ timestamp: data.timestamp
+ }]);
+ },
+ onError: (data) => {
+ console.error('Stream error:', data);
+ setLogs(prev => [...prev, {
+ type: 'error',
+ line: `Error: ${data.error}`,
+ timestamp: Date.now()
+ }]);
+ },
+ onClose: (data) => {
+ setStreaming(false);
+ setLogs(prev => [...prev, {
+ type: 'connected',
+ line: `Stream closed (code: ${data.code})`,
+ timestamp: Date.now()
+ }]);
+ }
+ });
+
+ setCleanupFn(() => cleanup);
+ }, [selectedProcess, lines, streaming, connected]);
+
+ const stopStreaming = useCallback(() => {
+ if (cleanupFn) {
+ cleanupFn();
+ setCleanupFn(null);
+ }
+ setStreaming(false);
+ setLogs(prev => [...prev, { type: 'connected', line: 'Streaming stopped', timestamp: Date.now() }]);
+ }, [cleanupFn]);
+
+ const clearLogs = () => setLogs([]);
+
+ const filteredLogs = filter
+ ? logs.filter(log => (log.line || '').toLowerCase().includes(filter.toLowerCase()))
+ : logs;
+
+ const getProcessStatus = (name) => {
+ const proc = processes.find(p => p.name === name);
+ return proc?.status || 'unknown';
+ };
+
+ if (loading && processes.length === 0) {
+ return (
+ <div className="flex items-center justify-center h-64">
+ <div className="text-gray-500">Loading processes...</div>
+ </div>
+ );
+ }
+
+ return (
+ <div className="space-y-4">
+ {/* Header */}
+ <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
+ <div>
+ <h2 className="text-2xl font-bold text-white">Logs</h2>
+ <p className="text-gray-500">View and stream PM2 process logs</p>
+ </div>
+ <div className="flex items-center gap-2">
+ <span className={`w-2 h-2 rounded-full ${connected ? 'bg-port-success' : 'bg-port-error'}`} />
+ <span className="text-sm text-gray-400">
+ {connected ? 'Socket connected' : 'Socket disconnected'}
+ </span>
+ </div>
+ </div>
+
+ {/* Controls */}
+ <div className="bg-port-card border border-port-border rounded-lg p-4">
+ <div className="flex flex-col lg:flex-row gap-4">
+ {/* Process selector */}
+ <div className="flex-1">
+ <label className="block text-sm text-gray-400 mb-1">Process</label>
+ <select
+ value={selectedProcess}
+ onChange={(e) => {
+ if (streaming) stopStreaming();
+ setSelectedProcess(e.target.value);
+ setLogs([]);
+ }}
+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white focus:border-port-accent focus:outline-none"
+ disabled={streaming}
+ >
+ <option value="">Select a process...</option>
+ {processes.map(proc => (
+ <option key={proc.name} value={proc.name}>
+ {proc.name} ({proc.status})
+ </option>
+ ))}
+ </select>
+ </div>
+
+ {/* Lines */}
+ <div className="w-full lg:w-32">
+ <label className="block text-sm text-gray-400 mb-1">Lines</label>
+ <select
+ value={lines}
+ onChange={(e) => setLines(parseInt(e.target.value))}
+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white focus:border-port-accent focus:outline-none"
+ disabled={streaming}
+ >
+ {LINES_OPTIONS.map(n => (
+ <option key={n} value={n}>{n}</option>
+ ))}
+ </select>
+ </div>
+
+ {/* Filter */}
+ <div className="flex-1">
+ <label className="block text-sm text-gray-400 mb-1">Filter</label>
+ <input
+ type="text"
+ value={filter}
+ onChange={(e) => setFilter(e.target.value)}
+ placeholder="Search logs..."
+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white focus:border-port-accent focus:outline-none"
+ />
+ </div>
+ </div>
+
+ {/* Action buttons */}
+ <div className="flex flex-wrap gap-2 mt-4">
+ <button
+ onClick={fetchLogs}
+ disabled={!selectedProcess || streaming}
+ className="px-4 py-2 bg-port-border hover:bg-port-border/80 text-white rounded-lg transition-colors disabled:opacity-50"
+ >
+ Fetch Logs
+ </button>
+
+ {!streaming ? (
+ <button
+ onClick={startStreaming}
+ disabled={!selectedProcess || !connected}
+ className="px-4 py-2 bg-port-success hover:bg-port-success/80 text-white rounded-lg transition-colors disabled:opacity-50"
+ >
+ Start Streaming
+ </button>
+ ) : (
+ <button
+ onClick={stopStreaming}
+ className="px-4 py-2 bg-port-error hover:bg-port-error/80 text-white rounded-lg transition-colors"
+ >
+ Stop Streaming
+ </button>
+ )}
+
+ <button
+ onClick={clearLogs}
+ className="px-4 py-2 bg-port-border hover:bg-port-border/80 text-gray-300 rounded-lg transition-colors"
+ >
+ Clear
+ </button>
+
+ {streaming && (
+ <div className="flex items-center gap-2 ml-auto">
+ <span className="w-2 h-2 rounded-full bg-port-success animate-pulse" />
+ <span className="text-sm text-port-success">Streaming live</span>
+ </div>
+ )}
+ </div>
+ </div>
+
+ {/* Selected process info */}
+ {selectedProcess && (
+ <div className="flex items-center gap-3 flex-wrap">
+ <span className="text-gray-400">Viewing:</span>
+ <span className="font-medium text-white">{selectedProcess}</span>
+ <StatusBadge status={getProcessStatus(selectedProcess)} size="sm" />
+ <span className="text-gray-500 text-sm">
+ {filteredLogs.length} lines {filter && '(filtered)'}
+ </span>
+ </div>
+ )}
+
+ {/* Log viewer */}
+ <LogViewer
+ logs={filteredLogs}
+ autoScroll={streaming}
+ maxHeight="calc(100vh - 400px)"
+ />
+
+ {/* Empty state */}
+ {processes.length === 0 && (
+ <div className="bg-port-card border border-port-border rounded-lg p-8 text-center">
+ <div className="text-4xl mb-4">📋</div>
+ <h3 className="text-lg font-semibold text-white mb-2">No PM2 processes found</h3>
+ <p className="text-gray-500">
+ Start an app from the Dashboard to see its logs here.
+ </p>
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/client/src/services/api.js b/client/src/services/api.js
index da4f46aee1..c44ecfe554 100644
--- a/client/src/services/api.js
+++ b/client/src/services/api.js
@@ -62,3 +62,132 @@ export const allocatePorts = (count = 1) => request('/ports/allocate', {
method: 'POST',
body: JSON.stringify({ count })
});
+
+// Logs
+export const getProcesses = () => request('/logs/processes');
+export const getProcessLogs = (processName, lines = 100) =>
+ request(`/logs/${encodeURIComponent(processName)}?lines=${lines}`);
+
+/**
+ * Create SSE connection for streaming logs
+ * @param {string} processName - PM2 process name
+ * @param {number} lines - Initial lines to fetch
+ * @param {function} onMessage - Callback for each log line
+ * @param {function} onError - Error callback
+ * @returns {function} Cleanup function to close connection
+ */
+export const streamLogs = (processName, lines, onMessage, onError) => {
+ const url = `/api/logs/${encodeURIComponent(processName)}?follow=true&lines=${lines}`;
+ const eventSource = new EventSource(url);
+
+ eventSource.addEventListener('stdout', (e) => {
+ const data = JSON.parse(e.data);
+ onMessage({ ...data, type: 'stdout' });
+ });
+
+ eventSource.addEventListener('stderr', (e) => {
+ const data = JSON.parse(e.data);
+ onMessage({ ...data, type: 'stderr' });
+ });
+
+ eventSource.addEventListener('connected', (e) => {
+ const data = JSON.parse(e.data);
+ onMessage({ type: 'connected', ...data });
+ });
+
+ eventSource.addEventListener('error', (e) => {
+ onError?.(e);
+ });
+
+ eventSource.addEventListener('close', () => {
+ eventSource.close();
+ });
+
+ return () => eventSource.close();
+};
+
+// Detect
+export const detectRepo = (path) => request('/detect/repo', {
+ method: 'POST',
+ body: JSON.stringify({ path })
+});
+
+export const detectPort = (port) => request('/detect/port', {
+ method: 'POST',
+ body: JSON.stringify({ port })
+});
+
+export const detectPm2 = (name) => request('/detect/pm2', {
+ method: 'POST',
+ body: JSON.stringify({ name })
+});
+
+export const detectWithAi = (path, providerId) => request('/detect/ai', {
+ method: 'POST',
+ body: JSON.stringify({ path, providerId })
+});
+
+// Templates & Scaffold
+export const getTemplates = () => request('/templates');
+
+export const scaffoldApp = (data) => request('/scaffold', {
+ method: 'POST',
+ body: JSON.stringify(data)
+});
+
+// Providers
+export const getProviders = () => request('/providers');
+export const getActiveProvider = () => request('/providers/active');
+export const setActiveProvider = (id) => request('/providers/active', {
+ method: 'PUT',
+ body: JSON.stringify({ id })
+});
+export const getProvider = (id) => request(`/providers/${id}`);
+export const createProvider = (data) => request('/providers', {
+ method: 'POST',
+ body: JSON.stringify(data)
+});
+export const updateProvider = (id, data) => request(`/providers/${id}`, {
+ method: 'PUT',
+ body: JSON.stringify(data)
+});
+export const deleteProvider = (id) => request(`/providers/${id}`, { method: 'DELETE' });
+export const testProvider = (id) => request(`/providers/${id}/test`, { method: 'POST' });
+export const refreshProviderModels = (id) => request(`/providers/${id}/refresh-models`, { method: 'POST' });
+
+// Runs
+export const getRuns = (limit = 50, offset = 0) =>
+ request(`/runs?limit=${limit}&offset=${offset}`);
+export const createRun = (data) => request('/runs', {
+ method: 'POST',
+ body: JSON.stringify(data)
+});
+export const getRun = (id) => request(`/runs/${id}`);
+export const getRunOutput = (id) => request(`/runs/${id}/output`);
+export const stopRun = (id) => request(`/runs/${id}/stop`, { method: 'POST' });
+export const deleteRun = (id) => request(`/runs/${id}`, { method: 'DELETE' });
+
+// History
+export const getHistory = (options = {}) => {
+ const params = new URLSearchParams();
+ if (options.limit) params.set('limit', options.limit);
+ if (options.offset) params.set('offset', options.offset);
+ if (options.action) params.set('action', options.action);
+ if (options.success !== undefined) params.set('success', options.success);
+ return request(`/history?${params}`);
+};
+export const getHistoryStats = () => request('/history/stats');
+export const getHistoryActions = () => request('/history/actions');
+export const clearHistory = (olderThanDays) => request(
+ olderThanDays ? `/history?olderThanDays=${olderThanDays}` : '/history',
+ { method: 'DELETE' }
+);
+
+// Commands
+export const executeCommand = (command, workspacePath) => request('/commands/execute', {
+ method: 'POST',
+ body: JSON.stringify({ command, workspacePath })
+});
+export const stopCommand = (id) => request(`/commands/${id}/stop`, { method: 'POST' });
+export const getAllowedCommands = () => request('/commands/allowed');
+export const getProcessesList = () => request('/commands/processes');
diff --git a/client/src/services/socket.js b/client/src/services/socket.js
new file mode 100644
index 0000000000..2a23b6c08e
--- /dev/null
+++ b/client/src/services/socket.js
@@ -0,0 +1,85 @@
+import { io } from 'socket.io-client';
+
+// Connect to Socket.IO using relative path (works with Tailscale)
+// The connection will use the same host the page was loaded from
+const socket = io({
+ path: '/socket.io',
+ transports: ['websocket', 'polling'],
+ autoConnect: true,
+ reconnection: true,
+ reconnectionAttempts: 10,
+ reconnectionDelay: 1000
+});
+
+socket.on('connect', () => {
+ console.log('Socket connected:', socket.id);
+});
+
+socket.on('disconnect', (reason) => {
+ console.log('Socket disconnected:', reason);
+});
+
+socket.on('connect_error', (error) => {
+ console.error('Socket connection error:', error.message);
+});
+
+export default socket;
+
+/**
+ * Subscribe to log streaming for a process
+ * @param {string} processName - PM2 process name
+ * @param {number} lines - Initial lines to fetch
+ * @param {function} onLine - Callback for each log line
+ * @param {function} onSubscribed - Callback when subscribed
+ * @param {function} onError - Error callback
+ * @returns {function} Cleanup function
+ */
+export function subscribeToLogs(processName, lines, { onLine, onSubscribed, onError, onClose }) {
+ const handleLine = (data) => {
+ if (data.processName === processName) {
+ onLine?.(data);
+ }
+ };
+
+ const handleSubscribed = (data) => {
+ if (data.processName === processName) {
+ onSubscribed?.(data);
+ }
+ };
+
+ const handleError = (data) => {
+ if (data.processName === processName) {
+ onError?.(data);
+ }
+ };
+
+ const handleClose = (data) => {
+ if (data.processName === processName) {
+ onClose?.(data);
+ }
+ };
+
+ socket.on('logs:line', handleLine);
+ socket.on('logs:subscribed', handleSubscribed);
+ socket.on('logs:error', handleError);
+ socket.on('logs:close', handleClose);
+
+ // Start subscription
+ socket.emit('logs:subscribe', { processName, lines });
+
+ // Return cleanup function
+ return () => {
+ socket.off('logs:line', handleLine);
+ socket.off('logs:subscribed', handleSubscribed);
+ socket.off('logs:error', handleError);
+ socket.off('logs:close', handleClose);
+ socket.emit('logs:unsubscribe');
+ };
+}
+
+/**
+ * Check if socket is connected
+ */
+export function isConnected() {
+ return socket.connected;
+}
diff --git a/client/vite.config.js b/client/vite.config.js
index 807ff51e72..275b5e057e 100644
--- a/client/vite.config.js
+++ b/client/vite.config.js
@@ -4,12 +4,17 @@ import react from '@vitejs/plugin-react';
export default defineConfig({
plugins: [react()],
server: {
- host: '127.0.0.1',
+ host: '0.0.0.0',
port: 5555,
proxy: {
'/api': {
- target: 'http://127.0.0.1:5554',
+ target: 'http://localhost:5554',
changeOrigin: true
+ },
+ '/socket.io': {
+ target: 'http://localhost:5554',
+ changeOrigin: true,
+ ws: true
}
}
}
diff --git a/ecosystem.config.cjs b/ecosystem.config.cjs
index a3b7dfa2fd..cf3b326b1b 100644
--- a/ecosystem.config.cjs
+++ b/ecosystem.config.cjs
@@ -8,12 +8,12 @@ module.exports = {
env: {
NODE_ENV: 'development',
PORT: 5554,
- HOST: '127.0.0.1'
+ HOST: '0.0.0.0'
},
env_production: {
NODE_ENV: 'production',
PORT: 5554,
- HOST: '127.0.0.1'
+ HOST: '0.0.0.0'
},
watch: false,
max_memory_restart: '500M'
@@ -22,7 +22,7 @@ module.exports = {
name: 'portos-client',
script: 'node_modules/.bin/vite',
cwd: `${__dirname}/client`,
- args: '--host 127.0.0.1 --port 5555',
+ args: '--host 0.0.0.0 --port 5555',
env: {
NODE_ENV: 'development'
},
diff --git a/server/index.js b/server/index.js
index ae17eb35d0..cfe4689e13 100644
--- a/server/index.js
+++ b/server/index.js
@@ -1,30 +1,64 @@
import express from 'express';
import cors from 'cors';
+import { createServer } from 'http';
+import { Server } from 'socket.io';
import { fileURLToPath } from 'url';
-import { dirname, join } from 'path';
+import { dirname } from 'path';
import healthRoutes from './routes/health.js';
import appsRoutes from './routes/apps.js';
import portsRoutes from './routes/ports.js';
+import logsRoutes from './routes/logs.js';
+import detectRoutes from './routes/detect.js';
+import scaffoldRoutes from './routes/scaffold.js';
+import providersRoutes from './routes/providers.js';
+import runsRoutes from './routes/runs.js';
+import historyRoutes from './routes/history.js';
+import commandsRoutes from './routes/commands.js';
+import { initSocket } from './services/socket.js';
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const app = express();
+const httpServer = createServer(app);
const PORT = process.env.PORT || 5554;
-const HOST = process.env.HOST || '127.0.0.1';
+const HOST = process.env.HOST || '0.0.0.0';
-// Middleware
+// Socket.IO with relative path support for Tailscale
+const io = new Server(httpServer, {
+ cors: {
+ origin: true, // Allow any origin (local network only)
+ credentials: true
+ },
+ path: '/socket.io'
+});
+
+// Initialize socket handlers
+initSocket(io);
+
+// Middleware - allow any origin for Tailscale access
app.use(cors({
- origin: ['http://localhost:5555', 'http://127.0.0.1:5555'],
+ origin: true,
credentials: true
}));
app.use(express.json());
+// Make io available to routes
+app.set('io', io);
+
// API Routes
app.use('/api', healthRoutes);
app.use('/api/apps', appsRoutes);
app.use('/api/ports', portsRoutes);
+app.use('/api/logs', logsRoutes);
+app.use('/api/detect', detectRoutes);
+app.use('/api/scaffold', scaffoldRoutes);
+app.use('/api', scaffoldRoutes); // Also mount at /api for /api/templates
+app.use('/api/providers', providersRoutes);
+app.use('/api/runs', runsRoutes);
+app.use('/api/history', historyRoutes);
+app.use('/api/commands', commandsRoutes);
// Error handler
app.use((err, req, res, next) => {
@@ -43,6 +77,6 @@ app.use((req, res) => {
});
});
-app.listen(PORT, HOST, () => {
+httpServer.listen(PORT, HOST, () => {
console.log(`PortOS server running at http://${HOST}:${PORT}`);
});
diff --git a/server/lib/validation.js b/server/lib/validation.js
index 8e6f9b37b5..2cacf1ba1a 100644
--- a/server/lib/validation.js
+++ b/server/lib/validation.js
@@ -4,15 +4,16 @@ import { z } from 'zod';
export const appSchema = z.object({
name: z.string().min(1).max(100),
repoPath: z.string().min(1),
- type: z.enum(['vite+express', 'single-node-server', 'static']),
- uiPort: z.number().int().min(1).max(65535).optional(),
- apiPort: z.number().int().min(1).max(65535).optional(),
+ type: z.string().optional().default('express'),
+ uiPort: z.number().int().min(1).max(65535).nullable().optional(),
+ apiPort: z.number().int().min(1).max(65535).nullable().optional(),
uiUrl: z.string().url().optional(),
startCommands: z.array(z.string()).min(1).optional(),
pm2ProcessNames: z.array(z.string()).optional(),
envFile: z.string().optional(),
icon: z.string().nullable().optional(),
- editorCommand: z.string().optional()
+ editorCommand: z.string().optional(),
+ description: z.string().optional()
});
// Partial schema for updates
diff --git a/server/package-lock.json b/server/package-lock.json
index 51f72d59a6..9ccc8c75f9 100644
--- a/server/package-lock.json
+++ b/server/package-lock.json
@@ -11,6 +11,7 @@
"cors": "^2.8.5",
"express": "^4.21.2",
"pm2": "^5.4.3",
+ "socket.io": "^4.8.3",
"uuid": "^11.0.3",
"zod": "^3.24.1"
},
@@ -971,12 +972,27 @@
"win32"
]
},
+ "node_modules/@socket.io/component-emitter": {
+ "version": "3.1.2",
+ "resolved": "https://registry.npmjs.org/@socket.io/component-emitter/-/component-emitter-3.1.2.tgz",
+ "integrity": "sha512-9BCxFwvbGg/RsZK9tjXd8s4UcwR0MWeFQ1XEKIQVVvAGJyINdrqKMcTRyLoK8Rse1GjzLV9cwjWV1olXRWEXVA==",
+ "license": "MIT"
+ },
"node_modules/@tootallnate/quickjs-emscripten": {
"version": "0.23.0",
"resolved": "https://registry.npmjs.org/@tootallnate/quickjs-emscripten/-/quickjs-emscripten-0.23.0.tgz",
"integrity": "sha512-C5Mc6rdnsaJDjO3UpGW/CQTHtCKaYlScZTly4JIu97Jxo/odCiH0ITnDXSJPTOrEKk/ycSZ0AOgTmkDtkOsvIA==",
"license": "MIT"
},
+ "node_modules/@types/cors": {
+ "version": "2.8.19",
+ "resolved": "https://registry.npmjs.org/@types/cors/-/cors-2.8.19.tgz",
+ "integrity": "sha512-mFNylyeyqN93lfe/9CSxOGREz8cpzAhH+E93xJ4xWQf62V8sQ/24reV2nyzUWM6H6Xji+GGHpkbLe7pVoUEskg==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/node": "*"
+ }
+ },
"node_modules/@types/estree": {
"version": "1.0.8",
"resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.8.tgz",
@@ -984,6 +1000,15 @@
"dev": true,
"license": "MIT"
},
+ "node_modules/@types/node": {
+ "version": "25.0.3",
+ "resolved": "https://registry.npmjs.org/@types/node/-/node-25.0.3.tgz",
+ "integrity": "sha512-W609buLVRVmeW693xKfzHeIV6nJGGz98uCPfeXI1ELMLXVeKYZ9m15fAMSaUPBHYLGFsVRcMmSCksQOrZV9BYA==",
+ "license": "MIT",
+ "dependencies": {
+ "undici-types": "~7.16.0"
+ }
+ },
"node_modules/@vitest/expect": {
"version": "2.1.9",
"resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-2.1.9.tgz",
@@ -1217,6 +1242,15 @@
"integrity": "sha512-htCUDlxyyCLMgaM3xXg0C0LW2xqfuQ6p05pCEIsXuyQ+a1koYKTuBMzRNwmybfLgvJDMd0r1LTn4+E0Ti6C2AA==",
"license": "MIT"
},
+ "node_modules/base64id": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/base64id/-/base64id-2.0.0.tgz",
+ "integrity": "sha512-lGe34o6EHj9y3Kts9R4ZYs/Gr+6N7MCaMlIFA3F1R2O5/m7K06AxfSeO5530PEERE6/WyEg3lsuyw4GHlPZHog==",
+ "license": "MIT",
+ "engines": {
+ "node": "^4.5.0 || >= 5.9"
+ }
+ },
"node_modules/basic-ftp": {
"version": "5.1.0",
"resolved": "https://registry.npmjs.org/basic-ftp/-/basic-ftp-5.1.0.tgz",
@@ -1608,6 +1642,79 @@
"node": ">= 0.8"
}
},
+ "node_modules/engine.io": {
+ "version": "6.6.5",
+ "resolved": "https://registry.npmjs.org/engine.io/-/engine.io-6.6.5.tgz",
+ "integrity": "sha512-2RZdgEbXmp5+dVbRm0P7HQUImZpICccJy7rN7Tv+SFa55pH+lxnuw6/K1ZxxBfHoYpSkHLAO92oa8O4SwFXA2A==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/cors": "^2.8.12",
+ "@types/node": ">=10.0.0",
+ "accepts": "~1.3.4",
+ "base64id": "2.0.0",
+ "cookie": "~0.7.2",
+ "cors": "~2.8.5",
+ "debug": "~4.4.1",
+ "engine.io-parser": "~5.2.1",
+ "ws": "~8.18.3"
+ },
+ "engines": {
+ "node": ">=10.2.0"
+ }
+ },
+ "node_modules/engine.io-parser": {
+ "version": "5.2.3",
+ "resolved": "https://registry.npmjs.org/engine.io-parser/-/engine.io-parser-5.2.3.tgz",
+ "integrity": "sha512-HqD3yTBfnBxIrbnM1DoD6Pcq8NECnh8d4As1Qgh0z5Gg3jRRIqijury0CL3ghu/edArpUYiYqQiDUQBIs4np3Q==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=10.0.0"
+ }
+ },
+ "node_modules/engine.io/node_modules/debug": {
+ "version": "4.4.3",
+ "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",
+ "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==",
+ "license": "MIT",
+ "dependencies": {
+ "ms": "^2.1.3"
+ },
+ "engines": {
+ "node": ">=6.0"
+ },
+ "peerDependenciesMeta": {
+ "supports-color": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/engine.io/node_modules/ms": {
+ "version": "2.1.3",
+ "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
+ "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
+ "license": "MIT"
+ },
+ "node_modules/engine.io/node_modules/ws": {
+ "version": "8.18.3",
+ "resolved": "https://registry.npmjs.org/ws/-/ws-8.18.3.tgz",
+ "integrity": "sha512-PEIGCY5tSlUt50cqyMXfCzX+oOPqN0vuGqWzbcJ2xvnkzkq46oOpz7dQaTDBdfICb4N14+GARUDw2XV2N4tvzg==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=10.0.0"
+ },
+ "peerDependencies": {
+ "bufferutil": "^4.0.1",
+ "utf-8-validate": ">=5.0.2"
+ },
+ "peerDependenciesMeta": {
+ "bufferutil": {
+ "optional": true
+ },
+ "utf-8-validate": {
+ "optional": true
+ }
+ }
+ },
"node_modules/enquirer": {
"version": "2.3.6",
"resolved": "https://registry.npmjs.org/enquirer/-/enquirer-2.3.6.tgz",
@@ -3420,6 +3527,137 @@
"npm": ">= 3.0.0"
}
},
+ "node_modules/socket.io": {
+ "version": "4.8.3",
+ "resolved": "https://registry.npmjs.org/socket.io/-/socket.io-4.8.3.tgz",
+ "integrity": "sha512-2Dd78bqzzjE6KPkD5fHZmDAKRNe3J15q+YHDrIsy9WEkqttc7GY+kT9OBLSMaPbQaEd0x1BjcmtMtXkfpc+T5A==",
+ "license": "MIT",
+ "dependencies": {
+ "accepts": "~1.3.4",
+ "base64id": "~2.0.0",
+ "cors": "~2.8.5",
+ "debug": "~4.4.1",
+ "engine.io": "~6.6.0",
+ "socket.io-adapter": "~2.5.2",
+ "socket.io-parser": "~4.2.4"
+ },
+ "engines": {
+ "node": ">=10.2.0"
+ }
+ },
+ "node_modules/socket.io-adapter": {
+ "version": "2.5.6",
+ "resolved": "https://registry.npmjs.org/socket.io-adapter/-/socket.io-adapter-2.5.6.tgz",
+ "integrity": "sha512-DkkO/dz7MGln0dHn5bmN3pPy+JmywNICWrJqVWiVOyvXjWQFIv9c2h24JrQLLFJ2aQVQf/Cvl1vblnd4r2apLQ==",
+ "license": "MIT",
+ "dependencies": {
+ "debug": "~4.4.1",
+ "ws": "~8.18.3"
+ }
+ },
+ "node_modules/socket.io-adapter/node_modules/debug": {
+ "version": "4.4.3",
+ "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",
+ "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==",
+ "license": "MIT",
+ "dependencies": {
+ "ms": "^2.1.3"
+ },
+ "engines": {
+ "node": ">=6.0"
+ },
+ "peerDependenciesMeta": {
+ "supports-color": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/socket.io-adapter/node_modules/ms": {
+ "version": "2.1.3",
+ "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
+ "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
+ "license": "MIT"
+ },
+ "node_modules/socket.io-adapter/node_modules/ws": {
+ "version": "8.18.3",
+ "resolved": "https://registry.npmjs.org/ws/-/ws-8.18.3.tgz",
+ "integrity": "sha512-PEIGCY5tSlUt50cqyMXfCzX+oOPqN0vuGqWzbcJ2xvnkzkq46oOpz7dQaTDBdfICb4N14+GARUDw2XV2N4tvzg==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=10.0.0"
+ },
+ "peerDependencies": {
+ "bufferutil": "^4.0.1",
+ "utf-8-validate": ">=5.0.2"
+ },
+ "peerDependenciesMeta": {
+ "bufferutil": {
+ "optional": true
+ },
+ "utf-8-validate": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/socket.io-parser": {
+ "version": "4.2.5",
+ "resolved": "https://registry.npmjs.org/socket.io-parser/-/socket.io-parser-4.2.5.tgz",
+ "integrity": "sha512-bPMmpy/5WWKHea5Y/jYAP6k74A+hvmRCQaJuJB6I/ML5JZq/KfNieUVo/3Mh7SAqn7TyFdIo6wqYHInG1MU1bQ==",
+ "license": "MIT",
+ "dependencies": {
+ "@socket.io/component-emitter": "~3.1.0",
+ "debug": "~4.4.1"
+ },
+ "engines": {
+ "node": ">=10.0.0"
+ }
+ },
+ "node_modules/socket.io-parser/node_modules/debug": {
+ "version": "4.4.3",
+ "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",
+ "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==",
+ "license": "MIT",
+ "dependencies": {
+ "ms": "^2.1.3"
+ },
+ "engines": {
+ "node": ">=6.0"
+ },
+ "peerDependenciesMeta": {
+ "supports-color": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/socket.io-parser/node_modules/ms": {
+ "version": "2.1.3",
+ "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
+ "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
+ "license": "MIT"
+ },
+ "node_modules/socket.io/node_modules/debug": {
+ "version": "4.4.3",
+ "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",
+ "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==",
+ "license": "MIT",
+ "dependencies": {
+ "ms": "^2.1.3"
+ },
+ "engines": {
+ "node": ">=6.0"
+ },
+ "peerDependenciesMeta": {
+ "supports-color": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/socket.io/node_modules/ms": {
+ "version": "2.1.3",
+ "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
+ "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
+ "license": "MIT"
+ },
"node_modules/socks": {
"version": "2.8.7",
"resolved": "https://registry.npmjs.org/socks/-/socks-2.8.7.tgz",
@@ -3692,6 +3930,12 @@
"node": ">= 0.6"
}
},
+ "node_modules/undici-types": {
+ "version": "7.16.0",
+ "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.16.0.tgz",
+ "integrity": "sha512-Zz+aZWSj8LE6zoxD+xrjh4VfkIG8Ya6LvYkZqtUQGJPZjYl53ypCaUwWqo7eI0x66KBGeRo+mlBEkMSeSZ38Nw==",
+ "license": "MIT"
+ },
"node_modules/unpipe": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz",
@@ -3738,6 +3982,7 @@
"integrity": "sha512-o5a9xKjbtuhY6Bi5S3+HvbRERmouabWbyUcpXXUA1u+GNUKoROi9byOJ8M0nHbHYHkYICiMlqxkg1KkYmm25Sw==",
"dev": true,
"license": "MIT",
+ "peer": true,
"dependencies": {
"esbuild": "^0.21.3",
"postcss": "^8.4.43",
diff --git a/server/package.json b/server/package.json
index 0aa8060f6b..8c4d0652bc 100644
--- a/server/package.json
+++ b/server/package.json
@@ -13,6 +13,7 @@
"cors": "^2.8.5",
"express": "^4.21.2",
"pm2": "^5.4.3",
+ "socket.io": "^4.8.3",
"uuid": "^11.0.3",
"zod": "^3.24.1"
},
diff --git a/server/routes/apps.js b/server/routes/apps.js
index bcf5b7e5da..efc75e97e0 100644
--- a/server/routes/apps.js
+++ b/server/routes/apps.js
@@ -1,6 +1,7 @@
import { Router } from 'express';
import * as appsService from '../services/apps.js';
import * as pm2Service from '../services/pm2.js';
+import { logAction } from '../services/history.js';
import { validate, appSchema, appUpdateSchema } from '../lib/validation.js';
const router = Router();
@@ -125,6 +126,9 @@ router.post('/:id/start', async (req, res, next) => {
results[name] = result;
}
+ const allSuccess = Object.values(results).every(r => r.success !== false);
+ await logAction('start', app.id, app.name, { processNames }, allSuccess);
+
res.json({ success: true, results });
});
@@ -144,6 +148,9 @@ router.post('/:id/stop', async (req, res, next) => {
results[name] = result;
}
+ const allSuccess = Object.values(results).every(r => r.success !== false);
+ await logAction('stop', app.id, app.name, { processNames: app.pm2ProcessNames }, allSuccess);
+
res.json({ success: true, results });
});
@@ -163,6 +170,9 @@ router.post('/:id/restart', async (req, res, next) => {
results[name] = result;
}
+ const allSuccess = Object.values(results).every(r => r.success !== false);
+ await logAction('restart', app.id, app.name, { processNames: app.pm2ProcessNames }, allSuccess);
+
res.json({ success: true, results });
});
diff --git a/server/routes/commands.js b/server/routes/commands.js
new file mode 100644
index 0000000000..56dd036dc5
--- /dev/null
+++ b/server/routes/commands.js
@@ -0,0 +1,78 @@
+import { Router } from 'express';
+import * as commands from '../services/commands.js';
+import * as pm2Service from '../services/pm2.js';
+
+const router = Router();
+
+// POST /api/commands/execute - Execute a command
+router.post('/execute', (req, res) => {
+ const { command, workspacePath } = req.body;
+
+ if (!command) {
+ return res.status(400).json({ error: 'Command is required', code: 'MISSING_COMMAND' });
+ }
+
+ const io = req.app.get('io');
+
+ const commandId = commands.executeCommand(
+ command,
+ workspacePath,
+ (data, stream) => {
+ io?.emit(`command:${commandId}:data`, { data, stream });
+ },
+ (result) => {
+ io?.emit(`command:${commandId}:complete`, result);
+ }
+ );
+
+ if (!commandId) {
+ return res.status(403).json({ error: 'Command not allowed', code: 'FORBIDDEN' });
+ }
+
+ res.status(202).json({ commandId, status: 'started' });
+});
+
+// POST /api/commands/:id/stop - Stop a running command
+router.post('/:id/stop', (req, res) => {
+ const stopped = commands.stopCommand(req.params.id);
+
+ if (!stopped) {
+ return res.status(404).json({ error: 'Command not found or not active', code: 'NOT_ACTIVE' });
+ }
+
+ res.json({ stopped: true });
+});
+
+// GET /api/commands/allowed - Get allowed commands
+router.get('/allowed', (req, res) => {
+ res.json(commands.getAllowedCommands());
+});
+
+// GET /api/commands/processes - Get PM2 process list with details
+router.get('/processes', async (req, res, next) => {
+ const processes = await pm2Service.listProcesses().catch(next);
+ if (processes) res.json(processes);
+});
+
+// GET /api/commands/processes/:name/monit - Get PM2 monit data for a process
+router.get('/processes/:name/monit', async (req, res, next) => {
+ const processes = await pm2Service.listProcesses().catch(next);
+ if (!processes) return;
+
+ const process = processes.find(p => p.name === req.params.name);
+ if (!process) {
+ return res.status(404).json({ error: 'Process not found', code: 'NOT_FOUND' });
+ }
+
+ res.json({
+ name: process.name,
+ status: process.status,
+ pid: process.pid,
+ cpu: process.cpu,
+ memory: process.memory,
+ uptime: process.uptime,
+ restarts: process.restarts
+ });
+});
+
+export default router;
diff --git a/server/routes/detect.js b/server/routes/detect.js
new file mode 100644
index 0000000000..60c2b582e0
--- /dev/null
+++ b/server/routes/detect.js
@@ -0,0 +1,195 @@
+import { Router } from 'express';
+import { existsSync, statSync } from 'fs';
+import { readFile } from 'fs/promises';
+import { join } from 'path';
+import { exec } from 'child_process';
+import { promisify } from 'util';
+import { detectAppWithAi } from '../services/aiDetect.js';
+
+const execAsync = promisify(exec);
+const router = Router();
+
+// POST /api/detect/repo - Validate repo path and detect project type
+router.post('/repo', async (req, res) => {
+ const { path } = req.body;
+
+ if (!path) {
+ return res.status(400).json({ error: 'Path is required', code: 'MISSING_PATH' });
+ }
+
+ // Check if path exists
+ if (!existsSync(path)) {
+ return res.json({
+ valid: false,
+ error: 'Path does not exist'
+ });
+ }
+
+ // Check if it's a directory
+ const stats = statSync(path);
+ if (!stats.isDirectory()) {
+ return res.json({
+ valid: false,
+ error: 'Path is not a directory'
+ });
+ }
+
+ // Detect project type
+ const result = {
+ valid: true,
+ path,
+ type: 'unknown',
+ hasPackageJson: false,
+ hasGit: false,
+ packageJson: null,
+ detectedPorts: {},
+ startCommands: []
+ };
+
+ // Check for package.json
+ const packageJsonPath = join(path, 'package.json');
+ if (existsSync(packageJsonPath)) {
+ result.hasPackageJson = true;
+ const content = await readFile(packageJsonPath, 'utf-8').catch(() => null);
+ if (content) {
+ const pkg = JSON.parse(content);
+ result.packageJson = {
+ name: pkg.name,
+ scripts: pkg.scripts || {}
+ };
+
+ // Detect type from dependencies/scripts
+ const deps = { ...pkg.dependencies, ...pkg.devDependencies };
+ if (deps.vite && deps.express) {
+ result.type = 'vite+express';
+ } else if (deps.vite || deps.react || deps.vue) {
+ result.type = 'vite';
+ } else if (deps.express || deps.fastify || deps.koa) {
+ result.type = 'single-node-server';
+ } else if (deps.next) {
+ result.type = 'nextjs';
+ }
+
+ // Suggest start commands from scripts
+ const scripts = pkg.scripts || {};
+ if (scripts.dev) result.startCommands.push('npm run dev');
+ if (scripts.start) result.startCommands.push('npm start');
+ if (scripts.serve) result.startCommands.push('npm run serve');
+ }
+ }
+
+ // Check for .git
+ if (existsSync(join(path, '.git'))) {
+ result.hasGit = true;
+ }
+
+ // Check for .env and extract port info
+ const envPath = join(path, '.env');
+ if (existsSync(envPath)) {
+ const envContent = await readFile(envPath, 'utf-8').catch(() => '');
+ const portMatch = envContent.match(/PORT\s*=\s*(\d+)/i);
+ if (portMatch) {
+ result.detectedPorts.main = parseInt(portMatch[1]);
+ }
+ const vitePortMatch = envContent.match(/VITE_PORT\s*=\s*(\d+)/i);
+ if (vitePortMatch) {
+ result.detectedPorts.vite = parseInt(vitePortMatch[1]);
+ }
+ }
+
+ // Check vite.config for port
+ for (const configFile of ['vite.config.js', 'vite.config.ts']) {
+ const configPath = join(path, configFile);
+ if (existsSync(configPath)) {
+ const content = await readFile(configPath, 'utf-8').catch(() => '');
+ const portMatch = content.match(/port\s*:\s*(\d+)/);
+ if (portMatch) {
+ result.detectedPorts.vite = parseInt(portMatch[1]);
+ }
+ }
+ }
+
+ res.json(result);
+});
+
+// POST /api/detect/port - Detect what process is running on a port
+router.post('/port', async (req, res) => {
+ const { port } = req.body;
+
+ if (!port || isNaN(port)) {
+ return res.status(400).json({ error: 'Valid port number is required', code: 'INVALID_PORT' });
+ }
+
+ const result = {
+ port: parseInt(port),
+ inUse: false,
+ process: null
+ };
+
+ // Use lsof on macOS/Linux to find process
+ const command = process.platform === 'darwin'
+ ? `lsof -i :${port} -P -n | grep LISTEN`
+ : `ss -lntp | grep :${port}`;
+
+ const { stdout } = await execAsync(command).catch(() => ({ stdout: '' }));
+
+ if (stdout.trim()) {
+ result.inUse = true;
+
+ // Parse lsof output: COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
+ const lines = stdout.trim().split('\n');
+ if (lines.length > 0) {
+ const parts = lines[0].split(/\s+/);
+ if (process.platform === 'darwin' && parts.length >= 2) {
+ result.process = {
+ command: parts[0],
+ pid: parseInt(parts[1])
+ };
+ }
+ }
+ }
+
+ res.json(result);
+});
+
+// POST /api/detect/pm2 - Check if a PM2 process exists with given name
+router.post('/pm2', async (req, res) => {
+ const { name } = req.body;
+
+ if (!name) {
+ return res.status(400).json({ error: 'Process name is required', code: 'MISSING_NAME' });
+ }
+
+ const { stdout } = await execAsync('pm2 jlist').catch(() => ({ stdout: '[]' }));
+ const processes = JSON.parse(stdout);
+ const found = processes.find(p => p.name === name);
+
+ res.json({
+ name,
+ exists: !!found,
+ process: found ? {
+ name: found.name,
+ status: found.pm2_env?.status,
+ pid: found.pid,
+ pm_id: found.pm_id
+ } : null
+ });
+});
+
+// POST /api/detect/ai - AI-powered app detection
+router.post('/ai', async (req, res, next) => {
+ const { path, providerId } = req.body;
+
+ if (!path) {
+ return res.status(400).json({ error: 'Path is required', code: 'MISSING_PATH' });
+ }
+
+ const result = await detectAppWithAi(path, providerId).catch(err => ({
+ success: false,
+ error: err.message
+ }));
+
+ res.json(result);
+});
+
+export default router;
diff --git a/server/routes/history.js b/server/routes/history.js
new file mode 100644
index 0000000000..06ad2debee
--- /dev/null
+++ b/server/routes/history.js
@@ -0,0 +1,39 @@
+import { Router } from 'express';
+import * as history from '../services/history.js';
+
+const router = Router();
+
+// GET /api/history - Get history entries
+router.get('/', async (req, res, next) => {
+ const options = {
+ limit: parseInt(req.query.limit) || 100,
+ offset: parseInt(req.query.offset) || 0,
+ action: req.query.action || undefined,
+ target: req.query.target || undefined,
+ success: req.query.success !== undefined ? req.query.success === 'true' : undefined
+ };
+
+ const result = await history.getHistory(options).catch(next);
+ if (result) res.json(result);
+});
+
+// GET /api/history/stats - Get history statistics
+router.get('/stats', async (req, res, next) => {
+ const stats = await history.getHistoryStats().catch(next);
+ if (stats) res.json(stats);
+});
+
+// GET /api/history/actions - Get unique action types
+router.get('/actions', async (req, res, next) => {
+ const actions = await history.getActionTypes().catch(next);
+ if (actions) res.json(actions);
+});
+
+// DELETE /api/history - Clear history
+router.delete('/', async (req, res, next) => {
+ const olderThanDays = req.query.olderThanDays ? parseInt(req.query.olderThanDays) : null;
+ const result = await history.clearHistory(olderThanDays).catch(next);
+ if (result) res.json(result);
+});
+
+export default router;
diff --git a/server/routes/logs.js b/server/routes/logs.js
new file mode 100644
index 0000000000..61b394b3c1
--- /dev/null
+++ b/server/routes/logs.js
@@ -0,0 +1,101 @@
+import { Router } from 'express';
+import { spawn } from 'child_process';
+import * as appsService from '../services/apps.js';
+import * as pm2Service from '../services/pm2.js';
+
+const router = Router();
+
+// GET /api/logs/processes - List all PM2 processes for log selection
+router.get('/processes', async (req, res) => {
+ const processes = await pm2Service.listProcesses().catch(() => []);
+ res.json(processes);
+});
+
+// GET /api/logs/:processName - Get logs for a process (static or streaming)
+router.get('/:processName', async (req, res) => {
+ const { processName } = req.params;
+ const lines = parseInt(req.query.lines) || 100;
+ const follow = req.query.follow === 'true';
+
+ if (!follow) {
+ // Static log fetch
+ const logs = await pm2Service.getLogs(processName, lines)
+ .catch(err => `Error: ${err.message}`);
+ return res.json({ processName, lines, logs });
+ }
+
+ // SSE streaming
+ res.setHeader('Content-Type', 'text/event-stream');
+ res.setHeader('Cache-Control', 'no-cache');
+ res.setHeader('Connection', 'keep-alive');
+ res.setHeader('X-Accel-Buffering', 'no');
+
+ // Send initial connection event
+ res.write(`event: connected\ndata: ${JSON.stringify({ processName, timestamp: Date.now() })}\n\n`);
+
+ // Spawn pm2 logs with --raw flag for clean output
+ const logProcess = spawn('pm2', ['logs', processName, '--raw', '--lines', String(lines)], {
+ shell: false
+ });
+
+ let buffer = '';
+
+ const sendLine = (line, type = 'log') => {
+ if (line.trim()) {
+ res.write(`event: ${type}\ndata: ${JSON.stringify({
+ line,
+ timestamp: Date.now(),
+ type
+ })}\n\n`);
+ }
+ };
+
+ logProcess.stdout.on('data', (data) => {
+ buffer += data.toString();
+ const lines = buffer.split('\n');
+ buffer = lines.pop() || '';
+ lines.forEach(line => sendLine(line, 'stdout'));
+ });
+
+ logProcess.stderr.on('data', (data) => {
+ buffer += data.toString();
+ const lines = buffer.split('\n');
+ buffer = lines.pop() || '';
+ lines.forEach(line => sendLine(line, 'stderr'));
+ });
+
+ logProcess.on('error', (err) => {
+ res.write(`event: error\ndata: ${JSON.stringify({ error: err.message })}\n\n`);
+ });
+
+ logProcess.on('close', (code) => {
+ res.write(`event: close\ndata: ${JSON.stringify({ code })}\n\n`);
+ res.end();
+ });
+
+ // Cleanup on client disconnect
+ req.on('close', () => {
+ logProcess.kill('SIGTERM');
+ });
+});
+
+// GET /api/logs/app/:appId - Get logs for all processes of an app
+router.get('/app/:appId', async (req, res) => {
+ const app = await appsService.getAppById(req.params.appId);
+
+ if (!app) {
+ return res.status(404).json({ error: 'App not found', code: 'NOT_FOUND' });
+ }
+
+ const lines = parseInt(req.query.lines) || 100;
+ const results = {};
+
+ for (const processName of app.pm2ProcessNames || []) {
+ results[processName] = await pm2Service.getLogs(processName, lines)
+ .catch(err => `Error: ${err.message}`);
+ }
+
+ res.json({ app: app.name, processes: results });
+});
+
+export default router;
diff --git a/server/routes/providers.js b/server/routes/providers.js
new file mode 100644
index 0000000000..3846dc016b
--- /dev/null
+++ b/server/routes/providers.js
@@ -0,0 +1,116 @@
+import { Router } from 'express';
+import * as providers from '../services/providers.js';
+
+const router = Router();
+
+// GET /api/providers - List all providers
+router.get('/', async (req, res, next) => {
+ const data = await providers.getAllProviders().catch(next);
+ if (data) res.json(data);
+});
+
+// GET /api/providers/active - Get active provider
+router.get('/active', async (req, res, next) => {
+ const provider = await providers.getActiveProvider().catch(next);
+ if (provider === undefined) return;
+ res.json(provider);
+});
+
+// PUT /api/providers/active - Set active provider
+router.put('/active', async (req, res, next) => {
+ const { id } = req.body;
+ if (!id) {
+ return res.status(400).json({ error: 'Provider ID required', code: 'MISSING_ID' });
+ }
+
+ const provider = await providers.setActiveProvider(id).catch(next);
+ if (provider === undefined) return;
+
+ if (!provider) {
+ return res.status(404).json({ error: 'Provider not found', code: 'NOT_FOUND' });
+ }
+
+ res.json(provider);
+});
+
+// GET /api/providers/:id - Get provider by ID
+router.get('/:id', async (req, res, next) => {
+ const provider = await providers.getProviderById(req.params.id).catch(next);
+ if (provider === undefined) return;
+
+ if (!provider) {
+ return res.status(404).json({ error: 'Provider not found', code: 'NOT_FOUND' });
+ }
+
+ res.json(provider);
+});
+
+// POST /api/providers - Create new provider
+router.post('/', async (req, res, next) => {
+ const { name, type } = req.body;
+
+ if (!name) {
+ return res.status(400).json({ error: 'Name is required', code: 'VALIDATION_ERROR' });
+ }
+
+ if (!type || !['cli', 'api'].includes(type)) {
+ return res.status(400).json({ error: 'Type must be "cli" or "api"', code: 'VALIDATION_ERROR' });
+ }
+
+ const provider = await providers.createProvider(req.body).catch(err => {
+ if (err.message.includes('already exists')) {
+ res.status(409).json({ error: err.message, code: 'CONFLICT' });
+ return undefined;
+ }
+ next(err);
+ return undefined;
+ });
+
+ if (provider === undefined) return;
+ res.status(201).json(provider);
+});
+
+// PUT /api/providers/:id - Update provider
+router.put('/:id', async (req, res, next) => {
+ const provider = await providers.updateProvider(req.params.id, req.body).catch(next);
+ if (provider === undefined) return;
+
+ if (!provider) {
+ return res.status(404).json({ error: 'Provider not found', code: 'NOT_FOUND' });
+ }
+
+ res.json(provider);
+});
+
+// DELETE /api/providers/:id - Delete provider
+router.delete('/:id', async (req, res, next) => {
+ const deleted = await providers.deleteProvider(req.params.id).catch(next);
+ if (deleted === undefined) return;
+
+ if (!deleted) {
+ return res.status(404).json({ error: 'Provider not found', code: 'NOT_FOUND' });
+ }
+
+ res.status(204).send();
+});
+
+// POST /api/providers/:id/test - Test provider connectivity
+router.post('/:id/test', async (req, res, next) => {
+ const result = await providers.testProvider(req.params.id).catch(next);
+ if (result === undefined) return;
+ res.json(result);
+});
+
+// POST /api/providers/:id/refresh-models - Refresh models for API provider
+router.post('/:id/refresh-models', async (req, res, next) => {
+ const provider = await providers.refreshProviderModels(req.params.id).catch(next);
+ if (provider === undefined) return;
+
+ if (!provider) {
+ return res.status(404).json({ error: 'Provider not found or not an API type', code: 'NOT_FOUND' });
+ }
+
+ res.json(provider);
+});
+
+export default router;
diff --git a/server/routes/runs.js b/server/routes/runs.js
new file mode 100644
index 0000000000..3d608a6b10
--- /dev/null
+++ b/server/routes/runs.js
@@ -0,0 +1,150 @@
+import { Router } from 'express';
+import * as runner from '../services/runner.js';
+
+const router = Router();
+
+// GET /api/runs - List runs
+router.get('/', async (req, res, next) => {
+ const limit = parseInt(req.query.limit) || 50;
+ const offset = parseInt(req.query.offset) || 0;
+
+ const result = await runner.listRuns(limit, offset).catch(next);
+ if (result) res.json(result);
+});
+
+// POST /api/runs - Create and execute a new run
+router.post('/', async (req, res, next) => {
+ const { providerId, model, prompt, workspacePath, workspaceName } = req.body;
+
+ if (!providerId) {
+ return res.status(400).json({ error: 'providerId is required', code: 'VALIDATION_ERROR' });
+ }
+
+ if (!prompt) {
+ return res.status(400).json({ error: 'prompt is required', code: 'VALIDATION_ERROR' });
+ }
+
+ const runData = await runner.createRun({
+ providerId,
+ model,
+ prompt,
+ workspacePath,
+ workspaceName
+ }).catch(err => {
+ res.status(400).json({ error: err.message, code: 'RUN_ERROR' });
+ return undefined;
+ });
+
+ if (!runData) return;
+
+ const { runId, provider, metadata } = runData;
+ const io = req.app.get('io');
+
+ // Execute based on provider type
+ if (provider.type === 'cli') {
+ runner.executeCliRun(
+ runId,
+ provider,
+ prompt,
+ workspacePath,
+ (data) => {
+ // Stream output via Socket.IO
+ io?.emit(`run:${runId}:data`, data);
+ },
+ (finalMetadata) => {
+ io?.emit(`run:${runId}:complete`, finalMetadata);
+ }
+ );
+ } else if (provider.type === 'api') {
+ runner.executeApiRun(
+ runId,
+ provider,
+ model,
+ prompt,
+ workspacePath,
+ (data) => {
+ io?.emit(`run:${runId}:data`, data);
+ },
+ (finalMetadata) => {
+ io?.emit(`run:${runId}:complete`, finalMetadata);
+ }
+ );
+ }
+
+ // Return immediately with run ID
+ res.status(202).json({
+ runId,
+ status: 'started',
+ metadata
+ });
+});
+
+// GET /api/runs/:id - Get run metadata
+router.get('/:id', async (req, res, next) => {
+ const metadata = await runner.getRun(req.params.id).catch(next);
+ if (metadata === undefined) return;
+
+ if (!metadata) {
+ return res.status(404).json({ error: 'Run not found', code: 'NOT_FOUND' });
+ }
+
+ res.json({
+ ...metadata,
+ isActive: runner.isRunActive(req.params.id)
+ });
+});
+
+// GET /api/runs/:id/output - Get run output
+router.get('/:id/output', async (req, res, next) => {
+ const output = await runner.getRunOutput(req.params.id).catch(next);
+ if (output === undefined) return;
+
+ if (output === null) {
+ return res.status(404).json({ error: 'Run not found', code: 'NOT_FOUND' });
+ }
+
+ res.type('text/plain').send(output);
+});
+
+// GET /api/runs/:id/prompt - Get run prompt
+router.get('/:id/prompt', async (req, res, next) => {
+ const prompt = await runner.getRunPrompt(req.params.id).catch(next);
+ if (prompt === undefined) return;
+
+ if (prompt === null) {
+ return res.status(404).json({ error: 'Run not found', code: 'NOT_FOUND' });
+ }
+
+ res.type('text/plain').send(prompt);
+});
+
+// POST /api/runs/:id/stop - Stop a running execution
+router.post('/:id/stop', async (req, res, next) => {
+ const stopped = await runner.stopRun(req.params.id).catch(next);
+ if (stopped === undefined) return;
+
+ if (!stopped) {
+ return res.status(404).json({ error: 'Run not found or not active', code: 'NOT_ACTIVE' });
+ }
+
+ res.json({ stopped: true });
+});
+
+// DELETE /api/runs/:id - Delete run and artifacts
+router.delete('/:id', async (req, res, next) => {
+ // Don't allow deleting active runs
+ if (runner.isRunActive(req.params.id)) {
+ return res.status(409).json({ error: 'Cannot delete active run', code: 'RUN_ACTIVE' });
+ }
+
+ const deleted = await runner.deleteRun(req.params.id).catch(next);
+ if (deleted === undefined) return;
+
+ if (!deleted) {
+ return res.status(404).json({ error: 'Run not found', code: 'NOT_FOUND' });
+ }
+
+ res.status(204).send();
+});
+
+export default router;
diff --git a/server/routes/scaffold.js b/server/routes/scaffold.js
new file mode 100644
index 0000000000..cc4358c1d1
--- /dev/null
+++ b/server/routes/scaffold.js
@@ -0,0 +1,319 @@
+import { Router } from 'express';
+import { mkdir, writeFile, readdir, copyFile, readFile } from 'fs/promises';
+import { existsSync } from 'fs';
+import { join, dirname } from 'path';
+import { fileURLToPath } from 'url';
+import { exec, spawn } from 'child_process';
+import { promisify } from 'util';
+import { createApp } from '../services/apps.js';
+
+const execAsync = promisify(exec);
+const __filename = fileURLToPath(import.meta.url);
+const __dirname = dirname(__filename);
+const TEMPLATES_DIR = join(__dirname, '../../templates');
+
+const router = Router();
+
+// GET /api/templates - List available templates
+router.get('/templates', async (req, res) => {
+ const templates = [
+ {
+ id: 'vite-react',
+ name: 'Vite + React',
+ description: 'React app with Vite bundler',
+ type: 'vite',
+ ports: { ui: true, api: false }
+ },
+ {
+ id: 'vite-express',
+ name: 'Vite + Express',
+ description: 'Full-stack with React frontend and Express API',
+ type: 'vite+express',
+ ports: { ui: true, api: true }
+ },
+ {
+ id: 'express-api',
+ name: 'Express API',
+ description: 'Node.js Express API server',
+ type: 'single-node-server',
+ ports: { ui: false, api: true }
+ }
+ ];
+
+ res.json(templates);
+});
+
+// POST /api/scaffold - Create a new app from template
+router.post('/', async (req, res) => {
+ const {
+ name,
+ template,
+ parentDir,
+ uiPort,
+ apiPort,
+ createGitHubRepo = false,
+ githubOrg = null
+ } = req.body;
+
+ // Validation
+ if (!name || !template || !parentDir) {
+ return res.status(400).json({
+ error: 'name, template, and parentDir are required',
+ code: 'VALIDATION_ERROR'
+ });
+ }
+
+ // Sanitize name for directory
+ const dirName = name.toLowerCase().replace(/[^a-z0-9-]/g, '-');
+ const repoPath = join(parentDir, dirName);
+
+ // Check parent exists
+ if (!existsSync(parentDir)) {
+ return res.status(400).json({
+ error: 'Parent directory does not exist',
+ code: 'INVALID_PARENT'
+ });
+ }
+
+ // Check target doesn't exist
+ if (existsSync(repoPath)) {
+ return res.status(400).json({
+ error: 'Directory already exists',
+ code: 'DIR_EXISTS'
+ });
+ }
+
+ const steps = [];
+ const addStep = (name, status, error = null) => {
+ steps.push({ name, status, error, timestamp: Date.now() });
+ };
+
+ // Create directory
+ await mkdir(repoPath, { recursive: true });
+ addStep('Create directory', 'done');
+
+ // Generate project files based on template
+ if (template === 'vite-react' || template === 'vite-express') {
+ // Create using npm create vite
+ const { stderr } = await execAsync(
+ `npm create vite@latest ${dirName} -- --template react`,
+ { cwd: parentDir }
+ ).catch(err => ({ stderr: err.message }));
+
+ if (stderr && !stderr.includes('npm warn')) {
+ addStep('Create Vite project', 'error', stderr);
+ } else {
+ addStep('Create Vite project', 'done');
+ }
+
+ // Update vite.config.js with port
+ if (uiPort) {
+ const viteConfigPath = join(repoPath, 'vite.config.js');
+ if (existsSync(viteConfigPath)) {
+ let config = await readFile(viteConfigPath, 'utf-8');
+ config = config.replace(
+ 'plugins: [react()]',
+ `plugins: [react()],\n server: {\n host: '0.0.0.0',\n port: ${uiPort}\n }`
+ );
+ await writeFile(viteConfigPath, config);
+ }
+ }
+
+ // Add Express server if vite-express template
+ if (template === 'vite-express') {
+ const serverDir = join(repoPath, 'server');
+ await mkdir(serverDir, { recursive: true });
+
+ await writeFile(join(serverDir, 'index.js'), `import express from 'express';
+import cors from 'cors';
+
+const app = express();
+const PORT = process.env.PORT || ${apiPort || 3001};
+
+app.use(cors());
+app.use(express.json());
+
+app.get('/api/health', (req, res) => {
+ res.json({ status: 'ok' });
+});
+
+app.listen(PORT, '0.0.0.0', () => {
+ console.log(\`Server running on port \${PORT}\`);
+});
+`);
+
+ // Update package.json to add express and server script
+ const pkgPath = join(repoPath, 'package.json');
+ const pkg = JSON.parse(await readFile(pkgPath, 'utf-8'));
+ pkg.dependencies = pkg.dependencies || {};
+ pkg.dependencies.express = '^4.21.2';
+ pkg.dependencies.cors = '^2.8.5';
+ pkg.scripts['server'] = 'node server/index.js';
+ pkg.scripts['dev:all'] = 'concurrently "npm run dev" "npm run server"';
+ pkg.devDependencies = pkg.devDependencies || {};
+ pkg.devDependencies.concurrently = '^8.2.2';
+ await writeFile(pkgPath, JSON.stringify(pkg, null, 2));
+
+ addStep('Add Express server', 'done');
+ }
+ } else if (template === 'express-api') {
+ // Create Express-only project
+ const pkg = {
+ name: dirName,
+ version: '0.1.0',
+ type: 'module',
+ scripts: {
+ dev: 'node --watch index.js',
+ start: 'node index.js'
+ },
+ dependencies: {
+ express: '^4.21.2',
+ cors: '^2.8.5'
+ }
+ };
+ await writeFile(join(repoPath, 'package.json'), JSON.stringify(pkg, null, 2));
+
+ await writeFile(join(repoPath, 'index.js'), `import express from 'express';
+import cors from 'cors';
+
+const app = express();
+const PORT = process.env.PORT || ${apiPort || 3000};
+
+app.use(cors());
+app.use(express.json());
+
+app.get('/api/health', (req, res) => {
+ res.json({ status: 'ok', timestamp: new Date().toISOString() });
+});
+
+app.listen(PORT, '0.0.0.0', () => {
+ console.log(\`API server running on port \${PORT}\`);
+});
+`);
+
+ addStep('Create Express project', 'done');
+ }
+
+ // Create .env file
+ const envContent = [
+ uiPort && `VITE_PORT=${uiPort}`,
+ apiPort && `PORT=${apiPort}`
+ ].filter(Boolean).join('\n');
+
+ if (envContent) {
+ await writeFile(join(repoPath, '.env'), envContent + '\n');
+ addStep('Create .env', 'done');
+ }
+
+ // Create PM2 ecosystem file
+ const pm2Config = {
+ apps: []
+ };
+
+ if (template === 'vite-express') {
+ pm2Config.apps.push(
+ {
+ name: `${dirName}-ui`,
+ script: 'npm',
+ args: 'run dev',
+ cwd: repoPath
+ },
+ {
+ name: `${dirName}-api`,
+ script: 'server/index.js',
+ cwd: repoPath
+ }
+ );
+ } else if (template === 'vite-react') {
+ pm2Config.apps.push({
+ name: dirName,
+ script: 'npm',
+ args: 'run dev',
+ cwd: repoPath
+ });
+ } else {
+ pm2Config.apps.push({
+ name: dirName,
+ script: 'index.js',
+ cwd: repoPath
+ });
+ }
+
+ await writeFile(
+ join(repoPath, 'ecosystem.config.cjs'),
+ `module.exports = ${JSON.stringify(pm2Config, null, 2)};\n`
+ );
+ addStep('Create PM2 config', 'done');
+
+ // Run npm install
+ const { stderr: installErr } = await execAsync('npm install', { cwd: repoPath })
+ .catch(err => ({ stderr: err.message }));
+
+ if (installErr && !installErr.includes('npm warn')) {
+ addStep('npm install', 'error', installErr);
+ } else {
+ addStep('npm install', 'done');
+ }
+
+ // Initialize git
+ await execAsync('git init', { cwd: repoPath });
+ await writeFile(join(repoPath, '.gitignore'), 'node_modules\n.env\ndist\n');
+ await execAsync('git add -A', { cwd: repoPath });
+ await execAsync('git commit -m "Initial commit"', { cwd: repoPath });
+ addStep('Initialize git', 'done');
+
+ // Create GitHub repo if requested
+ if (createGitHubRepo) {
+ const ghArgs = githubOrg
+ ? `repo create ${githubOrg}/${dirName} --source=. --push --private`
+ : `repo create ${dirName} --source=. --push --private`;
+
+ const { stderr: ghErr } = await execAsync(`gh ${ghArgs}`, { cwd: repoPath })
+ .catch(err => ({ stderr: err.message }));
+
+ if (ghErr && !ghErr.includes('Created repository')) {
+ addStep('Create GitHub repo', 'error', ghErr);
+ } else {
+ addStep('Create GitHub repo', 'done');
+ }
+ }
+
+ // Register in PortOS
+ const templateToType = {
+ 'vite-react': 'vite',
+ 'vite-express': 'vite+express',
+ 'express-api': 'single-node-server'
+ };
+
+ const pm2Names = template === 'vite-express'
+ ? [`${dirName}-ui`, `${dirName}-api`]
+ : [dirName];
+
+ const startCmds = template === 'vite-express'
+ ? ['npm run dev', 'npm run server']
+ : template === 'express-api'
+ ? ['npm run dev']
+ : ['npm run dev'];
+
+ const app = await createApp({
+ name,
+ repoPath,
+ type: templateToType[template] || 'unknown',
+ uiPort: uiPort || null,
+ apiPort: apiPort || null,
+ startCommands: startCmds,
+ pm2ProcessNames: pm2Names,
+ envFile: '.env'
+ });
+
+ addStep('Register in PortOS', 'done');
+
+ res.json({
+ success: true,
+ app,
+ repoPath,
+ steps
+ });
+});
+
+export default router;
diff --git a/server/services/aiDetect.js b/server/services/aiDetect.js
new file mode 100644
index 0000000000..c7eb71bd90
--- /dev/null
+++ b/server/services/aiDetect.js
@@ -0,0 +1,269 @@
+import { readFile, readdir, stat } from 'fs/promises';
+import { existsSync } from 'fs';
+import { join, basename } from 'path';
+import { getActiveProvider, getProviderById } from './providers.js';
+import { spawn } from 'child_process';
+
+/**
+ * Gather project context for AI analysis
+ */
+async function gatherProjectContext(dirPath) {
+ const context = {
+ dirName: basename(dirPath),
+ files: [],
+ packageJson: null,
+ envFiles: [],
+ configFiles: []
+ };
+
+ // Get directory listing
+ const entries = await readdir(dirPath, { withFileTypes: true }).catch(() => []);
+ context.files = entries.map(e => e.name);
+
+ // Read package.json
+ const pkgPath = join(dirPath, 'package.json');
+ if (existsSync(pkgPath)) {
+ const content = await readFile(pkgPath, 'utf-8').catch(() => null);
+ if (content) {
+ context.packageJson = content;
+ }
+ }
+
+ // Check for common config files
+ const configPatterns = [
+ 'vite.config.js', 'vite.config.ts',
+ 'next.config.js', 'next.config.mjs',
+ 'webpack.config.js',
+ 'ecosystem.config.cjs', 'ecosystem.config.js',
+ 'tsconfig.json',
+ 'Dockerfile', 'docker-compose.yml'
+ ];
+
+ for (const pattern of configPatterns) {
+ const configPath = join(dirPath, pattern);
+ if (existsSync(configPath)) {
+ const content = await readFile(configPath, 'utf-8').catch(() => null);
+ if (content) {
+ context.configFiles.push({ name: pattern, content: content.substring(0, 2000) });
+ }
+ }
+ }
+
+ // Check for .env files
+ const envPatterns = ['.env', '.env.local', '.env.development'];
+ for (const pattern of envPatterns) {
+ const envPath = join(dirPath, pattern);
+ if (existsSync(envPath)) {
+ const content = await readFile(envPath, 'utf-8').catch(() => '');
+ // Extract port-related lines only (don't expose secrets)
+ const portLines = content.split('\n')
+ .filter(line => /port/i.test(line) && !line.startsWith('#'))
+ .join('\n');
+ if (portLines) {
+ context.envFiles.push({ name: pattern, content: portLines });
+ }
+ }
+ }
+
+ // Check for README
+ for (const readme of ['README.md', 'readme.md', 'README']) {
+ const readmePath = join(dirPath, readme);
+ if (existsSync(readmePath)) {
+ const content = await readFile(readmePath, 'utf-8').catch(() => '');
+ context.readme = content.substring(0, 3000);
+ break;
+ }
+ }
+
+ return context;
+}
+
+/**
+ * Build prompt for AI analysis
+ */
+function buildAnalysisPrompt(context) {
+ return `Analyze this project and return JSON with the detected configuration.
+
+Directory: ${context.dirName}
+Files: ${context.files.slice(0, 50).join(', ')}
+
+${context.packageJson ? `package.json:\n${context.packageJson}\n` : ''}
+${context.configFiles.map(f => `${f.name}:\n${f.content}`).join('\n\n')}
+${context.envFiles.map(f => `${f.name}:\n${f.content}`).join('\n')}
+${context.readme ? `README excerpt:\n${context.readme.substring(0, 1000)}` : ''}
+
+Return ONLY valid JSON (no markdown, no explanation) with this exact structure:
+{
+ "name": "Human readable app name",
+ "description": "One sentence description",
+ "uiPort": null or number (frontend/dev server port),
+ "apiPort": null or number (backend/API port),
+ "startCommands": ["array of npm scripts to start the app"],
+ "pm2ProcessNames": ["suggested PM2 process names"],
+ "hasFrontend": true/false,
+ "hasBackend": true/false
+}
+
+Rules:
+- name: Use package.json name or derive from directory, make it human readable
+- Look for ports in vite.config, .env files, or package.json scripts
+- For startCommands, prefer "npm run dev" patterns
+- For pm2ProcessNames, use lowercase hyphenated names like "app-name-ui", "app-name-api"
+- If the app has both frontend and backend, suggest separate PM2 processes`;
+}
+
+/**
+ * Execute AI detection using CLI provider
+ */
+async function executeCliDetection(provider, prompt, cwd) {
+ return new Promise((resolve, reject) => {
+ const args = [...(provider.args || []), prompt];
+ let output = '';
+
+ const child = spawn(provider.command, args, {
+ cwd,
+ env: process.env,
+ shell: false
+ });
+
+ child.stdout.on('data', (data) => {
+ output += data.toString();
+ });
+
+ child.stderr.on('data', (data) => {
+ output += data.toString();
+ });
+
+ child.on('close', (code) => {
+ if (code === 0) {
+ resolve(output);
+ } else {
+ reject(new Error(`CLI exited with code ${code}`));
+ }
+ });
+
+ child.on('error', reject);
+
+ // Timeout after provider timeout or 60s
+ setTimeout(() => {
+ child.kill();
+ reject(new Error('Detection timed out'));
+ }, provider.timeout || 60000);
+ });
+}
+
+/**
+ * Execute AI detection using API provider
+ */
+async function executeApiDetection(provider, prompt) {
+ const headers = { 'Content-Type': 'application/json' };
+ if (provider.apiKey) {
+ headers['Authorization'] = `Bearer ${provider.apiKey}`;
+ }
+
+ const response = await fetch(`${provider.endpoint}/chat/completions`, {
+ method: 'POST',
+ headers,
+ body: JSON.stringify({
+ model: provider.defaultModel,
+ messages: [{ role: 'user', content: prompt }],
+ temperature: 0.1
+ })
+ });
+
+ if (!response.ok) {
+ throw new Error(`API error: ${response.status}`);
+ }
+
+ const data = await response.json();
+ return data.choices?.[0]?.message?.content || '';
+}
+
+/**
+ * Parse AI response to extract JSON
+ */
+function parseAiResponse(response) {
+ // Try to extract JSON from response
+ let jsonStr = response.trim();
+
+ // Remove markdown code blocks if present
+ const jsonMatch = jsonStr.match(/```(?:json)?\s*([\s\S]*?)```/);
+ if (jsonMatch) {
+ jsonStr = jsonMatch[1].trim();
+ }
+
+ // Try to find JSON object
+ const objectMatch = jsonStr.match(/\{[\s\S]*\}/);
+ if (objectMatch) {
+ jsonStr = objectMatch[0];
+ }
+
+ return JSON.parse(jsonStr);
+}
+
+/**
+ * Auto-detect app configuration using AI
+ */
+export async function detectAppWithAi(dirPath, providerId = null) {
+ // Validate directory
+ if (!existsSync(dirPath)) {
+ return { success: false, error: 'Directory does not exist' };
+ }
+
+ const stats = await stat(dirPath);
+ if (!stats.isDirectory()) {
+ return { success: false, error: 'Path is not a directory' };
+ }
+
+ // Get provider
+ const provider = providerId
+ ? await getProviderById(providerId)
+ : await getActiveProvider();
+
+ if (!provider) {
+ return { success: false, error: 'No AI provider configured' };
+ }
+
+ if (!provider.enabled) {
+ return { success: false, error: 'AI provider is disabled' };
+ }
+
+ // Gather context
+ const context = await gatherProjectContext(dirPath);
+ const prompt = buildAnalysisPrompt(context);
+
+ // Execute detection
+ let response;
+ if (provider.type === 'cli') {
+ response = await executeCliDetection(provider, prompt, dirPath)
+ .catch(err => { throw new Error(`CLI detection failed: ${err.message}`); });
+ } else if (provider.type === 'api') {
+ response = await executeApiDetection(provider, prompt)
+ .catch(err => { throw new Error(`API detection failed: ${err.message}`); });
+ } else {
+ return { success: false, error: 'Unknown provider type' };
+ }
+
+ // Parse response
+ const detected = parseAiResponse(response);
+
+ return {
+ success: true,
+ provider: provider.name,
+ detected: {
+ name: detected.name || context.dirName,
+ description: detected.description || '',
+ uiPort: detected.uiPort || null,
+ apiPort: detected.apiPort || null,
+ startCommands: detected.startCommands || ['npm run dev'],
+ pm2ProcessNames: detected.pm2ProcessNames || [context.dirName.toLowerCase().replace(/[^a-z0-9]/g, '-')],
+ hasFrontend: detected.hasFrontend !== false,
+ hasBackend: detected.hasBackend !== false
+ },
+ context: {
+ hasPackageJson: !!context.packageJson,
+ hasReadme: !!context.readme,
+ configFiles: context.configFiles.map(f => f.name)
+ }
+ };
+}
diff --git a/server/services/apps.js b/server/services/apps.js
index 6c80af619e..b52e7c934f 100644
--- a/server/services/apps.js
+++ b/server/services/apps.js
@@ -67,7 +67,8 @@ export async function createApp(appData) {
const app = {
id,
...appData,
- uiUrl: appData.uiUrl || (appData.uiPort ? `http://localhost:${appData.uiPort}` : null),
+ // Don't hardcode host - client will construct URL from current hostname
+ uiUrl: appData.uiUrl || null,
startCommands: appData.startCommands || ['npm run dev'],
pm2ProcessNames: appData.pm2ProcessNames || [appData.name.toLowerCase().replace(/\s+/g, '-')],
envFile: appData.envFile || '.env',
@@ -101,9 +102,9 @@ export async function updateApp(id, updates) {
updatedAt: new Date().toISOString()
};
- // Recompute uiUrl if uiPort changed
+ // Clear uiUrl if uiPort changed - client will construct URL dynamically
if (updates.uiPort && !updates.uiUrl) {
- app.uiUrl = `http://localhost:${updates.uiPort}`;
+ app.uiUrl = null;
}
data.apps[id] = app;
diff --git a/server/services/commands.js b/server/services/commands.js
new file mode 100644
index 0000000000..8bf02757ce
--- /dev/null
+++ b/server/services/commands.js
@@ -0,0 +1,139 @@
+import { spawn } from 'child_process';
+import { logAction } from './history.js';
+
+// Allowlist of safe commands
+const ALLOWED_COMMANDS = new Set([
+ 'npm', 'npx', 'pnpm', 'yarn', 'bun',
+ 'node', 'deno',
+ 'git', 'gh',
+ 'pm2',
+ 'ls', 'cat', 'head', 'tail', 'grep', 'find', 'wc',
+ 'pwd', 'which', 'echo', 'env',
+ 'curl', 'wget',
+ 'docker', 'docker-compose',
+ 'make', 'cargo', 'go', 'python', 'python3', 'pip', 'pip3',
+ 'brew'
+]);
+
+// Track active commands
+const activeCommands = new Map();
+
+/**
+ * Execute a shell command with safety checks
+ */
+export function executeCommand(command, workspacePath, onData, onComplete) {
+ const commandId = Date.now().toString(36) + Math.random().toString(36).substr(2);
+
+ // Parse command to check allowlist
+ const parts = command.trim().split(/\s+/);
+ const baseCommand = parts[0];
+
+ if (!ALLOWED_COMMANDS.has(baseCommand)) {
+ const error = `Command '${baseCommand}' is not in the allowlist`;
+ onComplete?.({ success: false, error, exitCode: 1 });
+ logAction('command', null, command.substring(0, 50), { command, workspacePath }, false, error);
+ return null;
+ }
+
+ const startTime = Date.now();
+ let output = '';
+
+ // Use shell to handle pipes, redirects, etc.
+ const child = spawn('sh', ['-c', command], {
+ cwd: workspacePath || process.cwd(),
+ env: { ...process.env, FORCE_COLOR: '1' }
+ });
+
+ activeCommands.set(commandId, child);
+
+ child.stdout.on('data', (data) => {
+ const text = data.toString();
+ output += text;
+ onData?.(text, 'stdout');
+ });
+
+ child.stderr.on('data', (data) => {
+ const text = data.toString();
+ output += text;
+ onData?.(text, 'stderr');
+ });
+
+ child.on('close', (code) => {
+ activeCommands.delete(commandId);
+ const duration = Date.now() - startTime;
+ const success = code === 0;
+
+ logAction('command', null, command.substring(0, 50), {
+ command,
+ workspacePath,
+ exitCode: code,
+ duration
+ }, success, success ? null : `Exit code ${code}`);
+
+ onComplete?.({
+ success,
+ exitCode: code,
+ duration,
+ output
+ });
+ });
+
+ child.on('error', (err) => {
+ activeCommands.delete(commandId);
+ logAction('command', null, command.substring(0, 50), { command, workspacePath }, false, err.message);
+ onComplete?.({
+ success: false,
+ error: err.message,
+ exitCode: 1
+ });
+ });
+
+ return commandId;
+}
+
+/**
+ * Stop a running command
+ */
+export function stopCommand(commandId) {
+ const child = activeCommands.get(commandId);
+ if (child) {
+ child.kill('SIGTERM');
+ activeCommands.delete(commandId);
+ return true;
+ }
+ return false;
+}
+
+/**
+ * Check if a command is active
+ */
+export function isCommandActive(commandId) {
+ return activeCommands.has(commandId);
+}
+
+/**
+ * Get list of allowed commands
+ */
+export function getAllowedCommands() {
+ return Array.from(ALLOWED_COMMANDS).sort();
+}
+
+/**
+ * Add a command to the allowlist (runtime only)
+ */
+export function addAllowedCommand(command) {
+ ALLOWED_COMMANDS.add(command);
+}
+
+/**
+ * Remove a command from the allowlist (runtime only)
+ */
+export function removeAllowedCommand(command) {
+ // Don't allow removing core commands
+ const core = ['npm', 'node', 'git', 'pm2'];
+ if (core.includes(command)) {
+ return false;
+ }
+ ALLOWED_COMMANDS.delete(command);
+ return true;
+}
diff --git a/server/services/history.js b/server/services/history.js
new file mode 100644
index 0000000000..58a325a3b2
--- /dev/null
+++ b/server/services/history.js
@@ -0,0 +1,147 @@
+import { readFile, writeFile, mkdir } from 'fs/promises';
+import { existsSync } from 'fs';
+import { join, dirname } from 'path';
+import { fileURLToPath } from 'url';
+import { v4 as uuidv4 } from 'uuid';
+
+const __filename = fileURLToPath(import.meta.url);
+const __dirname = dirname(__filename);
+const DATA_DIR = join(__dirname, '../../data');
+const HISTORY_FILE = join(DATA_DIR, 'history.json');
+const MAX_ENTRIES = 500;
+
+async function ensureDataDir() {
+ if (!existsSync(DATA_DIR)) {
+ await mkdir(DATA_DIR, { recursive: true });
+ }
+}
+
+async function loadHistory() {
+ await ensureDataDir();
+
+ if (!existsSync(HISTORY_FILE)) {
+ return { entries: [] };
+ }
+
+ const content = await readFile(HISTORY_FILE, 'utf-8');
+ return JSON.parse(content);
+}
+
+async function saveHistory(data) {
+ await ensureDataDir();
+ // Trim to max entries
+ if (data.entries.length > MAX_ENTRIES) {
+ data.entries = data.entries.slice(-MAX_ENTRIES);
+ }
+ await writeFile(HISTORY_FILE, JSON.stringify(data, null, 2));
+}
+
+/**
+ * Log an action to history
+ */
+export async function logAction(action, target, targetName, details = {}, success = true, error = null) {
+ const data = await loadHistory();
+
+ const entry = {
+ id: uuidv4(),
+ action,
+ target,
+ targetName,
+ details,
+ success,
+ error,
+ timestamp: new Date().toISOString()
+ };
+
+ data.entries.push(entry);
+ await saveHistory(data);
+
+ return entry;
+}
+
+/**
+ * Get history entries with optional filtering
+ */
+export async function getHistory(options = {}) {
+ const { limit = 100, offset = 0, action, target, success } = options;
+
+ const data = await loadHistory();
+ let entries = [...data.entries].reverse(); // Most recent first
+
+ // Apply filters
+ if (action) {
+ entries = entries.filter(e => e.action === action);
+ }
+ if (target) {
+ entries = entries.filter(e => e.target === target);
+ }
+ if (success !== undefined) {
+ entries = entries.filter(e => e.success === success);
+ }
+
+ return {
+ total: entries.length,
+ entries: entries.slice(offset, offset + limit)
+ };
+}
+
+/**
+ * Get unique action types in history
+ */
+export async function getActionTypes() {
+ const data = await loadHistory();
+ const types = new Set(data.entries.map(e => e.action));
+ return Array.from(types).sort();
+}
+
+/**
+ * Clear history (optionally older than days)
+ */
+export async function clearHistory(olderThanDays = null) {
+ const data = await loadHistory();
+
+ if (olderThanDays === null) {
+ data.entries = [];
+ } else {
+ const cutoff = new Date();
+ cutoff.setDate(cutoff.getDate() - olderThanDays);
+ data.entries = data.entries.filter(e => new Date(e.timestamp) >= cutoff);
+ }
+
+ await saveHistory(data);
+ return { cleared: true };
+}
+
+/**
+ * Get history stats
+ */
+export async function getHistoryStats() {
+ const data = await loadHistory();
+ const entries = data.entries;
+
+ const stats = {
+ total: entries.length,
+ byAction: {},
+ successRate: 0,
+ recentActivity: []
+ };
+
+ let successCount = 0;
+ for (const entry of entries) {
+ stats.byAction[entry.action] = (stats.byAction[entry.action] || 0) + 1;
+ if (entry.success) successCount++;
+ }
+
+ stats.successRate = entries.length > 0 ? (successCount / entries.length * 100).toFixed(1) : 0;
+
+ // Last 24 hours activity by hour
+ const now = new Date();
+ const last24h = entries.filter(e => {
+ const diff = now - new Date(e.timestamp);
+ return diff < 24 * 60 * 60 * 1000;
+ });
+
+ stats.last24h = last24h.length;
+
+ return stats;
+}
diff --git a/server/services/providers.js b/server/services/providers.js
new file mode 100644
index 0000000000..eb63436b75
--- /dev/null
+++ b/server/services/providers.js
@@ -0,0 +1,206 @@
+import { readFile, writeFile, mkdir } from 'fs/promises';
+import { existsSync } from 'fs';
+import { join, dirname } from 'path';
+import { fileURLToPath } from 'url';
+import { exec } from 'child_process';
+import { promisify } from 'util';
+
+const execAsync = promisify(exec);
+const __filename = fileURLToPath(import.meta.url);
+const __dirname = dirname(__filename);
+const DATA_DIR = join(__dirname, '../../data');
+const PROVIDERS_FILE = join(DATA_DIR, 'providers.json');
+const SAMPLE_FILE = join(__dirname, '../../data.sample/providers.json');
+
+async function ensureDataDir() {
+ if (!existsSync(DATA_DIR)) {
+ await mkdir(DATA_DIR, { recursive: true });
+ }
+}
+
+async function loadProviders() {
+ await ensureDataDir();
+
+ if (!existsSync(PROVIDERS_FILE)) {
+ // Copy from sample if exists
+ if (existsSync(SAMPLE_FILE)) {
+ const sample = await readFile(SAMPLE_FILE, 'utf-8');
+ await writeFile(PROVIDERS_FILE, sample);
+ return JSON.parse(sample);
+ }
+ return { activeProvider: null, providers: {} };
+ }
+
+ const content = await readFile(PROVIDERS_FILE, 'utf-8');
+ return JSON.parse(content);
+}
+
+async function saveProviders(data) {
+ await ensureDataDir();
+ await writeFile(PROVIDERS_FILE, JSON.stringify(data, null, 2));
+}
+
+export async function getAllProviders() {
+ const data = await loadProviders();
+ return {
+ activeProvider: data.activeProvider,
+ providers: Object.values(data.providers)
+ };
+}
+
+export async function getProviderById(id) {
+ const data = await loadProviders();
+ return data.providers[id] || null;
+}
+
+export async function getActiveProvider() {
+ const data = await loadProviders();
+ if (!data.activeProvider) return null;
+ return data.providers[data.activeProvider] || null;
+}
+
+export async function setActiveProvider(id) {
+ const data = await loadProviders();
+ if (!data.providers[id]) {
+ return null;
+ }
+ data.activeProvider = id;
+ await saveProviders(data);
+ return data.providers[id];
+}
+
+export async function createProvider(providerData) {
+ const data = await loadProviders();
+ const id = providerData.id || providerData.name.toLowerCase().replace(/[^a-z0-9]/g, '-');
+
+ if (data.providers[id]) {
+ throw new Error('Provider with this ID already exists');
+ }
+
+ const provider = {
+ id,
+ name: providerData.name,
+ type: providerData.type || 'cli', // cli | api
+ command: providerData.command || null,
+ args: providerData.args || [],
+ endpoint: providerData.endpoint || null,
+ apiKey: providerData.apiKey || '',
+ models: providerData.models || [],
+ defaultModel: providerData.defaultModel || null,
+ timeout: providerData.timeout || 300000,
+ enabled: providerData.enabled !== false,
+ envVars: providerData.envVars || {}
+ };
+
+ data.providers[id] = provider;
+
+ // Set as active if it's the first provider
+ if (!data.activeProvider) {
+ data.activeProvider = id;
+ }
+
+ await saveProviders(data);
+ return provider;
+}
+
+export async function updateProvider(id, updates) {
+ const data = await loadProviders();
+
+ if (!data.providers[id]) {
+ return null;
+ }
+
+ const provider = {
+ ...data.providers[id],
+ ...updates,
+ id // Prevent ID override
+ };
+
+ data.providers[id] = provider;
+ await saveProviders(data);
+ return provider;
+}
+
+export async function deleteProvider(id) {
+ const data = await loadProviders();
+
+ if (!data.providers[id]) {
+ return false;
+ }
+
+ delete data.providers[id];
+
+ // Clear active if it was deleted
+ if (data.activeProvider === id) {
+ const remaining = Object.keys(data.providers);
+ data.activeProvider = remaining.length > 0 ? remaining[0] : null;
+ }
+
+ await saveProviders(data);
+ return true;
+}
+
+export async function testProvider(id) {
+ const provider = await getProviderById(id);
+ if (!provider) {
+ return { success: false, error: 'Provider not found' };
+ }
+
+ if (provider.type === 'cli') {
+ // Test CLI availability
+ const { stdout, stderr } = await execAsync(`which ${provider.command}`).catch(() => ({ stdout: '', stderr: 'not found' }));
+
+ if (!stdout.trim()) {
+ return { success: false, error: `Command '${provider.command}' not found in PATH` };
+ }
+
+ // Try to get version or help
+ const { stdout: versionOut } = await execAsync(`${provider.command} --version 2>/dev/null || ${provider.command} -v 2>/dev/null || echo "available"`).catch(() => ({ stdout: 'available' }));
+
+ return {
+ success: true,
+ path: stdout.trim(),
+ version: versionOut.trim()
+ };
+ }
+
+ if (provider.type === 'api') {
+ // Test API endpoint
+ const modelsUrl = `${provider.endpoint}/models`;
+ const response = await fetch(modelsUrl, {
+ headers: provider.apiKey ? { 'Authorization': `Bearer ${provider.apiKey}` } : {}
+ }).catch(err => ({ ok: false, error: err.message }));
+
+ if (!response.ok) {
+ return { success: false, error: `API not reachable: ${response.error || response.status}` };
+ }
+
+ const models = await response.json().catch(() => ({ data: [] }));
+ return {
+ success: true,
+ endpoint: provider.endpoint,
+ models: models.data?.map(m => m.id) || []
+ };
+ }
+
+ return { success: false, error: 'Unknown provider type' };
+}
+
+export async function refreshProviderModels(id) {
+ const provider = await getProviderById(id);
+ if (!provider || provider.type !== 'api') {
+ return null;
+ }
+
+ const modelsUrl = `${provider.endpoint}/models`;
+ const response = await fetch(modelsUrl, {
+ headers: provider.apiKey ? { 'Authorization': `Bearer ${provider.apiKey}` } : {}
+ }).catch(() => null);
+
+ if (!response?.ok) return null;
+
+ const data = await response.json().catch(() => ({ data: [] }));
+ const models = data.data?.map(m => m.id) || [];
+
+ return updateProvider(id, { models });
+}
diff --git a/server/services/runner.js b/server/services/runner.js
new file mode 100644
index 0000000000..e92ed21d17
--- /dev/null
+++ b/server/services/runner.js
@@ -0,0 +1,327 @@
+import { spawn } from 'child_process';
+import { mkdir, writeFile, readFile, readdir, rm } from 'fs/promises';
+import { existsSync } from 'fs';
+import { join, dirname } from 'path';
+import { fileURLToPath } from 'url';
+import { v4 as uuidv4 } from 'uuid';
+import { getProviderById } from './providers.js';
+
+const __filename = fileURLToPath(import.meta.url);
+const __dirname = dirname(__filename);
+const DATA_DIR = join(__dirname, '../../data');
+const RUNS_DIR = join(DATA_DIR, 'runs');
+
+// Track active runs for cancellation
+const activeRuns = new Map();
+
+async function ensureRunsDir() {
+ if (!existsSync(RUNS_DIR)) {
+ await mkdir(RUNS_DIR, { recursive: true });
+ }
+}
+
+export async function createRun(options) {
+ const {
+ providerId,
+ model,
+ prompt,
+ workspacePath,
+ workspaceName
+ } = options;
+
+ const provider = await getProviderById(providerId);
+ if (!provider) {
+ throw new Error('Provider not found');
+ }
+
+ if (!provider.enabled) {
+ throw new Error('Provider is disabled');
+ }
+
+ await ensureRunsDir();
+
+ const runId = uuidv4();
+ const runDir = join(RUNS_DIR, runId);
+ await mkdir(runDir);
+
+ const metadata = {
+ id: runId,
+ type: 'ai',
+ providerId,
+ providerName: provider.name,
+ model: model || provider.defaultModel,
+ workspacePath,
+ workspaceName,
+ prompt: prompt.substring(0, 500), // Store truncated prompt in metadata
+ startTime: new Date().toISOString(),
+ endTime: null,
+ duration: null,
+ exitCode: null,
+ success: null,
+ error: null,
+ outputSize: 0
+ };
+
+ await writeFile(join(runDir, 'metadata.json'), JSON.stringify(metadata, null, 2));
+ await writeFile(join(runDir, 'prompt.txt'), prompt);
+ await writeFile(join(runDir, 'output.txt'), '');
+
+ return { runId, runDir, provider, metadata };
+}
+
+export async function executeCliRun(runId, provider, prompt, workspacePath, onData, onComplete) {
+ const runDir = join(RUNS_DIR, runId);
+ const outputPath = join(runDir, 'output.txt');
+ const metadataPath = join(runDir, 'metadata.json');
+
+ // Build command args
+ const args = [...(provider.args || [])];
+
+ // For claude CLI, the prompt goes at the end
+ if (provider.command === 'claude') {
+ args.push(prompt);
+ } else {
+ // For other CLIs, try stdin or args
+ args.push(prompt);
+ }
+
+ const startTime = Date.now();
+ let output = '';
+
+ const child = spawn(provider.command, args, {
+ cwd: workspacePath || process.cwd(),
+ env: { ...process.env, ...provider.envVars },
+ shell: false
+ });
+
+ activeRuns.set(runId, child);
+
+ const appendOutput = async (data) => {
+ const text = data.toString();
+ output += text;
+ await writeFile(outputPath, output);
+ onData?.(text);
+ };
+
+ child.stdout.on('data', appendOutput);
+ child.stderr.on('data', appendOutput);
+
+ child.on('close', async (code) => {
+ activeRuns.delete(runId);
+
+ const endTime = Date.now();
+ const metadata = JSON.parse(await readFile(metadataPath, 'utf-8'));
+
+ metadata.endTime = new Date().toISOString();
+ metadata.duration = endTime - startTime;
+ metadata.exitCode = code;
+ metadata.success = code === 0;
+ metadata.outputSize = Buffer.byteLength(output);
+
+ await writeFile(metadataPath, JSON.stringify(metadata, null, 2));
+ onComplete?.(metadata);
+ });
+
+ child.on('error', async (err) => {
+ activeRuns.delete(runId);
+
+ const metadata = JSON.parse(await readFile(metadataPath, 'utf-8'));
+ metadata.endTime = new Date().toISOString();
+ metadata.duration = Date.now() - startTime;
+ metadata.success = false;
+ metadata.error = err.message;
+
+ await writeFile(metadataPath, JSON.stringify(metadata, null, 2));
+ onComplete?.(metadata);
+ });
+
+ // Set timeout
+ if (provider.timeout) {
+ setTimeout(() => {
+ if (activeRuns.has(runId)) {
+ child.kill('SIGTERM');
+ }
+ }, provider.timeout);
+ }
+
+ return runId;
+}
+
+export async function executeApiRun(runId, provider, model, prompt, workspacePath, onData, onComplete) {
+ const runDir = join(RUNS_DIR, runId);
+ const outputPath = join(runDir, 'output.txt');
+ const metadataPath = join(runDir, 'metadata.json');
+
+ const startTime = Date.now();
+ let output = '';
+
+ const headers = {
+ 'Content-Type': 'application/json'
+ };
+ if (provider.apiKey) {
+ headers['Authorization'] = `Bearer ${provider.apiKey}`;
+ }
+
+ const controller = new AbortController();
+ activeRuns.set(runId, controller);
+
+ const response = await fetch(`${provider.endpoint}/chat/completions`, {
+ method: 'POST',
+ headers,
+ signal: controller.signal,
+ body: JSON.stringify({
+ model: model || provider.defaultModel,
+ messages: [{ role: 'user', content: prompt }],
+ stream: true
+ })
+ }).catch(err => ({ ok: false, error: err.message }));
+
+ if (!response.ok) {
+ activeRuns.delete(runId);
+ const metadata = JSON.parse(await readFile(metadataPath, 'utf-8'));
+ metadata.endTime = new Date().toISOString();
+ metadata.duration = Date.now() - startTime;
+ metadata.success = false;
+ metadata.error = response.error || `API error: ${response.status}`;
+ await writeFile(metadataPath, JSON.stringify(metadata, null, 2));
+ onComplete?.(metadata);
+ return runId;
+ }
+
+ // Handle streaming response
+ const reader = response.body.getReader();
+ const decoder = new TextDecoder();
+
+ const processStream = async () => {
+ while (true) {
+ const { done, value } = await reader.read();
+ if (done) break;
+
+ const chunk = decoder.decode(value);
+ const lines = chunk.split('\n').filter(line => line.startsWith('data: '));
+
+ for (const line of lines) {
+ const data = line.slice(6);
+ if (data === '[DONE]') continue;
+
+ const parsed = JSON.parse(data).catch?.(() => null);
+ if (parsed?.choices?.[0]?.delta?.content) {
+ const text = parsed.choices[0].delta.content;
+ output += text;
+ onData?.(text);
+ }
+ }
+ }
+
+ await writeFile(outputPath, output);
+ activeRuns.delete(runId);
+
+ const metadata = JSON.parse(await readFile(metadataPath, 'utf-8'));
+ metadata.endTime = new Date().toISOString();
+ metadata.duration = Date.now() - startTime;
+ metadata.exitCode = 0;
+ metadata.success = true;
+ metadata.outputSize = Buffer.byteLength(output);
+ await writeFile(metadataPath, JSON.stringify(metadata, null, 2));
+ onComplete?.(metadata);
+ };
+
+ processStream().catch(async (err) => {
+ activeRuns.delete(runId);
+ const metadata = JSON.parse(await readFile(metadataPath, 'utf-8'));
+ metadata.endTime = new Date().toISOString();
+ metadata.duration = Date.now() - startTime;
+ metadata.success = false;
+ metadata.error = err.message;
+ await writeFile(metadataPath, JSON.stringify(metadata, null, 2));
+ onComplete?.(metadata);
+ });
+
+ return runId;
+}
+
+export async function stopRun(runId) {
+ const active = activeRuns.get(runId);
+ if (!active) {
+ return false;
+ }
+
+ if (active.kill) {
+ // It's a child process
+ active.kill('SIGTERM');
+ } else if (active.abort) {
+ // It's an AbortController
+ active.abort();
+ }
+
+ activeRuns.delete(runId);
+ return true;
+}
+
+export async function getRun(runId) {
+ const runDir = join(RUNS_DIR, runId);
+ if (!existsSync(runDir)) {
+ return null;
+ }
+
+ const metadata = JSON.parse(await readFile(join(runDir, 'metadata.json'), 'utf-8'));
+ return metadata;
+}
+
+export async function getRunOutput(runId) {
+ const runDir = join(RUNS_DIR, runId);
+ if (!existsSync(runDir)) {
+ return null;
+ }
+
+ return readFile(join(runDir, 'output.txt'), 'utf-8');
+}
+
+export async function getRunPrompt(runId) {
+ const runDir = join(RUNS_DIR, runId);
+ if (!existsSync(runDir)) {
+ return null;
+ }
+
+ return readFile(join(runDir, 'prompt.txt'), 'utf-8');
+}
+
+export async function listRuns(limit = 50, offset = 0) {
+ await ensureRunsDir();
+
+ const entries = await readdir(RUNS_DIR, { withFileTypes: true });
+ const runIds = entries
+ .filter(e => e.isDirectory())
+ .map(e => e.name);
+
+ // Load all metadata and sort by start time
+ const runs = [];
+ for (const runId of runIds) {
+ const metadataPath = join(RUNS_DIR, runId, 'metadata.json');
+ if (existsSync(metadataPath)) {
+ const metadata = JSON.parse(await readFile(metadataPath, 'utf-8'));
+ runs.push(metadata);
+ }
+ }
+
+ runs.sort((a, b) => new Date(b.startTime) - new Date(a.startTime));
+
+ return {
+ total: runs.length,
+ runs: runs.slice(offset, offset + limit)
+ };
+}
+
+export async function deleteRun(runId) {
+ const runDir = join(RUNS_DIR, runId);
+ if (!existsSync(runDir)) {
+ return false;
+ }
+
+ await rm(runDir, { recursive: true });
+ return true;
+}
+
+export function isRunActive(runId) {
+ return activeRuns.has(runId);
+}
diff --git a/server/services/socket.js b/server/services/socket.js
new file mode 100644
index 0000000000..e165743278
--- /dev/null
+++ b/server/services/socket.js
@@ -0,0 +1,95 @@
+import { spawn } from 'child_process';
+
+// Store active log streams per socket
+const activeStreams = new Map();
+
+export function initSocket(io) {
+ io.on('connection', (socket) => {
+ console.log('Client connected:', socket.id);
+
+ // Handle log streaming requests
+ socket.on('logs:subscribe', ({ processName, lines = 100 }) => {
+ // Clean up any existing stream for this socket
+ cleanupStream(socket.id);
+
+ console.log(`Starting log stream for ${processName} (${lines} lines)`);
+
+ // Spawn pm2 logs with --raw flag
+ const logProcess = spawn('pm2', ['logs', processName, '--raw', '--lines', String(lines)], {
+ shell: false
+ });
+
+ activeStreams.set(socket.id, { process: logProcess, processName });
+
+ let buffer = '';
+
+ logProcess.stdout.on('data', (data) => {
+ buffer += data.toString();
+ const lines = buffer.split('\n');
+ buffer = lines.pop() || '';
+ lines.forEach(line => {
+ if (line.trim()) {
+ socket.emit('logs:line', {
+ line,
+ type: 'stdout',
+ timestamp: Date.now(),
+ processName
+ });
+ }
+ });
+ });
+
+ logProcess.stderr.on('data', (data) => {
+ buffer += data.toString();
+ const lines = buffer.split('\n');
+ buffer = lines.pop() || '';
+ lines.forEach(line => {
+ if (line.trim()) {
+ socket.emit('logs:line', {
+ line,
+ type: 'stderr',
+ timestamp: Date.now(),
+ processName
+ });
+ }
+ });
+ });
+
+ logProcess.on('error', (err) => {
+ socket.emit('logs:error', { error: err.message, processName });
+ });
+
+ logProcess.on('close', (code) => {
+ socket.emit('logs:close', { code, processName });
+ activeStreams.delete(socket.id);
+ });
+
+ socket.emit('logs:subscribed', { processName, timestamp: Date.now() });
+ });
+
+ // Handle unsubscribe
+ socket.on('logs:unsubscribe', () => {
+ cleanupStream(socket.id);
+ socket.emit('logs:unsubscribed');
+ });
+
+ // Cleanup on disconnect
+ socket.on('disconnect', () => {
+ console.log('Client disconnected:', socket.id);
+ cleanupStream(socket.id);
+ });
+ });
+}
+
+function cleanupStream(socketId) {
+ const stream = activeStreams.get(socketId);
+ if (stream) {
+ stream.process.kill('SIGTERM');
+ activeStreams.delete(socketId);
+ }
+}
+
+// Broadcast to all connected clients
+export function broadcast(io, event, data) {
+ io.emit(event, data);
+}