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

feat: enhanced DevTools, Apps page, and detection improvements

Adam Eivy41ab25ee6948
diff --git a/PLAN.md b/PLAN.md
index d88e7bb72b..27055b331e 100644
--- a/PLAN.md
+++ b/PLAN.md
@@ -34,8 +34,11 @@ pm2 logs
- [x] M5: AI providers + headless executor
- [x] M6: Dev tools (history, command runner)
- [ ] M7: App templates (create from templates, template management)
-- [ ] M8: Prompt manager (customizable AI prompts, variables, stages)
+- [x] M8: Prompt manager (customizable AI prompts, variables, stages)
- [x] M9: Streaming import detection (websocket updates, progressive discovery)
+- [x] M10: Enhanced DevTools (provider/model selection, screenshot upload, git status, usage metrics)
+- [x] M11: AI Agents Page (process detection, kill ability, colorful UI, expandable details)
+- [x] M12: History Improvements (expandable entries, runtime/output capture, full command display)
### Documentation
- [Contributing Guide](./docs/CONTRIBUTING.md) - Code guidelines, git workflow
@@ -143,6 +146,9 @@ Scaffold a new project from template:
| POST /api/templates/create | Create app from template |
| POST /api/templates | Add custom template |
| DELETE /api/templates/:id | Delete custom template |
+| GET /api/agents | List running AI agent processes |
+| GET /api/agents/:pid | Get agent process details |
+| DELETE /api/agents/:pid | Kill agent process |
---
diff --git a/README.md b/README.md
index 25bf63f126..cf6b9aa693 100644
--- a/README.md
+++ b/README.md
@@ -1,25 +1,51 @@
-# Port OS
+# PortOS
A self-hosted App OS portal for your dev machine. Manage all your local development apps from a single dashboard — accessible from anywhere via [Tailscale](https://tailscale.com).
Think Umbrel, but for your active git repos and dev environments. Access your dev apps from your phone, tablet, or any device on your Tailscale network.
+![PortOS Dashboard](./docs/media/portos_1.png)
+
## Features
-- **App Dashboard**: Grid of app tiles with status, ports, and quick actions (start/stop/restart)
-- **App Management**: Register existing projects or scaffold new ones from templates
-- **AI Auto-Detection**: Point to a directory and let AI analyze your project to configure it
-- **Log Viewer**: Real-time log streaming from PM2 processes via Socket.IO
-- **Dev Tools**: Process monitor, action history, and command runner
-- **AI Providers**: Run prompts via Claude Code CLI, Codex, Gemini CLI, LM Studio, or Ollama
-- **Mobile Ready**: Responsive design with collapsible sidebar for on-the-go access
+- **App Dashboard** — Grid of app tiles with status indicators, port links, and quick actions
+- **Start/Stop/Restart** — Control your apps directly from the dashboard or apps table
+- **Real-time Logs** — Stream PM2 logs via Socket.IO with tail length control
+- **Smart Import** — Point to a directory and auto-detect project config from package.json, vite.config, and ecosystem.config
+- **Dev Tools** — Process monitor, action history, git status, and shell command runner
+- **AI Runner** — Execute prompts via Claude Code CLI, Codex, Gemini CLI, or local models
+- **Mobile Ready** — Responsive design with collapsible sidebar for on-the-go access
+
+## Screenshots
+
+### Apps Management
+Expandable app rows with start/stop controls, PM2 process status, and quick actions.
+
+![Apps Page](./docs/media/portos_2.png)
+
+### Dev Tools
+Monitor AI agents, view action history, run commands, and check git status.
+
+![Dev Tools](./docs/media/portos_3.png)
+
+### App Import
+Auto-detect project configuration from your codebase — ports, start commands, and PM2 process names.
+
+![Add App](./docs/media/portos_4.png)
## Quick Start
```bash
+# Clone the repo
+git clone https://github.com/atomantic/PortOS.git
+cd PortOS
+
# Install dependencies
npm run install:all
+# Copy sample data (first time only)
+cp -r data.sample data
+
# Start with PM2 (recommended)
pm2 start ecosystem.config.cjs
@@ -27,37 +53,32 @@ pm2 start ecosystem.config.cjs
npm run dev
```
-Access PortOS:
-- **Local**: http://localhost:5555
-- **Tailscale**: http://[your-tailscale-ip]:5555
+**Access PortOS:**
+- Local: http://localhost:5555
+- Tailscale: http://[your-machine-name]:5555
## Network Access
-PortOS binds to `0.0.0.0` to allow access from your Tailscale network. This means you can:
+PortOS binds to `0.0.0.0` so you can access it from any device on your Tailscale network:
-- Access your dev dashboard from your phone while on the go
- Manage apps running on your home dev machine from anywhere
-- View logs and restart services remotely
+- Check logs and restart services from your phone
+- View dashboard on your tablet while coding on your laptop
-**Security Note**: PortOS is designed for private Tailscale networks. Do not expose ports 5554/5555 to the public internet.
+> **Security Note**: PortOS is designed for private Tailscale networks. Do not expose ports 5554/5555 to the public internet.
## Project Structure
```
PortOS/
-├── client/ # React + Vite frontend (port 5555)
-├── server/ # Express.js API (port 5554)
-├── data/ # Runtime data (gitignored)
-├── data.sample/ # Sample configurations
-├── docs/ # Documentation
-└── ecosystem.config.cjs # PM2 configuration
+├── client/ # React + Vite frontend (port 5555)
+├── server/ # Express.js API (port 5554)
+├── data/ # Runtime data (apps, providers, history)
+├── data.sample/ # Sample configurations to copy
+├── docs/ # Documentation and screenshots
+└── ecosystem.config.cjs # PM2 configuration
```
-## Documentation
-
-- [Contributing Guide](./docs/CONTRIBUTING.md) - Development setup, code guidelines
-- [Versioning & Releases](./docs/VERSIONING.md) - Version format, release process
-
## PM2 Commands
```bash
@@ -68,70 +89,46 @@ pm2 start ecosystem.config.cjs
pm2 status
# View logs
-pm2 logs portos-server
-pm2 logs portos-client
+pm2 logs portos-server --lines 100
+pm2 logs portos-client --lines 100
-# Restart
+# Restart both processes
pm2 restart portos-server portos-client
-# Stop
+# Stop both processes
pm2 stop portos-server portos-client
# Save process list (survives reboot)
pm2 save
```
-## API Endpoints
-
-### Apps
-| Method | Route | Description |
-|--------|-------|-------------|
-| GET | /api/apps | List all registered apps |
-| POST | /api/apps | Register new app |
-| GET | /api/apps/:id | Get app details |
-| PUT | /api/apps/:id | Update app |
-| DELETE | /api/apps/:id | Delete app |
-| POST | /api/apps/:id/start | Start app via PM2 |
-| POST | /api/apps/:id/stop | Stop app |
-| POST | /api/apps/:id/restart | Restart app |
-
-### AI & Detection
-| Method | Route | Description |
-|--------|-------|-------------|
-| POST | /api/detect/repo | Validate path and detect project type |
-| POST | /api/detect/ai | AI-powered app configuration detection |
-| GET | /api/providers | List AI providers |
-| POST | /api/runs | Execute AI prompt |
-
-### Dev Tools
-| Method | Route | Description |
-|--------|-------|-------------|
-| GET | /api/logs/:process | Stream logs via SSE |
-| GET | /api/history | Action history |
-| POST | /api/commands/execute | Run shell command |
-| GET | /api/commands/processes | List PM2 processes |
-
## Configuration
-### Apps
-Apps are stored in `data/apps.json`. Each app entry includes:
-- `name`: Display name
-- `repoPath`: Path to project directory
-- `uiPort` / `apiPort`: Port numbers
-- `startCommands`: Commands to start the app
-- `pm2ProcessNames`: PM2 process identifiers
+### Apps (`data/apps.json`)
+Each registered app includes:
+- **name** — Display name in the dashboard
+- **repoPath** — Absolute path to project directory
+- **uiPort / apiPort** — Port numbers for quick access links
+- **startCommands** — Commands to start the app (used by PM2)
+- **pm2ProcessNames** — PM2 process identifiers for status tracking
-### AI Providers
-Providers are stored in `data/providers.json`. Supported types:
-- **CLI**: Claude Code, Codex, Gemini CLI
-- **API**: LM Studio, Ollama (OpenAI-compatible endpoints)
+### AI Providers (`data/providers.json`)
+Configure AI providers for the runner:
+- **CLI-based**: Claude Code, Codex, Gemini CLI, Aider
+- **API-based**: LM Studio, Ollama (OpenAI-compatible endpoints)
## Security
-- Binds to `0.0.0.0` for Tailscale network access
-- Command runner uses an allowlist (npm, git, pm2, etc.)
-- No shell interpolation — commands use spawn with arg arrays
-- Designed for private networks only
+- Command runner uses an allowlist (npm, git, pm2, docker, etc.)
+- No shell interpolation — commands use spawn with argument arrays
+- Designed for private Tailscale networks only
+- No authentication (relies on network-level security)
+
+## Documentation
+
+- [Contributing Guide](./docs/CONTRIBUTING.md) — Development setup and code guidelines
+- [Versioning & Releases](./docs/VERSIONING.md) — Version format and release process
+- [Implementation Plan](./PLAN.md) — Detailed feature roadmap and API reference
## License
diff --git a/client/src/App.jsx b/client/src/App.jsx
index af3a460f5b..523e31fd2d 100644
--- a/client/src/App.jsx
+++ b/client/src/App.jsx
@@ -6,7 +6,7 @@ import Logs from './pages/Logs';
import CreateApp from './pages/CreateApp';
import Templates from './pages/Templates';
import AIProviders from './pages/AIProviders';
-import DevTools from './pages/DevTools';
+import { HistoryPage, RunnerPage, GitPage, UsagePage, ProcessesPage, AgentsPage } from './pages/DevTools';
import PromptManager from './pages/PromptManager';
export default function App() {
@@ -17,7 +17,12 @@ export default function App() {
<Route path="apps" element={<Apps />} />
<Route path="logs" element={<Logs />} />
<Route path="devtools" element={<Navigate to="/devtools/history" replace />} />
- <Route path="devtools/:tab" element={<DevTools />} />
+ <Route path="devtools/history" element={<HistoryPage />} />
+ <Route path="devtools/runner" element={<RunnerPage />} />
+ <Route path="devtools/git" element={<GitPage />} />
+ <Route path="devtools/usage" element={<UsagePage />} />
+ <Route path="devtools/processes" element={<ProcessesPage />} />
+ <Route path="devtools/agents" element={<AgentsPage />} />
<Route path="ai" element={<AIProviders />} />
<Route path="prompts" element={<PromptManager />} />
<Route path="create" element={<CreateApp />} />
diff --git a/client/src/components/Layout.jsx b/client/src/components/Layout.jsx
index 46d1c046a2..fd2a42c7fc 100644
--- a/client/src/components/Layout.jsx
+++ b/client/src/components/Layout.jsx
@@ -13,7 +13,10 @@ import {
Menu,
History,
Play,
- Activity
+ Activity,
+ GitBranch,
+ BarChart3,
+ Cpu
} from 'lucide-react';
import packageJson from '../../package.json';
import Logo from './Logo';
@@ -28,7 +31,10 @@ const navItems = [
children: [
{ to: '/devtools/history', label: 'History', icon: History },
{ to: '/devtools/runner', label: 'Runner', icon: Play },
- { to: '/devtools/processes', label: 'Processes', icon: Activity }
+ { to: '/devtools/git', label: 'Git Status', icon: GitBranch },
+ { to: '/devtools/usage', label: 'Usage', icon: BarChart3 },
+ { to: '/devtools/processes', label: 'Processes', icon: Activity },
+ { to: '/devtools/agents', label: 'AI Agents', icon: Cpu }
]
},
{
diff --git a/client/src/pages/AIProviders.jsx b/client/src/pages/AIProviders.jsx
index acf0f167ac..a0a98b3523 100644
--- a/client/src/pages/AIProviders.jsx
+++ b/client/src/pages/AIProviders.jsx
@@ -248,6 +248,14 @@ export default function AIProviders() {
{provider.defaultModel && (
<p>Default: <code className="text-gray-300">{provider.defaultModel}</code></p>
)}
+ {(provider.lightModel || provider.mediumModel || provider.heavyModel) && (
+ <p className="text-xs">
+ Tiers:
+ {provider.lightModel && <span className="ml-1 text-green-400">{provider.lightModel}</span>}
+ {provider.mediumModel && <span className="ml-1 text-yellow-400">{provider.mediumModel}</span>}
+ {provider.heavyModel && <span className="ml-1 text-red-400">{provider.heavyModel}</span>}
+ </p>
+ )}
</div>
{testResults[provider.id] && !testResults[provider.id].testing && (
@@ -377,6 +385,9 @@ function ProviderForm({ provider, onClose, onSave }) {
endpoint: provider?.endpoint || '',
apiKey: provider?.apiKey || '',
defaultModel: provider?.defaultModel || '',
+ lightModel: provider?.lightModel || '',
+ mediumModel: provider?.mediumModel || '',
+ heavyModel: provider?.heavyModel || '',
timeout: provider?.timeout || 300000,
enabled: provider?.enabled !== false
});
@@ -495,6 +506,43 @@ function ProviderForm({ provider, onClose, onSave }) {
/>
</div>
+ {/* Model Tiers */}
+ <div className="border-t border-port-border pt-4 mt-4">
+ <h4 className="text-sm font-medium text-gray-300 mb-3">Model Tiers</h4>
+ <div className="grid grid-cols-3 gap-3">
+ <div>
+ <label className="block text-xs text-gray-400 mb-1">Light (fast)</label>
+ <input
+ type="text"
+ value={formData.lightModel}
+ onChange={(e) => setFormData(prev => ({ ...prev, lightModel: e.target.value }))}
+ placeholder="haiku"
+ className="w-full px-2 py-1.5 bg-port-bg border border-port-border rounded-lg text-white text-sm focus:border-port-accent focus:outline-none"
+ />
+ </div>
+ <div>
+ <label className="block text-xs text-gray-400 mb-1">Medium (balanced)</label>
+ <input
+ type="text"
+ value={formData.mediumModel}
+ onChange={(e) => setFormData(prev => ({ ...prev, mediumModel: e.target.value }))}
+ placeholder="sonnet"
+ className="w-full px-2 py-1.5 bg-port-bg border border-port-border rounded-lg text-white text-sm focus:border-port-accent focus:outline-none"
+ />
+ </div>
+ <div>
+ <label className="block text-xs text-gray-400 mb-1">Heavy (powerful)</label>
+ <input
+ type="text"
+ value={formData.heavyModel}
+ onChange={(e) => setFormData(prev => ({ ...prev, heavyModel: e.target.value }))}
+ placeholder="opus"
+ className="w-full px-2 py-1.5 bg-port-bg border border-port-border rounded-lg text-white text-sm focus:border-port-accent focus:outline-none"
+ />
+ </div>
+ </div>
+ </div>
+
<div>
<label className="block text-sm text-gray-400 mb-1">Timeout (ms)</label>
<input
diff --git a/client/src/pages/Apps.jsx b/client/src/pages/Apps.jsx
index 1205a23379..17dac99650 100644
--- a/client/src/pages/Apps.jsx
+++ b/client/src/pages/Apps.jsx
@@ -1,6 +1,6 @@
-import { useState, useEffect } from 'react';
+import { useState, useEffect, Fragment } from 'react';
import { Link } from 'react-router-dom';
-import { ExternalLink } from 'lucide-react';
+import { ExternalLink, Play, Square, RotateCcw, FolderOpen, Terminal, Code } from 'lucide-react';
import StatusBadge from '../components/StatusBadge';
import * as api from '../services/api';
@@ -9,6 +9,8 @@ export default function Apps() {
const [loading, setLoading] = useState(true);
const [editingApp, setEditingApp] = useState(null);
const [confirmingDelete, setConfirmingDelete] = useState(null);
+ const [expandedId, setExpandedId] = useState(null);
+ const [actionLoading, setActionLoading] = useState({});
const fetchApps = async () => {
const data = await api.getApps().catch(() => []);
@@ -18,6 +20,8 @@ export default function Apps() {
useEffect(() => {
fetchApps();
+ const interval = setInterval(fetchApps, 5000);
+ return () => clearInterval(interval);
}, []);
const handleDelete = async (app) => {
@@ -26,6 +30,37 @@ export default function Apps() {
fetchApps();
};
+ const handleStart = async (app) => {
+ setActionLoading(prev => ({ ...prev, [app.id]: 'start' }));
+ await api.startApp(app.id).catch(() => null);
+ setTimeout(() => {
+ setActionLoading(prev => ({ ...prev, [app.id]: null }));
+ fetchApps();
+ }, 1500);
+ };
+
+ const handleStop = async (app) => {
+ setActionLoading(prev => ({ ...prev, [app.id]: 'stop' }));
+ await api.stopApp(app.id).catch(() => null);
+ setTimeout(() => {
+ setActionLoading(prev => ({ ...prev, [app.id]: null }));
+ fetchApps();
+ }, 1500);
+ };
+
+ const handleRestart = async (app) => {
+ setActionLoading(prev => ({ ...prev, [app.id]: 'restart' }));
+ await api.restartApp(app.id).catch(() => null);
+ setTimeout(() => {
+ setActionLoading(prev => ({ ...prev, [app.id]: null }));
+ fetchApps();
+ }, 2000);
+ };
+
+ const toggleExpand = (id) => {
+ setExpandedId(prev => prev === id ? null : id);
+ };
+
if (loading) {
return (
<div className="flex items-center justify-center h-64">
@@ -69,79 +104,223 @@ export default function Apps() {
<table className="w-full">
<thead className="bg-port-border/50">
<tr>
+ <th className="w-8 px-4 py-3"></th>
<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">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-center px-4 py-3 text-sm font-medium text-gray-400">Controls</th>
<th className="text-right px-4 py-3 text-sm font-medium text-gray-400">Actions</th>
</tr>
</thead>
<tbody className="divide-y divide-port-border">
{apps.map(app => (
- <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">
- {(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.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">
- {confirmingDelete === app.id ? (
- <div className="flex items-center justify-end gap-2">
- <span className="text-xs text-gray-400">Remove from PortOS?</span>
- <button
- onClick={() => handleDelete(app)}
- className="text-sm px-2 py-1 bg-port-error/20 text-port-error hover:bg-port-error/30 rounded"
- >
- Yes
- </button>
- <button
- onClick={() => setConfirmingDelete(null)}
- className="text-sm px-2 py-1 text-gray-400 hover:text-white"
- >
- No
- </button>
+ <Fragment key={app.id}>
+ <tr className="hover:bg-port-border/30">
+ <td className="px-4 py-3">
+ <button
+ onClick={() => toggleExpand(app.id)}
+ className="text-gray-400 hover:text-white transition-transform"
+ >
+ <span className={`inline-block transition-transform ${expandedId === app.id ? 'rotate-90' : ''}`}>▶</span>
+ </button>
+ </td>
+ <td className="px-4 py-3">
+ <div className="font-medium text-white">{app.name}</div>
+ <div className="text-xs text-gray-500">
+ {(app.pm2ProcessNames || []).join(', ')}
</div>
- ) : (
- <>
+ </td>
+ <td className="px-4 py-3 text-sm">
+ <div className="flex items-center gap-3">
{app.uiPort && (
<button
onClick={() => window.open(`http://localhost:${app.uiPort}`, '_blank')}
- className="text-sm text-green-400 hover:text-green-300 mr-3"
+ className="text-cyan-400 hover:text-cyan-300 font-mono flex items-center gap-1"
title={`Open UI at localhost:${app.uiPort}`}
>
- <ExternalLink size={16} className="inline" />
+ :{app.uiPort} <ExternalLink size={12} />
</button>
)}
- <button
- onClick={() => setEditingApp(app)}
- className="text-sm text-port-accent hover:text-port-accent/80 mr-3"
- >
- Edit
- </button>
- <button
- onClick={() => setConfirmingDelete(app.id)}
- className="text-sm text-port-error hover:text-port-error/80"
- >
- Delete
- </button>
- </>
- )}
- </td>
- </tr>
+ {app.apiPort && (
+ <span className="text-gray-400 font-mono">API:{app.apiPort}</span>
+ )}
+ {!app.uiPort && !app.apiPort && <span className="text-gray-500">-</span>}
+ </div>
+ </td>
+ <td className="px-4 py-3">
+ <StatusBadge status={app.overallStatus} size="sm" />
+ </td>
+ <td className="px-4 py-3">
+ {/* Start/Stop/Restart Button Group */}
+ <div className="flex justify-center">
+ <div className="inline-flex rounded-lg overflow-hidden border border-port-border">
+ {app.overallStatus === 'online' ? (
+ <>
+ <button
+ onClick={() => handleStop(app)}
+ disabled={actionLoading[app.id]}
+ className="px-3 py-1.5 bg-port-error/20 text-port-error hover:bg-port-error/30 transition-colors disabled:opacity-50 flex items-center gap-1"
+ title="Stop"
+ >
+ <Square size={14} />
+ <span className="text-xs">Stop</span>
+ </button>
+ <button
+ onClick={() => handleRestart(app)}
+ disabled={actionLoading[app.id]}
+ className="px-3 py-1.5 bg-port-warning/20 text-port-warning hover:bg-port-warning/30 transition-colors disabled:opacity-50 border-l border-port-border flex items-center gap-1"
+ title="Restart"
+ >
+ <RotateCcw size={14} className={actionLoading[app.id] === 'restart' ? 'animate-spin' : ''} />
+ <span className="text-xs">Restart</span>
+ </button>
+ </>
+ ) : (
+ <button
+ onClick={() => handleStart(app)}
+ disabled={actionLoading[app.id]}
+ className="px-3 py-1.5 bg-port-success/20 text-port-success hover:bg-port-success/30 transition-colors disabled:opacity-50 flex items-center gap-1"
+ title="Start"
+ >
+ <Play size={14} />
+ <span className="text-xs">{actionLoading[app.id] === 'start' ? 'Starting...' : 'Start'}</span>
+ </button>
+ )}
+ </div>
+ </div>
+ </td>
+ <td className="px-4 py-3 text-right">
+ {confirmingDelete === app.id ? (
+ <div className="flex items-center justify-end gap-2">
+ <span className="text-xs text-gray-400">Remove?</span>
+ <div className="inline-flex rounded-lg overflow-hidden border border-port-border">
+ <button
+ onClick={() => handleDelete(app)}
+ className="px-2 py-1 bg-port-error/20 text-port-error hover:bg-port-error/30 text-xs"
+ >
+ Yes
+ </button>
+ <button
+ onClick={() => setConfirmingDelete(null)}
+ className="px-2 py-1 bg-port-border/50 text-gray-400 hover:text-white text-xs border-l border-port-border"
+ >
+ No
+ </button>
+ </div>
+ </div>
+ ) : (
+ <div className="inline-flex rounded-lg overflow-hidden border border-port-border">
+ <button
+ onClick={() => setEditingApp(app)}
+ className="px-3 py-1.5 bg-port-accent/20 text-port-accent hover:bg-port-accent/30 transition-colors text-xs"
+ >
+ Edit
+ </button>
+ <button
+ onClick={() => setConfirmingDelete(app.id)}
+ className="px-3 py-1.5 bg-port-error/10 text-port-error hover:bg-port-error/20 transition-colors text-xs border-l border-port-border"
+ >
+ Delete
+ </button>
+ </div>
+ )}
+ </td>
+ </tr>
+
+ {/* Expanded Details Row */}
+ {expandedId === app.id && (
+ <tr>
+ <td colSpan={6} className="p-0">
+ <div className="bg-port-bg border-t border-port-border">
+ <div className="px-6 py-4 space-y-4">
+ {/* Details Grid */}
+ <div className="grid grid-cols-2 gap-6">
+ <div>
+ <div className="text-xs text-gray-500 uppercase tracking-wide mb-2">Repository Path</div>
+ <div className="flex items-center gap-2">
+ <FolderOpen size={16} className="text-yellow-400" />
+ <code className="text-sm text-gray-300 font-mono">{app.repoPath}</code>
+ </div>
+ </div>
+ <div>
+ <div className="text-xs text-gray-500 uppercase tracking-wide mb-2">Editor Command</div>
+ <div className="flex items-center gap-2">
+ <Code size={16} className="text-blue-400" />
+ <code className="text-sm text-gray-300 font-mono">{app.editorCommand || 'code .'}</code>
+ </div>
+ </div>
+ </div>
+
+ {/* Start Commands */}
+ {app.startCommands?.length > 0 && (
+ <div>
+ <div className="text-xs text-gray-500 uppercase tracking-wide mb-2">Start Commands</div>
+ <div className="bg-port-card border border-port-border rounded-lg p-3">
+ {app.startCommands.map((cmd, i) => (
+ <div key={i} className="flex items-center gap-2 py-1">
+ <Terminal size={14} className="text-green-400" />
+ <code className="text-sm text-cyan-300 font-mono">{cmd}</code>
+ </div>
+ ))}
+ </div>
+ </div>
+ )}
+
+ {/* PM2 Processes Status */}
+ {app.pm2Status && Object.keys(app.pm2Status).length > 0 && (
+ <div>
+ <div className="text-xs text-gray-500 uppercase tracking-wide mb-2">PM2 Processes</div>
+ <div className="flex flex-wrap gap-2">
+ {Object.values(app.pm2Status).map((proc, i) => (
+ <div
+ key={i}
+ className="flex items-center gap-2 px-3 py-1.5 bg-port-card border border-port-border rounded-lg"
+ >
+ <span className={`w-2 h-2 rounded-full ${
+ proc.status === 'online' ? 'bg-port-success' :
+ proc.status === 'stopped' ? 'bg-gray-500' : 'bg-port-error'
+ }`} />
+ <span className="text-sm text-white font-mono">{proc.name}</span>
+ <span className="text-xs text-gray-500">{proc.status}</span>
+ {proc.cpu !== undefined && (
+ <span className="text-xs text-green-400">{proc.cpu}%</span>
+ )}
+ {proc.memory !== undefined && (
+ <span className="text-xs text-blue-400">{(proc.memory / 1024 / 1024).toFixed(0)}MB</span>
+ )}
+ </div>
+ ))}
+ </div>
+ </div>
+ )}
+
+ {/* Quick Actions */}
+ <div className="flex gap-2 pt-2">
+ <button
+ onClick={() => {
+ const cmd = `cd "${app.repoPath}" && ${app.editorCommand || 'code .'}`;
+ api.executeCommand(cmd).catch(() => null);
+ }}
+ className="px-3 py-1.5 bg-port-border hover:bg-port-border/80 text-white rounded-lg text-xs flex items-center gap-1"
+ >
+ <Code size={14} /> Open in Editor
+ </button>
+ <button
+ onClick={() => {
+ const cmd = `open "${app.repoPath}"`;
+ api.executeCommand(cmd).catch(() => null);
+ }}
+ className="px-3 py-1.5 bg-port-border hover:bg-port-border/80 text-white rounded-lg text-xs flex items-center gap-1"
+ >
+ <FolderOpen size={14} /> Open Folder
+ </button>
+ </div>
+ </div>
+ </div>
+ </td>
+ </tr>
+ )}
+ </Fragment>
))}
</tbody>
</table>
diff --git a/client/src/pages/CreateApp.jsx b/client/src/pages/CreateApp.jsx
index 2d220374df..7a40877bb3 100644
--- a/client/src/pages/CreateApp.jsx
+++ b/client/src/pages/CreateApp.jsx
@@ -10,7 +10,7 @@ const DETECTION_STEPS = [
{ id: 'package', label: 'Reading package.json' },
{ id: 'config', label: 'Checking configs' },
{ id: 'pm2', label: 'Checking PM2' },
- { id: 'ai', label: 'AI analysis' }
+ { id: 'readme', label: 'Reading README' }
];
export default function CreateApp() {
@@ -55,7 +55,13 @@ export default function CreateApp() {
if (data.apiPort) setApiPort(String(data.apiPort));
if (data.startCommands?.length) setStartCommands(data.startCommands.join('\n'));
if (data.pm2ProcessNames?.length) setPm2Names(data.pm2ProcessNames.join(', '));
- if (data.pm2Status) setPm2Status(data.pm2Status);
+ if (data.pm2Status) {
+ setPm2Status(data.pm2Status);
+ // Also set pm2Names from found processes if available
+ if (!data.pm2ProcessNames?.length && Array.isArray(data.pm2Status)) {
+ setPm2Names(data.pm2Status.map(p => p.name).join(', '));
+ }
+ }
});
socketRef.current.on('detect:complete', ({ success, result, error: err }) => {
diff --git a/client/src/pages/DevTools.jsx b/client/src/pages/DevTools.jsx
index 4ae55fb37f..466b7e90e5 100644
--- a/client/src/pages/DevTools.jsx
+++ b/client/src/pages/DevTools.jsx
@@ -1,63 +1,16 @@
-import { useState, useEffect, useRef } from 'react';
-import { useParams, useNavigate, Link } from 'react-router-dom';
+import { useState, useEffect, useRef, Fragment } from 'react';
+import { GitBranch, Plus, Minus, FileText, Clock, RefreshCw, Activity, BarChart3, Image, X, XCircle, Cpu, MemoryStick, Terminal } from 'lucide-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 { tab = 'history' } = useParams();
- const navigate = useNavigate();
-
- // Redirect invalid tabs to history
- useEffect(() => {
- if (!TABS.find(t => t.id === tab)) {
- navigate('/devtools/history', { replace: true });
- }
- }, [tab, navigate]);
-
- 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(t => (
- <Link
- key={t.id}
- to={`/devtools/${t.id}`}
- className={`flex-1 px-4 py-2 rounded-md text-sm font-medium transition-colors text-center ${
- tab === t.id
- ? 'bg-port-accent text-white'
- : 'text-gray-400 hover:text-white hover:bg-port-border/50'
- }`}
- >
- {t.label}
- </Link>
- ))}
- </div>
-
- {/* Tab Content */}
- {tab === 'history' && <HistoryTab />}
- {tab === 'runner' && <RunnerTab />}
- {tab === 'processes' && <ProcessesTab />}
- </div>
- );
-}
-
-function HistoryTab() {
+export function HistoryPage() {
const [history, setHistory] = useState([]);
const [stats, setStats] = useState(null);
const [loading, setLoading] = useState(true);
const [filter, setFilter] = useState({ action: '', success: '' });
const [actions, setActions] = useState([]);
const [confirmingClear, setConfirmingClear] = useState(false);
+ const [expandedId, setExpandedId] = useState(null);
useEffect(() => {
loadData();
@@ -109,12 +62,25 @@ function HistoryTab() {
return icons[action] || '📋';
};
+ const formatRuntime = (ms) => {
+ if (!ms) return null;
+ if (ms < 1000) return `${ms}ms`;
+ if (ms < 60000) return `${(ms / 1000).toFixed(1)}s`;
+ return `${(ms / 60000).toFixed(1)}m`;
+ };
+
+ const toggleExpand = (id) => {
+ setExpandedId(prev => prev === id ? null : id);
+ };
+
if (loading) {
return <div className="text-center py-8 text-gray-400">Loading history...</div>;
}
return (
- <div className="space-y-4">
+ <div className="space-y-6">
+ <h1 className="text-2xl font-bold text-white">Action History</h1>
+
{/* Stats */}
{stats && (
<div className="grid grid-cols-4 gap-4">
@@ -195,25 +161,122 @@ function HistoryTab() {
) : (
<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 key={entry.id}>
+ <div
+ className="p-4 hover:bg-port-border/20 cursor-pointer"
+ onClick={() => toggleExpand(entry.id)}
+ >
+ <div className="flex items-center gap-4">
+ <button className="text-gray-400 hover:text-white">
+ <span className={`inline-block transition-transform ${expandedId === entry.id ? 'rotate-90' : ''}`}>▶</span>
+ </button>
+ <span className="text-xl">{getActionIcon(entry.action)}</span>
+ <div className="flex-1 min-w-0">
+ <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>
+ )}
+ {entry.details?.runtime && (
+ <span className="text-xs text-cyan-400 font-mono">{formatRuntime(entry.details.runtime)}</span>
+ )}
+ </div>
+ {entry.details?.command && (
+ <code className="text-xs text-gray-500 font-mono truncate block">{entry.details.command}</code>
)}
</div>
- {entry.details?.command && (
- <code className="text-xs text-gray-500 font-mono">{entry.details.command}</code>
- )}
+ <span className={`w-2 h-2 rounded-full flex-shrink-0 ${entry.success ? 'bg-port-success' : 'bg-port-error'}`} />
+ <span className="text-sm text-gray-500 flex-shrink-0">{formatTime(entry.timestamp)}</span>
</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>
+
+ {/* Expanded Details */}
+ {expandedId === entry.id && (
+ <div className="px-4 pb-4 bg-port-bg border-t border-port-border">
+ <div className="pt-4 space-y-4">
+ {/* Metadata Grid */}
+ <div className="grid grid-cols-4 gap-4 text-sm">
+ <div>
+ <div className="text-xs text-gray-500 uppercase tracking-wide mb-1">Timestamp</div>
+ <div className="text-gray-300">{new Date(entry.timestamp).toLocaleString()}</div>
+ </div>
+ <div>
+ <div className="text-xs text-gray-500 uppercase tracking-wide mb-1">Status</div>
+ <div className={entry.success ? 'text-port-success' : 'text-port-error'}>
+ {entry.success ? 'Success' : 'Failed'}
+ </div>
+ </div>
+ {entry.details?.runtime && (
+ <div>
+ <div className="text-xs text-gray-500 uppercase tracking-wide mb-1">Runtime</div>
+ <div className="text-cyan-400 font-mono">{formatRuntime(entry.details.runtime)}</div>
+ </div>
+ )}
+ {entry.details?.exitCode !== undefined && (
+ <div>
+ <div className="text-xs text-gray-500 uppercase tracking-wide mb-1">Exit Code</div>
+ <div className={`font-mono ${entry.details.exitCode === 0 ? 'text-port-success' : 'text-port-error'}`}>
+ {entry.details.exitCode}
+ </div>
+ </div>
+ )}
+ </div>
+
+ {/* Command */}
+ {entry.details?.command && (
+ <div>
+ <div className="text-xs text-gray-500 uppercase tracking-wide mb-2">Command</div>
+ <div className="bg-port-card border border-port-border rounded-lg p-3">
+ <code className="text-sm text-cyan-300 font-mono whitespace-pre-wrap break-all">
+ {entry.details.command}
+ </code>
+ </div>
+ </div>
+ )}
+
+ {/* Output */}
+ {entry.details?.output && (
+ <div>
+ <div className="text-xs text-gray-500 uppercase tracking-wide mb-2">Output</div>
+ <div className="bg-port-card border border-port-border rounded-lg p-3 max-h-64 overflow-auto">
+ <pre className="text-xs text-gray-300 font-mono whitespace-pre-wrap break-all">
+ {entry.details.output}
+ </pre>
+ </div>
+ </div>
+ )}
+
+ {/* Error */}
+ {entry.error && (
+ <div>
+ <div className="text-xs text-gray-500 uppercase tracking-wide mb-2">Error</div>
+ <div className="bg-port-error/10 border border-port-error/30 rounded-lg p-3">
+ <pre className="text-sm text-port-error font-mono whitespace-pre-wrap">
+ {entry.error}
+ </pre>
+ </div>
+ </div>
+ )}
+
+ {/* Other Details */}
+ {entry.details && Object.keys(entry.details).filter(k => !['command', 'output', 'runtime', 'exitCode'].includes(k)).length > 0 && (
+ <div>
+ <div className="text-xs text-gray-500 uppercase tracking-wide mb-2">Additional Details</div>
+ <div className="bg-port-card border border-port-border rounded-lg p-3">
+ <pre className="text-xs text-gray-400 font-mono whitespace-pre-wrap">
+ {JSON.stringify(
+ Object.fromEntries(
+ Object.entries(entry.details).filter(([k]) => !['command', 'output', 'runtime', 'exitCode'].includes(k))
+ ),
+ null,
+ 2
+ )}
+ </pre>
+ </div>
+ </div>
+ )}
+ </div>
+ </div>
)}
</div>
))}
@@ -224,21 +287,72 @@ function HistoryTab() {
);
}
-function RunnerTab() {
+export function RunnerPage() {
+ const [mode, setMode] = useState('ai'); // 'ai' or 'command'
+ const [prompt, setPrompt] = useState('');
const [command, setCommand] = useState('');
const [workspacePath, setWorkspacePath] = useState('');
const [output, setOutput] = useState('');
const [running, setRunning] = useState(false);
+ const [runId, setRunId] = useState(null);
const [commandId, setCommandId] = useState(null);
const [apps, setApps] = useState([]);
+ const [providers, setProviders] = useState([]);
+ const [selectedProvider, setSelectedProvider] = useState('');
+ const [selectedModel, setSelectedModel] = useState('');
+ const [timeout, setTimeout] = useState(30);
const [allowedCommands, setAllowedCommands] = useState([]);
+ const [screenshots, setScreenshots] = useState([]);
+ const fileInputRef = useRef(null);
const outputRef = useRef(null);
useEffect(() => {
- api.getApps().then(setApps).catch(() => []);
- api.getAllowedCommands().then(setAllowedCommands).catch(() => []);
+ Promise.all([
+ api.getApps().catch(() => []),
+ api.getProviders().catch(() => ({ providers: [] })),
+ api.getAllowedCommands().catch(() => [])
+ ]).then(([appsData, providersRes, cmds]) => {
+ setApps(appsData);
+ const allProviders = providersRes.providers || [];
+ const enabledProviders = allProviders.filter(p => p.enabled);
+ setProviders(enabledProviders);
+ if (enabledProviders.length > 0) {
+ const active = enabledProviders.find(p => p.id === providersRes.activeProvider) || enabledProviders[0];
+ setSelectedProvider(active.id);
+ setSelectedModel(active.defaultModel || '');
+ }
+ setAllowedCommands(cmds);
+ });
}, []);
+ // Subscribe to run output
+ useEffect(() => {
+ if (!runId) return;
+
+ const handleData = (data) => {
+ setOutput(prev => prev + data);
+ if (outputRef.current) {
+ outputRef.current.scrollTop = outputRef.current.scrollHeight;
+ }
+ };
+
+ const handleComplete = (metadata) => {
+ setRunning(false);
+ setRunId(null);
+ const status = metadata.success ? '✓ Completed' : `✗ Failed (${metadata.error || 'unknown error'})`;
+ setOutput(prev => prev + `\n\n--- ${status} (${Math.round(metadata.duration / 1000)}s) ---\n`);
+ };
+
+ socket.on(`run:${runId}:data`, handleData);
+ socket.on(`run:${runId}:complete`, handleComplete);
+
+ return () => {
+ socket.off(`run:${runId}:data`, handleData);
+ socket.off(`run:${runId}:complete`, handleComplete);
+ };
+ }, [runId]);
+
+ // Subscribe to command output
useEffect(() => {
if (!commandId) return;
@@ -264,7 +378,30 @@ function RunnerTab() {
};
}, [commandId]);
- const handleRun = async () => {
+ const handleRunAI = async () => {
+ if (!prompt.trim() || !selectedProvider) return;
+
+ setOutput('');
+ setRunning(true);
+
+ const result = await api.createRun({
+ providerId: selectedProvider,
+ model: selectedModel || undefined,
+ prompt: prompt.trim(),
+ workspacePath: workspacePath || undefined,
+ workspaceName: apps.find(a => a.repoPath === workspacePath)?.name
+ }).catch(err => ({ error: err.message }));
+
+ if (result.error) {
+ setOutput(`Error: ${result.error}`);
+ setRunning(false);
+ return;
+ }
+
+ setRunId(result.runId);
+ };
+
+ const handleRunCommand = async () => {
if (!command.trim()) return;
setOutput('');
@@ -283,6 +420,11 @@ function RunnerTab() {
};
const handleStop = async () => {
+ if (runId) {
+ await api.stopRun(runId);
+ setRunning(false);
+ setRunId(null);
+ }
if (commandId) {
await api.stopCommand(commandId);
setRunning(false);
@@ -290,73 +432,247 @@ function RunnerTab() {
}
};
+ const handleFileSelect = async (e) => {
+ const files = Array.from(e.target.files);
+ for (const file of files) {
+ if (!file.type.startsWith('image/')) continue;
+
+ const reader = new FileReader();
+ reader.onload = async (ev) => {
+ const base64 = ev.target.result.split(',')[1];
+ const uploaded = await api.uploadScreenshot(base64, file.name, file.type).catch(() => null);
+ if (uploaded) {
+ setScreenshots(prev => [...prev, {
+ id: uploaded.id,
+ filename: uploaded.filename,
+ preview: ev.target.result,
+ path: uploaded.path
+ }]);
+ }
+ };
+ reader.readAsDataURL(file);
+ }
+ e.target.value = '';
+ };
+
+ const removeScreenshot = (id) => {
+ setScreenshots(prev => prev.filter(s => s.id !== id));
+ };
+
+ const currentProvider = providers.find(p => p.id === selectedProvider);
+
return (
- <div className="space-y-4">
- {/* Workspace Selector */}
- <div className="flex gap-4">
+ <div className="space-y-6">
+ <h1 className="text-2xl font-bold text-white">AI Runner</h1>
+
+ {/* Mode Toggle */}
+ <div className="flex gap-2">
+ <button
+ onClick={() => setMode('ai')}
+ className={`px-4 py-2 rounded-lg transition-colors ${
+ mode === 'ai' ? 'bg-port-accent text-white' : 'bg-port-card text-gray-400 hover:text-white'
+ }`}
+ >
+ AI Assistant
+ </button>
+ <button
+ onClick={() => setMode('command')}
+ className={`px-4 py-2 rounded-lg transition-colors ${
+ mode === 'command' ? 'bg-port-accent text-white' : 'bg-port-card text-gray-400 hover:text-white'
+ }`}
+ >
+ Shell Command
+ </button>
+ </div>
+
+ {/* Configuration Row */}
+ <div className="flex flex-wrap gap-3">
+ {/* Workspace */}
<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"
+ className="px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm"
>
<option value="">Current directory</option>
{apps.map(app => (
- <option key={app.id} value={app.repoPath}>{app.name} ({app.repoPath})</option>
+ <option key={app.id} value={app.repoPath}>{app.name}</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>
+ {mode === 'ai' && (
+ <>
+ {/* Provider */}
+ <select
+ value={selectedProvider}
+ onChange={(e) => {
+ setSelectedProvider(e.target.value);
+ const p = providers.find(p => p.id === e.target.value);
+ setSelectedModel(p?.defaultModel || '');
+ }}
+ className="px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm"
+ >
+ {providers.map(p => (
+ <option key={p.id} value={p.id}>{p.name}</option>
+ ))}
+ </select>
+
+ {/* Model */}
+ {currentProvider?.models?.length > 0 && (
+ <select
+ value={selectedModel}
+ onChange={(e) => setSelectedModel(e.target.value)}
+ className="px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm"
+ >
+ {currentProvider.models.map(m => (
+ <option key={m} value={m}>{m}</option>
+ ))}
+ </select>
+ )}
+
+ {/* Timeout */}
+ <div className="flex items-center gap-2">
+ <Clock size={16} className="text-gray-400" />
+ <select
+ value={timeout}
+ onChange={(e) => setTimeout(Number(e.target.value))}
+ className="px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm"
+ >
+ <option value={5}>5 min</option>
+ <option value={15}>15 min</option>
+ <option value={30}>30 min</option>
+ <option value={60}>60 min</option>
+ </select>
+ </div>
+
+ {/* Screenshot Upload */}
+ <button
+ onClick={() => fileInputRef.current?.click()}
+ className="flex items-center gap-2 px-3 py-2 bg-port-bg border border-port-border rounded-lg text-gray-400 hover:text-white text-sm"
+ >
+ <Image size={16} />
+ Add Screenshot
+ </button>
+ <input
+ ref={fileInputRef}
+ type="file"
+ accept="image/*"
+ multiple
+ onChange={handleFileSelect}
+ className="hidden"
+ />
+ </>
)}
</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>
+ {/* Screenshot Previews */}
+ {mode === 'ai' && screenshots.length > 0 && (
+ <div className="flex gap-2 flex-wrap">
+ {screenshots.map(s => (
+ <div key={s.id} className="relative group">
+ <img
+ src={s.preview}
+ alt={s.filename}
+ className="w-20 h-20 object-cover rounded-lg border border-port-border"
+ />
+ <button
+ onClick={() => removeScreenshot(s.id)}
+ className="absolute -top-2 -right-2 w-5 h-5 bg-port-error rounded-full flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity"
+ >
+ <X size={12} />
+ </button>
+ </div>
+ ))}
+ </div>
+ )}
+
+ {/* Input Area */}
+ {mode === 'ai' ? (
+ <div className="flex gap-2">
+ <textarea
+ value={prompt}
+ onChange={(e) => setPrompt(e.target.value)}
+ placeholder="Describe what you want the AI to do..."
+ rows={3}
+ 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 resize-none"
+ />
+ {running ? (
+ <button
+ onClick={handleStop}
+ className="px-6 bg-port-error hover:bg-port-error/80 text-white rounded-lg transition-colors"
+ >
+ Stop
+ </button>
+ ) : (
+ <button
+ onClick={handleRunAI}
+ disabled={!prompt.trim() || !selectedProvider}
+ className="px-6 bg-port-success hover:bg-port-success/80 text-white rounded-lg transition-colors disabled:opacity-50"
+ >
+ Run
+ </button>
+ )}
+ </div>
+ ) : (
+ <>
+ <div className="flex gap-2">
+ <input
+ type="text"
+ value={command}
+ onChange={(e) => setCommand(e.target.value)}
+ onKeyDown={(e) => e.key === 'Enter' && !running && handleRunCommand()}
+ 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={handleRunCommand}
+ 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>
+ <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 className="space-y-1">
+ <div className="text-xs text-gray-500">Output:</div>
+ <div
+ ref={outputRef}
+ className="bg-port-bg border border-port-border rounded-lg p-4 h-80 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>
</div>
);
}
-function ProcessesTab() {
+export function ProcessesPage() {
const [processes, setProcesses] = useState([]);
const [loading, setLoading] = useState(true);
+ const [expandedProcess, setExpandedProcess] = useState(null);
+ const [logs, setLogs] = useState([]);
+ const [restarting, setRestarting] = useState({});
+ const [tailLines, setTailLines] = useState(500);
+ const [subscribed, setSubscribed] = useState(false);
+ const logsRef = useRef(null);
useEffect(() => {
loadProcesses();
@@ -364,12 +680,105 @@ function ProcessesTab() {
return () => clearInterval(interval);
}, []);
+ useEffect(() => {
+ if (!expandedProcess) {
+ setLogs([]);
+ setSubscribed(false);
+ return;
+ }
+
+ // Subscribe to logs via socket
+ socket.emit('logs:subscribe', { processName: expandedProcess, lines: tailLines });
+
+ const handleLog = (data) => {
+ if (data.processName === expandedProcess) {
+ setLogs(prev => [...prev.slice(-1000), {
+ line: data.line,
+ type: data.type,
+ timestamp: data.timestamp
+ }]);
+ setTimeout(() => {
+ if (logsRef.current) {
+ logsRef.current.scrollTop = logsRef.current.scrollHeight;
+ }
+ }, 10);
+ }
+ };
+
+ const handleSubscribed = (data) => {
+ if (data.processName === expandedProcess) {
+ setSubscribed(true);
+ }
+ };
+
+ const handleError = (data) => {
+ if (data.processName === expandedProcess) {
+ setLogs(prev => [...prev, { line: `Error: ${data.error}`, type: 'stderr', timestamp: Date.now() }]);
+ }
+ };
+
+ socket.on('logs:line', handleLog);
+ socket.on('logs:subscribed', handleSubscribed);
+ socket.on('logs:error', handleError);
+
+ return () => {
+ socket.emit('logs:unsubscribe', { processName: expandedProcess });
+ socket.off('logs:line', handleLog);
+ socket.off('logs:subscribed', handleSubscribed);
+ socket.off('logs:error', handleError);
+ };
+ }, [expandedProcess, tailLines]);
+
const loadProcesses = async () => {
const data = await api.getProcessesList().catch(() => []);
setProcesses(data);
setLoading(false);
};
+ const handleRestart = async (name) => {
+ setRestarting(prev => ({ ...prev, [name]: true }));
+ await fetch('/api/commands/execute', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ command: `pm2 restart ${name}` })
+ }).catch(() => null);
+ setTimeout(() => {
+ setRestarting(prev => ({ ...prev, [name]: false }));
+ loadProcesses();
+ }, 2000);
+ };
+
+ const handleStop = async (name) => {
+ setRestarting(prev => ({ ...prev, [name]: true }));
+ await fetch('/api/commands/execute', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ command: `pm2 stop ${name}` })
+ }).catch(() => null);
+ setTimeout(() => {
+ setRestarting(prev => ({ ...prev, [name]: false }));
+ loadProcesses();
+ }, 2000);
+ };
+
+ const handleStart = async (name) => {
+ setRestarting(prev => ({ ...prev, [name]: true }));
+ await fetch('/api/commands/execute', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ command: `pm2 start ${name}` })
+ }).catch(() => null);
+ setTimeout(() => {
+ setRestarting(prev => ({ ...prev, [name]: false }));
+ loadProcesses();
+ }, 2000);
+ };
+
+ const toggleExpand = (name) => {
+ setExpandedProcess(prev => prev === name ? null : name);
+ setLogs([]);
+ };
+
const formatMemory = (bytes) => {
if (!bytes) return '0 MB';
return `${(bytes / 1024 / 1024).toFixed(1)} MB`;
@@ -399,9 +808,9 @@ function ProcessesTab() {
}
return (
- <div className="space-y-4">
+ <div className="space-y-6">
<div className="flex justify-between items-center">
- <p className="text-gray-400">{processes.length} PM2 processes</p>
+ <h1 className="text-2xl font-bold text-white">PM2 Processes</h1>
<button
onClick={loadProcesses}
className="px-4 py-2 bg-port-border hover:bg-port-border/80 text-white rounded-lg transition-colors"
@@ -414,6 +823,7 @@ function ProcessesTab() {
<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 w-8"></th>
<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>
@@ -421,30 +831,135 @@ function ProcessesTab() {
<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>
+ <th className="px-4 py-3 text-right text-sm font-medium text-gray-400">Actions</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>
+ <Fragment key={proc.pm_id}>
+ <tr className="hover:bg-port-border/20">
+ <td className="px-4 py-3">
+ <button
+ onClick={() => toggleExpand(proc.name)}
+ className="text-gray-400 hover:text-white transition-transform"
+ >
+ <span className={`inline-block transition-transform ${expandedProcess === proc.name ? 'rotate-90' : ''}`}>▶</span>
+ </button>
+ </td>
+ <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>
+ <td className="px-4 py-3 text-right">
+ <div className="flex justify-end gap-1">
+ {proc.status === 'online' ? (
+ <>
+ <button
+ onClick={() => handleRestart(proc.name)}
+ disabled={restarting[proc.name]}
+ className="px-2 py-1 text-xs bg-port-warning/20 text-port-warning hover:bg-port-warning/30 rounded disabled:opacity-50"
+ >
+ {restarting[proc.name] ? '...' : 'Restart'}
+ </button>
+ <button
+ onClick={() => handleStop(proc.name)}
+ disabled={restarting[proc.name]}
+ className="px-2 py-1 text-xs bg-port-error/20 text-port-error hover:bg-port-error/30 rounded disabled:opacity-50"
+ >
+ Stop
+ </button>
+ </>
+ ) : (
+ <button
+ onClick={() => handleStart(proc.name)}
+ disabled={restarting[proc.name]}
+ className="px-2 py-1 text-xs bg-port-success/20 text-port-success hover:bg-port-success/30 rounded disabled:opacity-50"
+ >
+ {restarting[proc.name] ? '...' : 'Start'}
+ </button>
+ )}
+ </div>
+ </td>
+ </tr>
+ {expandedProcess === proc.name && (
+ <tr>
+ <td colSpan={9} className="p-0">
+ <div className="bg-port-bg border-t border-port-border">
+ <div className="flex items-center justify-between px-4 py-2 border-b border-port-border">
+ <div className="flex items-center gap-3">
+ <span className="text-xs text-gray-400">Live logs for {proc.name}</span>
+ {subscribed && (
+ <span className="text-xs text-port-success">● streaming</span>
+ )}
+ </div>
+ <div className="flex items-center gap-3">
+ <div className="flex items-center gap-2">
+ <label className="text-xs text-gray-500">Tail lines:</label>
+ <select
+ value={tailLines}
+ onChange={(e) => {
+ setTailLines(Number(e.target.value));
+ setLogs([]);
+ }}
+ className="px-2 py-1 text-xs bg-port-card border border-port-border rounded text-white"
+ >
+ <option value={100}>100</option>
+ <option value={250}>250</option>
+ <option value={500}>500</option>
+ <option value={1000}>1000</option>
+ <option value={2000}>2000</option>
+ </select>
+ </div>
+ <span className="text-xs text-gray-600">{logs.length} lines</span>
+ <button
+ onClick={() => setLogs([])}
+ className="text-xs text-gray-500 hover:text-white"
+ >
+ Clear
+ </button>
+ </div>
+ </div>
+ <div
+ ref={logsRef}
+ className="h-64 overflow-auto p-3 font-mono text-xs"
+ >
+ {logs.length === 0 ? (
+ <div className="text-gray-500">
+ {subscribed ? 'No logs yet...' : 'Connecting to log stream...'}
+ </div>
+ ) : (
+ logs.map((log, i) => (
+ <div
+ key={i}
+ className={`py-0.5 ${log.type === 'stderr' ? 'text-port-error' : 'text-gray-300'}`}
+ >
+ <span className="text-gray-600 mr-2">
+ {new Date(log.timestamp).toLocaleTimeString()}
+ </span>
+ {log.line}
+ </div>
+ ))
+ )}
+ </div>
+ </div>
+ </td>
+ </tr>
+ )}
+ </Fragment>
))}
{processes.length === 0 && (
<tr>
- <td colSpan={7} className="px-4 py-12 text-center text-gray-500">
+ <td colSpan={9} className="px-4 py-12 text-center text-gray-500">
No PM2 processes running
</td>
</tr>
@@ -455,3 +970,607 @@ function ProcessesTab() {
</div>
);
}
+
+export function GitPage() {
+ const [apps, setApps] = useState([]);
+ const [selectedApp, setSelectedApp] = useState('');
+ const [gitInfo, setGitInfo] = useState(null);
+ const [diff, setDiff] = useState('');
+ const [showDiff, setShowDiff] = useState(false);
+ const [loading, setLoading] = useState(false);
+ const [commitMessage, setCommitMessage] = useState('');
+ const [committing, setCommitting] = useState(false);
+
+ useEffect(() => {
+ api.getApps().then(apps => {
+ setApps(apps);
+ if (apps.length > 0) {
+ setSelectedApp(apps[0].repoPath);
+ }
+ }).catch(() => []);
+ }, []);
+
+ useEffect(() => {
+ if (selectedApp) loadGitInfo();
+ }, [selectedApp]);
+
+ const loadGitInfo = async () => {
+ if (!selectedApp) return;
+ setLoading(true);
+ const info = await api.getGitInfo(selectedApp).catch(() => null);
+ setGitInfo(info);
+ setLoading(false);
+ };
+
+ const loadDiff = async () => {
+ if (!selectedApp) return;
+ const result = await api.getGitDiff(selectedApp).catch(() => ({ diff: '' }));
+ setDiff(result.diff || '');
+ setShowDiff(true);
+ };
+
+ const handleStage = async (file) => {
+ await api.stageFiles(selectedApp, [file]);
+ await loadGitInfo();
+ };
+
+ const handleUnstage = async (file) => {
+ await api.unstageFiles(selectedApp, [file]);
+ await loadGitInfo();
+ };
+
+ const handleCommit = async () => {
+ if (!commitMessage.trim()) return;
+ setCommitting(true);
+ await api.createCommit(selectedApp, commitMessage).catch(() => null);
+ setCommitMessage('');
+ setCommitting(false);
+ await loadGitInfo();
+ };
+
+ const getStatusIcon = (file) => {
+ if (file.added) return <Plus size={14} className="text-port-success" />;
+ if (file.deleted) return <Minus size={14} className="text-port-error" />;
+ return <FileText size={14} className="text-port-warning" />;
+ };
+
+ return (
+ <div className="space-y-6">
+ <div className="flex items-center justify-between">
+ <h1 className="text-2xl font-bold text-white">Git Status</h1>
+ <div className="flex items-center gap-4">
+ <select
+ value={selectedApp}
+ onChange={(e) => setSelectedApp(e.target.value)}
+ className="px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white"
+ >
+ {apps.map(app => (
+ <option key={app.id} value={app.repoPath}>{app.name}</option>
+ ))}
+ </select>
+ <button
+ onClick={loadGitInfo}
+ className="p-2 text-gray-400 hover:text-white"
+ >
+ <RefreshCw size={18} />
+ </button>
+ </div>
+ </div>
+
+ {loading ? (
+ <div className="text-center py-8 text-gray-400">Loading...</div>
+ ) : gitInfo && gitInfo.isRepo ? (
+ <div className="grid grid-cols-2 gap-6">
+ {/* Status Panel */}
+ <div className="space-y-4">
+ {/* Branch Info */}
+ <div className="bg-port-card border border-port-border rounded-xl p-4">
+ <div className="flex items-center gap-2 mb-3">
+ <GitBranch size={18} className="text-port-accent" />
+ <span className="font-medium text-white">{gitInfo.branch}</span>
+ {gitInfo.status?.clean && (
+ <span className="text-xs text-port-success px-2 py-0.5 bg-port-success/20 rounded">Clean</span>
+ )}
+ </div>
+ <div className="flex gap-4 text-sm">
+ <div className="text-gray-400">
+ <span className="text-port-success">+{gitInfo.diffStats?.insertions || 0}</span>
+ <span className="mx-1">/</span>
+ <span className="text-port-error">-{gitInfo.diffStats?.deletions || 0}</span>
+ </div>
+ <div className="text-gray-500">
+ {gitInfo.diffStats?.files || 0} files changed
+ </div>
+ </div>
+ </div>
+
+ {/* Changed Files */}
+ <div className="bg-port-card border border-port-border rounded-xl p-4">
+ <div className="flex items-center justify-between mb-3">
+ <h3 className="text-sm font-medium text-gray-400">Changed Files</h3>
+ <button
+ onClick={loadDiff}
+ className="text-xs text-port-accent hover:underline"
+ >
+ View Diff
+ </button>
+ </div>
+ <div className="space-y-1 max-h-64 overflow-auto">
+ {gitInfo.status?.files?.map((file, i) => (
+ <div key={i} className="flex items-center gap-2 text-sm py-1 group">
+ {getStatusIcon(file)}
+ <span className={`flex-1 font-mono text-xs ${file.staged ? 'text-port-success' : 'text-gray-300'}`}>
+ {file.path}
+ </span>
+ <span className="text-xs text-gray-500">{file.status}</span>
+ {file.staged ? (
+ <button
+ onClick={() => handleUnstage(file.path)}
+ className="opacity-0 group-hover:opacity-100 text-xs text-gray-400 hover:text-white"
+ >
+ Unstage
+ </button>
+ ) : (
+ <button
+ onClick={() => handleStage(file.path)}
+ className="opacity-0 group-hover:opacity-100 text-xs text-gray-400 hover:text-white"
+ >
+ Stage
+ </button>
+ )}
+ </div>
+ ))}
+ {(!gitInfo.status?.files || gitInfo.status.files.length === 0) && (
+ <div className="text-gray-500 text-sm">No changes</div>
+ )}
+ </div>
+ </div>
+
+ {/* Quick Commit */}
+ {gitInfo.status?.staged > 0 && (
+ <div className="bg-port-card border border-port-border rounded-xl p-4">
+ <h3 className="text-sm font-medium text-gray-400 mb-2">Quick Commit</h3>
+ <div className="flex gap-2">
+ <input
+ type="text"
+ value={commitMessage}
+ onChange={(e) => setCommitMessage(e.target.value)}
+ placeholder="Commit message..."
+ className="flex-1 px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm"
+ />
+ <button
+ onClick={handleCommit}
+ disabled={committing || !commitMessage.trim()}
+ className="px-4 py-2 bg-port-success hover:bg-port-success/80 text-white rounded-lg text-sm disabled:opacity-50"
+ >
+ Commit
+ </button>
+ </div>
+ </div>
+ )}
+ </div>
+
+ {/* Recent Commits */}
+ <div className="bg-port-card border border-port-border rounded-xl p-4">
+ <h3 className="text-sm font-medium text-gray-400 mb-3">Recent Commits</h3>
+ <div className="space-y-2">
+ {gitInfo.recentCommits?.map((commit, i) => (
+ <div key={i} className="py-2 border-b border-port-border last:border-0">
+ <div className="flex items-center gap-2">
+ <code className="text-xs text-port-accent">{commit.hash}</code>
+ <span className="text-sm text-white truncate">{commit.message}</span>
+ </div>
+ <div className="text-xs text-gray-500 mt-1">
+ {commit.author} • {new Date(commit.date).toLocaleDateString()}
+ </div>
+ </div>
+ ))}
+ {(!gitInfo.recentCommits || gitInfo.recentCommits.length === 0) && (
+ <div className="text-gray-500 text-sm">No commits</div>
+ )}
+ </div>
+ </div>
+ </div>
+ ) : (
+ <div className="bg-port-card border border-port-border rounded-xl p-8 text-center text-gray-500">
+ {gitInfo ? 'Not a git repository' : 'Select an app to view git status'}
+ </div>
+ )}
+
+ {/* Diff Modal */}
+ {showDiff && (
+ <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50" onClick={() => setShowDiff(false)}>
+ <div className="bg-port-card border border-port-border rounded-xl w-3/4 max-h-[80vh] overflow-hidden" onClick={e => e.stopPropagation()}>
+ <div className="flex items-center justify-between p-4 border-b border-port-border">
+ <h3 className="font-medium text-white">Git Diff</h3>
+ <button onClick={() => setShowDiff(false)} className="text-gray-400 hover:text-white">×</button>
+ </div>
+ <pre className="p-4 overflow-auto max-h-[70vh] text-sm font-mono">
+ {diff.split('\n').map((line, i) => {
+ let color = 'text-gray-300';
+ if (line.startsWith('+') && !line.startsWith('+++')) color = 'text-port-success';
+ if (line.startsWith('-') && !line.startsWith('---')) color = 'text-port-error';
+ if (line.startsWith('@@')) color = 'text-port-accent';
+ return <div key={i} className={color}>{line}</div>;
+ })}
+ {!diff && <span className="text-gray-500">No changes to display</span>}
+ </pre>
+ </div>
+ </div>
+ )}
+ </div>
+ );
+}
+
+export function UsagePage() {
+ const [usage, setUsage] = useState(null);
+ const [loading, setLoading] = useState(true);
+
+ useEffect(() => {
+ loadUsage();
+ }, []);
+
+ const loadUsage = async () => {
+ setLoading(true);
+ const data = await api.getUsage().catch(() => null);
+ setUsage(data);
+ setLoading(false);
+ };
+
+ const formatNumber = (num) => {
+ if (num >= 1000000) return `${(num / 1000000).toFixed(1)}M`;
+ if (num >= 1000) return `${(num / 1000).toFixed(1)}K`;
+ return String(num);
+ };
+
+ if (loading) {
+ return <div className="text-center py-8 text-gray-400">Loading usage data...</div>;
+ }
+
+ if (!usage) {
+ return <div className="text-center py-8 text-gray-500">No usage data available</div>;
+ }
+
+ const maxActivity = Math.max(...(usage.last7Days?.map(d => d.sessions) || [1]));
+
+ return (
+ <div className="space-y-6">
+ <h1 className="text-2xl font-bold text-white">Usage Metrics</h1>
+
+ {/* Summary Stats */}
+ <div className="grid grid-cols-5 gap-4">
+ <div className="bg-port-card border border-port-border rounded-xl p-4 text-center">
+ <div className="text-2xl font-bold text-white">{formatNumber(usage.totalSessions)}</div>
+ <div className="text-sm text-gray-400">Sessions</div>
+ </div>
+ <div className="bg-port-card border border-port-border rounded-xl p-4 text-center">
+ <div className="text-2xl font-bold text-white">{formatNumber(usage.totalMessages)}</div>
+ <div className="text-sm text-gray-400">Messages</div>
+ </div>
+ <div className="bg-port-card border border-port-border rounded-xl p-4 text-center">
+ <div className="text-2xl font-bold text-white">{formatNumber(usage.totalToolCalls)}</div>
+ <div className="text-sm text-gray-400">Tool Calls</div>
+ </div>
+ <div className="bg-port-card border border-port-border rounded-xl p-4 text-center">
+ <div className="text-2xl font-bold text-white">{formatNumber(usage.totalTokens?.input + usage.totalTokens?.output)}</div>
+ <div className="text-sm text-gray-400">Tokens</div>
+ </div>
+ <div className="bg-port-card border border-port-border rounded-xl p-4 text-center">
+ <div className="text-2xl font-bold text-port-success">${usage.estimatedCost?.toFixed(2)}</div>
+ <div className="text-sm text-gray-400">Est. Cost</div>
+ </div>
+ </div>
+
+ <div className="grid grid-cols-2 gap-6">
+ {/* 7-Day Activity */}
+ <div className="bg-port-card border border-port-border rounded-xl p-4">
+ <h3 className="text-sm font-medium text-gray-400 mb-4">Last 7 Days</h3>
+ <div className="flex items-end gap-2 h-32">
+ {usage.last7Days?.map((day, i) => (
+ <div key={i} className="flex-1 flex flex-col items-center">
+ <div
+ className="w-full bg-port-accent/60 rounded-t"
+ style={{ height: `${(day.sessions / maxActivity) * 100}%`, minHeight: day.sessions > 0 ? 4 : 0 }}
+ />
+ <div className="text-xs text-gray-500 mt-2">{day.label}</div>
+ <div className="text-xs text-gray-400">{day.sessions}</div>
+ </div>
+ ))}
+ </div>
+ </div>
+
+ {/* Hourly Distribution */}
+ <div className="bg-port-card border border-port-border rounded-xl p-4">
+ <h3 className="text-sm font-medium text-gray-400 mb-4">Hourly Distribution</h3>
+ <div className="flex items-end gap-0.5 h-32">
+ {usage.hourlyActivity?.map((count, hour) => {
+ const maxHour = Math.max(...usage.hourlyActivity);
+ return (
+ <div key={hour} className="flex-1 flex flex-col items-center">
+ <div
+ className="w-full bg-port-accent/40 rounded-t"
+ style={{ height: `${(count / (maxHour || 1)) * 100}%`, minHeight: count > 0 ? 2 : 0 }}
+ title={`${hour}:00 - ${count} sessions`}
+ />
+ </div>
+ );
+ })}
+ </div>
+ <div className="flex justify-between text-xs text-gray-500 mt-2">
+ <span>12am</span>
+ <span>6am</span>
+ <span>12pm</span>
+ <span>6pm</span>
+ <span>12am</span>
+ </div>
+ </div>
+ </div>
+
+ <div className="grid grid-cols-2 gap-6">
+ {/* Top Providers */}
+ <div className="bg-port-card border border-port-border rounded-xl p-4">
+ <h3 className="text-sm font-medium text-gray-400 mb-3">Top Providers</h3>
+ <div className="space-y-2">
+ {usage.topProviders?.map((provider, i) => (
+ <div key={i} className="flex items-center justify-between py-2 border-b border-port-border last:border-0">
+ <span className="text-white">{provider.name}</span>
+ <div className="text-sm text-gray-400">
+ <span>{provider.sessions} sessions</span>
+ <span className="mx-2">•</span>
+ <span>{formatNumber(provider.tokens)} tokens</span>
+ </div>
+ </div>
+ ))}
+ {(!usage.topProviders || usage.topProviders.length === 0) && (
+ <div className="text-gray-500 text-sm">No provider data</div>
+ )}
+ </div>
+ </div>
+
+ {/* Top Models */}
+ <div className="bg-port-card border border-port-border rounded-xl p-4">
+ <h3 className="text-sm font-medium text-gray-400 mb-3">Top Models</h3>
+ <div className="space-y-2">
+ {usage.topModels?.map((model, i) => (
+ <div key={i} className="flex items-center justify-between py-2 border-b border-port-border last:border-0">
+ <span className="text-white font-mono text-sm">{model.model}</span>
+ <div className="text-sm text-gray-400">
+ <span>{model.sessions} sessions</span>
+ <span className="mx-2">•</span>
+ <span>{formatNumber(model.tokens)} tokens</span>
+ </div>
+ </div>
+ ))}
+ {(!usage.topModels || usage.topModels.length === 0) && (
+ <div className="text-gray-500 text-sm">No model data</div>
+ )}
+ </div>
+ </div>
+ </div>
+
+ {/* Refresh button */}
+ <div className="flex justify-end">
+ <button
+ onClick={loadUsage}
+ className="flex items-center gap-2 px-4 py-2 text-gray-400 hover:text-white"
+ >
+ <RefreshCw size={16} /> Refresh
+ </button>
+ </div>
+ </div>
+ );
+}
+
+export function AgentsPage() {
+ const [agents, setAgents] = useState([]);
+ const [loading, setLoading] = useState(true);
+ const [killing, setKilling] = useState({});
+ const [expandedPid, setExpandedPid] = useState(null);
+ const REFRESH_INTERVAL = 3;
+
+ useEffect(() => {
+ loadAgents();
+ const interval = setInterval(loadAgents, REFRESH_INTERVAL * 1000);
+ return () => clearInterval(interval);
+ }, []);
+
+ const loadAgents = async () => {
+ const data = await api.getAgents().catch(() => []);
+ setAgents(data);
+ setLoading(false);
+ };
+
+ const handleKill = async (pid) => {
+ setKilling(prev => ({ ...prev, [pid]: true }));
+ await api.killAgent(pid).catch(() => null);
+ setTimeout(() => {
+ setKilling(prev => ({ ...prev, [pid]: false }));
+ loadAgents();
+ }, 1000);
+ };
+
+ const toggleExpand = (pid) => {
+ setExpandedPid(prev => prev === pid ? null : pid);
+ };
+
+ const formatStartTime = (timestamp) => {
+ return new Date(timestamp).toLocaleString();
+ };
+
+ const totalCpu = agents.reduce((sum, a) => sum + (a.cpu || 0), 0);
+ const totalMemory = agents.reduce((sum, a) => sum + (a.memory || 0), 0);
+
+ if (loading) {
+ return <div className="text-center py-8 text-gray-400">Scanning for AI agents...</div>;
+ }
+
+ return (
+ <div className="space-y-6">
+ {/* Header */}
+ <div className="flex items-center justify-between">
+ <div className="flex items-center gap-3">
+ <Activity size={28} className="text-purple-400" />
+ <h1 className="text-2xl font-bold text-white font-mono">AI Agent Processes</h1>
+ <span className="text-gray-500 text-sm">(auto-refresh: {REFRESH_INTERVAL}s)</span>
+ </div>
+ <button
+ onClick={loadAgents}
+ className="flex items-center gap-2 px-4 py-2 bg-port-card border border-port-border hover:border-gray-500 text-white rounded-lg transition-colors"
+ >
+ <RefreshCw size={16} />
+ Refresh
+ </button>
+ </div>
+
+ {/* Summary Cards */}
+ <div className="grid grid-cols-3 gap-4">
+ <div className="bg-port-card border border-port-border rounded-xl p-5 flex items-center justify-between">
+ <div>
+ <div className="text-gray-400 text-sm mb-1">Total Processes</div>
+ <div className="text-3xl font-bold text-white font-mono">{agents.length}</div>
+ </div>
+ <Terminal size={32} className="text-purple-400" />
+ </div>
+ <div className="bg-port-card border border-port-border rounded-xl p-5 flex items-center justify-between">
+ <div>
+ <div className="text-gray-400 text-sm mb-1">Total CPU</div>
+ <div className="text-3xl font-bold text-white font-mono">{totalCpu.toFixed(1)}%</div>
+ </div>
+ <Cpu size={32} className="text-blue-400" />
+ </div>
+ <div className="bg-port-card border border-port-border rounded-xl p-5 flex items-center justify-between">
+ <div>
+ <div className="text-gray-400 text-sm mb-1">Total Memory</div>
+ <div className="text-3xl font-bold text-white font-mono">{totalMemory.toFixed(1)}%</div>
+ </div>
+ <MemoryStick size={32} className="text-green-400" />
+ </div>
+ </div>
+
+ {/* Running Processes Table */}
+ <div className="bg-port-card border border-port-border rounded-xl overflow-hidden">
+ <div className="px-6 py-4 border-b border-port-border">
+ <h2 className="text-lg font-semibold text-white">Running Processes</h2>
+ </div>
+ <table className="w-full">
+ <thead>
+ <tr className="border-b border-port-border">
+ <th className="px-4 py-4 text-left text-sm font-semibold text-gray-400 w-8"></th>
+ <th className="px-4 py-4 text-left text-sm font-semibold text-gray-400">PID</th>
+ <th className="px-4 py-4 text-left text-sm font-semibold text-gray-400">Runtime</th>
+ <th className="px-4 py-4 text-left text-sm font-semibold text-gray-400">CPU %</th>
+ <th className="px-4 py-4 text-left text-sm font-semibold text-gray-400">Memory %</th>
+ <th className="px-4 py-4 text-left text-sm font-semibold text-gray-400">Command</th>
+ <th className="px-4 py-4 text-center text-sm font-semibold text-gray-400">Actions</th>
+ </tr>
+ </thead>
+ <tbody>
+ {agents.map(agent => (
+ <Fragment key={agent.pid}>
+ <tr className="border-b border-port-border/50 hover:bg-port-border/20">
+ <td className="px-4 py-4">
+ <button
+ onClick={() => toggleExpand(agent.pid)}
+ className="text-gray-400 hover:text-white transition-transform"
+ >
+ <span className={`inline-block transition-transform ${expandedPid === agent.pid ? 'rotate-90' : ''}`}>▶</span>
+ </button>
+ </td>
+ <td className="px-4 py-4 font-mono text-white">{agent.pid}</td>
+ <td className="px-4 py-4 font-mono text-cyan-400">{agent.runtimeFormatted}</td>
+ <td className="px-4 py-4 font-mono text-green-400">{agent.cpu?.toFixed(1)}%</td>
+ <td className="px-4 py-4 font-mono text-blue-400">{agent.memory?.toFixed(1)}%</td>
+ <td className="px-4 py-4 font-mono text-gray-300">{agent.agentName.toLowerCase()}</td>
+ <td className="px-4 py-4 text-center">
+ <button
+ onClick={() => handleKill(agent.pid)}
+ disabled={killing[agent.pid]}
+ className="text-red-400 hover:text-red-300 disabled:opacity-50 transition-colors"
+ title="Kill process"
+ >
+ <XCircle size={22} className={killing[agent.pid] ? 'animate-pulse' : ''} />
+ </button>
+ </td>
+ </tr>
+ {expandedPid === agent.pid && (
+ <tr>
+ <td colSpan={7} className="p-0">
+ <div className="bg-port-bg border-t border-port-border">
+ <div className="px-6 py-4 space-y-4">
+ {/* Process Details Grid */}
+ <div className="grid grid-cols-4 gap-4">
+ <div>
+ <div className="text-xs text-gray-500 uppercase tracking-wide mb-1">Agent Type</div>
+ <div className="text-sm text-purple-400 font-medium">{agent.agentName}</div>
+ </div>
+ <div>
+ <div className="text-xs text-gray-500 uppercase tracking-wide mb-1">Parent PID</div>
+ <div className="text-sm text-gray-300 font-mono">{agent.ppid}</div>
+ </div>
+ <div>
+ <div className="text-xs text-gray-500 uppercase tracking-wide mb-1">Started At</div>
+ <div className="text-sm text-gray-300">{formatStartTime(agent.startTime)}</div>
+ </div>
+ <div>
+ <div className="text-xs text-gray-500 uppercase tracking-wide mb-1">Runtime (ms)</div>
+ <div className="text-sm text-gray-300 font-mono">{agent.runtime?.toLocaleString()}</div>
+ </div>
+ </div>
+
+ {/* Full Command */}
+ <div>
+ <div className="text-xs text-gray-500 uppercase tracking-wide mb-2">Full Command</div>
+ <div className="bg-port-card border border-port-border rounded-lg p-3 overflow-x-auto">
+ <code className="text-sm text-cyan-300 font-mono whitespace-pre-wrap break-all">
+ {agent.command}
+ </code>
+ </div>
+ </div>
+
+ {/* Resource Usage Bar */}
+ <div className="grid grid-cols-2 gap-4">
+ <div>
+ <div className="flex items-center justify-between text-xs mb-1">
+ <span className="text-gray-500 uppercase tracking-wide">CPU Usage</span>
+ <span className="text-green-400 font-mono">{agent.cpu?.toFixed(1)}%</span>
+ </div>
+ <div className="h-2 bg-port-border rounded-full overflow-hidden">
+ <div
+ className="h-full bg-green-500 rounded-full transition-all"
+ style={{ width: `${Math.min(agent.cpu || 0, 100)}%` }}
+ />
+ </div>
+ </div>
+ <div>
+ <div className="flex items-center justify-between text-xs mb-1">
+ <span className="text-gray-500 uppercase tracking-wide">Memory Usage</span>
+ <span className="text-blue-400 font-mono">{agent.memory?.toFixed(1)}%</span>
+ </div>
+ <div className="h-2 bg-port-border rounded-full overflow-hidden">
+ <div
+ className="h-full bg-blue-500 rounded-full transition-all"
+ style={{ width: `${Math.min(agent.memory || 0, 100)}%` }}
+ />
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+ </td>
+ </tr>
+ )}
+ </Fragment>
+ ))}
+ {agents.length === 0 && (
+ <tr>
+ <td colSpan={7} className="px-6 py-12 text-center text-gray-500">
+ No AI agents currently running
+ </td>
+ </tr>
+ )}
+ </tbody>
+ </table>
+ </div>
+ </div>
+ );
+}
diff --git a/client/src/services/api.js b/client/src/services/api.js
index 0b843caf10..79f78c13f4 100644
--- a/client/src/services/api.js
+++ b/client/src/services/api.js
@@ -196,3 +196,49 @@ export const executeCommand = (command, workspacePath) => request('/commands/exe
export const stopCommand = (id) => request(`/commands/${id}/stop`, { method: 'POST' });
export const getAllowedCommands = () => request('/commands/allowed');
export const getProcessesList = () => request('/commands/processes');
+
+// Git
+export const getGitInfo = (path) => request('/git/info', {
+ method: 'POST',
+ body: JSON.stringify({ path })
+});
+export const getGitStatus = (path) => request('/git/status', {
+ method: 'POST',
+ body: JSON.stringify({ path })
+});
+export const getGitDiff = (path, staged = false) => request('/git/diff', {
+ method: 'POST',
+ body: JSON.stringify({ path, staged })
+});
+export const getGitCommits = (path, limit = 10) => request('/git/commits', {
+ method: 'POST',
+ body: JSON.stringify({ path, limit })
+});
+export const stageFiles = (path, files) => request('/git/stage', {
+ method: 'POST',
+ body: JSON.stringify({ path, files })
+});
+export const unstageFiles = (path, files) => request('/git/unstage', {
+ method: 'POST',
+ body: JSON.stringify({ path, files })
+});
+export const createCommit = (path, message) => request('/git/commit', {
+ method: 'POST',
+ body: JSON.stringify({ path, message })
+});
+
+// Usage
+export const getUsage = () => request('/usage');
+export const getUsageRaw = () => request('/usage/raw');
+export const resetUsage = () => request('/usage', { method: 'DELETE' });
+
+// Screenshots
+export const uploadScreenshot = (base64Data, filename, mimeType) => request('/screenshots', {
+ method: 'POST',
+ body: JSON.stringify({ data: base64Data, filename, mimeType })
+});
+
+// Agents
+export const getAgents = () => request('/agents');
+export const getAgentInfo = (pid) => request(`/agents/${pid}`);
+export const killAgent = (pid) => request(`/agents/${pid}`, { method: 'DELETE' });
diff --git a/docs/media/portos_1.png b/docs/media/portos_1.png
new file mode 100644
index 0000000000..ccae6153f4
Binary files /dev/null and b/docs/media/portos_1.png differ
diff --git a/docs/media/portos_2.png b/docs/media/portos_2.png
new file mode 100644
index 0000000000..c0277bd647
Binary files /dev/null and b/docs/media/portos_2.png differ
diff --git a/docs/media/portos_3.png b/docs/media/portos_3.png
new file mode 100644
index 0000000000..89dc78fcd7
Binary files /dev/null and b/docs/media/portos_3.png differ
diff --git a/docs/media/portos_4.png b/docs/media/portos_4.png
new file mode 100644
index 0000000000..5611a1bb48
Binary files /dev/null and b/docs/media/portos_4.png differ
diff --git a/ecosystem.config.cjs b/ecosystem.config.cjs
index cf3b326b1b..c1c43e35dc 100644
--- a/ecosystem.config.cjs
+++ b/ecosystem.config.cjs
@@ -10,11 +10,6 @@ module.exports = {
PORT: 5554,
HOST: '0.0.0.0'
},
- env_production: {
- NODE_ENV: 'production',
- PORT: 5554,
- HOST: '0.0.0.0'
- },
watch: false,
max_memory_restart: '500M'
},
diff --git a/server/index.js b/server/index.js
index 526a1fe249..5d9d4fe401 100644
--- a/server/index.js
+++ b/server/index.js
@@ -16,6 +16,10 @@ import runsRoutes from './routes/runs.js';
import historyRoutes from './routes/history.js';
import commandsRoutes from './routes/commands.js';
import promptsRoutes from './routes/prompts.js';
+import gitRoutes from './routes/git.js';
+import usageRoutes from './routes/usage.js';
+import screenshotsRoutes from './routes/screenshots.js';
+import agentsRoutes from './routes/agents.js';
import { initSocket } from './services/socket.js';
const __filename = fileURLToPath(import.meta.url);
@@ -61,6 +65,10 @@ app.use('/api/runs', runsRoutes);
app.use('/api/history', historyRoutes);
app.use('/api/commands', commandsRoutes);
app.use('/api/prompts', promptsRoutes);
+app.use('/api/git', gitRoutes);
+app.use('/api/usage', usageRoutes);
+app.use('/api/screenshots', screenshotsRoutes);
+app.use('/api/agents', agentsRoutes);
// Error handler
app.use((err, req, res, next) => {
diff --git a/server/routes/agents.js b/server/routes/agents.js
new file mode 100644
index 0000000000..c9acd9cab3
--- /dev/null
+++ b/server/routes/agents.js
@@ -0,0 +1,29 @@
+import { Router } from 'express';
+import { getRunningAgents, killProcess, getProcessInfo } from '../services/agents.js';
+
+const router = Router();
+
+// GET /api/agents - Get all running AI agents
+router.get('/', async (req, res) => {
+ const agents = await getRunningAgents();
+ res.json(agents);
+});
+
+// GET /api/agents/:pid - Get specific process info
+router.get('/:pid', async (req, res) => {
+ const pid = parseInt(req.params.pid);
+ const info = await getProcessInfo(pid);
+ if (!info) {
+ return res.status(404).json({ error: 'Process not found' });
+ }
+ res.json(info);
+});
+
+// DELETE /api/agents/:pid - Kill a process
+router.delete('/:pid', async (req, res) => {
+ const pid = parseInt(req.params.pid);
+ await killProcess(pid);
+ res.json({ success: true, pid });
+});
+
+export default router;
diff --git a/server/routes/apps.js b/server/routes/apps.js
index efc75e97e0..2d047c9a04 100644
--- a/server/routes/apps.js
+++ b/server/routes/apps.js
@@ -8,14 +8,20 @@ const router = Router();
// GET /api/apps - List all apps
router.get('/', async (req, res, next) => {
+ console.log('📱 GET /api/apps - fetching apps list');
const apps = await appsService.getAllApps();
+ console.log(`📱 GET /api/apps - found ${apps.length} apps`);
+
+ // Get all PM2 processes once
+ const allPm2 = await pm2Service.listProcesses().catch(() => []);
+ const pm2Map = new Map(allPm2.map(p => [p.name, p]));
// Enrich with PM2 status
- const enriched = await Promise.all(apps.map(async (app) => {
+ const enriched = apps.map((app) => {
const statuses = {};
for (const processName of app.pm2ProcessNames || []) {
- const status = await pm2Service.getAppStatus(processName).catch(() => ({ status: 'unknown' }));
- statuses[processName] = status;
+ const pm2Proc = pm2Map.get(processName);
+ statuses[processName] = pm2Proc || { name: processName, status: 'not_found', pm2_env: null };
}
// Compute overall status
@@ -34,8 +40,9 @@ router.get('/', async (req, res, next) => {
pm2Status: statuses,
overallStatus
};
- }));
+ });
+ console.log(`📱 GET /api/apps - responding with ${enriched.length} apps`);
res.json(enriched);
});
diff --git a/server/routes/git.js b/server/routes/git.js
new file mode 100644
index 0000000000..b203c4a1cb
--- /dev/null
+++ b/server/routes/git.js
@@ -0,0 +1,138 @@
+import { Router } from 'express';
+import * as git from '../services/git.js';
+
+const router = Router();
+
+// GET /api/git/:appId - Get git info for an app
+router.get('/:appId', async (req, res, next) => {
+ const { appId } = req.params;
+
+ // Get app to find its path
+ const apps = req.app.get('apps');
+ const app = apps?.find(a => a.id === appId);
+
+ if (!app) {
+ return res.status(404).json({ error: 'App not found' });
+ }
+
+ const info = await git.getGitInfo(app.repoPath).catch(err => {
+ res.status(500).json({ error: err.message });
+ return undefined;
+ });
+
+ if (info) res.json(info);
+});
+
+// POST /api/git/status - Get status for a path
+router.post('/status', async (req, res, next) => {
+ const { path } = req.body;
+
+ if (!path) {
+ return res.status(400).json({ error: 'path is required' });
+ }
+
+ const status = await git.getStatus(path).catch(err => {
+ res.status(500).json({ error: err.message });
+ return undefined;
+ });
+
+ if (status) res.json(status);
+});
+
+// POST /api/git/diff - Get diff for a path
+router.post('/diff', async (req, res, next) => {
+ const { path, staged } = req.body;
+
+ if (!path) {
+ return res.status(400).json({ error: 'path is required' });
+ }
+
+ const diff = await git.getDiff(path, staged).catch(err => {
+ res.status(500).json({ error: err.message });
+ return undefined;
+ });
+
+ if (diff !== undefined) res.json({ diff });
+});
+
+// POST /api/git/commits - Get recent commits
+router.post('/commits', async (req, res, next) => {
+ const { path, limit = 10 } = req.body;
+
+ if (!path) {
+ return res.status(400).json({ error: 'path is required' });
+ }
+
+ const commits = await git.getCommits(path, limit).catch(err => {
+ res.status(500).json({ error: err.message });
+ return undefined;
+ });
+
+ if (commits) res.json({ commits });
+});
+
+// POST /api/git/stage - Stage files
+router.post('/stage', async (req, res, next) => {
+ const { path, files } = req.body;
+
+ if (!path || !files) {
+ return res.status(400).json({ error: 'path and files are required' });
+ }
+
+ const result = await git.stageFiles(path, files).catch(err => {
+ res.status(500).json({ error: err.message });
+ return undefined;
+ });
+
+ if (result) res.json({ success: true });
+});
+
+// POST /api/git/unstage - Unstage files
+router.post('/unstage', async (req, res, next) => {
+ const { path, files } = req.body;
+
+ if (!path || !files) {
+ return res.status(400).json({ error: 'path and files are required' });
+ }
+
+ const result = await git.unstageFiles(path, files).catch(err => {
+ res.status(500).json({ error: err.message });
+ return undefined;
+ });
+
+ if (result) res.json({ success: true });
+});
+
+// POST /api/git/commit - Create a commit
+router.post('/commit', async (req, res, next) => {
+ const { path, message } = req.body;
+
+ if (!path || !message) {
+ return res.status(400).json({ error: 'path and message are required' });
+ }
+
+ const result = await git.commit(path, message).catch(err => {
+ res.status(500).json({ error: err.message });
+ return undefined;
+ });
+
+ if (result) res.json(result);
+});
+
+// POST /api/git/info - Get full git info for a path
+router.post('/info', async (req, res, next) => {
+ const { path } = req.body;
+
+ if (!path) {
+ return res.status(400).json({ error: 'path is required' });
+ }
+
+ const info = await git.getGitInfo(path).catch(err => {
+ res.status(500).json({ error: err.message });
+ return undefined;
+ });
+
+ if (info) res.json(info);
+});
+
+export default router;
diff --git a/server/routes/health.js b/server/routes/health.js
index 7010e15f07..5e69adc060 100644
--- a/server/routes/health.js
+++ b/server/routes/health.js
@@ -3,6 +3,7 @@ import { Router } from 'express';
const router = Router();
router.get('/health', (req, res) => {
+ console.log('💓 GET /api/health');
res.json({
status: 'ok',
timestamp: new Date().toISOString(),
diff --git a/server/routes/screenshots.js b/server/routes/screenshots.js
new file mode 100644
index 0000000000..5c3b72561b
--- /dev/null
+++ b/server/routes/screenshots.js
@@ -0,0 +1,61 @@
+import { Router } from 'express';
+import { 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 SCREENSHOTS_DIR = join(__dirname, '../../data/screenshots');
+
+const router = Router();
+
+// POST /api/screenshots - Upload a screenshot (base64)
+router.post('/', async (req, res) => {
+ const { data, filename, mimeType } = req.body;
+
+ if (!data) {
+ return res.status(400).json({ error: 'data is required (base64)' });
+ }
+
+ // Ensure screenshots directory exists
+ if (!existsSync(SCREENSHOTS_DIR)) {
+ await mkdir(SCREENSHOTS_DIR, { recursive: true });
+ }
+
+ const id = uuidv4();
+ const ext = mimeType?.includes('png') ? 'png' : 'jpg';
+ const fname = filename || `screenshot-${id}.${ext}`;
+ const filepath = join(SCREENSHOTS_DIR, fname);
+
+ // Decode base64 and write file
+ const buffer = Buffer.from(data, 'base64');
+ await writeFile(filepath, buffer);
+
+ console.log(`📸 Screenshot saved: ${fname} (${buffer.length} bytes)`);
+
+ res.json({
+ id,
+ filename: fname,
+ path: filepath,
+ size: buffer.length
+ });
+});
+
+// GET /api/screenshots/:filename - Serve a screenshot
+router.get('/:filename', async (req, res) => {
+ const { filename } = req.params;
+ const filepath = join(SCREENSHOTS_DIR, filename);
+
+ if (!existsSync(filepath)) {
+ return res.status(404).json({ error: 'Screenshot not found' });
+ }
+
+ const ext = filename.split('.').pop().toLowerCase();
+ const mimeType = ext === 'png' ? 'image/png' : 'image/jpeg';
+
+ res.type(mimeType).sendFile(filepath);
+});
+
+export default router;
diff --git a/server/routes/usage.js b/server/routes/usage.js
new file mode 100644
index 0000000000..e3f368abb5
--- /dev/null
+++ b/server/routes/usage.js
@@ -0,0 +1,45 @@
+import { Router } from 'express';
+import * as usage from '../services/usage.js';
+
+const router = Router();
+
+// GET /api/usage - Get usage summary
+router.get('/', async (req, res) => {
+ const summary = usage.getUsageSummary();
+ res.json(summary);
+});
+
+// GET /api/usage/raw - Get raw usage data
+router.get('/raw', async (req, res) => {
+ const data = usage.getUsage();
+ res.json(data);
+});
+
+// POST /api/usage/session - Record a session
+router.post('/session', async (req, res) => {
+ const { providerId, providerName, model } = req.body;
+ const sessionNumber = await usage.recordSession(providerId, providerName, model);
+ res.json({ sessionNumber });
+});
+
+// POST /api/usage/messages - Record messages
+router.post('/messages', async (req, res) => {
+ const { providerId, model, messageCount, tokenCount } = req.body;
+ await usage.recordMessages(providerId, model, messageCount, tokenCount);
+ res.json({ success: true });
+});
+
+// POST /api/usage/tokens - Record token usage
+router.post('/tokens', async (req, res) => {
+ const { inputTokens, outputTokens } = req.body;
+ await usage.recordTokens(inputTokens || 0, outputTokens || 0);
+ res.json({ success: true });
+});
+
+// DELETE /api/usage - Reset usage data
+router.delete('/', async (req, res) => {
+ await usage.resetUsage();
+ res.json({ success: true });
+});
+
+export default router;
diff --git a/server/services/agents.js b/server/services/agents.js
new file mode 100644
index 0000000000..b546dbe219
--- /dev/null
+++ b/server/services/agents.js
@@ -0,0 +1,238 @@
+import { exec } from 'child_process';
+import { promisify } from 'util';
+
+const execAsync = promisify(exec);
+
+// Agent process patterns to detect
+const AGENT_PATTERNS = [
+ { name: 'Claude', pattern: 'claude', command: 'claude' },
+ { name: 'Codex', pattern: 'codex', command: 'codex' },
+ { name: 'Gemini', pattern: 'gemini', command: 'gemini' },
+ { name: 'Aider', pattern: 'aider', command: 'aider' },
+ { name: 'Cursor', pattern: 'cursor', command: 'cursor' },
+ { name: 'Copilot', pattern: 'copilot', command: 'copilot' }
+];
+
+/**
+ * Get list of running agent processes
+ */
+export async function getRunningAgents() {
+ const agents = [];
+
+ for (const agent of AGENT_PATTERNS) {
+ const procs = await findProcesses(agent.pattern);
+ procs.forEach(proc => {
+ agents.push({
+ ...proc,
+ agentName: agent.name,
+ agentType: agent.command
+ });
+ });
+ }
+
+ // Sort by start time (newest first)
+ agents.sort((a, b) => b.startTime - a.startTime);
+
+ return agents;
+}
+
+/**
+ * Find processes matching a pattern
+ */
+async function findProcesses(pattern) {
+ const platform = process.platform;
+
+ if (platform === 'darwin' || platform === 'linux') {
+ return findUnixProcesses(pattern);
+ } else if (platform === 'win32') {
+ return findWindowsProcesses(pattern);
+ }
+
+ return [];
+}
+
+/**
+ * Find processes on Unix-like systems (macOS, Linux)
+ */
+async function findUnixProcesses(pattern) {
+ // ps command to get process info
+ // -e: all processes, -o: output format
+ const cmd = `ps -eo pid,ppid,%cpu,%mem,etime,command | grep -i "${pattern}" | grep -v grep`;
+
+ const result = await execAsync(cmd, { maxBuffer: 10 * 1024 * 1024 }).catch(() => ({ stdout: '' }));
+
+ const lines = result.stdout.trim().split('\n').filter(Boolean);
+ const processes = [];
+
+ for (const line of lines) {
+ const parts = line.trim().split(/\s+/);
+ if (parts.length >= 6) {
+ const pid = parseInt(parts[0]);
+ const ppid = parseInt(parts[1]);
+ const cpu = parseFloat(parts[2]);
+ const mem = parseFloat(parts[3]);
+ const etime = parts[4];
+ const command = parts.slice(5).join(' ');
+
+ // Skip if it's a grep or our own process
+ if (command.includes('grep') || command.includes('ps -eo')) continue;
+
+ // Parse elapsed time to get start time
+ const runtime = parseElapsedTime(etime);
+
+ processes.push({
+ pid,
+ ppid,
+ cpu,
+ memory: mem,
+ runtime,
+ runtimeFormatted: formatRuntime(runtime),
+ command,
+ startTime: Date.now() - runtime
+ });
+ }
+ }
+
+ return processes;
+}
+
+/**
+ * Find processes on Windows
+ */
+async function findWindowsProcesses(pattern) {
+ const cmd = `wmic process where "name like '%${pattern}%'" get ProcessId,ParentProcessId,PercentProcessorTime,WorkingSetSize,CreationDate,CommandLine /format:csv`;
+
+ const result = await execAsync(cmd).catch(() => ({ stdout: '' }));
+
+ const lines = result.stdout.trim().split('\n').filter(Boolean);
+ const processes = [];
+
+ // Skip header line
+ for (let i = 1; i < lines.length; i++) {
+ const parts = lines[i].split(',');
+ if (parts.length >= 6) {
+ const command = parts[1];
+ const creationDate = parts[2];
+ const ppid = parseInt(parts[3]);
+ const cpu = parseFloat(parts[4]) || 0;
+ const memory = parseInt(parts[5]) / 1024 / 1024; // Convert to MB
+ const pid = parseInt(parts[6]);
+
+ const startTime = parseWindowsDate(creationDate);
+ const runtime = Date.now() - startTime;
+
+ processes.push({
+ pid,
+ ppid,
+ cpu,
+ memory,
+ runtime,
+ runtimeFormatted: formatRuntime(runtime),
+ command,
+ startTime
+ });
+ }
+ }
+
+ return processes;
+}
+
+/**
+ * Parse Unix elapsed time format (HH:MM:SS or MM:SS or SS)
+ */
+function parseElapsedTime(etime) {
+ const parts = etime.split(':').map(p => parseInt(p.replace(/-/g, '')));
+
+ if (etime.includes('-')) {
+ // Days-HH:MM:SS format
+ const [days, rest] = etime.split('-');
+ const timeParts = rest.split(':').map(p => parseInt(p));
+ const d = parseInt(days);
+ const [h, m, s] = timeParts.length === 3 ? timeParts : [0, ...timeParts];
+ return ((d * 24 + h) * 60 + m) * 60 * 1000 + s * 1000;
+ }
+
+ if (parts.length === 3) {
+ // HH:MM:SS
+ return (parts[0] * 3600 + parts[1] * 60 + parts[2]) * 1000;
+ } else if (parts.length === 2) {
+ // MM:SS
+ return (parts[0] * 60 + parts[1]) * 1000;
+ }
+
+ return parts[0] * 1000;
+}
+
+/**
+ * Parse Windows date format
+ */
+function parseWindowsDate(dateStr) {
+ if (!dateStr) return Date.now();
+ // Format: YYYYMMDDHHmmss.ffffff
+ const year = parseInt(dateStr.substring(0, 4));
+ const month = parseInt(dateStr.substring(4, 6)) - 1;
+ const day = parseInt(dateStr.substring(6, 8));
+ const hour = parseInt(dateStr.substring(8, 10));
+ const min = parseInt(dateStr.substring(10, 12));
+ const sec = parseInt(dateStr.substring(12, 14));
+ return new Date(year, month, day, hour, min, sec).getTime();
+}
+
+/**
+ * Format runtime in human-readable format
+ */
+function formatRuntime(ms) {
+ const seconds = Math.floor(ms / 1000);
+ const minutes = Math.floor(seconds / 60);
+ const hours = Math.floor(minutes / 60);
+ const days = Math.floor(hours / 24);
+
+ if (days > 0) return `${days}d ${hours % 24}h`;
+ if (hours > 0) return `${hours}h ${minutes % 60}m`;
+ if (minutes > 0) return `${minutes}m ${seconds % 60}s`;
+ return `${seconds}s`;
+}
+
+/**
+ * Kill a process by PID
+ */
+export async function killProcess(pid) {
+ const platform = process.platform;
+
+ if (platform === 'win32') {
+ await execAsync(`taskkill /PID ${pid} /F`);
+ } else {
+ await execAsync(`kill -9 ${pid}`);
+ }
+
+ console.log(`🔪 Killed process ${pid}`);
+ return true;
+}
+
+/**
+ * Get detailed info for a specific process
+ */
+export async function getProcessInfo(pid) {
+ const platform = process.platform;
+
+ if (platform === 'darwin' || platform === 'linux') {
+ const cmd = `ps -p ${pid} -o pid,ppid,%cpu,%mem,etime,command`;
+ const result = await execAsync(cmd).catch(() => null);
+ if (!result) return null;
+
+ const lines = result.stdout.trim().split('\n');
+ if (lines.length < 2) return null;
+
+ const parts = lines[1].trim().split(/\s+/);
+ return {
+ pid: parseInt(parts[0]),
+ ppid: parseInt(parts[1]),
+ cpu: parseFloat(parts[2]),
+ memory: parseFloat(parts[3]),
+ runtime: parseElapsedTime(parts[4]),
+ command: parts.slice(5).join(' ')
+ };
+ }
+
+ return null;
+}
diff --git a/server/services/apps.js b/server/services/apps.js
index b52e7c934f..726ec7743e 100644
--- a/server/services/apps.js
+++ b/server/services/apps.js
@@ -41,19 +41,20 @@ async function saveApps(data) {
}
/**
- * Get all apps
+ * Get all apps (injects id from key)
*/
export async function getAllApps() {
const data = await loadApps();
- return Object.values(data.apps);
+ return Object.entries(data.apps).map(([id, app]) => ({ id, ...app }));
}
/**
- * Get app by ID
+ * Get app by ID (injects id from key)
*/
export async function getAppById(id) {
const data = await loadApps();
- return data.apps[id] || null;
+ const app = data.apps[id];
+ return app ? { id, ...app } : null;
}
/**
@@ -64,11 +65,14 @@ export async function createApp(appData) {
const id = uuidv4();
const now = new Date().toISOString();
+ // Store without id (key is id) and without uiUrl (derived from uiPort)
const app = {
- id,
- ...appData,
- // Don't hardcode host - client will construct URL from current hostname
- uiUrl: appData.uiUrl || null,
+ name: appData.name,
+ description: appData.description || '',
+ repoPath: appData.repoPath,
+ type: appData.type || 'unknown',
+ uiPort: appData.uiPort || null,
+ apiPort: appData.apiPort || null,
startCommands: appData.startCommands || ['npm run dev'],
pm2ProcessNames: appData.pm2ProcessNames || [appData.name.toLowerCase().replace(/\s+/g, '-')],
envFile: appData.envFile || '.env',
@@ -81,7 +85,8 @@ export async function createApp(appData) {
data.apps[id] = app;
await saveApps(data);
- return app;
+ // Return with id injected
+ return { id, ...app };
}
/**
@@ -94,23 +99,21 @@ export async function updateApp(id, updates) {
return null;
}
+ // Remove id and uiUrl from updates if present (id is key, uiUrl is derived)
+ const { id: _id, uiUrl: _uiUrl, ...cleanUpdates } = updates;
+
const app = {
...data.apps[id],
- ...updates,
- id, // Prevent ID override
+ ...cleanUpdates,
createdAt: data.apps[id].createdAt, // Preserve creation date
updatedAt: new Date().toISOString()
};
- // Clear uiUrl if uiPort changed - client will construct URL dynamically
- if (updates.uiPort && !updates.uiUrl) {
- app.uiUrl = null;
- }
-
data.apps[id] = app;
await saveApps(data);
- return app;
+ // Return with id injected
+ return { id, ...app };
}
/**
diff --git a/server/services/commands.js b/server/services/commands.js
index 8bf02757ce..3bb4283655 100644
--- a/server/services/commands.js
+++ b/server/services/commands.js
@@ -60,20 +60,21 @@ export function executeCommand(command, workspacePath, onData, onComplete) {
child.on('close', (code) => {
activeCommands.delete(commandId);
- const duration = Date.now() - startTime;
+ const runtime = Date.now() - startTime;
const success = code === 0;
logAction('command', null, command.substring(0, 50), {
command,
workspacePath,
exitCode: code,
- duration
+ runtime,
+ output: output.substring(0, 10000) // Truncate to prevent huge history
}, success, success ? null : `Exit code ${code}`);
onComplete?.({
success,
exitCode: code,
- duration,
+ runtime,
output
});
});
diff --git a/server/services/git.js b/server/services/git.js
new file mode 100644
index 0000000000..50c5698351
--- /dev/null
+++ b/server/services/git.js
@@ -0,0 +1,178 @@
+import { exec } from 'child_process';
+import { promisify } from 'util';
+
+const execAsync = promisify(exec);
+
+/**
+ * Get git status for a directory
+ */
+export async function getStatus(dir) {
+ const result = await execAsync('git status --porcelain', { cwd: dir });
+ const lines = result.stdout.trim().split('\n').filter(Boolean);
+
+ const files = lines.map(line => {
+ const status = line.substring(0, 2);
+ const path = line.substring(3);
+ return {
+ path,
+ status: parseStatus(status),
+ staged: status[0] !== ' ' && status[0] !== '?',
+ modified: status[1] === 'M',
+ added: status[0] === 'A' || status === '??',
+ deleted: status[0] === 'D' || status[1] === 'D'
+ };
+ });
+
+ return {
+ clean: files.length === 0,
+ files,
+ staged: files.filter(f => f.staged).length,
+ unstaged: files.filter(f => !f.staged).length
+ };
+}
+
+function parseStatus(status) {
+ const map = {
+ '??': 'untracked',
+ 'A ': 'added',
+ 'M ': 'modified (staged)',
+ ' M': 'modified',
+ 'MM': 'modified (partial)',
+ 'D ': 'deleted (staged)',
+ ' D': 'deleted',
+ 'R ': 'renamed',
+ 'C ': 'copied',
+ 'AM': 'added (modified)',
+ 'AD': 'added (deleted)'
+ };
+ return map[status] || status.trim();
+}
+
+/**
+ * Get current branch name
+ */
+export async function getBranch(dir) {
+ const result = await execAsync('git rev-parse --abbrev-ref HEAD', { cwd: dir });
+ return result.stdout.trim();
+}
+
+/**
+ * Get recent commits
+ */
+export async function getCommits(dir, limit = 10) {
+ const format = '--format={"hash":"%h","message":"%s","author":"%an","date":"%ci"}';
+ const result = await execAsync(`git log ${format} -n ${limit}`, { cwd: dir });
+
+ const commits = result.stdout.trim().split('\n').filter(Boolean).map(line => {
+ return JSON.parse(line);
+ });
+
+ return commits;
+}
+
+/**
+ * Get diff for unstaged changes
+ */
+export async function getDiff(dir, staged = false) {
+ const cmd = staged ? 'git diff --cached' : 'git diff';
+ const result = await execAsync(cmd, { cwd: dir, maxBuffer: 10 * 1024 * 1024 });
+ return result.stdout;
+}
+
+/**
+ * Get diff stats
+ */
+export async function getDiffStats(dir) {
+ const result = await execAsync('git diff --stat', { cwd: dir });
+ const statsLine = result.stdout.trim().split('\n').pop() || '';
+
+ const filesMatch = statsLine.match(/(\d+) files? changed/);
+ const insertionsMatch = statsLine.match(/(\d+) insertions?/);
+ const deletionsMatch = statsLine.match(/(\d+) deletions?/);
+
+ return {
+ files: filesMatch ? parseInt(filesMatch[1]) : 0,
+ insertions: insertionsMatch ? parseInt(insertionsMatch[1]) : 0,
+ deletions: deletionsMatch ? parseInt(deletionsMatch[1]) : 0
+ };
+}
+
+/**
+ * Stage files
+ */
+export async function stageFiles(dir, files) {
+ const paths = Array.isArray(files) ? files.join(' ') : files;
+ await execAsync(`git add ${paths}`, { cwd: dir });
+ return true;
+}
+
+/**
+ * Unstage files
+ */
+export async function unstageFiles(dir, files) {
+ const paths = Array.isArray(files) ? files.join(' ') : files;
+ await execAsync(`git reset HEAD ${paths}`, { cwd: dir });
+ return true;
+}
+
+/**
+ * Create commit
+ */
+export async function commit(dir, message) {
+ const result = await execAsync(`git commit -m "${message.replace(/"/g, '\\"')}"`, { cwd: dir });
+ const hashMatch = result.stdout.match(/\[[\w-]+ ([a-f0-9]+)\]/);
+ return {
+ hash: hashMatch ? hashMatch[1] : null,
+ message
+ };
+}
+
+/**
+ * Check if directory is a git repo
+ */
+export async function isRepo(dir) {
+ const result = await execAsync('git rev-parse --is-inside-work-tree', { cwd: dir }).catch(() => null);
+ return result?.stdout.trim() === 'true';
+}
+
+/**
+ * Get remote info
+ */
+export async function getRemote(dir) {
+ const result = await execAsync('git remote -v', { cwd: dir }).catch(() => null);
+ if (!result) return null;
+
+ const lines = result.stdout.trim().split('\n');
+ const origins = {};
+
+ lines.forEach(line => {
+ const [name, url, type] = line.split(/\s+/);
+ if (!origins[name]) origins[name] = {};
+ origins[name][type?.replace(/[()]/g, '')] = url;
+ });
+
+ return origins;
+}
+
+/**
+ * Get comprehensive git info
+ */
+export async function getGitInfo(dir) {
+ const [isGit, branch, status, commits, diffStats, remote] = await Promise.all([
+ isRepo(dir),
+ getBranch(dir).catch(() => null),
+ getStatus(dir).catch(() => ({ clean: true, files: [] })),
+ getCommits(dir, 5).catch(() => []),
+ getDiffStats(dir).catch(() => ({ files: 0, insertions: 0, deletions: 0 })),
+ getRemote(dir).catch(() => null)
+ ]);
+
+ return {
+ isRepo: isGit,
+ branch,
+ status,
+ recentCommits: commits,
+ diffStats,
+ remote
+ };
+}
diff --git a/server/services/pm2.js b/server/services/pm2.js
index e4a9accc5f..6e7424b58c 100644
--- a/server/services/pm2.js
+++ b/server/services/pm2.js
@@ -95,62 +95,78 @@ export async function deleteApp(name) {
}
/**
- * Get status of a specific process
+ * Get status of a specific process using CLI (avoids connection deadlocks)
* @param {string} name PM2 process name
*/
export async function getAppStatus(name) {
- return connectAndRun((pm2) => {
- return new Promise((resolve, reject) => {
- pm2.describe(name, (err, processDescription) => {
- if (err) return reject(err);
+ return new Promise((resolve) => {
+ const child = spawn('pm2', ['jlist'], { shell: false });
+ let stdout = '';
+
+ child.stdout.on('data', (data) => {
+ stdout += data.toString();
+ });
+
+ child.on('close', () => {
+ const processes = JSON.parse(stdout || '[]');
+ const proc = processes.find(p => p.name === name);
- if (!processDescription || processDescription.length === 0) {
- return resolve({
- name,
- status: 'not_found',
- pm2_env: null
- });
- }
-
- const proc = processDescription[0];
- resolve({
- name: proc.name,
- status: proc.pm2_env?.status || 'unknown',
- pid: proc.pid,
- pm_id: proc.pm_id,
- cpu: proc.monit?.cpu || 0,
- memory: proc.monit?.memory || 0,
- uptime: proc.pm2_env?.pm_uptime || null,
- restarts: proc.pm2_env?.restart_time || 0,
- createdAt: proc.pm2_env?.created_at || null
+ if (!proc) {
+ return resolve({
+ name,
+ status: 'not_found',
+ pm2_env: null
});
+ }
+
+ resolve({
+ name: proc.name,
+ status: proc.pm2_env?.status || 'unknown',
+ pid: proc.pid,
+ pm_id: proc.pm_id,
+ cpu: proc.monit?.cpu || 0,
+ memory: proc.monit?.memory || 0,
+ uptime: proc.pm2_env?.pm_uptime || null,
+ restarts: proc.pm2_env?.restart_time || 0,
+ createdAt: proc.pm2_env?.created_at || null
});
});
+
+ child.on('error', () => {
+ resolve({ name, status: 'error', pm2_env: null });
+ });
});
}
/**
- * List all PM2 processes
+ * List all PM2 processes using CLI (avoids connection deadlocks)
*/
export async function listProcesses() {
- return connectAndRun((pm2) => {
- return new Promise((resolve, reject) => {
- pm2.list((err, list) => {
- if (err) return reject(err);
+ return new Promise((resolve) => {
+ const child = spawn('pm2', ['jlist'], { shell: false });
+ let stdout = '';
- const processes = list.map(proc => ({
- name: proc.name,
- status: proc.pm2_env?.status || 'unknown',
- pid: proc.pid,
- pm_id: proc.pm_id,
- cpu: proc.monit?.cpu || 0,
- memory: proc.monit?.memory || 0,
- uptime: proc.pm2_env?.pm_uptime || null,
- restarts: proc.pm2_env?.restart_time || 0
- }));
-
- resolve(processes);
- });
+ child.stdout.on('data', (data) => {
+ stdout += data.toString();
+ });
+
+ child.on('close', () => {
+ const list = JSON.parse(stdout || '[]');
+ const processes = list.map(proc => ({
+ name: proc.name,
+ status: proc.pm2_env?.status || 'unknown',
+ pid: proc.pid,
+ pm_id: proc.pm_id,
+ cpu: proc.monit?.cpu || 0,
+ memory: proc.monit?.memory || 0,
+ uptime: proc.pm2_env?.pm_uptime || null,
+ restarts: proc.pm2_env?.restart_time || 0
+ }));
+ resolve(processes);
+ });
+
+ child.on('error', () => {
+ resolve([]);
});
});
}
diff --git a/server/services/streamingDetect.js b/server/services/streamingDetect.js
index 388804327d..78c6a0c6fe 100644
--- a/server/services/streamingDetect.js
+++ b/server/services/streamingDetect.js
@@ -3,15 +3,13 @@ import { existsSync } from 'fs';
import { join, basename } from 'path';
import { exec } from 'child_process';
import { promisify } from 'util';
-import { getActiveProvider, getProviderById } from './providers.js';
-import { spawn } from 'child_process';
const execAsync = promisify(exec);
/**
* Stream detection results to a socket as each step completes
*/
-export async function streamDetection(socket, dirPath, providerId = null) {
+export async function streamDetection(socket, dirPath) {
const emit = (step, status, data = {}) => {
socket.emit('detect:step', { step, status, data, timestamp: Date.now() });
};
@@ -55,12 +53,11 @@ export async function streamDetection(socket, dirPath, providerId = null) {
// Step 3: Read package.json
emit('package', 'running', { message: 'Reading package.json...' });
const pkgPath = join(dirPath, 'package.json');
- let pkg = null;
if (existsSync(pkgPath)) {
const content = await readFile(pkgPath, 'utf-8').catch(() => null);
if (content) {
- pkg = JSON.parse(content);
+ const pkg = JSON.parse(content);
result.name = pkg.name || result.name;
result.description = pkg.description || '';
@@ -114,10 +111,41 @@ export async function streamDetection(socket, dirPath, providerId = null) {
}
}
+ // Check ecosystem.config.js/cjs for PM2 configuration
+ for (const ecosystemFile of ['ecosystem.config.js', 'ecosystem.config.cjs']) {
+ const ecosystemPath = join(dirPath, ecosystemFile);
+ if (existsSync(ecosystemPath)) {
+ const content = await readFile(ecosystemPath, 'utf-8').catch(() => '');
+ if (content) {
+ // Extract PORT from env_development or env_production
+ const portMatch = content.match(/PORT\s*:\s*(\d+)/);
+ if (portMatch && !result.apiPort) {
+ result.apiPort = parseInt(portMatch[1]);
+ }
+
+ // Extract UI port from CLIENT_URL
+ const clientUrlMatch = content.match(/CLIENT_URL\s*:\s*['"]https?:\/\/[^:]+:(\d+)/);
+ if (clientUrlMatch && !result.uiPort) {
+ result.uiPort = parseInt(clientUrlMatch[1]);
+ }
+
+ // Extract PM2 process names
+ const nameMatches = content.matchAll(/name\s*:\s*['"]([^'"]+)['"]/g);
+ const ecosystemNames = [...nameMatches].map(m => m[1]);
+ if (ecosystemNames.length > 0) {
+ result.pm2ProcessNames = ecosystemNames;
+ }
+
+ configFiles.push(ecosystemFile);
+ }
+ }
+ }
+
emit('config', 'done', {
message: configFiles.length ? `Found: ${configFiles.join(', ')}` : 'No config files found',
uiPort: result.uiPort,
apiPort: result.apiPort,
+ pm2ProcessNames: result.pm2ProcessNames.length > 0 ? result.pm2ProcessNames : undefined,
configFiles
});
@@ -145,135 +173,56 @@ export async function streamDetection(socket, dirPath, providerId = null) {
status: p.pm2_env?.status,
pid: p.pid
}));
+ // Use actual found PM2 process names
+ result.pm2ProcessNames = matchingProcesses.map(p => p.name);
emit('pm2', 'done', {
message: `Found ${matchingProcesses.length} running process(es)`,
- pm2Status: result.pm2Status
+ pm2Status: result.pm2Status,
+ pm2ProcessNames: result.pm2ProcessNames
});
} else {
emit('pm2', 'done', { message: 'No matching PM2 processes found' });
+ // Generate PM2 process names only if none found from ecosystem.config
+ if (result.pm2ProcessNames.length === 0) {
+ const baseName = result.name.toLowerCase().replace(/[^a-z0-9]/g, '-');
+ if (result.type === 'vite+express') {
+ result.pm2ProcessNames = [`${baseName}-ui`, `${baseName}-api`];
+ } else {
+ result.pm2ProcessNames = [baseName];
+ }
+ }
}
- // Generate PM2 process names
- const baseName = result.name.toLowerCase().replace(/[^a-z0-9]/g, '-');
- if (result.type === 'vite+express') {
- result.pm2ProcessNames = [`${baseName}-ui`, `${baseName}-api`];
- } else {
- result.pm2ProcessNames = [baseName];
- }
-
- // Step 6: AI-powered analysis (if provider available)
- const provider = providerId
- ? await getProviderById(providerId)
- : await getActiveProvider();
-
- if (provider?.enabled) {
- emit('ai', 'running', { message: `Analyzing with ${provider.name}...` });
-
- const aiResult = await runAiAnalysis(dirPath, provider, { pkg, files }).catch(err => {
- console.log(`⚠️ AI analysis failed: ${err.message}`);
- return null;
- });
-
- if (aiResult) {
- // Merge AI results (AI takes precedence for name/description)
- if (aiResult.name) result.name = aiResult.name;
- if (aiResult.description) result.description = aiResult.description;
- if (aiResult.uiPort && !result.uiPort) result.uiPort = aiResult.uiPort;
- if (aiResult.apiPort && !result.apiPort) result.apiPort = aiResult.apiPort;
- if (aiResult.startCommands?.length) result.startCommands = aiResult.startCommands;
- if (aiResult.pm2ProcessNames?.length) result.pm2ProcessNames = aiResult.pm2ProcessNames;
-
- emit('ai', 'done', {
- message: 'AI analysis complete',
- name: result.name,
- description: result.description
- });
- } else {
- emit('ai', 'skipped', { message: 'AI analysis unavailable' });
+ // Step 6: Read README.md for description (fast, no AI needed)
+ if (!result.description) {
+ emit('readme', 'running', { message: 'Reading README.md...' });
+ let foundReadme = false;
+ for (const readmeFile of ['README.md', 'readme.md', 'Readme.md']) {
+ const readmePath = join(dirPath, readmeFile);
+ if (existsSync(readmePath)) {
+ const content = await readFile(readmePath, 'utf-8').catch(() => '');
+ if (content) {
+ // Extract first paragraph or heading as description
+ const lines = content.split('\n').filter(l => l.trim() && !l.startsWith('#') && !l.startsWith('!'));
+ if (lines.length > 0) {
+ result.description = lines[0].trim().substring(0, 200);
+ }
+ emit('readme', 'done', { message: `Found: ${readmeFile}`, description: result.description });
+ foundReadme = true;
+ break;
+ }
+ }
+ }
+ if (!foundReadme) {
+ emit('readme', 'done', { message: 'No README found' });
}
} else {
- emit('ai', 'skipped', { message: 'No AI provider configured' });
+ emit('readme', 'skipped', { message: 'Description already found in package.json' });
}
// Complete
socket.emit('detect:complete', {
success: true,
- result,
- provider: provider?.name || null
+ result
});
}
-
-/**
- * Run AI analysis on project
- */
-async function runAiAnalysis(dirPath, provider, context) {
- const prompt = buildPrompt(dirPath, context);
-
- let response;
- if (provider.type === 'cli') {
- response = await executeCliPrompt(provider, prompt, dirPath);
- } else if (provider.type === 'api') {
- response = await executeApiPrompt(provider, prompt);
- } else {
- throw new Error('Unknown provider type');
- }
-
- return parseResponse(response);
-}
-
-function buildPrompt(dirPath, { pkg, files }) {
- return `Analyze this project and return JSON configuration.
-
-Directory: ${basename(dirPath)}
-Files: ${files.slice(0, 30).join(', ')}
-${pkg ? `package.json name: ${pkg.name}, scripts: ${Object.keys(pkg.scripts || {}).join(', ')}` : 'No package.json'}
-
-Return ONLY valid JSON:
-{
- "name": "Human readable app name",
- "description": "One sentence description",
- "uiPort": null or number,
- "apiPort": null or number,
- "startCommands": ["npm run dev"],
- "pm2ProcessNames": ["app-name"]
-}`;
-}
-
-async function executeCliPrompt(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', d => output += d.toString());
- child.stderr.on('data', d => output += d.toString());
- child.on('close', code => code === 0 ? resolve(output) : reject(new Error(`Exit ${code}`)));
- child.on('error', reject);
- setTimeout(() => { child.kill(); reject(new Error('Timeout')); }, provider.timeout || 60000);
- });
-}
-
-async function executeApiPrompt(provider, prompt) {
- const headers = { 'Content-Type': 'application/json' };
- if (provider.apiKey) headers['Authorization'] = `Bearer ${provider.apiKey}`;
-
- const res = await fetch(`${provider.endpoint}/chat/completions`, {
- method: 'POST',
- headers,
- body: JSON.stringify({
- model: provider.defaultModel,
- messages: [{ role: 'user', content: prompt }],
- temperature: 0.1
- })
- });
-
- if (!res.ok) throw new Error(`API ${res.status}`);
- const data = await res.json();
- return data.choices?.[0]?.message?.content || '';
-}
-
-function parseResponse(response) {
- let str = response.trim();
- const match = str.match(/```(?:json)?\s*([\s\S]*?)```/) || str.match(/\{[\s\S]*\}/);
- if (match) str = match[1] || match[0];
- return JSON.parse(str);
-}
diff --git a/server/services/usage.js b/server/services/usage.js
new file mode 100644
index 0000000000..49403f0fde
--- /dev/null
+++ b/server/services/usage.js
@@ -0,0 +1,223 @@
+import { readFile, writeFile, mkdir } from 'fs/promises';
+import { existsSync } from 'fs';
+import { join, dirname } from 'path';
+import { fileURLToPath } from 'url';
+
+const __filename = fileURLToPath(import.meta.url);
+const __dirname = dirname(__filename);
+const DATA_DIR = join(__dirname, '../../data');
+const USAGE_FILE = join(DATA_DIR, 'usage.json');
+
+let usageData = null;
+
+/**
+ * Initialize usage data structure
+ */
+function getEmptyUsage() {
+ return {
+ totalSessions: 0,
+ totalMessages: 0,
+ totalToolCalls: 0,
+ totalTokens: {
+ input: 0,
+ output: 0
+ },
+ byProvider: {},
+ byModel: {},
+ dailyActivity: {},
+ hourlyActivity: Array(24).fill(0),
+ lastUpdated: null
+ };
+}
+
+/**
+ * Load usage data from disk
+ */
+export async function loadUsage() {
+ if (!existsSync(DATA_DIR)) {
+ await mkdir(DATA_DIR, { recursive: true });
+ }
+
+ if (existsSync(USAGE_FILE)) {
+ usageData = JSON.parse(await readFile(USAGE_FILE, 'utf-8'));
+ } else {
+ usageData = getEmptyUsage();
+ await saveUsage();
+ }
+
+ console.log(`📊 Loaded usage: ${usageData.totalSessions} sessions, ${usageData.totalMessages} messages`);
+ return usageData;
+}
+
+/**
+ * Save usage data to disk
+ */
+async function saveUsage() {
+ usageData.lastUpdated = new Date().toISOString();
+ await writeFile(USAGE_FILE, JSON.stringify(usageData, null, 2));
+}
+
+/**
+ * Get current usage stats
+ */
+export function getUsage() {
+ return usageData || getEmptyUsage();
+}
+
+/**
+ * Record a new session
+ */
+export async function recordSession(providerId, providerName, model) {
+ if (!usageData) await loadUsage();
+
+ usageData.totalSessions++;
+
+ // Track by provider
+ if (!usageData.byProvider[providerId]) {
+ usageData.byProvider[providerId] = { name: providerName, sessions: 0, messages: 0, tokens: 0 };
+ }
+ usageData.byProvider[providerId].sessions++;
+
+ // Track by model
+ if (model) {
+ if (!usageData.byModel[model]) {
+ usageData.byModel[model] = { sessions: 0, messages: 0, tokens: 0 };
+ }
+ usageData.byModel[model].sessions++;
+ }
+
+ // Track daily activity
+ const today = new Date().toISOString().split('T')[0];
+ if (!usageData.dailyActivity[today]) {
+ usageData.dailyActivity[today] = { sessions: 0, messages: 0, tokens: 0 };
+ }
+ usageData.dailyActivity[today].sessions++;
+
+ // Track hourly activity
+ const hour = new Date().getHours();
+ usageData.hourlyActivity[hour]++;
+
+ await saveUsage();
+ return usageData.totalSessions;
+}
+
+/**
+ * Record messages in a session
+ */
+export async function recordMessages(providerId, model, messageCount, tokenCount = 0) {
+ if (!usageData) await loadUsage();
+
+ usageData.totalMessages += messageCount;
+
+ if (tokenCount > 0) {
+ usageData.totalTokens.output += tokenCount;
+ }
+
+ // Track by provider
+ if (usageData.byProvider[providerId]) {
+ usageData.byProvider[providerId].messages += messageCount;
+ usageData.byProvider[providerId].tokens += tokenCount;
+ }
+
+ // Track by model
+ if (model && usageData.byModel[model]) {
+ usageData.byModel[model].messages += messageCount;
+ usageData.byModel[model].tokens += tokenCount;
+ }
+
+ // Track daily
+ const today = new Date().toISOString().split('T')[0];
+ if (usageData.dailyActivity[today]) {
+ usageData.dailyActivity[today].messages += messageCount;
+ usageData.dailyActivity[today].tokens += tokenCount;
+ }
+
+ await saveUsage();
+}
+
+/**
+ * Record tool calls
+ */
+export async function recordToolCalls(count) {
+ if (!usageData) await loadUsage();
+ usageData.totalToolCalls += count;
+ await saveUsage();
+}
+
+/**
+ * Record token usage
+ */
+export async function recordTokens(inputTokens, outputTokens) {
+ if (!usageData) await loadUsage();
+ usageData.totalTokens.input += inputTokens;
+ usageData.totalTokens.output += outputTokens;
+ await saveUsage();
+}
+
+/**
+ * Get usage summary
+ */
+export function getUsageSummary() {
+ if (!usageData) return getEmptyUsage();
+
+ // Get last 7 days activity
+ const last7Days = [];
+ for (let i = 6; i >= 0; i--) {
+ const date = new Date();
+ date.setDate(date.getDate() - i);
+ const dateStr = date.toISOString().split('T')[0];
+ last7Days.push({
+ date: dateStr,
+ label: date.toLocaleDateString('en-US', { weekday: 'short' }),
+ ...(usageData.dailyActivity[dateStr] || { sessions: 0, messages: 0, tokens: 0 })
+ });
+ }
+
+ // Calculate totals
+ const totalCost = estimateCost(usageData.totalTokens.input, usageData.totalTokens.output);
+
+ return {
+ totalSessions: usageData.totalSessions,
+ totalMessages: usageData.totalMessages,
+ totalToolCalls: usageData.totalToolCalls,
+ totalTokens: usageData.totalTokens,
+ estimatedCost: totalCost,
+ last7Days,
+ hourlyActivity: usageData.hourlyActivity,
+ topProviders: Object.entries(usageData.byProvider)
+ .map(([id, data]) => ({ id, ...data }))
+ .sort((a, b) => b.sessions - a.sessions)
+ .slice(0, 5),
+ topModels: Object.entries(usageData.byModel)
+ .map(([model, data]) => ({ model, ...data }))
+ .sort((a, b) => b.sessions - a.sessions)
+ .slice(0, 5),
+ lastUpdated: usageData.lastUpdated
+ };
+}
+
+/**
+ * Estimate cost based on token usage
+ */
+function estimateCost(inputTokens, outputTokens) {
+ // Average costs per 1M tokens (rough estimates)
+ const inputCostPer1M = 3.00;
+ const outputCostPer1M = 15.00;
+
+ const inputCost = (inputTokens / 1_000_000) * inputCostPer1M;
+ const outputCost = (outputTokens / 1_000_000) * outputCostPer1M;
+
+ return Math.round((inputCost + outputCost) * 100) / 100;
+}
+
+/**
+ * Reset usage data
+ */
+export async function resetUsage() {
+ usageData = getEmptyUsage();
+ await saveUsage();
+ return true;
+}
+
+// Load on startup
+loadUsage().catch(err => console.error(`❌ Failed to load usage: ${err.message}`));